Getting ETH Wallet/Contract Balance with Ethers.js

·

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


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


Advanced Tips

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


Conclusion