The release of Solana’s Web3.js 2.0 SDK marks a major leap forward for developers building on the Solana blockchain. With performance enhancements, reduced bundle sizes, and improved flexibility, this update streamlines development workflows and unlocks new possibilities for scalable, efficient dApps. Whether you're building on Node.js, web, or React Native, Web3.js 2.0 brings modern JavaScript standards to the forefront—making it faster, lighter, and more developer-friendly than ever.
This guide walks you through the key improvements in the new SDK, migration tips from v1.x, and a practical walkthrough of sending optimized transactions using best practices. We’ll also cover core concepts like blockhash usage, priority fees, and compute unit management—all essential for high-success transaction delivery.
👉 Discover powerful tools to enhance your Solana development workflow today.
What's New in Web3.js 2.0?
The Web3.js 2.0 SDK introduces several foundational upgrades that significantly improve developer experience and application performance.
1. Performance Improvements
Cryptographic operations such as keypair generation, transaction signing, and message verification are now up to 10x faster by leveraging native cryptographic APIs available in modern environments like Node.js and current browsers. This means quicker wallet interactions, faster batch processing, and reduced latency in real-time applications.
2. Smaller and More Efficient Applications
Web3.js 2.0 fully supports tree-shaking, allowing you to import only the modules you use—drastically reducing final bundle size. Unlike previous versions, the new SDK has zero external dependencies, ensuring leaner builds and improved security.
3. Enhanced Flexibility
Developers can now create highly customized solutions by:
- Defining custom RPC instances with tailored methods
- Using alternative network transports or signature providers
- Composing custom primitives for networking, confirmation strategies, and encoding
Additionally, the new TypeScript clients are hosted under the @solana-program GitHub organization and are auto-generated via Codama, enabling rapid client generation for custom on-chain programs.
Should You Migrate to Web3.js v2?
As of 2025:
- ✅ New projects: If you're starting fresh with standard Solana programs (e.g., System Program, Token Program), migrate to v2 now.
- ⚠️ Anchor-based apps: Anchor does not yet support Web3.js v2. Consider waiting for an official update—or explore Codama-generated clients for your programs if you need early adoption.
Migrating from Web3.js v1 to v2
If you've used the older version, here are the most important breaking changes:
Keypairs and Signers
Replace Keypair with KeyPairSigner. Use generateKeyPairSigner() instead of Keypair.generate(). The private key is now accessed via .privateKey, not .secretKey.
import { generateKeyPairSigner } from "@solana/web3.js";
const signer = await generateKeyPairSigner();
console.log(signer.privateKey); // Access private keyAddresses Instead of PublicKeys
You no longer work directly with PublicKey. Instead, use address—a type-safe string representation.
import { address } from "@solana/web3.js";
const addr = address("your-public-key-string");BigInt for Amounts
All token and lamport values must be BigInt. Append n to numbers:
lamports(1_000_000n); // Correct
// lamports(1_000_000); // Error in v2Factory Pattern for Reusable Functions
Many utilities now use factory functions to promote reusability and configurability.
For example:
const sendTx = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions });
// Now use sendTx() anywhereThis pattern reduces redundant configuration and improves consistency across your app.
How to Send a Transaction Using Web3.js 2.0
Let’s build a simple Node.js app that sends lamports with optimized settings for speed and reliability.
Prerequisites
- Node.js installed
- A code editor (VS Code recommended)
Step 1: Initialize Project
Create a new project directory and initialize it:
npm init -y
mkdir src
touch src/index.tsInstall required dependencies:
npm install @solana/web3.js@2 @solana-program/system @solana-program/compute-budget esrun@solana/web3.js: Core SDK@solana-program/system: For SOL transfers@solana-program/compute-budget: For setting compute units and priority feesesrun: Run TypeScript directly without bundling
Step 2: Define Source and Destination
In src/index.ts, define your signer and recipient:
import { address, createKeyPairSignerFromBytes, getBase58Encoder } from "@solana/web3.js";
const destinationAddress = address("recipient-public-key-here");
const secretKey = "your-private-key-here";
const sourceKeypair = await createKeyPairSignerFromBytes(getBase58Encoder().encode(secretKey));👉 Learn how top teams optimize transaction success rates on Solana.
Step 3: Configure RPC Connection
Use a reliable RPC provider like Helius. Set up HTTP and WebSocket connections:
import {
createSolanaRpc,
createSolanaRpcSubscriptions,
sendAndConfirmTransactionFactory,
} from "@solana/web3.js";
const rpcUrl = "https://mainnet.helius-rpc.com/?api-key=your-key";
const wssUrl = "wss://mainnet.helius-rpc.com/?api-key=your-key";
const rpc = createSolanaRpc(rpcUrl);
const rpcSubscriptions = createSolanaRpcSubscriptions(wssUrl);
const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions });Step 4: Create Transfer Instruction
Fetch the latest blockhash and create a transfer instruction:
import { getTransferSolInstruction, lamports } from "@solana/web3.js";
const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
const instruction = getTransferSolInstruction({
amount: lamports(1n),
destination: destinationAddress,
source: sourceKeypair,
});Step 5: Build Transaction Message
Construct a versioned transaction message using functional composition:
import {
pipe,
createTransactionMessage,
setTransactionMessageFeePayer,
setTransactionMessageLifetimeUsingBlockhash,
appendTransactionMessageInstruction,
} from "@solana/web3.js";
const transactionMessage = pipe(
createTransactionMessage({ version: 0 }),
(msg) => setTransactionMessageFeePayer(sourceKeypair.address, msg),
(msg) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, msg),
(msg) => appendTransactionMessageInstruction(instruction, msg)
);The pipe function applies transformations sequentially—clean, readable, and functional.
Step 6: Sign the Transaction
Sign using your keypair signer:
import { signTransactionMessageWithSigners } from "@solana/web3.js";
const signedTransaction = await signTransactionMessageWithSigners(transactionMessage);Step 7: Estimate Priority Fee
Use Helius Priority Fee API to optimize transaction inclusion:
import { getBase64EncodedWireTransaction } from "@solana/web3.js";
const serialized = getBase64EncodedWireTransaction(signedTransaction);
const response = await fetch(rpcUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
jsonrpc: "2.0",
id: "priority-fee",
method: "getPriorityFeeEstimate",
params: [{
transaction: serialized,
options: { transactionEncoding: "base64", priorityLevel: "High" }
}]
})
});
const { result } = await response.json();
const priorityFee = result.priorityFeeEstimate;Step 8: Optimize Compute Units
Estimate required compute units and add a 10% buffer:
import { getComputeUnitEstimateForTransactionMessageFactory } from "@solana/web3.js";
const getEstimate = getComputeUnitEstimateForTransactionMessageFactory({ rpc });
let computeUnits = await getEstimate(transactionMessage);
computeUnits = computeUnits < 1000 ? 1000 : Math.ceil(computeUnits * 1.1);Step 9: Rebuild and Resign Transaction
Add instructions for compute limit and price:
import {
appendTransactionMessageInstructions,
} from "@solana/web3.js";
import {
getSetComputeUnitLimitInstruction,
getSetComputeUnitPriceInstruction
} from "@solana-program/compute-budget";
const { value: freshBlockhash } = await rpc.getLatestBlockhash().send();
const finalMessage = appendTransactionMessageInstructions(
[
getSetComputeUnitPriceInstruction({ microLamports: priorityFee }),
getSetComputeUnitLimitInstruction({ units: computeUnits })
],
transactionMessage
);
setTransactionMessageLifetimeUsingBlockhash(freshBlockhash, finalMessage);
const finalSignedTx = await signTransactionMessageWithSigners(finalMessage);Step 10: Send and Confirm
Submit with optimized settings:
await sendAndConfirmTransaction(finalSignedTx, {
commitment: "confirmed",
maxRetries: 0n,
skipPreflight: true,
});
console.log("Transaction confirmed:", getSignatureFromTransaction(finalSignedTx));Set skipPreflight: true only when confident in transaction validity—this bypasses simulation checks for speed.
Frequently Asked Questions (FAQ)
Q: Is Web3.js 2.0 backward compatible with v1?
A: No. Web3.js 2.0 contains breaking changes in types, naming conventions, and architecture. You must update your codebase accordingly.
Q: Why use factory functions instead of direct methods?
A: Factory functions promote reusability and allow one-time configuration of RPCs, subscriptions, and options—ideal for production apps.
Q: How do I handle private keys securely?
A: Never hardcode private keys. Use environment variables or secure key management systems (e.g., Hashicorp Vault).
Q: Can I use Web3.js 2.0 with Anchor programs?
A: Not directly. Anchor currently uses v1. However, you can generate compatible clients using Codama.
Q: What is tree-shaking and why does it matter?
A: Tree-shaking removes unused code during bundling. With full support in v2, your final app bundles are smaller and faster.
Q: How can I improve transaction success during congestion?
A: Use dynamic priority fees (via Helius API), optimize compute units, set skipPreflight, and use confirmed commitments.
👉 Maximize your dApp’s performance with advanced Solana tooling.
Conclusion
Solana’s Web3.js 2.0 SDK represents a major evolution in blockchain development tools—delivering faster execution, smaller bundles, and greater flexibility. By embracing modern JavaScript standards like native BigInt and cryptographic APIs, it sets a new benchmark for developer efficiency.
Whether you're building a DeFi protocol, NFT marketplace, or wallet service, adopting Web3.js 2.0 ensures your application is future-ready, performant, and scalable.
For full code examples, visit the GitHub repository.
Core Keywords: Solana Web3.js SDK, Web3.js 2.0 migration, Solana transaction optimization, Solana TypeScript client, priority fee Solana, compute unit management, blockchain development tools