Skip to main content
const web3 = require("@solana/web3.js");
const bs58 = require("bs58");

const connection = new web3.Connection('YOUR_CHAINSTACK_ENDPOINT');

const privateKey = new Uint8Array(bs58.decode('YOUR_PRIVATE_KEY'));
const account = web3.Keypair.fromSecretKey(privateKey);
const account2 = web3.Keypair.generate();

(async () => {
  const transaction = new web3.Transaction().add(
    web3.SystemProgram.transfer({
      fromPubkey: account.publicKey,
      toPubkey: account2.publicKey,
      lamports: web3.LAMPORTS_PER_SOL * 0.001,
    }),
  );
  const signature = await web3.sendAndConfirmTransaction(
    connection,
    transaction,
    [account],
  );
})();
This recipe shows how you can use the solana/web3.js library to send transactions programmatically using a Solana Chainstack node.
Install node.js if it is not installed yet.Create a new directory for your project, then install the solana/web3.js and bs58 libraries:npm install --save @solana/web3.js bs58
To run this code, you will need a Chainstack account and a Solana Elastic node.
  1. Sign up with Chainstack.
  2. Deploy a node.
  3. View node access and credentials.
This script starts by importing the necessary libraries.@solana/web3.js is the Solana JavaScript API, which provides the functionality needed to interact with the Solana blockchain. bs58 is a library for encoding and decoding data in base58, a binary-to-text encoding often used in cryptocurrencies.
The connection const establishes a connection to the Solana blockchain using a Chainstack endpoint.The next few lines set up two accounts. The first account is created from a private key. The second account is a new account that’s generated on the fly to be a fresh recipient account.
This is an async function to transfer a certain amount of Lamports, the smallest unit of the SOL token in Solana, from the first to the second account. In this case, it’s sending 0.001 SOL (LAMPORTS_PER_SOL * 0.001).It then sends the transaction and waits for confirmation.
Now you can get your endpoint and paste it into the connection const.Then you can run it with node YOUR_SCRIPT_NAMEThe transaction has been sent successfully if you don’t get any errors in the console.
const web3 = require("@solana/web3.js");
const bs58 = require("bs58");

const connection = new web3.Connection('YOUR_CHAINSTACK_ENDPOINT');

const privateKey = new Uint8Array(bs58.decode('YOUR_PRIVATE_KEY'));
const account = web3.Keypair.fromSecretKey(privateKey);
const account2 = web3.Keypair.generate();

(async () => {
  const transaction = new web3.Transaction().add(
    web3.SystemProgram.transfer({
      fromPubkey: account.publicKey,
      toPubkey: account2.publicKey,
      lamports: web3.LAMPORTS_PER_SOL * 0.001,
    }),
  );
  const signature = await web3.sendAndConfirmTransaction(
    connection,
    transaction,
    [account],
  );
})();
I