Introduction
Fetching the balance of an Ethereum wallet or smart contract is a foundational skill for blockchain developers. Ethers.js, a robust JavaScript library, streamlines this process by abstracting complex RPC calls. In this guide, you'll learn how to retrieve ETH balances efficiently using Ethers.js while understanding the underlying mechanics.
Key Takeaways
- Use
provider.getBalance()to fetch balances in wei. - Convert wei to ETH with
ethers.utils.formatEther(). - Ethers.js handles RPC calls like
eth_getBalanceseamlessly.
How ETH Balances Work: The RPC Layer
Ethereum balances are retrieved via the eth_getBalance JSON-RPC method, which returns the value in wei (1 ETH = 10¹⁸ wei).
Raw RPC Call Example (Using curl)
curl --request POST \
--url https://rpc.ankr.com/eth \
--header 'Content-Type: application/json' \
--data '{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [
"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"latest"
],
"id": 1
}'Output: A hex string (e.g., 0x1bc16d674ec80000) representing the wei balance.
Step-by-Step: Fetch Balances with Ethers.js
1. Initialize a Provider
Connect to Ethereum using a JSON-RPC provider:
import { providers, utils } from "ethers";
const provider = new providers.JsonRpcProvider("https://rpc.ankr.com/eth");2. Retrieve and Convert the Balance
const address = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045";
const weiBalance = await provider.getBalance(address);
const ethBalance = utils.formatEther(weiBalance);
console.log(`Balance: ${ethBalance} ETH`);3. Handling Edge Cases
- Invalid addresses: Ethers.js throws an error for malformed inputs.
- Contract addresses: Works identically to wallet addresses.
Advanced Tips
- Batch Requests: Use
provider.send("batch", [...])for multiple balances. - Historical Balances: Query balances at specific block numbers by modifying the
paramsineth_getBalance.
👉 Explore Ethers.js documentation for advanced features like event filtering and gas pricing.
FAQ Section
Q1: Why does getBalance return a value in wei?
A: Ethereum operates in wei for precision. Use formatEther() for human-readable ETH values.
Q2: Can I check balances without a provider?
A: No—you need a connection to an Ethereum node (via Infura, Alchemy, etc.).
Q3: How often should I refresh balances?
A: For real-time apps, poll every 15 seconds or use WebSocket providers for live updates.
Q4: Is Ethers.js better than Web3.js for balances?
A: Yes—Ethers.js has a smaller bundle size and clearer syntax for common tasks.