Getting ETH Wallet/Contract Balance with Ethers.js

·

2 min read

Getting ETH Wallet/Contract Balance with Ethers.js

Introduction

Fetching the balance of an Ethereum wallet or contract address is a common task in blockchain applications. Ethers.js simplifies this process significantly. This tutorial demonstrates how to use Ethers.js to retrieve the ETH balance for a specific address.

TLDR: Quick Guide

Use the getBalance function from Ethers.js' Provider:

const b = await provider.getBalance("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045");

Understanding eth_getBalance

To obtain an ETH balance, you call the eth_getBalance RPC method. This method returns the balance of a specified account address in wei, the smallest denomination of ETH.

Using curl to Call RPC

Here's how you can use curl to call the eth_getBalance RPC:

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

The result is a hexadecimal value representing the balance in wei.

Converting Wei to ETH

To convert the hexadecimal wei value to ETH, you first convert it to decimal and then divide by (10^{18}) (since 1 ETH = (10^{18}) wei).

Using Ethers.js

Ethers.js streamlines the process of getting the balance and converting it to ETH.

Initialize the Provider

import { providers, utils } from "ethers";

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

Get Balance and Convert to ETH

const wei = await provider.getBalance("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045");
const eth = utils.formatEther(wei);
console.log("ETH balance:", eth);

Conclusion

With Ethers.js, you can easily fetch and correctly format the ETH balance of any given address. This library simplifies interactions with the Ethereum blockchain, making it a valuable tool for blockchain developers.