Solana has emerged as one of the most high-performance blockchain platforms, offering fast transaction speeds and low fees—making it a top choice for developers building decentralized applications (dApps). If you're a frontend developer looking to integrate your app with the Solana blockchain, Solana web3.js is the official JavaScript library that enables seamless interaction.
This guide walks you through core functionalities of @solana/web3.js, from setting up your environment to querying balances, transferring SOL, interacting with on-chain programs, and listening to account changes in real time. Whether you're new to Solana or expanding your Web3 development skills, this tutorial provides practical, executable code examples tailored for real-world use.
Getting Started: Install Solana Web3.js
To begin working with Solana in your JavaScript or TypeScript project, install the @solana/web3.js package using npm:
npm install @solana/web3.jsOnce installed, you can import and use the library to connect to Solana clusters like devnet, testnet, or mainnet-beta.
1. Querying SOL Balance
One of the most basic operations in any blockchain application is checking an account’s balance. In Solana, balances are stored in lamports (1 SOL = 1,000,000,000 lamports).
Here's how to connect to the devnet cluster and retrieve a wallet’s SOL balance:
import { Connection, Keypair, clusterApiUrl, LAMPORTS_PER_SOL } from '@solana/web3.js';
// Connect to Solana devnet
let connection = new Connection(clusterApiUrl('devnet'));
// Restore keypair from secret key array
let secretKey = Uint8Array.from([
254, 233, 47, 184, 38, 87, 109, 215, 23, 19, 232, 58, 158, 100, 20, 113,
114, 166, 245, 54, 156, 124, 150, 200, 102, 168, 189, 23, 167, 217, 250,
37, 4, 250, 253, 205, 123, 153, 120, 40, 76, 97, 155, 241, 245, 242,
16, 124, 107, 84, 183, 155, 167, 20, 153, 15, 155, 181, 72, 219, 246,
224, 14, 112
]);
let wallet = Keypair.fromSecretKey(secretKey);
// Fetch balance
let balanceInLamports = await connection.getBalance(wallet.publicKey);
let balanceInSOL = balanceInLamports / LAMPORTS_PER_SOL;
console.log(`Balance: ${balanceInSOL} SOL`);👉 Learn how to securely manage private keys and connect to mainnet
2. Transfer SOL Between Wallets
Sending SOL involves creating a transaction with a transfer instruction via the SystemProgram. Each transaction must be signed and submitted to the network.
Here’s how to send SOL from one address to another:
import { PublicKey, SystemProgram, TransactionMessage, VersionedTransaction } from '@solana/web3.js';
// Recipient address
let recipient = new PublicKey("B2V5kYvGyBGyoYvFJzYJh8ighH2Hn6FdM8xxgqMq9cbK");
// Create transfer instruction
let transferInstruction = SystemProgram.transfer({
fromPubkey: wallet.publicKey,
toPubkey: recipient,
lamports: 10000000 // Equivalent to 0.01 SOL
});
// Get latest blockhash for transaction validity
let { blockhash } = await connection.getLatestBlockhash();
// Build versioned transaction message
let message = new TransactionMessage({
payerKey: wallet.publicKey,
recentBlockhash: blockhash,
instructions: [transferInstruction]
}).compileToV0Message();
// Create and sign transaction
let transaction = new VersionedTransaction(message);
transaction.sign([wallet]);
// Send transaction
let txId = await connection.sendTransaction(transaction);
console.log("Transaction sent:", txId);
// Confirm transaction
await connection.confirmTransaction({
signature: txId,
blockhash,
lastValidBlockHeight: (await connection.getLatestBlockhash()).lastValidBlockHeight
});
console.log("Transaction confirmed!");🔍 Best Practice: Always confirm transactions using confirmTransaction() to ensure they are finalized on-chain.FAQ: Common Questions About Transfers
Q: What is lamport in Solana?
A: A lamport is the smallest unit of SOL (1 SOL = 1 billion lamports), named after computer scientist Leslie Lamport.
Q: Why do I need the latest blockhash?
A: The blockhash ensures your transaction is processed within a specific time window and prevents replay attacks.
Q: Can I send multiple transfers in one transaction?
A: Yes! Just add multiple SystemProgram.transfer instructions to the instructions array before compiling the message.
3. Interact With On-Chain Programs (Smart Contracts)
Solana programs—similar to smart contracts on other blockchains—can be invoked by sending transactions containing custom instructions.
Let’s assume you have a simple "Hello World" program deployed at address: 4eFvSUYCLMwVCx1aWyuCYf3mKo3UPgA4gNVAWViRVhk1
To call this program:
import { PublicKey, TransactionInstruction } from '@solana/web3.js';
// Define account used by the program
let accountMeta = {
pubkey: wallet.publicKey,
isSigner: false,
isWritable: false
};
// Data buffer (e.g., function selector or input)
let data = Buffer.from([0]); // Often used as a method ID
// Create instruction to call program
let programId = new PublicKey("4eFvSUYCLMwVCx1aWyuCYf3mKo3UPgA4gNVAWViRVhk1");
let instruction = new TransactionInstruction({
programId: programId,
keys: [accountMeta],
data: data
});
// Build and send transaction
let message = new TransactionMessage({
payerKey: wallet.publicKey,
recentBlockhash: (await connection.getLatestBlockhash()).blockhash,
instructions: [instruction]
}).compileToV0Message();
let tx = new VersionedTransaction(message);
tx.sign([wallet]);
let txId = await connection.sendTransaction(tx);
console.log("Program interaction successful:", txId);You can view the transaction details on explorers like Solscan by searching for the returned transaction ID.
👉 Explore how leading dApps interact with Solana programs
FAQ: Working With Solana Programs
Q: How do I find a program’s ABI or interface?
A: Unlike Ethereum, Solana doesn’t standardize ABIs. You’ll need IDL files (Interface Definition Language) often generated using Anchor framework.
Q: What does Buffer.from([0]) mean?
A: This typically represents a function selector or instruction discriminator—commonly used in Anchor-based programs to identify which method to call.
Q: Can I read data returned by a program?
A: Direct return values aren't supported. Instead, programs modify account states; you must query those accounts afterward to see results.
4. Listen to Account Changes in Real Time
For dynamic dApps like wallets or trading platforms, real-time updates are crucial. You can listen to changes in any account using WebSocket connections.
Here’s how to set up live account change monitoring:
// Use WebSocket endpoint for real-time updates
let wsConnection = new Connection(
clusterApiUrl('devnet'),
{
wsEndpoint: "wss://docs-demo.solana-devnet.quiknode.pro/"
}
);
// Set up listener
wsConnection.onAccountChange(
wallet.publicKey,
(updatedAccountInfo, context) => {
console.log("Account updated:", {
lamports: updatedAccountInfo.lamports,
owner: updatedAccountInfo.owner.toBase58(),
executable: updatedAccountInfo.executable
});
},
'confirmed' // Listen for confirmed updates only
);⚠️ Note: Make sure your node supports WebSocket subscriptions. Public endpoints may throttle frequent requests.
FAQ: Real-Time Monitoring
Q: What are the different commitment levels?
A: 'processed' (fastest), 'confirmed' (recommended), and 'finalized' (most secure). Use 'confirmed' for most use cases.
Q: Can I stop listening to account changes?
A: Yes—store the subscription ID returned by onAccountChange() and use removeAccountChangeListener() to unsubscribe.
Q: Are there rate limits on WebSocket connections?
A: Yes. Free nodes may limit concurrent connections. For production apps, consider using dedicated RPC providers.
Core Keywords for SEO Optimization
- Solana web3.js
- Solana JavaScript SDK
- Interact with Solana blockchain
- Send SOL using web3.js
- Call Solana program
- Real-time account monitoring
- Solana transaction tutorial
- Frontend blockchain integration
These keywords naturally appear throughout this guide and align with common developer search queries related to Solana development.
Whether you're building a wallet interface, NFT marketplace, or DeFi dashboard, mastering @solana/web3.js is essential. With its robust API and growing ecosystem support, you can create powerful Web3 experiences that respond instantly and securely to on-chain activity.
👉 Start building real-time Solana dApps with advanced tools and APIs