Ethers.js How to get the ETH & ERC-20 tokens balance of an address at a particular blocknumber

Hello Infura community,

In this short tutorial, we will be looking at how to retrieve the balance of an ETH or ERC-20 token at a particular blockNumber with ethers.js.

Please don’t forget to use your Infura API Key .

const { ethers } = require('ethers');
// Set your Infura endpoint URL and project ID
const infuraUrl = '<YOUR-KEY>';
// Set the Ethereum address you want to check the balance of
const address = '0x1da6e624D82B2AF557E6FC3956515E9fbd6d0C02';
// Set the block number you want to check the balance at
const blockNumber = 5941451; // Example block number
// Set the contract address and ABI of the ERC-20 token you want to check the balance of
const tokenAddress = '0x51fCe89b9f6D4c530698f181167043e1bB4abf89'; // USDC Token contract address
const tokenAbi = ['function balanceOf(address) view returns (uint256)'];
// Create an Ethereum provider using Infura
const provider = new ethers.providers.JsonRpcProvider(infuraUrl);
// Get the balance of the ERC-20 token at the specified block number
const tokenContract = new ethers.Contract(tokenAddress, tokenAbi, provider);
async function getBalances() {
  try {
    // Get ETH balance at a specific block
    const ethBalance = await provider.getBalance(address, blockNumber);
    // Get ERC-20 token balance at a specific block
    const tokenBalance = await tokenContract.balanceOf(address, { blockTag: blockNumber });
    console.log(`ETH balance of ${address} at block number ${blockNumber}: ${ethBalance}`);
    console.log(`Token balance of ${address} at block number ${blockNumber}: ${tokenBalance}`);
  } catch (error) {

Each function from above is having a comment to explain the steps needed to get the script running.

Hope you’ll enjoy it.