Tutorial:- Building and Submitting Transactions

Introduction

Transactions are the core of the Stellar network. This tutorial will guide you through building and submitting a custom transaction 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 first 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 buildTransaction.js and add the following code:

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

// Source account keys
const sourceKeys = StellarSdk.Keypair.fromSecret('SOURCE_SECRET_KEY');

// Destination account public key
const destinationPublicKey = 'DESTINATION_PUBLIC_KEY';

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

Replace SOURCE_SECRET_KEY with the secret key of your source account and DESTINATION_PUBLIC_KEY with the public key of your destination account.

Step 3: Build and Sign the Transaction

Add the following code to build a transaction with a memo and a payment operation:

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

buildAndSubmitTransaction();

This script builds a transaction with a memo and a payment operation, signs it, and submits it to the Stellar test network.

Step 4: Run the Script

Run the script using Node.js:

node buildTransaction.js

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

Conclusion

You've successfully built and submitted a transaction on the Stellar network using the Stellar SDK for JavaScript. You can add more operations, adjust the memo, or interact with different accounts as needed. For more details on building transactions, check out the Stellar Transactions documentation.