Skip to content

Instantly share code, notes, and snippets.

@sondnm
Created September 19, 2023 16:20
Show Gist options
  • Save sondnm/96434a91fd0d05cbf87a0bd23dea6b45 to your computer and use it in GitHub Desktop.
Save sondnm/96434a91fd0d05cbf87a0bd23dea6b45 to your computer and use it in GitHub Desktop.
How to get an ERC20 token balance of an address at a particular block
const ethers = require('ethers');
const provider = new ethers.providers.JsonRpcProvider('https://eth.llamarpc.com');
const walletAddress = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'; // vitalik.eth
const contractAddress = '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'; // weth
const tokenDecimals = 18;
// ERC20 ABI for balanceOf
const abi = [
'function balanceOf(address account)'
];
const iface = new ethers.utils.Interface(abi);
const data = iface.encodeFunctionData("balanceOf", [walletAddress]);
let blockNumber = 17947911;
// Get balance at a particular block using eth_call
let balance = await provider.call({
to: contractAddress,
data,
}, blockNumber);
balance = ethers.utils.formatUnits(balance, tokenDecimals);
console.log(`Balance of ${walletAddress} at block ${blockNumber}: ${balance} WETH`);
blockNumber = 6938784; // first tx of that wallet
balance = await provider.call({
to: contractAddress,
data,
}, blockNumber);
balance = ethers.utils.formatUnits(balance, tokenDecimals);
console.log(`Balance of ${walletAddress} at block ${blockNumber}: ${balance} WETH`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment