In this tutorial, you’ll learn how to fetch the balance of ETH or ERC-20 tokens for a given address at a specific historical timestamp using ethers.js, a powerful Ethereum JavaScript library.
Prerequisites
- Infura API Key: Required to interact with the Ethereum blockchain.
- Basic knowledge of JavaScript and Ethereum smart contracts.
Step-by-Step Implementation
1. Setup Ethers.js Provider
Configure the Infura provider to connect to the Ethereum network:
const { ethers } = require('ethers');
const infuraUrl = 'https://mainnet.infura.io/v3/YOUR_INFURA_API_KEY';
const provider = new ethers.providers.JsonRpcProvider(infuraUrl);2. Define Address and Timestamp
Specify the wallet address and Unix timestamp (e.g., 1633046400 for October 1, 2021) for balance retrieval:
const address = '0xYourWalletAddress';
const timestamp = 1633046400; // Example timestamp3. Fetch ETH Balance
Use provider.getBalance() to get the ETH balance at the given timestamp:
const ethBalancePromise = provider.getBalance(address, timestamp);4. Fetch ERC-20 Token Balance
Initialize the token contract with its ABI and call balanceOf():
const tokenAddress = '0xTokenContractAddress';
const tokenAbi = ['function balanceOf(address) view returns (uint256)'];
const tokenContract = new ethers.Contract(tokenAddress, tokenAbi, provider);
const tokenBalancePromise = tokenContract.balanceOf(address, timestamp);5. Execute and Log Balances
Combine promises using Promise.all() and handle results:
Promise.all([ethBalancePromise, tokenBalancePromise])
.then(([ethBalance, tokenBalance]) => {
console.log(`ETH Balance: ${ethers.utils.formatEther(ethBalance)} ETH`);
console.log(`Token Balance: ${ethers.utils.formatUnits(tokenBalance, 18)}`); // Adjust decimals
})
.catch(console.error);Key Concepts
- Historical State Queries: Blockchain nodes like Infura archive past states for timestamp-based queries.
- ERC-20 ABI: The token’s ABI defines its functions (e.g.,
balanceOf).
FAQ
Q1: Can I use Alchemy instead of Infura?
A: Yes! Replace the Infura URL with Alchemy’s RPC endpoint.
👉 Explore Alchemy’s API options
Q2: How do I convert Unix timestamp to a readable date?
A: Use tools like Epoch Converter.
Q3: Why does my token balance show 0?
A: Verify:
- Correct token contract address.
- The address held tokens at the specified timestamp.
👉 Check token holders on Etherscan
Best Practices
- Error Handling: Add try-catch blocks for robust code.
- Gas Fees: Historical queries don’t incur gas costs.
By following this guide, you can audit wallets, track historical holdings, or analyze transactions programmatically.