Skip to main content

Listening for ADA payments using cardano-cli

Overview#

note

This guide assumes that you have basic understanding of cardano-cli, how to use it and that you have installed it into your system. Otherwise we recommend reading Installing cardano-node, Running cardano-node and Exploring Cardano Wallets guides first.

This guide also assumes that you have cardano-node running in the background and connected to the testnet network.

Use case#

There are many possible reasons why you would want to have the functionality of listening for ADA payments, but a very obvious use case would be for something like an online shop or a payment gateway that uses ADA tokens as the currency.

img

Technical flow#

To understand how something like this could work in a technical point of view, let's take a look at the following diagram:

img

So let's imagine a very basic scenario where a customer is browsing an online shop. Once the user has choosen and added all the items into the shopping cart. The next step would then be to checkout and pay for the items, Of course we will be using Cardano for that!

The front-end application would then request for a wallet address from the backend service and render a QR code to the customer to be scanned via a Cardano wallet. The backend service would then know that it has to query the wallet address using cardano-cli with a certain time interval to confirm and alert the front-end application that the payment has completed succesfully.

In the meantime the transaction is then being processed and settled within the Cardano network. We can see in the diagram above that both parties are ultimately connected to the network via the cardano-node software component.

Time to code#

Now let's get our hands dirty and see how we can implement something like this in actual code.

note

In this section, We will use the path /home/user/receive-ada-sample to store all the related files as an example, please replace it with the directory you have choosen to store the files. All the code examples in this article assumes that you will save all the source-code-files under the root of this directory.

Generate keys and request tADA#

First, lets create a directory to store our sample project:

mkdir -p /home/user/receive-ada-sample/keys

Next, we generate our payment key-pair using cardano-cli:

cardano-cli address key-gen \--verification-key-file /home/user/receive-ada-sample/keys/payment.vkey \--signing-key-file /home/user/receive-ada-sample/keys/payment.skey

Since we now have our payment key-pair, the next step would be to generate a wallet address for the testnet network like so:

cardano-cli address build \--payment-verification-key-file /home/user/receive-ada-sample/keys/payment.vkey \--out-file /home/user/receive-ada-sample/keys/payment.addr \--testnet-magic 1097911063

Your directory structure should now look like this:

/home/user/receive-ada-sample/receive-ada-sampleโ””โ”€โ”€ keys    โ”œโ”€โ”€ payment.addr    โ”œโ”€โ”€ payment.skey    โ””โ”€โ”€ payment.vkey

Now using your programming language of choice we create our first few lines of code!

Initial variables#

First we will set the initial variables that we will be using as explained below:

checkPayment.js
import * as fs from 'fs';// Please add this dependency using npm install node-cmdimport cmd from 'node-cmd';
// Path to the cardano-cli binary or use the global oneconst CARDANO_CLI_PATH = "cardano-cli";// The `testnet` identifier numberconst CARDANO_NETWORK_MAGIC = 1097911063;// The directory where we store our payment keys// assuming our current directory context is /home/user/receive-ada-sampleconst CARDANO_KEYS_DIR = "keys";// The total payment we expect in lovelace unitconst TOTAL_EXPECTED_LOVELACE = 1000000;

Read wallet address value#

Next, we get the string value of the wallet address from the payment.addr file that we generated awhile ago. Add the following lines to your code:

checkPayment.js
// Read wallet address value from payment.addr fileconst walletAddress = fs.readFileSync(`${CARDANO_KEYS_DIR}/payment.addr`).toString();

Query UTxO#

Then we execute cardano-cli programatically and telling it to query the UTxO for the wallet address that we have generated with our keys and save the stdout result to our rawUtxoTable variable.

checkPayment.js
// We use the node-cmd npm library to execute shell commands and read the output dataconst rawUtxoTable = cmd.runSync([    CARDANO_CLI_PATH,    "query", "utxo",    "--testnet-magic", CARDANO_NETWORK_MAGIC,    "--address", walletAddress].join(" "));

Process UTxO table#

Once we have access to the UTXO table string, we will then parse it and compute the total lovelace that the wallet currently has.

checkPayment.js
// Calculate total lovelace of the UTXO(s) inside the wallet addressconst utxoTableRows = rawUtxoTable.data.trim().split('\n');let totalLovelaceRecv = 0;let isPaymentComplete = false;
for (let x = 2; x < utxoTableRows.length; x++) {    const cells = utxoTableRows[x].split(" ").filter(i => i);    totalLovelaceRecv += parseInt(cells[2]);}

Determine if payment is succesful#

Once we have the total lovelace amount, we will then determine using our code if a specific payment is a success, ultimately sending or shipping the item if it is indeed succesful. In our example, we expect that the payment is equal to 1,000,000 lovelace that we defined in our TOTAL_EXPECTED_LOVELACE constant variable.

checkPayment.js
// Determine if the total lovelace received is more than or equal to// the total expected lovelace and displaying the results.isPaymentComplete = totalLovelaceRecv >= TOTAL_EXPECTED_LOVELACE;
console.log(`Total Received: ${totalLovelaceRecv} LOVELACE`);console.log(`Expected Payment: ${TOTAL_EXPECTED_LOVELACE} LOVELACE`);console.log(`Payment Complete: ${(isPaymentComplete ? "โœ…" : "โŒ")}`);

Running and testing#

Our final code should look something like this:

checkPayment.js
import * as fs from 'fs';// Please add this dependency using npm install node-cmdimport cmd from 'node-cmd';
// Path to the cardano-cli binary or use the global oneconst CARDANO_CLI_PATH = "cardano-cli";// The `testnet` identifier numberconst CARDANO_NETWORK_MAGIC = 1097911063;// The directory where we store our payment keys// assuming our current directory context is /home/user/receive-ada-sample/receive-ada-sampleconst CARDANO_KEYS_DIR = "keys";// The imaginary total payment we expect in lovelace unitconst TOTAL_EXPECTED_LOVELACE = 1000000;
// Read wallet address string value from payment.addr fileconst walletAddress = fs.readFileSync(`${CARDANO_KEYS_DIR}/payment.addr`).toString();
// We use the node-cmd npm library to execute shell commands and read the output dataconst rawUtxoTable = cmd.runSync([    CARDANO_CLI_PATH,    "query", "utxo",    "--testnet-magic", CARDANO_NETWORK_MAGIC,    "--address", walletAddress].join(" "));
// Calculate total lovelace of the UTXO(s) inside the wallet addressconst utxoTableRows = rawUtxoTable.data.trim().split('\n');let totalLovelaceRecv = 0;let isPaymentComplete = false;
for(let x = 2; x < utxoTableRows.length; x++) {    const cells = utxoTableRows[x].split(" ").filter(i => i);    totalLovelaceRecv += parseInt(cells[2]);}
// Determine if the total lovelace received is more than or equal to// the total expected lovelace and displaying the results.isPaymentComplete = totalLovelaceRecv >= TOTAL_EXPECTED_LOVELACE;
console.log(`Total Received: ${totalLovelaceRecv} LOVELACE`);console.log(`Expected Payment: ${TOTAL_EXPECTED_LOVELACE} LOVELACE`);console.log(`Payment Complete: ${(isPaymentComplete ? "โœ…" : "โŒ")}`);

Your project directory should look something like this:

# Excluding node_modules directory
/home/user/receive-ada-sample/receive-ada-sampleโ”œโ”€โ”€ checkPayment.jsโ”œโ”€โ”€ keysโ”‚ย ย  โ”œโ”€โ”€ payment.addrโ”‚ย ย  โ”œโ”€โ”€ payment.skeyโ”‚ย ย  โ””โ”€โ”€ payment.vkeyโ”œโ”€โ”€ package-lock.jsonโ””โ”€โ”€ package.json
1 directories, 6 files

Now we are ready to test ๐Ÿš€, running the code should give us the following result:

โฏ node checkPayment.jsTotal Received: 0 LOVELACEExpected Payment: 1000000 LOVELACEPayment Complete: โŒ

The code is telling us that our current wallet has received a total of 0 lovelace and it expected 1,000,000 lovelace, therefore it concluded that the payment is not complete.

Complete the payment#

What we can do to simulate a succesful payment is to send atleast 1,000,000 lovelace into the wallet address that we have just generated for this project. We can get the wallet address by reading the contents of the payment.addr file like so:

cat /home/user/receive-ada-sample/receive-ada-sample/keys/payment.addr

You should see the wallet address value:

addr_test1vpfkp665a6wn7nxvjql5vdn5g5a94tc22njf4lf98afk6tgnz5ge4

Now simply send atleast 1,000,000 lovelace to this wallet address or request some test ADA funds from the Cardano Testnet Faucet. Once complete, we can now run the code again and we should see a succesful result this time.

โฏ node checkPayment.jsTotal Received: 1000000000 LOVELACEExpected Payment: 1000000 LOVELACEPayment Complete: โœ…
note

It might take 20 seconds or more for the transaction to propagate within the network depending on the network health, so you will have to be patient.

Congratulations, you are now able to detect succesful Cardano payments programatically. This should help you bring integrations to your existing or new upcoming applications. ๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰