Tutorial:- Making Payments with Stellar

Introduction

Once you have a funded Stellar account, you can send payments to other accounts on the network. This tutorial will guide you through making a payment using the Stellar SDK for JavaScript.

Prerequisites

Ensure you have:

  • Node.js installed.
  • A text editor or IDE (like VSCode).
  • Basic knowledge of JavaScript.
  • A funded Stellar account (refer to the previous tutorial).
Step 1: Set Up the Project

First, create a new project directory and install the Stellar SDK:

mkdir stellar-custom-asset
cd stellar-custom-asset
npm init -y
npm install stellar-sdk
Step 2: Load the Stellar SDK and Configure Accounts

Create a file named sendPayment.js and add the following code:

const StellarSdk = require('stellar-sdk');
const server = new StellarSdk.Server('https://horizon-testnet.stellar.org');

// Sender's keys
const senderKeys = StellarSdk.Keypair.fromSecret('SENDER_SECRET_KEY');

// Receiver's public key
const receiverPublicKey = 'RECEIVER_PUBLIC_KEY';

// Transaction details
const amount = '10'; // Amount of XLM to send

Replace SENDER_SECRET_KEY with the secret key of your sender account and RECEIVER_PUBLIC_KEY with the public key of your receiver account.

Step 3: Build and Sign the Transaction

Add the following code to build and sign the transaction:

async function sendPayment() {
  try {
    const account = await server.loadAccount(senderKeys.publicKey());
   
    const transaction = new StellarSdk.TransactionBuilder(account, {
      fee: StellarSdk.BASE_FEE,
      networkPassphrase: StellarSdk.Networks.TESTNET,
    })
    .addOperation(StellarSdk.Operation.payment({
      destination: receiverPublicKey,
      asset: StellarSdk.Asset.native(),
      amount: amount,
    }))
    .setTimeout(30)
    .build();
   
    transaction.sign(senderKeys);
   
    const transactionResult = await server.submitTransaction(transaction);
    console.log('Payment successful!', transactionResult);
  }
  catch (error) {
    console.error('Error!', error);
  }
}

sendPayment();

This script loads the sender's account, builds a payment transaction, signs it, and submits it to the Stellar test network.

Step 4: Run the Script

Run the script using Node.js:

node sendPayment.js

If successful, you'll see a message indicating the payment was successful along with the transaction details.

Conclusion

You've successfully sent a payment on the Stellar network using the Stellar SDK for JavaScript. You can adjust the script to send different amounts, use different assets, or interact with other accounts. For more advanced payment options, check out the Stellar Payment Operations documentation.