Using solana-web3.js to interact with Solana’s stake program to delegate 0.02 SOL.
Overview
@solana/web3.js
) is among one of the most popular ways of connecting to and interacting with the Solana blockchain.Included within the functionality of solana-web3.js is the ability to interact with Solana’s StakeProgram
, enabling programmatic delegation.Today, we’ll be delegating 0.02 SOL with solana-web3.js.Environment setup
@solana/web3.js
, this is what you’ll be using to interact with Solana.bs58
for converting a traditional string private key to a Uint8Array
in the account definition process.Connecting to Solana
connection
, and passed in a Chainstack Solana Global Elastic Node HTTPS and WSS endpoint.To launch a Solana Global Elastic Node, do the following:Connection
constructorImporting a wallet
solanaWeb3.Keypair.generate()
)For importing an existing wallet, you’ll need to leverage the fromSecretKey
function on Keypair
. fromSecretKey
takes a Uint8Array
as a parameter, so you’ll need to convert your string private key with bs58.decode
.Creating the stake account
StakeProgram.createAccount
.You’ll first need to generate a fresh wallet with solanaWeb3.Keypair.generate()
, this will represent the keypair for the stake account.With the keypair generated, you’ll then need to create the transaction instructions; in this case, we’ll call this createStakeAccountInstruction
and pass the following parameters:fromPubkey
, the public key of our funded wallet (the delegator).stakePubkey
, the public key of the stake account we just generated.authorized
, the authorities of the new stake account. We’ll have this set to the funded wallet we previously imported.lamports
, the value of the delegation.createStakeAccountTransaction
, then sign it and push it to the network.Delegating the stake
PublicKey
) of the validator we’d like to delegate to, we can define this in votePubkey
.From there, similar to the stake account creation, we’ll need to build the delegation instructions. We can do this in a variable called delegateInstructions
and pass the following parameters:stakePubkey
, the public key of the previously generated stake account.authorizedPubkey
, the public key of the stake authority.votePubkey
, the public key of the validator you’d like to stake with. We already defined this, so we’ll just pass it directly.