Created
September 19, 2023 16:20
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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