Implementing Blockchain Interaction via ethers.js/web3.js on Website
ethers.js v6 and web3.js v4 — two mature libraries for EVM blockchain interaction. ethers.js is used more often: smaller bundle, better typing, cleaner API. web3.js found in legacy projects and where stack was historically used. Let's cover both.
ethers.js v6: Key Concepts
In ethers v6, imports changed and ESM support appeared without CJS fallback:
import {
BrowserProvider, // for window.ethereum (user wallet)
JsonRpcProvider, // for server RPC access
Contract, // for contract interaction
formatEther, // BigInt → string in ETH
parseEther, // string in ETH → BigInt
formatUnits, // with decimals
parseUnits,
isAddress, // address validation
getAddress, // normalize to checksum
} from 'ethers';
Providers
// Server provider (for SSR, API routes, cron)
const serverProvider = new JsonRpcProvider(process.env.ETH_RPC_URL);
// Client provider via user wallet
async function getWalletProvider() {
if (!window.ethereum) throw new Error('Wallet not found');
const provider = new BrowserProvider(window.ethereum);
const signer = await provider.getSigner();
return { provider, signer };
}
// Fallback: try multiple RPCs
import { FallbackProvider } from 'ethers';
const fallbackProvider = new FallbackProvider([
{ provider: new JsonRpcProvider('https://rpc1.example.com'), priority: 1, weight: 2 },
{ provider: new JsonRpcProvider('https://rpc2.example.com'), priority: 2, weight: 1 },
]);
Working with Contracts via ethers.js
const ERC20_ABI = [
'function balanceOf(address owner) view returns (uint256)',
'function transfer(address to, uint256 amount) returns (bool)',
'function approve(address spender, uint256 amount) returns (bool)',
'function allowance(address owner, address spender) view returns (uint256)',
'event Transfer(address indexed from, address indexed to, uint256 value)',
];
// Read-only contract (server provider)
const tokenRead = new Contract(TOKEN_ADDRESS, ERC20_ABI, serverProvider);
// Contract with signature (user wallet)
const { signer } = await getWalletProvider();
const tokenWrite = new Contract(TOKEN_ADDRESS, ERC20_ABI, signer);
// Reading
const balance = await tokenRead.balanceOf(walletAddress);
console.log(formatUnits(balance, 18));
// Writing
const tx = await tokenWrite.transfer(recipientAddress, parseUnits('10', 18));
const receipt = await tx.wait(); // wait for confirmation
console.log('Confirmed in block', receipt.blockNumber);
Event Subscription
// Listen to Transfer events in real-time
tokenRead.on('Transfer', (from, to, value, event) => {
console.log(`${from} → ${to}: ${formatUnits(value, 18)} tokens`);
console.log('Block:', event.log.blockNumber);
});
// Filtered events — only incoming to address
const filter = tokenRead.filters.Transfer(null, walletAddress);
tokenRead.on(filter, (from, to, value) => {
console.log(`Received ${formatUnits(value, 18)} from ${from}`);
});
// Unsubscribe on unmount
return () => { tokenRead.removeAllListeners(); };
Historical Events
async function getTransferHistory(
contractAddress: string,
walletAddress: string,
fromBlock: number,
) {
const contract = new Contract(contractAddress, ERC20_ABI, serverProvider);
const filter = contract.filters.Transfer(null, walletAddress);
const events = await contract.queryFilter(filter, fromBlock, 'latest');
return events.map(event => ({
from: event.args[0],
to: event.args[1],
amount: formatUnits(event.args[2], 18),
blockNumber: event.blockNumber,
txHash: event.transactionHash,
}));
}
web3.js v4: Basic Patterns
web3.js v4 — complete rewrite with native TypeScript support:
import { Web3 } from 'web3';
const web3 = new Web3(window.ethereum);
// Or with HTTP provider
const web3Server = new Web3(process.env.ETH_RPC_URL);
// Contract via web3.js
const erc20Contract = new web3.eth.Contract(ERC20_ABI, TOKEN_ADDRESS);
// Reading
const balance = await erc20Contract.methods.balanceOf(walletAddress).call();
const formatted = web3.utils.fromWei(balance, 'ether');
// Writing
const accounts = await web3.eth.getAccounts();
const receipt = await erc20Contract.methods
.transfer(recipient, web3.utils.toWei('10', 'ether'))
.send({ from: accounts[0] });
Handling BigInt in UI
ethers v6 returns native BigInt, web3.js v4 too. Problem — JSON.stringify doesn't serialize BigInt:
// Safe serialization for state/API
const replacer = (_: string, value: unknown) =>
typeof value === 'bigint' ? value.toString() : value;
JSON.stringify(data, replacer);
// Or use SuperJSON for Prisma/tRPC stack
import superjson from 'superjson';
superjson.stringify(data); // automatically handles BigInt
Utilities Needed in Every Project
// Shorten address for display
export function shortenAddress(address: string): string {
return `${address.slice(0, 6)}…${address.slice(-4)}`;
}
// Check and normalize address
export function safeGetAddress(input: string): string | null {
try {
return getAddress(input); // throws if invalid
} catch {
return null;
}
}
// Convert block timestamp to date
export async function blockToDate(blockNumber: number): Promise<Date> {
const block = await serverProvider.getBlock(blockNumber);
return new Date(Number(block!.timestamp) * 1000);
}
Timeline: integrating contract data reading and event subscription via ethers.js — 1–2 days. Full interaction layer with multiple contracts, error handling, fallback providers, and historical events — 3–4 days.







