Writing to Network
In the previous section, you learned how to read data from the Solana network. Now explore how to write data to it. Writing to the Solana network involves sending transactions that contain one or more instructions.
Programs (smart contracts) process these instructions according to their business logic for each respective instruction. When you submit a transaction, the Solana runtime executes each instruction in sequence and atomically (meaning either all instructions succeed or the entire transaction fails).
In this section, you'll see two basic examples:
- Transferring SOL between accounts
- Creating a new token
These examples show how to build and send transactions to invoke Solana programs. For more details, refer to the Transactions and Instructions and Fees on Solana pages.
Transfer SOL
In this example, you'll learn how to transfer SOL between two accounts.
On Solana, each account has a specific program as its owner. Only the program owner can deduct an account's SOL (lamport) balance.
The System Program is the owner for all "wallet" accounts. To transfer SOL, you must invoke the System Program's transfer instruction.
import {LAMPORTS_PER_SOL,SystemProgram,Transaction,sendAndConfirmTransaction,Keypair,Connection} from "@solana/web3.js";const connection = new Connection("http://localhost:8899", "confirmed");const sender = new Keypair();const receiver = new Keypair();const signature = await connection.requestAirdrop(sender.publicKey,LAMPORTS_PER_SOL);await connection.confirmTransaction(signature, "confirmed");const transferInstruction = SystemProgram.transfer({fromPubkey: sender.publicKey,toPubkey: receiver.publicKey,lamports: 0.01 * LAMPORTS_PER_SOL});const transaction = new Transaction().add(transferInstruction);const transactionSignature = await sendAndConfirmTransaction(connection,transaction,[sender]);console.log("Transaction Signature:", `${transactionSignature}`);
You must enable the "Enable Custom URL Param" setting on Solana Explorer.
If not enabled, links will default to localhost:8899 instead of the Mirror.ad RPC URL.
These are the steps for building transactions to interact with any program on Solana.
Create the instruction you want to invoke.
const transferInstruction = SystemProgram.transfer({fromPubkey: sender.publicKey,toPubkey: receiver.publicKey,lamports: 0.01 * LAMPORTS_PER_SOL});
Add the instruction to a transaction:
const transaction = new Transaction().add(transferInstruction);
Sign and Send the Transaction:
const transactionSignature = await sendAndConfirmTransaction(connection,transaction,[sender] // signer keypair);
Create a Token
In this example, you'll learn how to create a new token on Solana using the Token Extensions Program. This requires two instructions:
- Invoke the System Program to create a new account.
- Invoke the Token Extensions Program to initialize that account as a Mint.
import {Connection,Keypair,SystemProgram,Transaction,sendAndConfirmTransaction,LAMPORTS_PER_SOL} from "@solana/web3.js";import {MINT_SIZE,TOKEN_2022_PROGRAM_ID,createInitializeMint2Instruction,getMinimumBalanceForRentExemptMint} from "@solana/spl-token";const connection = new Connection("http://localhost:8899", "confirmed");const wallet = new Keypair();// Fund the wallet with SOLconst signature = await connection.requestAirdrop(wallet.publicKey,LAMPORTS_PER_SOL);await connection.confirmTransaction(signature, "confirmed");// Generate keypair to use as address of mint accountconst mint = new Keypair();// Calculate lamports required for rent exemptionconst rentExemptionLamports =await getMinimumBalanceForRentExemptMint(connection);// Instruction to create new account with space for new mint accountconst createAccountInstruction = SystemProgram.createAccount({fromPubkey: wallet.publicKey,newAccountPubkey: mint.publicKey,space: MINT_SIZE,lamports: rentExemptionLamports,programId: TOKEN_2022_PROGRAM_ID});// Instruction to initialize mint accountconst initializeMintInstruction = createInitializeMint2Instruction(mint.publicKey,2, // decimalswallet.publicKey, // mint authoritywallet.publicKey, // freeze authorityTOKEN_2022_PROGRAM_ID);// Build transaction with instructions to create new account and initialize mint accountconst transaction = new Transaction().add(createAccountInstruction,initializeMintInstruction);const transactionSignature = await sendAndConfirmTransaction(connection,transaction,[wallet, // payermint // mint address keypair]);console.log("Mint Account:", `${mint.publicKey}`);console.log("Transaction Signature:", `${transactionSignature}`);
You must enable the "Enable Custom URL Param" setting on Solana Explorer.
If not enabled, links will default to localhost:8899 instead of the Mirror.ad RPC URL.
Here's a step-by-step breakdown of what the example does:
Create a connection and fund the wallet
const connection = new Connection("http://localhost:8899", "confirmed");const wallet = new Keypair();const signature = await connection.requestAirdrop(wallet.publicKey,LAMPORTS_PER_SOL);await connection.confirmTransaction(signature, "confirmed");
Generate a keypair for the Mint account
const mint = new Keypair();
Calculate the minimum lamports for rent exemption
const rentExemptionLamports =await getMinimumBalanceForRentExemptMint(connection);
Create an instruction to create a new account
- Allocate the required space for storing mint data
- Transfer lamports from the wallet to fund the new account
- Assign ownership of the account to the Token Extensions
program (
TOKEN_2022_PROGRAM_ID
)
const createAccountInstruction = SystemProgram.createAccount({fromPubkey: wallet.publicKey,newAccountPubkey: mint.publicKey,space: MINT_SIZE,lamports: rentExemptionLamports,programId: TOKEN_2022_PROGRAM_ID});
Create an instruction to initialize the Mint account
const initializeMintInstruction = createInitializeMint2Instruction(mint.publicKey,2, // decimalswallet.publicKey, // mint authoritywallet.publicKey, // freeze authorityTOKEN_2022_PROGRAM_ID);
Add both instructions to a transaction
const transaction = new Transaction().add(createAccountInstruction,initializeMintInstruction);
Send and confirm the transaction with both required signers
const transactionSignature = await sendAndConfirmTransaction(connection,transaction,[wallet, mint]);
Print the Mint account and transaction signature
console.log("Mint Account:", `${mint.publicKey}`);console.log("Transaction Signature:", `${transactionSignature}`);
By combining both instructions into a single transaction, you ensure that the account creation and initialization happen atomically. Either both instructions succeed, or neither does. This approach is common when building more complex Solana transactions, as it guarantees that all instructions execute together.
Is this page helpful?