Send Solana transactions using solana/web3.js
This Recipe shows how you can use the solana/web3.js library to send transactions programmatically.
Overview
Overview
This recipe shows how you can use the solana/web3.js library to send transactions programmatically using a Solana Chainstack node.
Environment setup
Environment setup
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
Get your Chainstack endpoint
Get your Chainstack endpoint
To run this code, you will need a Chainstack account and a Solana Elastic node.
The code
The code
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.
Connection and accounts setup
Connection and accounts setup
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.
The transfer function
The transfer function
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.
Run the code
Run the code
Now you can get your endpoint and paste it into the connection const.
Then you can run it with node YOUR_SCRIPT_NAME
The transaction has been sent successfully if you don’t get any errors in the console.