Getting ETH Wallet or Contract Balance with Ethers.js

·

Ethereum has become a cornerstone of decentralized applications, and understanding how to interact with wallets and contracts is essential for any blockchain developer. One of the most common tasks? Retrieving the ETH balance of an address—whether it's a user wallet or a smart contract.

With Ethers.js, one of the most popular JavaScript libraries for Ethereum development, this process becomes both simple and efficient. In this guide, you’ll learn how to use Ethers.js to get the ETH balance of any address, understand the underlying RPC mechanics, and convert values from wei to human-readable ETH.


Understanding How Ethereum Balances Work

Before diving into code, it’s important to understand what an Ethereum balance actually represents.

Every Ethereum address—be it an externally owned account (EOA) or a contract—has a balance measured in wei, the smallest unit of ETH. One ETH equals $10^{18}$ wei. When querying a balance via the Ethereum network, you’ll receive a hexadecimal value in wei, which must be converted for readability.

The core method used behind the scenes is eth_getBalance, part of the Ethereum JSON-RPC API.


What Is eth_getBalance?

The eth_getBalance RPC call retrieves the current balance of a given address in wei. It takes two parameters:

👉 See how easy it is to interact with Ethereum using modern tools.

This method returns a hex-encoded integer representing the balance in wei.

Example Using curl

You can directly query a node using curl like so:

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
}'

A sample response might look like:

{ "jsonrpc": "2.0", "id": 1, "result": "0x21cfd03a8d80000" }

This hex value (0x21cfd03a8d80000) needs to be converted to decimal and then divided by $10^{18}$ to get the balance in ETH.


Simplifying Balance Checks with Ethers.js

While raw RPC calls give you low-level control, using Ethers.js abstracts away much of the complexity. It handles connection management, data formatting, and unit conversion seamlessly.

Why Use Ethers.js?

Let’s walk through how to retrieve and display an ETH balance using Ethers.js.


Step 1: Install and Import Ethers.js

First, install the library via npm:

npm install ethers

Then import the necessary components:

import { providers, utils } from "ethers";
Note: If you're working in a browser environment, you can also load Ethers.js via CDN.

Step 2: Initialize a Provider

A provider connects your app to the Ethereum network. You can use public RPC endpoints like Ankr, Infura, or Alchemy.

const provider = new providers.JsonRpcProvider("https://rpc.ankr.com/eth");

This creates a connection to the Ethereum mainnet using Ankr’s free public RPC service.

👉 Start building on Ethereum with powerful developer tools today.


Step 3: Fetch and Format the Balance

Now comes the core functionality: retrieving the balance and converting it from wei to ETH.

const address = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"; // Vitalik Buterin's address
const weiBalance = await provider.getBalance(address);
const ethBalance = utils.formatEther(weiBalance);

console.log("ETH Balance:", ethBalance);

That’s it! utils.formatEther() automatically divides the wei amount by $10^{18}$ and returns a readable string (e.g., "3256.78").

If you need more precision or want to work with BigNumber operations, Ethers.js provides full support via its BigNumber class.


Handling Edge Cases

Not all addresses have a positive balance—and some may not exist on-chain yet. Here are a few considerations:


Converting Between Units Like a Pro

Ethers.js includes utils.parseEther() and utils.formatEther() for seamless conversions between ETH and wei.

// Convert ETH to wei
const wei = utils.parseEther("1.5"); // Returns BigNumber: 1500000000000000000

// Convert wei to ETH
const eth = utils.formatEther(wei); // Returns string: "1.5"

These utilities support other units as well (gwei, kwei, etc.), making it easy to handle gas fees or microtransactions.


Frequently Asked Questions (FAQ)

Q: Can I check balances on testnets like Sepolia or Goerli?

Yes! Just change your provider URL to point to a testnet endpoint:

const provider = new providers.JsonRpcProvider("https://rpc.sepolia.org");

Ensure the address you're querying has activity on that specific network.


Q: Does getBalance work for ERC-20 tokens?

No. The getBalance method only retrieves ETH (native token) balances. For ERC-20 tokens, you need to call the token contract’s balanceOf(address) function using its ABI.


Q: What if I get an error saying “invalid address”?

Double-check:

Ethers.js will throw an error if the format is invalid.


Q: How often does the balance update?

The balance reflects the latest confirmed block. Since Ethereum blocks are produced roughly every 12 seconds, balances update frequently but only after transaction finality.

For real-time updates, you can listen to block events using provider.on("block", ...) and re-fetch balances as needed.


Q: Is it safe to use public RPC providers like Ankr?

Public RPCs are fine for development and light usage. However, for production applications requiring high uptime and speed, consider using authenticated endpoints from services like Infura, Alchemy, or dedicated nodes.


Q: Can contracts have ETH balances?

Absolutely. Smart contracts can receive and hold ETH. For example, crowdfunding contracts often accumulate funds before releasing them. You can query their balance just like any wallet.


Final Thoughts

Retrieving an Ethereum address’s ETH balance is a foundational skill in blockchain development. With Ethers.js, what could be a complex chain of manual conversions becomes just a few lines of clean, readable code.

Whether you're building a wallet interface, analytics dashboard, or DeFi protocol, knowing how to fetch and format balances accurately is crucial.

As Ethereum continues to evolve—with upgrades like EIP-4844 and proto-danksharding on the horizon—the tools we use must keep pace. Ethers.js remains at the forefront, empowering developers to build efficiently and securely.

👉 Explore next-gen blockchain development tools and accelerate your projects.


Core Keywords:
ethers.js, ETH balance, Ethereum wallet balance, getBalance, contract balance, wei to eth, JsonRpcProvider, blockchain development