Skip to main content

Send and Receive Payments

info

Need testnet tokens? Contact us on AIBlock discord and we will sort you out 😎

After setting up a wallet, you can send and receive payments very easily through the 2Way.js SDK. If you're developing this in a test environment, you can create 2 new keypairs. We'll use address 1 as our sender (Alice) and address 2 as our receiver (Bob).

import { Wallet } from '@2waychain/2wayjs';

const wallet = new Wallet();

// ... Initialize the wallet correctly

// ALICE ADDRESS

const aliceKeypairResult = wallet.getNewKeypair([]);
const aliceKeypair: IKeypairEncrypted = newKeypairResult.content.newKeypairResponse;
const aliceAddress = newKeypair.address;

// BOB ADDRESS

const bobKeypairResult = wallet.getNewKeypair([]);
const bobKeypair: IKeypairEncrypted = newKeypairResult.content.newKeypairResponse;
const bobAddress = newKeypair.address;

With these addresses available, we can now send and receive payments.


Sending a Payment​

The wallet provides a makeTokenPayment method, which simplifies the entire token payment process. This method does all the transaction construction for you, but importantly it does not check the validity of the payment address, so as the developer you'll need to make sure your application verifies that Bob's address is in fact valid. Otherwise we can make the payment simply:

const paymentResult = await wallet.makeTokenPayment({
bobAddress, // Address to pay (in this case we want to pay Bob)
10, // Payment amount
[aliceKeypair], // An array of keypairs to pay from
aliceKeypair // Where the change of your payment should go to
});

For this example we're assuming that Alice has 10 tokens to pay Bob. It's also important to note that the makeTokenPayment method is async, since it's making a call to the blockchain in order to effect the payment. That means you'll need to await the result, or handle it asynchronously.


Receiving a Payment​

The balance of Bob's address can then be checked on the UTXO, after a sufficient amount of time for the payment to go through on the chain

const bobBalanceCall = await wallet.fetchBalance([bobAddress]);
const bobBalance = bobBalanceCall.content.fetchBalanceResponse;

The response structure for bobBalance will then be something like the following:

{
"total": {
"tokens": 10,
"items": {}
},
"address_list": {
"a0b08...c02e5": [
{
"out_point": {
"t_hash": "g3b13...3353f",
"n": 0
},
"value": {
"Token": 10
}
},
]
}
}

That's it! 2Way.js has been designed to make sending and receiving payments as quick and easy as possible. Next, we'll take a look at how to make atomic, 2-way payments.