DEV Community

Cover image for Creating and Sending Transactions with Stellar’s JavaScript SDK
Suleiman Alhaji Mohammed
Suleiman Alhaji Mohammed

Posted on

2 2 3 2 2

Creating and Sending Transactions with Stellar’s JavaScript SDK

Let’s get into the tutorial on how to interact with the Stellar blockchain using its SDK. We’ll focus on creating and sending transactions with Steller's JavaScript SDK, which is useful for developers who want to integrate Stellar into their applications

Tutorial: Creating and Sending Transactions with Stellar’s JavaScript SDK

Prerequisites
Node.js: Ensure you have Node.js installed on your system. You can download it from nodejs.org.

Stellar SDK: We will use the Stellar SDK for JavaScript. You can install it using npm.

Basic JavaScript Knowledge: Understanding of JavaScript basics is helpful.

Stellar Account: You’ll need a Stellar account to interact with the Stellar network. You can create one using the Stellar Laboratory or other Stellar wallet providers.

Step 1: Setting Up Your Environment
First, create a new project directory and initialize it with npm:

mkdir stellar-tutorial
cd stellar-tutorial
npm init -y

Install the Stellar SDK:

npm install @stellar/sdk

Step 2: Writing the Code
Create a file named 'index.js' in your project directory and open it in your favorite code editor eg. Sublime Text, Visual Studio code and Bracket etc.
Add the following code to 'index.js':

`const StellarSdk = require('@stellar/sdk');
const fetch = require('node-fetch');
global.fetch = fetch;

// Configure network
const server = new StellarSdk.Server('https://horizon-testnet.stellar.org'); // Use testnet for development
const networkPassphrase = StellarSdk.Networks.TESTNET;

// Replace with your Stellar account details
const sourceSecretKey = 'YOUR_SOURCE_ACCOUNT_SECRET_KEY';
const destinationPublicKey = 'DESTINATION_ACCOUNT_PUBLIC_KEY';
const amount = '10'; // Amount to send in XLM

// Create a keypair from the source secret key
const sourceKeypair = StellarSdk.Keypair.fromSecret(sourceSecretKey);

// Create a transaction object
async function sendTransaction() {
try {
// Load source account
const account = await server.loadAccount(sourceKeypair.publicKey());

    // Create a payment operation
    const paymentOperation = StellarSdk.Operation.payment({
        destination: destinationPublicKey,
        asset: StellarSdk.Asset.native(),
        amount: amount
    });

    // Create a transaction
    const transaction = new StellarSdk.TransactionBuilder(account, {
        fee: StellarSdk.BASE_FEE,
        networkPassphrase: networkPassphrase
    })
    .addOperation(paymentOperation)
    .setTimeout(30)
    .build();

    // Sign the transaction
    transaction.sign(sourceKeypair);

    // Submit the transaction
    const response = await server.submitTransaction(transaction);
    console.log('Transaction successful:', response);
} catch (error) {
    console.error('Transaction failed:', error);
}
Enter fullscreen mode Exit fullscreen mode

}

// Run the function
sendTransaction();`

Step 3: Understanding the Code

  1. Network Configuration: We use the Stellar Testnet for development to avoid using real assets. For production, you’d use 'https://horizon.stellar.org' and 'StellarSdk.Networks.PUBLIC'.

  2. Source and Destination Accounts: Replace 'YOUR_SOURCE_ACCOUNT_SECRET_KEY' with the secret key of the account sending the XLM, and 'DESTINATION_ACCOUNT_PUBLIC_KEY' with the public key of the recipient account.

  3. Building the Transaction: We create a 'Payment' operation, build the transaction, sign it with the source account’s private key, and submit it to the network.

  4. Error Handling: *The *'try...catch' block helps handle any errors that might occur during the transaction process.

Step 4: Running the Code
Run the script using Node.js:

node index.js

You should see a success message if everything goes smoothly. If there are issues, the error message will provide details on what went wrong.

Additional Tips
Stellar Laboratory: Use Stellar Laboratory for experimenting with transactions and key management.

Environment Variables: For security reasons, consider using environment variables to store sensitive information like secret keys.

Error Codes: Familiarize yourself with common Stellar error codes to troubleshoot issues effectively.

Jetbrains image

Don’t Become a Data Breach Headline

57% of organizations have suffered from a security incident related to DevOps toolchain exposures. Is your CI/CD protected? Check out these nine practical tips to keep your CI/CD secure—without adding friction.

Learn more

Top comments (0)

ACI image

ACI.dev: The Only MCP Server Your AI Agents Need

ACI.dev’s open-source tool-use platform and Unified MCP Server turns 600+ functions into two simple MCP tools on one server—search and execute. Comes with multi-tenant auth and natural-language permission scopes. 100% open-source under Apache 2.0.

Star our GitHub!

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay