Web3 Libraries Comparison
Overview
Web3 libraries provide JavaScript interfaces for interacting with Ethereum. Understanding their differences helps choose the right tool for your project.
âšī¸
The ecosystem has evolved from Web3.js â Ethers.js â viem. Each generation improves on developer experience, TypeScript support, and bundle size.
Library Evolution
Comparison Matrix
| Feature | Web3.js | Ethers.js | viem |
|---|---|---|---|
| Bundle Size | ~1.2MB | ~200KB | ~80KB |
| TypeScript | Optional | Yes | Yes (native) |
| Tree Shaking | No | Partial | Yes |
| Promise-based | Mixed | Yes | Yes |
| Provider Support | Broad | Broad | Broad |
| React Hooks | Manual | @web3-react | @wagmi |
| Gas Estimation | Manual | Built-in | Built-in |
| ENS Support | Yes | Yes | Yes |
| License | LGPL-3.0 | MIT | MIT |
Web3.js
Basic Usage
// Web3.js
const Web3 = require('web3');
// Initialize provider
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_KEY');
// Get account balance
const getBalance = async (address) => {
const balance = await web3.eth.getBalance(address);
return web3.utils.fromWei(balance, 'ether');
};
// Contract interaction
const contract = new web3.eth.Contract(ABI, CONTRACT_ADDRESS);
// Read function
const totalSupply = await contract.methods.totalSupply().call();
// Write function
const tx = await contract.methods.transfer(toAddress, amount)
.send({ from: userAddress });
// Event listening
contract.events.Transfer({}, (error, event) => {
console.log(event);
});
Web3.js Strengths
| Strength | Description |
|---|---|
| Legacy Support | Most tutorials/examples use Web3.js |
| Broad Provider Support | Works with most wallet providers |
| Extensive Documentation | Large community and resources |
| Contract Abstraction | High-level contract interaction |
Ethers.js
Basic Usage
// Ethers.js v6
import { ethers } from 'ethers';
// Initialize provider
const provider = new ethers.JsonRpcProvider('https://mainnet.infura.io/v3/YOUR_KEY');
// Get account balance
const getBalance = async (address: string) => {
const balance = await provider.getBalance(address);
return ethers.formatEther(balance);
};
// Contract interaction
const contract = new ethers.Contract(CONTRACT_ADDRESS, ABI, provider);
// Read function
const totalSupply = await contract.totalSupply();
// Write function (with signer)
const signer = await provider.getSigner();
const contractWithSigner = contract.connect(signer);
const tx = await contractWithSigner.transfer(toAddress, amount);
await tx.wait(); // Wait for confirmation
// Event listening
contract.on('Transfer', (from, to, value, event) => {
console.log({ from, to, value });
});
Ethers.js Strengths
| Strength | Description |
|---|---|
| TypeScript | Excellent type inference |
| Documentation | Comprehensive and clear |
| Security | Built-in wallet management |
| Standards | Follows Ethereum standards |
viem
Basic Usage
// viem
import { createPublicClient, http, parseEther, formatEther } from 'viem';
import { mainnet } from 'viem/chains';
// Initialize client
const client = createPublicClient({
chain: mainnet,
transport: http('https://mainnet.infura.io/v3/YOUR_KEY'),
});
// Get account balance
const getBalance = async (address: `0x${string}`) => {
const balance = await client.getBalance({ address });
return formatEther(balance);
};
// Contract interaction (read)
const totalSupply = await client.readContract({
address: CONTRACT_ADDRESS,
abi: ABI,
functionName: 'totalSupply',
});
// Contract interaction (write - with wallet client)
import { createWalletClient, custom } from 'viem';
const walletClient = createWalletClient({
chain: mainnet,
transport: custom(window.ethereum),
});
const [account] = await walletClient.getAddresses();
const hash = await walletClient.writeContract({
account,
address: CONTRACT_ADDRESS,
abi: ABI,
functionName: 'transfer',
args: [toAddress, parseEther('1.0')],
});
// Event listening
const unwatch = client.watchContractEvent({
address: CONTRACT_ADDRESS,
abi: ABI,
eventName: 'Transfer',
onLogs: (logs) => console.log(logs),
});
viem Strengths
| Strength | Description |
|---|---|
| Bundle Size | Smallest (~80KB) |
| TypeScript | First-class support |
| Tree Shaking | Excellent support |
| Performance | Optimized for speed |
Provider Management
Provider Comparison
// Web3.js
const web3 = new Web3(window.ethereum);
// Ethers.js
const provider = new ethers.BrowserProvider(window.ethereum);
// viem
const client = createWalletClient({
chain: mainnet,
transport: custom(window.ethereum),
});
Provider Types
| Provider | Use Case | Example |
|---|---|---|
| HTTP | Server-side, simple reads | JsonRpcProvider |
| WebSocket | Real-time updates | WebSocketProvider |
| Browser | Wallet integration | BrowserProvider |
| Fallback | Redundancy | FallbackProvider |
Fallback Provider
// Ethers.js fallback
const provider = new ethers.FallbackProvider([
new ethers.JsonRpcProvider('https://mainnet.infura.io/v3/KEY1'),
new ethers.JsonRpcProvider('https://mainnet.alchemy.io/v2/KEY2'),
new ethers.JsonRpcProvider('https://rpc.ankr.com/eth'),
], {
quorum: 2, // Require 2/3 agreement
});
// viem fallback
const client = createPublicClient({
chain: mainnet,
transport: fallback([
http('https://mainnet.infura.io/v3/KEY1'),
http('https://mainnet.alchemy.io/v2/KEY2'),
http('https://rpc.ankr.com/eth'),
]),
});
Contract Interaction
ABI Encoding Comparison
// Web3.js
const encodedData = web3.eth.abi.encodeFunctionCall(ABI, [toAddress, amount]);
// Ethers.js
const iface = new ethers.Interface(ABI);
const encodedData = iface.encodeFunctionData('transfer', [toAddress, amount]);
// viem
import { encodeFunctionData } from 'viem';
const encodedData = encodeFunctionData({
abi: ABI,
functionName: 'transfer',
args: [toAddress, amount],
});
Decode Transaction Data
// Ethers.js
const iface = new ethers.Interface(ABI);
const decoded = iface.decodeFunctionData('transfer', txData);
// viem
import { decodeFunctionData } from 'viem';
const decoded = decodeFunctionData({
abi: ABI,
data: txData,
});
Event Parsing
Event Handling Comparison
// Web3.js
const events = await contract.getPastEvents('Transfer', {
fromBlock: 0,
toBlock: 'latest',
});
// Ethers.js
const filter = contract.filters.Transfer(fromAddress);
const events = await contract.queryFilter(filter, 0, 'latest');
// viem
import { getLogs } from 'viem';
const logs = await client.getLogs({
address: CONTRACT_ADDRESS,
event: {
type: 'event',
name: 'Transfer',
inputs: [
{ name: 'from', type: 'address', indexed: true },
{ name: 'to', type: 'address', indexed: true },
{ name: 'value', type: 'uint256', indexed: false },
],
},
fromBlock: 0n,
toBlock: 'latest',
});
Event Log Structure
| Property | Web3.js | Ethers.js | viem |
|---|---|---|---|
| Event Name | event.event | event.fragment.name | log.eventName |
| Args | event.returnValues | event.args | log.args |
| Block | event.blockNumber | event.blockNumber | log.blockNumber |
| TX Hash | event.transactionHash | event.transactionHash | log.transactionHash |
Multicall
Batch Requests
// Ethers.js multicall
const contract = new ethers.Contract(CONTRACT_ADDRESS, ABI, provider);
const [totalSupply, name, symbol] = await Promise.all([
contract.totalSupply(),
contract.name(),
contract.symbol(),
]);
// viem multicall
import { multicall } from 'viem';
const results = await multicall(client, {
contracts: [
{
address: CONTRACT_ADDRESS,
abi: ABI,
functionName: 'totalSupply',
},
{
address: CONTRACT_ADDRESS,
abi: ABI,
functionName: 'name',
},
{
address: CONTRACT_ADDRESS,
abi: ABI,
functionName: 'symbol',
},
],
});
Multicall Benefits
| Benefit | Description | Gas Savings |
|---|---|---|
| Batch RPC | Single HTTP request | Network overhead |
| Single TX | Multiple reads in one call | ~21,000 per TX |
| Atomic | All succeed or fail | No partial state |
Gas Optimization
Gas Estimation
// Ethers.js
const gasEstimate = await contract.transfer.estimateGas(toAddress, amount);
// viem
const gasEstimate = await client.estimateContractGas({
account: userAddress,
address: CONTRACT_ADDRESS,
abi: ABI,
functionName: 'transfer',
args: [toAddress, amount],
});
Gas Settings
// Ethers.js
const tx = await contract.transfer(toAddress, amount, {
gasLimit: 100000,
gasPrice: ethers.parseUnits('20', 'gwei'),
});
// viem
const hash = await walletClient.writeContract({
account,
address: CONTRACT_ADDRESS,
abi: ABI,
functionName: 'transfer',
args: [toAddress, amount],
gas: 100000n,
maxFeePerGas: parseGwei('20'),
maxPriorityFeePerGas: parseGwei('1'),
});
Real-World Example: DApp Integration
Complete DApp Setup
// lib/ethereum.ts
import { createPublicClient, createWalletClient, http, custom } from 'viem';
import { mainnet, polygon } from 'viem/chains';
// Public client for reads
export const publicClient = createPublicClient({
chain: mainnet,
transport: http(process.env.NEXT_PUBLIC_RPC_URL),
});
// Wallet client for writes
export const getWalletClient = async () => {
if (!window.ethereum) throw new Error('No wallet');
return createWalletClient({
chain: mainnet,
transport: custom(window.ethereum),
});
};
// Contract configuration
export const contractConfig = {
address: process.env.NEXT_PUBLIC_CONTRACT_ADDRESS as `0x${string}`,
abi: [
{
name: 'transfer',
type: 'function',
stateMutability: 'nonpayable',
inputs: [
{ name: 'to', type: 'address' },
{ name: 'amount', type: 'uint256' },
],
outputs: [{ name: '', type: 'bool' }],
},
],
} as const;
React Hook
// hooks/useContract.ts
import { useState } from 'react';
import { parseEther } from 'viem';
import { publicClient, getWalletClient, contractConfig } from '@/lib/ethereum';
export function useContract() {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const read = async (functionName: string, args?: any[]) => {
try {
const data = await publicClient.readContract({
...contractConfig,
functionName: functionName as any,
args: args as any,
});
return data;
} catch (err) {
setError(err as Error);
throw err;
}
};
const write = async (functionName: string, args: any[], value?: bigint) => {
setLoading(true);
setError(null);
try {
const walletClient = await getWalletClient();
const [account] = await walletClient.getAddresses();
const hash = await walletClient.writeContract({
account,
...contractConfig,
functionName: functionName as any,
args: args as any,
value,
});
const receipt = await publicClient.waitForTransactionReceipt({ hash });
return receipt;
} catch (err) {
setError(err as Error);
throw err;
} finally {
setLoading(false);
}
};
return { read, write, loading, error };
}
Trade-offs
| Decision | Option A | Option B | Recommendation |
|---|---|---|---|
| Library | Web3.js | Ethers.js/viem | Use viem for new projects |
| Client Type | Public | Wallet | Use both for read/write |
| Provider | Single | Fallback | Use fallback for production |
| Caching | None | SWR/React Query | Always cache reads |
Interview Questions
-
Compare Web3.js, Ethers.js, and viem in terms of bundle size, TypeScript support, and performance.
Web3.js is largest (~1.2MB) with optional TypeScript. Ethers.js is medium (~200KB) with good TypeScript. viem is smallest (~80KB) with native TypeScript and best tree-shaking. For new projects, viem offers best performance.
-
How do you handle provider failover in a production DApp?
Use fallback providers with quorum settings. For example, Ethers.js
FallbackProvideror viemfallback()transport. Configure multiple RPC endpoints (Infura, Alchemy, public) and require agreement from multiple providers before accepting data. -
Explain how multicall works and why it's important for DApp performance.
Multicall batches multiple read calls into a single RPC request or transaction. This reduces network overhead, lowers latency, and can save gas. Libraries like viem have built-in multicall support that automatically batches contract reads.
Quiz Questions
-
Which library has the smallest bundle size?
- A) Web3.js
- B) Ethers.js
- C) viem
- D) All same
Answer: C - viem is optimized for size (~80KB) with tree-shaking support.
-
What is the primary advantage of using FallbackProvider?
- A) Better performance
- B) Provider redundancy
- C) Lower cost
- D) Better security
Answer: B - FallbackProvider provides redundancy by querying multiple providers and requiring agreement.
-
How do you properly wait for transaction confirmation in viem?
- A) tx.wait()
- B) client.waitForTransactionReceipt()
- C) client.getTransaction()
- D) walletClient.confirm()
Answer: B - Use
publicClient.waitForTransactionReceipt()to wait for confirmation.