Solana Web3.js Guide: Interact with the Blockchain Using JavaScript

·

Solana has emerged as one of the most high-performance blockchains, offering fast transaction speeds and low fees. For developers building decentralized applications (dApps), Solana web3.js is the essential JavaScript library that enables frontend applications to interact directly with the Solana network. Whether you're checking balances, sending SOL, calling smart contracts, or listening to account changes in real time, web3.js provides all the tools you need.

This guide walks you through practical use cases of Solana web3.js with clear, executable code examples—perfect for developers getting started or expanding their blockchain skillset.

👉 Get started building on Solana with powerful developer tools and resources.

Setting Up Solana Web3.js

Before diving into interactions, install the @solana/web3.js package via npm:

npm install @solana/web3.js

Once installed, import and initialize a connection to the Solana cluster. Most developers start with the devnet for testing:

import { Connection, clusterApiUrl } from '@solana/web3.js';

const connection = new Connection(clusterApiUrl('devnet'));

This connection object will be used across all operations to query data and submit transactions.

Core Keywords


1. Check SOL Balance

One of the most basic actions in any blockchain application is retrieving an account's balance. On Solana, balances are stored in lamports (1 SOL = 1,000,000,000 lamports).

Here’s how to check a wallet's SOL balance:

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
]);

const pay = Keypair.fromSecretKey(secretKey);
const balanceInLamports = await connection.getBalance(pay.publicKey);
console.log(`Balance: ${balanceInLamports / LAMPORTS_PER_SOL} SOL`);
🔍 Tip: Always use LAMPORTS_PER_SOL constant for accurate conversion.

2. Transfer SOL Between Wallets

Transferring SOL involves creating a transaction with a transfer instruction using SystemProgram.transfer.

Each transaction must include:

Here’s how to send SOL:

import { PublicKey, SystemProgram } from '@solana/web3.js';

const toPubkey = new PublicKey("B2V5kYvGyBGyoYvFJzYJh8ighH2Hn6FdM8xxgqMq9cbK");

const instruction = SystemProgram.transfer({
  fromPubkey: pay.publicKey,
  toPubkey: toPubkey,
  lamports: 10_000_000 // ~0.01 SOL
});

const { blockhash } = await connection.getLatestBlockhash();
const messageV0 = new TransactionMessage({
  payerKey: pay.publicKey,
  recentBlockhash: blockhash,
  instructions: [instruction]
}).compileToV0Message();

const transaction = new VersionedTransaction(messageV0);
transaction.sign([pay]);

const txId = await connection.sendTransaction(transaction);
console.log("Transaction sent:", txId);

After sending, you can view the transaction on explorers like Solscan.

👉 Explore live transaction data and testnet tools for your dApp.


3. Interact with On-Chain Programs (Smart Contracts)

Solana programs—similar to Ethereum smart contracts—are written in Rust or C and deployed to specific addresses. You can invoke them by sending custom instructions.

Suppose we have a simple "Hello World" program deployed at:

4eFvSUYCLMwVCx1aWyuCYf3mKo3UPgA4gNVAWViRVhk1

To interact with it:

const programId = new PublicKey("4eFvSUYCLMwVCx1aWyuCYf3mKo3UPgA4gNVAWViRVhk1");
const key1 = { pubkey: pay.publicKey, isSigner: false, isWritable: false };
const data = Buffer.from([0]); // First function call (index 0)

const instruction = new TransactionInstruction({
  programId: programId,
  keys: [key1],
  data: data
});

const { blockhash } = await connection.getLatestBlockhash();
const messageV0 = new TransactionMessage({
  payerKey: pay.publicKey,
  recentBlockhash: blockhash,
  instructions: [instruction]
}).compileToV0Message();

const tx = new VersionedTransaction(messageV0);
tx.sign([pay]);

const txId = await connection.sendTransaction(tx);
console.log("Program interaction successful:", txId);

This pattern powers everything from NFT mints to DeFi protocols.


4. Listen to Account Changes in Real Time

For dynamic dApps like wallets or trading platforms, real-time updates are crucial. Use onAccountChange() to monitor balance or state changes.

You’ll need a WebSocket endpoint for live subscriptions:

const wsEndpoint = "wss://docs-demo.solana-devnet.quiknode.pro/";
const connection = new Connection(
  clusterApiUrl('devnet'),
  { wsEndpoint }
);

connection.onAccountChange(
  pay.publicKey,
  (updatedAccountInfo) => {
    console.log("Account updated:", {
      lamports: updatedAccountInfo.lamports,
      owner: updatedAccountInfo.owner.toBase58()
    });
  },
  'confirmed'
);
⚠️ Note: Ensure your node supports WebSocket connections. Free devnet endpoints may have rate limits.

Frequently Asked Questions (FAQ)

Q: What is Solana web3.js used for?

A: Solana web3.js is a JavaScript library that allows developers to connect frontend apps to the Solana blockchain. It supports querying data, sending transactions, interacting with programs, and listening to real-time events.

Q: How do I convert lamports to SOL?

A: Divide the lamport value by LAMPORTS_PER_SOL, which equals 1_000_000_000. For example: balance / LAMPORTS_PER_SOL.

Q: Can I use web3.js in a browser environment?

A: Yes. While originally designed for Node.js, modern bundlers (like Vite or Webpack) allow web3.js to run in browsers. Just ensure secure handling of private keys—never expose them client-side in production.

Q: Why use VersionedTransaction instead of Transaction?

A: VersionedTransaction supports v0 messages and future upgrades like address lookup tables. The legacy Transaction class doesn’t support these features and is being phased out.

Q: Is it safe to hardcode secret keys in code?

A: No. Hardcoding keys is extremely risky and should only be done in isolated test environments. In production, use secure key management solutions like wallets (e.g., Phantom) or environment variables.

Q: Where can I find more Solana development tools?

A: Many platforms offer SDKs, APIs, and testnet access for building dApps efficiently.

👉 Access advanced blockchain tools and APIs for seamless development.


By mastering Solana web3.js, you unlock the ability to build responsive, interactive dApps on one of the fastest-growing blockchain ecosystems. From checking balances to real-time event monitoring, this library forms the backbone of modern Solana development.

Whether you're building a wallet interface, DeFi dashboard, or NFT marketplace, integrating these patterns will set a strong foundation for your project.