Skip to main content

Listening for ada payments using cardano-wallet

Overview#

note

This guide assumes that you have basic understanding of cardano-wallet, 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 and cardano-wallet 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 cardano-wallet 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.

Generate wallet and request tAda#

First, we create our new wallet via cardano-wallet REST API:

Generate seed#

// Please add this dependency using npm install node-cmdimport cmd from 'node-cmd';const mnemonic = cmd.runSync(["cardano-wallet","recovery-phrase", "generate"].join(" ")).data;

Restore wallet from seed#

We will then pass the generated seed to the wallet create / restore endpoint of cardano-wallet.

// Please add this dependency using npm install node-fetchimport fetch from 'node-fetch';
const resp = await fetch("http://localhost:9998/v2/wallets", {    method: 'POST',    headers: {        'Content-Type': 'application/json'    },    body: JSON.stringify({        name: "test_cf_1",        mnemonic_sentence: ["expose", "biology", "will", "pause", "taxi", "behave", "inquiry", "lock", "matter", "pride", "divorce", "model", "little", "easily", "solid", "need", "dose", "sadness", "kitchen", "pyramid", "erosion", "shoulder", "double", "fragile"],        passphrase: "test123456"    })});

Get unused wallet address to receive some payments#

We will get a wallet address to show to the customers and for them to send payments to the wallet. In this case we can use the address to request some tAda from the Cardano Testnet Faucet and simulate a payment:

// Please add this dependency using npm install node-fetchimport fetch from 'node-fetch';const walletId = "101b3814d6977de4b58c9dedc67b87c63a4f36dd";const resp = await fetch(`http://localhost:9998/v2/wallets/${walletId}/addresses?state=unused`);const addresses = await resp.json();const firstWalletAddress = addresses[0].id;

Retrieve wallet balance#

We will then retrieve the wallet details to get stuff like its sync status, native assets and balance (lovelace). We can then use the balance to check if we have received a some payment.

// Please add this dependency using npm install node-fetchimport fetch from 'node-fetch';const walletId = "101b3814d6977de4b58c9dedc67b87c63a4f36dd";// The total payment we expect in lovelace unitconst totalExpectedLovelace = 1000000;const resp = await fetch(`http://localhost:9998/v2/wallets/${walletId}`);const wallet = await resp.json();const balance = wallet.balance.total.quantity;

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 succesful. In our example, we expect that the payment is equal to 1,000,000 lovelace that we defined in our totalExpectedLovelace constant.

// Check if payment is completeconst isPaymentComplete = balance >= totalExpectedLovelace;
console.log(`Total Received: ${balance} LOVELACE`);console.log(`Expected Payment: ${totalExpectedLovelace} LOVELACE`);console.log(`Payment Complete: ${(isPaymentComplete ? "โœ…":"โŒ")}`);

Running and testing#

Our final code should look something like this:

// Please add this dependency using npm install node-fetchimport fetch from 'node-fetch';const walletId = "101b3814d6977de4b58c9dedc67b87c63a4f36dd";// The total payment we expect in lovelace unitconst totalExpectedLovelace = 1000000;const resp = await fetch(`http://localhost:9998/v2/wallets/${walletId}`);const wallet = await resp.json();const balance = wallet.balance.total.quantity;
// Check if payment is completeconst isPaymentComplete = balance >= totalExpectedLovelace;
console.log(`Total Received: ${balance} LOVELACE`);console.log(`Expected Payment: ${totalExpectedLovelace} LOVELACE`);console.log(`Payment Complete: ${(isPaymentComplete ? "โœ…":"โŒ")}`);

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 show how you can get the wallet address via code in the examples above.

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. ๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰