The @solana/web3.js library provides comprehensive coverage of the Solana JSON RPC API. Below you'll find practical examples and key reference information for working with Solana's Web3 implementation.
Core Components
Establishing Connections
The Connection class enables interaction with Solana's JSON RPC endpoints. Here's how to create and use a connection:
const web3 = require("@solana/web3.js");
// Devnet connection with confirmed commitment level
let connection = new web3.Connection(
web3.clusterApiUrl("devnet"),
"confirmed"
);
// Get current slot information
let slot = await connection.getSlot();
console.log(`Current slot: ${slot}`);
// Retrieve block data
let block = await connection.getBlock(slot);
console.log(block);Key connection methods include:
getSlot()- Gets current chain slotgetBlock()- Retrieves block datagetSlotLeader()- Identifies current validator
๐ Explore more Solana RPC methods
Transaction Processing
Transactions form the basis of Solana operations:
// Basic transaction example
let transaction = new web3.Transaction().add(
web3.SystemProgram.transfer({
fromPubkey: sender.publicKey,
toPubkey: recipient.publicKey,
lamports: 1000 // 0.000001 SOL
})
);
// Send and confirm
await web3.sendAndConfirmTransaction(
connection,
transaction,
[senderKeypair]
);Transactions can include multiple instructions and interact with various programs simultaneously.
Account Management
Keypair Generation
Create cryptographic keypairs for accounts:
// Random keypair generation
let account = web3.Keypair.generate();
// From seed (deterministic)
let seed = Uint8Array.from([...32 bytes...]);
let accountFromSeed = web3.Keypair.fromSeed(seed);
// From existing secret key
let accountFromSecret = Keypair.fromSecretKey(existingSecret);Security Note: Always protect private keys and seeds.
Public Keys
Public keys serve as universal identifiers:
// Creating from base58 string
let pubkey = new web3.PublicKey("BASE58STRING");
// Program address derivation
let programAddress = await web3.PublicKey.createProgramAddress(
[seedBuffer],
programId
);System Programs
Core Functionality
The SystemProgram provides fundamental blockchain operations:
// Account creation
web3.SystemProgram.createAccount({
fromPubkey: funder.publicKey,
newAccountPubkey: newAccount.publicKey,
lamports: initialBalance,
space: accountSize,
programId: owningProgram
});
// Transfer operations
web3.SystemProgram.transfer({
fromPubkey: source.publicKey,
toPubkey: destination.publicKey,
lamports: amount
});Staking Operations
Stake Program
Delegate SOL to validators:
// Create stake account
web3.StakeProgram.createAccount({
fromPubkey: funder.publicKey,
stakePubkey: stakeAccount.publicKey,
authorized: new web3.Authorized(
stakerPubkey,
withdrawerPubkey
),
lamports: stakeAmount
});
// Delegate to validator
web3.StakeProgram.delegate({
stakePubkey: stakeAccount.publicKey,
votePubkey: validatorVoteAccount,
authorizedPubkey: stakerKeypair.publicKey
});๐ Learn advanced staking strategies
Frequently Asked Questions
How do I estimate transaction fees?
Fees vary by network conditions but typically range 5000-10000 lamports (0.000005-0.00001 SOL) per signature.
What's the difference between a stake account and regular account?
Stake accounts are special system accounts that hold delegated SOL and earn staking rewards, while regular accounts hold transferable SOL.
How can I monitor transaction confirmation?
Use connection.confirmTransaction() or monitor via:
connection.onSignature(signature, callback);What are lamports?
1 lamport = 0.000000001 SOL. The smallest fractional unit of SOL used in all API calculations.
How do I handle failed transactions?
Check the error object for details:
- Insufficient funds
- Invalid blockhash
- Program execution errors
- Signature verification failures