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 a 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 chosen 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 successfully.

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/receive-ada-sample to store all the related files as an example, please replace it with the directory you have chosen to store the files. All the code examples in this article assume that you will save all the source-code-files under the root of this directory.

Generate keys and request tAda

First, let's create a directory to store our sample project:

mkdir -p $HOME/receive-ada-sample/keys

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

cardano-cli address key-gen \
--verification-key-file $HOME/receive-ada-sample/keys/payment.vkey \
--signing-key-file $HOME/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 a testnet network like so:

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

Your directory structure should now look like this:

$HOME/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-cmd
import cmd from 'node-cmd';

// Path to the cardano-cli binary or use the global one
const CARDANO_CLI_PATH = "cardano-cli";
// The testnet identifier number
const CARDANO_NETWORK_MAGIC = 1097911063;
// The directory where we store our payment keys
// assuming our current directory context is $HOME/receive-ada-sample
const CARDANO_KEYS_DIR = "keys";
// The total payment we expect in lovelace unit
const 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 file
const walletAddress = fs.readFileSync(`${CARDANO_KEYS_DIR}/payment.addr`).toString();

Query UTxO

Then we execute cardano-cli programmatically 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 data
const 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 address
const 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 successful

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 successful. 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-cmd
import cmd from 'node-cmd';

// Path to the cardano-cli binary or use the global one
const CARDANO_CLI_PATH = "cardano-cli";
// The `testnet` identifier number
const CARDANO_NETWORK_MAGIC = 1097911063;
// The directory where we store our payment keys
// assuming our current directory context is $HOME/receive-ada-sample/receive-ada-sample
const CARDANO_KEYS_DIR = "keys";
// The imaginary total payment we expect in lovelace unit
const TOTAL_EXPECTED_LOVELACE = 1000000;

// Read wallet address string value from payment.addr file
const walletAddress = fs.readFileSync(`${CARDANO_KEYS_DIR}/payment.addr`).toString();

// We use the node-cmd npm library to execute shell commands and read the output data
const 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 address
const 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/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.js
Total Received: 0 LOVELACE
Expected Payment: 1000000 LOVELACE
Payment 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 successful payment is to send at least 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/receive-ada-sample/receive-ada-sample/keys/payment.addr

You should see the wallet address value:

addr_test1vpfkp665a6wn7nxvjql5vdn5g5a94tc22njf4lf98afk6tgnz5ge4

Now simply send at least 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 successful result this time.

❯ node checkPayment.js
Total Received: 1000000000 LOVELACE
Expected Payment: 1000000 LOVELACE
Payment 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 successful Cardano payments programmatically. This should help you bring integrations to your existing or new upcoming applications. 🎉🎉🎉