The Solana Web3.js SDK is a powerful JavaScript library for building decentralized applications across Node.js, web, and React Native platforms. On November 7, 2024, Anza Labs launched the highly anticipated Web3.js 2.0 SDK — a major leap forward in performance, developer experience, and modularity. This upgrade introduces modern JavaScript features, native cryptographic operations, and a tree-shakable architecture that empowers developers to build faster, leaner, and more reliable Solana applications.
Whether you're maintaining legacy scripts or starting a new project, understanding the changes in Web3.js 2.0 is essential. In this guide, we’ll walk through the key improvements, migration considerations, and a practical example of sending a transaction using the latest SDK.
What’s New in Web3.js 2.0?
Web3.js 2.0 brings several groundbreaking enhancements designed to streamline development and improve runtime efficiency.
1. Performance Boost with Native Cryptography
One of the most impactful upgrades is the integration of native Ed25519 cryptographic APIs available in modern environments like Node.js and Safari 17. This enables up to 10x faster key pair generation, transaction signing, and message verification — significantly reducing latency in critical operations.
👉 Discover how high-performance blockchain tools can accelerate your development cycle.
2. Smaller, Tree-Shakable Bundles
The new SDK is fully tree-shakable, meaning your final build only includes the modules you actually use. This reduces bundle size and improves load times — especially crucial for frontend applications. With zero external dependencies, Web3.js 2.0 ensures a lightweight, secure foundation for your dApp.
3. Enhanced Developer Flexibility
Web3.js 2.0 offers greater customization through:
- Custom RPC instances with user-defined methods
- Support for alternative network transports and signing mechanisms
- Extensible primitives for network configuration, confirmation logic, and encoding
Additionally, TypeScript clients for on-chain programs are now hosted under the @solana-program GitHub organization. These are auto-generated using Codama IDL, allowing developers to instantly create type-safe clients for custom Solana programs.
How to Send a Transaction Using Web3.js 2.0
Let’s walk through a complete example: sending lamports from one wallet to another using best practices for reliability and speed.
Prerequisites
- Node.js installed
- A code editor (e.g., VS Code)
- A Solana wallet with testnet/mainnet SOL
- An RPC endpoint (e.g., from Helius or QuickNode)
Installation
Start by initializing a new Node.js project:
npm init -y
mkdir src
touch src/index.jsInstall the required packages:
npm install @solana/web3.js@2
npm install @solana-program/system
npm install @solana-program/compute-budget@solana/web3.js: Core SDK for interacting with Solana@solana-program/system: Provides access to the System Program for transfers@solana-program/compute-budget: Enables setting compute units and priority fees
Define Source and Destination Addresses
In src/index.js, import necessary functions and define your source (signer) and destination addresses:
import {
address,
createKeyPairSignerFromBytes,
getBase58Encoder,
} from '@solana/web3.js';
async function main() {
const destinationAddress = address('public-key-to-send-lamports-to');
const secretKey = "your-private-key-here"; // Keep this secure!
const sourceKeypair = await createKeyPairSignerFromBytes(
getBase58Encoder().encode(secretKey)
);
}
main();Set Up RPC Connection
Create an RPC client and subscription handler for real-time status updates:
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,
});👉 Access fast, reliable RPC endpoints to power your Solana dApp today.
Create Transfer Instruction
Use getTransferSolInstruction to generate a transfer command:
import { getTransferSolInstruction, lamports } from '@solana-program/system';
const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
const instruction = getTransferSolInstruction({
amount: lamports(1),
destination: destinationAddress,
source: sourceKeypair,
});Build Transaction Message
Construct the transaction using a functional pipeline:
import {
pipe,
createTransactionMessage,
setTransactionMessageFeePayer,
setTransactionMessageLifetimeUsingBlockhash,
appendTransactionMessageInstruction,
} from '@solana/web3.js';
const transactionMessage = pipe(
createTransactionMessage({ version: 0 }),
tx => setTransactionMessageFeePayer(sourceKeypair.address, tx),
tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),
tx => appendTransactionMessageInstruction(instruction, tx)
);The pipe function chains transformations, making the code clean and readable.
Sign the Transaction
Sign the message with your keypair:
import { signTransactionMessageWithSigners } from '@solana/web3.js';
const signedTransaction = await signTransactionMessageWithSigners(transactionMessage);Estimate Priority Fee
Optimize execution by fetching a recommended priority fee via Helius API:
import { getBase64EncodedWireTransaction } from '@solana/web3.js';
const serializedTx = 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: serializedTx,
options: { transactionEncoding: 'base64', recommended: true }
}]
})
});
const { result } = await response.json();
const priorityFee = result.priorityFeeEstimate;Optimize Compute Units
Estimate and buffer compute unit usage:
import { getComputeUnitEstimateForTransactionMessageFactory } from '@solana/web3.js';
const getEstimate = getComputeUnitEstimateForTransactionMessageFactory({ rpc });
let computeUnitsEstimate = await getEstimate(transactionMessage);
computeUnitsEstimate = Math.max(1000, Math.ceil(computeUnitsEstimate * 1.1));Rebuild and Sign Final Transaction
Update with priority fee and compute limit instructions:
import {
getSetComputeUnitPriceInstruction,
getSetComputeUnitLimitInstruction,
} from '@solana-program/compute-budget';
const { value: finalBlockhash } = await rpc.getLatestBlockhash().send();
const finalMessage = pipe(
transactionMessage,
tx => setTransactionMessageLifetimeUsingBlockhash(finalBlockhash, tx),
tx => appendTransactionMessageInstructions([
getSetComputeUnitPriceInstruction({ microLamports: priorityFee }),
getSetComputeUnitLimitInstruction({ units: computeUnitsEstimate })
], tx)
);
const finalSignedTx = await signTransactionMessageWithSigners(finalMessage);Send and Confirm Transaction
Submit the transaction with optimized settings:
import { getSignatureFromTransaction, isSolanaError } from '@solana/web3.js';
try {
await sendAndConfirmTransaction(finalSignedTx, {
commitment: 'confirmed',
maxRetries: 0,
skipPreflight: true
});
console.log('Transfer confirmed:', getSignatureFromTransaction(finalSignedTx));
} catch (e) {
if (isSolanaError(e)) {
console.error('Transaction failed:', e);
} else {
throw e;
}
}Setting skipPreflight: true speeds up submission but should only be used when you’re confident the transaction is valid.
Frequently Asked Questions
Q: Is Web3.js 2.0 backward compatible with v1.x?
A: No, it’s not backward compatible. You’ll need to update your codebase or lock dependencies to @solana/web3.js@1 if migration isn’t immediate.
Q: Why is tree-shaking important?
A: Tree-shaking eliminates unused code from your bundle, reducing app size and improving performance — especially critical in browser-based dApps.
Q: How do I handle private keys securely?
A: Never hardcode private keys in source files. Use environment variables or secure key management services in production.
Q: Can I use Web3.js 2.0 in React apps?
A: Yes! It works seamlessly in browser environments and supports modern bundlers like Vite and Webpack.
Q: What are the benefits of native Ed25519 APIs?
A: They offer up to 10x faster crypto operations by leveraging built-in browser and Node.js capabilities instead of JavaScript-based libraries.
Q: Do I need to use Helius for RPC?
A: No — any Solana-compatible RPC provider works. Helius is recommended for its enhanced APIs like priority fee estimation.
Conclusion
Solana’s Web3.js 2.0 SDK marks a transformative step in blockchain development. With native cryptography, modular design, and improved performance, it empowers developers to build scalable, efficient dApps on one of the fastest blockchains today.
By following best practices — such as optimizing compute units, setting priority fees, and leveraging tree-shaking — you can ensure your applications perform reliably even during peak network congestion.
Whether you're building DeFi protocols, NFT marketplaces, or Web3 games, Web3.js 2.0 provides the foundation you need to succeed.
👉 Start building high-performance Solana applications with cutting-edge developer tools.