🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Web3 Libraries Comparison

Blockchain DevelopmentđŸŸĸ Free Lesson

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

Web3 Library Evolutionv1Web3.js2015 - Presentv6Ethers.js2016 - Presentv2viem2022 - PresentLegacyLarge bundlePopularTypeScriptModernLightweight

Comparison Matrix

FeatureWeb3.jsEthers.jsviem
Bundle Size~1.2MB~200KB~80KB
TypeScriptOptionalYesYes (native)
Tree ShakingNoPartialYes
Promise-basedMixedYesYes
Provider SupportBroadBroadBroad
React HooksManual@web3-react@wagmi
Gas EstimationManualBuilt-inBuilt-in
ENS SupportYesYesYes
LicenseLGPL-3.0MITMIT

Web3.js

Basic Usage

javascript
// 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

StrengthDescription
Legacy SupportMost tutorials/examples use Web3.js
Broad Provider SupportWorks with most wallet providers
Extensive DocumentationLarge community and resources
Contract AbstractionHigh-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

StrengthDescription
TypeScriptExcellent type inference
DocumentationComprehensive and clear
SecurityBuilt-in wallet management
StandardsFollows 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

StrengthDescription
Bundle SizeSmallest (~80KB)
TypeScriptFirst-class support
Tree ShakingExcellent support
PerformanceOptimized 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

ProviderUse CaseExample
HTTPServer-side, simple readsJsonRpcProvider
WebSocketReal-time updatesWebSocketProvider
BrowserWallet integrationBrowserProvider
FallbackRedundancyFallbackProvider

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

PropertyWeb3.jsEthers.jsviem
Event Nameevent.eventevent.fragment.namelog.eventName
Argsevent.returnValuesevent.argslog.args
Blockevent.blockNumberevent.blockNumberlog.blockNumber
TX Hashevent.transactionHashevent.transactionHashlog.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

BenefitDescriptionGas Savings
Batch RPCSingle HTTP requestNetwork overhead
Single TXMultiple reads in one call~21,000 per TX
AtomicAll succeed or failNo 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

DecisionOption AOption BRecommendation
LibraryWeb3.jsEthers.js/viemUse viem for new projects
Client TypePublicWalletUse both for read/write
ProviderSingleFallbackUse fallback for production
CachingNoneSWR/React QueryAlways cache reads

Interview Questions

  1. 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.

  2. How do you handle provider failover in a production DApp?

    Use fallback providers with quorum settings. For example, Ethers.js FallbackProvider or viem fallback() transport. Configure multiple RPC endpoints (Infura, Alchemy, public) and require agreement from multiple providers before accepting data.

  3. 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

  1. 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.

  2. 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.

  3. 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.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-09-22

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Blockchain Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement