Integrating Stellar with JavaScript: Building dApp is Easy (for Absolute Beginners)

Jitendra Choudhary - Aug 13 - - Dev Community

Stellar is an open-source blockchain network for fast and cross-border financial transactions. If you are a JavaScript developer and wanna build dApp on a stellar network, this is the thing for you. In this tutorial, we will learn how to integrate Stellar with JavaScript, from setting up the environment to making your first transaction.

So, let's start.

Oh, before we begin, we need basic knowledge of JavaScript and have npm and Node.js installed on your machine.

1. Sitting Up the Environment

First, open your terminal or command prompt and create a new directory for the project:

mkdir stellar-js
cd stellar-js
npm init -y
Enter fullscreen mode Exit fullscreen mode

This command will initialize a new Node.js project.

Now, install the Stellar SDK for JavaScript.

npm install stellar-sdk
Enter fullscreen mode Exit fullscreen mode

But, wait What is Stellar-SDK?

Stellar SDK is a powerful library to interact with the Stellar network using JavaScript.

2. Connecting to the Stellar Network

Now, that the environment is set up, we will connect with the Stellar network. We require Stellar SDK and connect to the testnet.

What's Testnet?

Testnet is a free-to-use network for a developer to test their application without connecting to real money. Where there is a mainnet that connects to real money and requires XLM to cover transaction fees, etc. The testnet is similar to the mainnet, it has free test Lumens (XLM) called Friendbot.

const StellarSdk = require("stellar-sdk");
const server = new StellarSdk.Server("https://horizon-testnet.stellar.org");
Enter fullscreen mode Exit fullscreen mode

This will initialize the SDK and set the server to connect to the testnet.

3. Creating a New Account

To interact with the Stellar network, you need to have a Stellar account. You can easily create a new account using SDK by generating a key-value pair. The value pair consists of a public and a private key.

const pair = StellarSdk.Keypair.random();

console.log('Public Key:', pair.publicKey());
console.log('Secret Key:', pair.secret());
Enter fullscreen mode Exit fullscreen mode

The publicKey() is your account’s identifier, while the secret() is your private key, which should be kept secure.

4. Funding the Account

In the testnet, you can fund your account using Stellar's Friendbot service.

const fetch = require("node-fetch");

const fundAccount = async (publicKey) => {
  try {
    const response = await fetch(
      `https://friendbot.stellar.org?addr=${publicKey}`
    );
    const data = await response.json();
    console.log("Account funded:", data);
  } catch (error) {
    console.error("Error funding account:", error);
  }
};

fundAccount(pair.publicKey());
Enter fullscreen mode Exit fullscreen mode

The fundAccount function sends a request to Friendbot to deposit 10k test Lumens in your account. Accordingly, to the status of the transaction, it will log the message.

5. Making a Transaction

Now, that your account is founded, you can make your first transaction on the stellar network. We'll build, sign, and submit the transaction to the stellar network. We'll send 10 XLM from our account to another account.

const sendPayment = async (publicKey) => {
  try {
    const account = await server.loadAccount(pair.publicKey());

    const transaction = new StellarSdk.TransactionBuilder(account, {
      fee: StellarSdk.BASE_FEE,
      networkPassphrase: StellarSdk.Networks.TESTNET,
    })
      .addOperation(
        StellarSdk.Operation.payment({
          destination: publicKey,
          asset: StellarSdk.Asset.native(),
          amount: "10",
        })
      )
      .setTimeout(30)
      .build();

    transaction.sign(pair);

    const result = await server.submitTransaction(transaction);
    console.log("Transaction successful:", result);
  } catch (error) {
    console.error("Error sending payment:", error);
  }
};

sendPayment("Another_Account's_Public_Key");
Enter fullscreen mode Exit fullscreen mode

6. Error Handling and Debugging

Even a single comma ( , ) can ruin your code. Handling errors is very important to keep the code on the expected track.

try {
  const result = await server.submitTransaction(transaction);
  console.log("Success:", result);
} catch (error) {
  console.error("Error:", error.response.data.extras.result_codes);
}
Enter fullscreen mode Exit fullscreen mode

This catches any errors during the transaction and logs the specific error which helps to debug the code.

Conclusion

We just integrated Stellar with JavaScript and made our first transaction on the Stellar testnet. As JavaScript is widely adopted among developers, transitioning to the blockchain with Stellar is more convenient.

The best way to learn any new skill is to practice more projects. Build small projects and experiment with the concepts.

If you find this post helpful don't forget to keep showing me love. Until next time like, share, and learn.

You can also stay connected with me by following me here and on X, GitHub, and LinkedIn.

. . . . . . . . . . . . . . .