In ethers.js v6, you read a contract by creating a provider (JsonRpcProvider for a node URL, BrowserProvider for a wallet like MetaMask), then a Contract from the address, an ABI and that provider, and calling its view functions with await: results come back as native bigint. To send a transaction, attach a signer (a Wallet or await browserProvider.getSigner()), call the state-changing function, and await tx.wait() for the receipt. Use parseUnits and formatUnits for token amounts, fn.staticCall() to simulate before sending, and isError() to handle failures.
This guide walks through each step on Ethereum with an ERC-20 token, then lists what changed from v5, since half the examples online still use the old API.
Installing and connecting
npm install ethers
Everything is exported from the package root in v6; there's no ethers.utils or ethers.providers namespace any more.
import { ethers } from "ethers";
// Read-only connection to a node (Infura, Alchemy, your own node, a local Anvil...)
const provider = new ethers.JsonRpcProvider(process.env.RPC_URL);
const network = await provider.getNetwork();
console.log(network.chainId); // a bigint, e.g. 1n for mainnet, 11155111n for Sepolia
console.log(await provider.getBlockNumber());
The main building blocks:
| Class | What it is | Typical use |
|---|---|---|
JsonRpcProvider | Connection to a node over HTTP | Scripts, backends, reads |
WebSocketProvider | Connection over WebSocket | Event subscriptions |
BrowserProvider | Wraps an injected wallet (window.ethereum) | dApp frontends |
Wallet | A private key plus a provider | Server-side signing, scripts |
JsonRpcSigner | The user's account in a browser wallet | Frontend transactions |
Contract | ABI plus address plus a runner (provider or signer) | Calling functions, reading events |
How do I read from a contract?
You need the contract's address and an ABI fragment for the functions you'll call. ethers accepts human-readable ABI strings, so you don't need the full JSON:
import { ethers } from "ethers";
const provider = new ethers.JsonRpcProvider(process.env.RPC_URL);
const erc20Abi = [
"function name() view returns (string)",
"function symbol() view returns (string)",
"function decimals() view returns (uint8)",
"function balanceOf(address owner) view returns (uint256)",
"function allowance(address owner, address spender) view returns (uint256)",
"function transfer(address to, uint256 amount) returns (bool)",
"function approve(address spender, uint256 amount) returns (bool)",
"event Transfer(address indexed from, address indexed to, uint256 value)",
"error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed)",
];
// USDC on Ethereum mainnet
const usdc = new ethers.Contract("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", erc20Abi, provider);
const holder = "0x0000000000000000000000000000000000000001";
const [symbol, decimals, raw] = await Promise.all([
usdc.symbol(),
usdc.decimals(),
usdc.balanceOf(holder),
]);
console.log(raw); // e.g. 1234500000n (a bigint)
console.log(`${ethers.formatUnits(raw, decimals)} ${symbol}`); // "1234.5 USDC"
Three things to notice:
- Reads are free. A
viewcall is aneth_callto the node; nothing is signed or mined. - Numbers are
bigint.uint256values come back as1234500000n. Don't convert them toNumberfor maths: values above 2^53 lose precision. UseformatUnitsonly for display. - Decimals vary. USDC uses 6, most tokens use 18. Always read
decimals()rather than assuming.
To read state at a past block, pass an overrides object as the last argument: await usdc.balanceOf(holder, { blockTag: 20_000_000 }). That needs an archive node for old blocks.
How do I send a transaction?
Writes need a signer, which pays gas and signs. In a script or backend, use a Wallet with a private key from the environment (never hard-code it):
import { ethers } from "ethers";
const provider = new ethers.JsonRpcProvider(process.env.RPC_URL);
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!, provider);
const token = new ethers.Contract(process.env.TOKEN_ADDRESS!, erc20Abi, wallet);
const decimals = await token.decimals();
const amount = ethers.parseUnits("25.5", decimals); // 25.5 tokens -> bigint
const tx = await token.transfer("0xRecipientAddress", amount);
console.log("sent:", tx.hash); // broadcast, not yet mined
const receipt = await tx.wait(); // waits for 1 confirmation by default
console.log("mined in block", receipt!.blockNumber, "status", receipt!.status); // status 1 = success
tx.wait() resolves when the transaction is mined, and throws if it reverted on chain. Pass a number, tx.wait(3), to wait for more confirmations; how many confirmations to wait for depends on the value at stake.
You can override transaction fields with a final argument:
const tx = await token.transfer(to, amount, {
gasLimit: 80_000n,
maxFeePerGas: ethers.parseUnits("30", "gwei"),
maxPriorityFeePerGas: ethers.parseUnits("1", "gwei"),
});
Usually you shouldn't: ethers estimates gas and fills EIP-1559 fees from provider.getFeeData(). Override when you have a reason, such as replacing a stuck transaction, covered in speeding up or cancelling a pending transaction.
Sending plain ETH doesn't need a contract:
const tx = await wallet.sendTransaction({ to: "0xRecipientAddress", value: ethers.parseEther("0.01") });
await tx.wait();
In the browser
In a dApp, the user's wallet signs. getSigner() is async in v6 and triggers the wallet's connection prompt:
const browserProvider = new ethers.BrowserProvider(window.ethereum);
const signer = await browserProvider.getSigner();
const { chainId } = await browserProvider.getNetwork();
if (chainId !== 11155111n) throw new Error("Please switch your wallet to Sepolia");
const token = new ethers.Contract(TOKEN_ADDRESS, erc20Abi, signer);
const tx = await token.approve(SPENDER, ethers.parseUnits("100", 18));
await tx.wait();
Approve the amount you need rather than an unlimited allowance; why ERC-20 approvals are risky explains the trade-offs.
How do I simulate a call before sending it?
Every contract method has helpers attached to it:
// Run the call without sending it; returns the function's return value or throws the revert
const ok: boolean = await token.transfer.staticCall(to, amount);
// Gas estimate (a bigint); also throws if the call would revert
const gas = await token.transfer.estimateGas(to, amount);
// Build the unsigned transaction without sending it
const unsigned = await token.transfer.populateTransaction(to, amount);
staticCall is the cheapest way to catch a failing transaction before the user pays gas for it.
How do I handle errors?
ethers v6 errors carry a code. Check them with isError, which also narrows the type in TypeScript:
import { isError } from "ethers";
try {
const tx = await token.transfer(to, amount);
await tx.wait();
} catch (e) {
if (isError(e, "ACTION_REJECTED")) {
console.log("user rejected the request in their wallet");
} else if (isError(e, "INSUFFICIENT_FUNDS")) {
console.log("not enough ETH to pay for gas");
} else if (isError(e, "CALL_EXCEPTION")) {
// reason is set for require("...") strings; revert is set for decoded custom errors
console.log("reverted:", e.reason ?? e.revert?.name, e.revert?.args);
} else {
throw e;
}
}
Custom errors only decode if they're in your ABI, which is why the ABI above includes ERC20InsufficientBalance from OpenZeppelin's ERC-20. If you only see raw revert data, see how to find the real reason behind "execution reverted".
How do I read events?
Query past events with filters built from the ABI, or subscribe to new ones:
const me = await wallet.getAddress();
// Past transfers to me in the last 10,000 blocks
const latest = await provider.getBlockNumber();
const events = await token.queryFilter(token.filters.Transfer(null, me), latest - 10_000, latest);
for (const ev of events) {
if ("args" in ev) console.log(ev.args.from, ethers.formatUnits(ev.args.value, decimals));
}
// Live subscription
token.on("Transfer", (from, to, value, event) => {
console.log(`${from} -> ${to}: ${value}`, event.log.transactionHash);
});
Many RPC providers cap the block range per eth_getLogs request, so page through large ranges in chunks.
What changed from ethers v5?
| v5 | v6 |
|---|---|
BigNumber, .add(), .mul() | Native bigint, +, * |
ethers.utils.parseEther(...) | ethers.parseEther(...) |
new ethers.providers.Web3Provider(window.ethereum) | new ethers.BrowserProvider(window.ethereum) |
new ethers.providers.JsonRpcProvider(url) | new ethers.JsonRpcProvider(url) |
provider.getSigner() (sync) | await provider.getSigner() |
contract.address | contract.target or await contract.getAddress() |
contract.callStatic.transfer(...) | contract.transfer.staticCall(...) |
contract.estimateGas.transfer(...) | contract.transfer.estimateGas(...) |
ethers.constants.AddressZero, MaxUint256 | ethers.ZeroAddress, ethers.MaxUint256 |
utils.formatBytes32String | encodeBytes32String |
utils.solidityKeccak256 | solidityPackedKeccak256 |
utils.arrayify | getBytes |
Checklist
- Use
JsonRpcProviderfor scripts andBrowserProviderplusawait getSigner()in dApps. - Keep amounts as
bigint; convert withparseUnitsandformatUnitsusing the token's realdecimals(). - Check
chainIdbefore sending from a browser wallet. - Simulate with
staticCallbefore sending, and include custom errors in your ABI. await tx.wait()and checkreceipt.status; wait for more confirmations for high-value actions.- Handle
ACTION_REJECTED,INSUFFICIENT_FUNDSandCALL_EXCEPTIONexplicitly. - Keep private keys in environment variables or a key manager, never in frontend code.
- When one key sends many transactions concurrently, manage nonces deliberately (see fixing "nonce too low" errors).
JSON.stringifycan't serialisebigint; convert with.toString()before logging or returning JSON.
Get the weekly commit
New blockchain deep dives every week.