Beginner

Follow Received Payments

This guide demonstrates the ease of utilizing Horizon to monitor incoming payments on an account using JavaScript and EventSource. It will bypass the usage of js-stellar-sdk, a high-level helper library, to demonstrate that it is possible to perform this task with any preferred programming language.

It is assumed that the reader:

  • Has node.js installed on their local machine.
  • Has curl installed on their local machine.
  • Is working on Linux, macOS, or any other system with access to a bash-like shell.
  • Is familiar with launching and executing commands in a terminal.

The tutorial will cover the following topics:

  • Creating a new account.
  • Funding the account using friendbot.
  • Tracking payments to the account using curl and EventSource.

 

Project Skeleton​

Let’s begin by creating a project skeleton for our project:

bash

$ mkdir follow_tutorial
$ cd follow_tutorial
$ npm install --save stellar-base
$ npm install --save eventsource

 

This should have created a package.json in the follow_tutorial directory. You can check that everything went well by running the following command:

  • bash

Everything was successful if no output was generated from the above command. Now let’s write a script to create a new account.

Creating an account​

Create a new file with the name of make_account.js and paste the following code into it:

  • JavaScript
var Keypair = require("stellar-base").Keypair;

var newAccount = Keypair.random();

console.log("New key pair created!");
console.log("  Account ID: " + newAccount.publicKey());
console.log("  Secret: " + newAccount.secret());

Save the file and run it:

  • bash
$ node make_account.js
New key pair created!
  Account ID: GB7JFK56QXQ4DVJRNPDBXABNG3IVKIXWWJJRJICHRU22Z5R5PI65GAK3
  Secret: SCU36VV2OYTUMDSSU4EIVX4UUHY3XC7N44VL4IJ26IOG6HVNC7DY5UJO
$

Before our account can do anything it must be funded. Indeed, before an account is funded it does not truly exist! 

Funding your account

The Stellar test network offers the Friendbot, a useful tool for developers to obtain testnet lumens for testing purposes. To provide funding to your account, execute the following curl command:

bash

$ curl "https://friendbot.stellar.org/?addr=GB7JFK56QXQ4DVJRNPDBXABNG3IVKIXWWJJRJICHRU22Z5R5PI65GAK3"

Don’t forget to replace the account id above with your own. If the request succeeds, you should see a response like:

  • JSON
{
  "hash": "ed9e96e136915103f5d8978cbb2036628e811f2c59c4c3d88534444cf504e360",
  "result": "received",
  "submission_result": "000000000000000a0000000000000001000000000000000000000000"
}

After a few seconds, the Stellar network will perform consensus, close the ledger, and your account will have been created. Next up we will write a command that watches for new payments to your account and outputs a message to the terminal.

Following payments using curl​

To follow new payments connected to your account you simply need to send the Accept: text/event-stream header to the /payments endpoint.

  • bash
$ curl -H "Accept: text/event-stream" "https://horizon-testnet.stellar.org/accounts/GB7JFK56QXQ4DVJRNPDBXABNG3IVKIXWWJJRJICHRU22Z5R5PI65GAK3/payments"

As a result you will see something like:

  • bash
retry: 1000
event: open
data: "hello"

id: 713226564145153
data: {"_links":{"effects":{"href":"/operations/713226564145153/effects/{?cursor,limit,order}","templated":true},
       "precedes":{"href":"/operations?cursor=713226564145153\u0026order=asc"},
       "self":{"href":"/operations/713226564145153"},
       "succeeds":{"href":"/operations?cursor=713226564145153\u0026order=desc"},
       "transactions":{"href":"/transactions/713226564145152"}},
       "account":"GB7JFK56QXQ4DVJRNPDBXABNG3IVKIXWWJJRJICHRU22Z5R5PI65GAK3",
       "funder":"GBS43BF24ENNS3KPACUZVKK2VYPOZVBQO2CISGZ777RYGOPYC2FT6S3K",
       "id":713226564145153,
       "paging_token":"713226564145153",
       "starting_balance":"10000",
       "type_i":0,
       "type":"create_account"}

Every time you receive a new payment you will get a new row of data. Payments is not the only endpoint that supports streaming. You can also stream transactions /transactions and operations /operations.

Following payments using EventStream​

Warning! EventSource object does not reconnect for certain error types so it can stop working. If you need a reliable streaming connection please use our SDK.

Another way to follow payments is writing a simple JS script that will stream payments and print them to console. Create stream_payments.js file and paste the following code into it:

  • JavaScript
var EventSource = require("eventsource");
var es = new EventSource(
  "https://horizon-testnet.stellar.org/accounts/GB7JFK56QXQ4DVJRNPDBXABNG3IVKIXWWJJRJICHRU22Z5R5PI65GAK3/payments",
);
es.onmessage = function (message) {
  var result = message.data ? JSON.parse(message.data) : message;
  console.log("New payment:");
  console.log(result);
};
es.onerror = function (error) {
  console.log("An error occurred!");
};

Now, run our script: node stream_payments.js. You should see following output:

  • bash
New payment:
{ _links:
   { effects:
      { href: '/operations/713226564145153/effects/{?cursor,limit,order}',
        templated: true },
     precedes: { href: '/operations?cursor=713226564145153&order=asc' },
     self: { href: '/operations/713226564145153' },
     succeeds: { href: '/operations?cursor=713226564145153&order=desc' },
     transactions: { href: '/transactions/713226564145152' } },
  account: 'GB7JFK56QXQ4DVJRNPDBXABNG3IVKIXWWJJRJICHRU22Z5R5PI65GAK3',
  funder: 'GBS43BF24ENNS3KPACUZVKK2VYPOZVBQO2CISGZ777RYGOPYC2FT6S3K',
  id: 713226564145153,
  paging_token: '713226564145153',
  starting_balance: '10000',
  type_i: 0,
  type: 'create_account' }

 

Testing it out​

Now that we understand how to obtain a stream of transactions for an account, let’s verify if our solution is effective and if new payments are appearing. Let’s observe as we send a payment (create_account operation) from our account to another account.

We are using the create_account operation as we are sending payment to a new, unfunded account. On the other hand, if we were sending payment to an account that is already funded, we would use the payment operation.

First, let’s check the account sequence number in order to create a payment transaction. This can be done by sending a request to Horizon:

  • bash
$ curl "https://horizon-testnet.stellar.org/accounts/GB7JFK56QXQ4DVJRNPDBXABNG3IVKIXWWJJRJICHRU22Z5R5PI65GAK3"

Sequence number can be found under the sequence field. For our example, the current sequence number is 713226564141056. Save your value somewhere.

Now, create make_payment.js file and paste the following code into it, replacing the sequence number accordingly:

  • JavaScript
var StellarBase = require("stellar-base");
var StellarSdk = require("stellar-sdk");

var keypair = StellarBase.Keypair.fromSecret(
  "SCU36VV2OYTUMDSSU4EIVX4UUHY3XC7N44VL4IJ26IOG6HVNC7DY5UJO",
);
var account = new StellarBase.Account(keypair.publicKey(), "713226564141056");

var amount = "100";
var transaction = new StellarSdk.TransactionBuilder(account, {
  networkPassphrase: StellarBase.Networks.TESTNET,
  fee: StellarSdk.BASE_FEE,
})
  .addOperation(
    StellarBase.Operation.createAccount({
      destination: StellarBase.Keypair.random().publicKey(),
      startingBalance: amount,
    }),
  )
  .setTimeout(180)
  .build();

transaction.sign(keypair);

console.log(transaction.toEnvelope().toXDR().toString("base64"));

After executing this script, you should see a signed transaction blob. To submit this transaction, we will send it to Horizon or Stellar-Core. Before we do that, let’s open a new console and launch our previous script by using the command “node stream_payments.js”.

Now, to send a transaction, use Horizon:

  • bash
curl -H "Content-Type: application/json" -X POST -d '{"tx":"AAAAAgAAAAB+kqu+heHB1TFrxhuALTbRVSL2slMUoEeNNaz2PXo90wAAAGQAAoitAAAAAQAAAAEAAAAAAAAAAAAAAABgJHaDAAAAAAAAAAEAAAAAAAAAAAAAAAByS4gefO1iu/ZfYlr+PMA2AZsHJmSK/4NActJ1Oa1BIgAAAAA7msoAAAAAAAAAAAE9ej3TAAAAQPo1YHJMpdWKatEQxj7DqP1rrR6pA+OjK9q3WcU/sBwvKk6GhpdwA3gkUDrkREU0cFQSNKwugNFkGkR0zFmROgw="}' "https://horizon-testnet.stellar.org/transactions"

You should see a new payment in a window running stream_payments.js script.