In this section we'll learn how to get the ERC20 balance for an account using ethers.
Check a particular token balance of an EVM address using ethers.js
const ethers = require('ethers');
// Replace these variables with your specific values
const walletAddress = '0xYourWalletAddress';
const tokenAddress = '0xTokenContractAddress';
// Ethereum JSON-RPC endpoint
const provider = new ethers.providers.JsonRpcProvider('https://moonbeam.unitedbloc.com');
// ERC-20 ABI (replace with the actual ABI of the token)
const erc20Abi = [
// Standard ERC-20 functions
'function balanceOf(address) view returns (uint)',
];
// Create a contract instance
const tokenContract = new ethers.Contract(tokenAddress, erc20Abi, provider);
// Get the balance of the specified wallet
async function getBalance() {
try {
const balance = await tokenContract.balanceOf(walletAddress);
console.log(`Balance of ${walletAddress} is: ${ethers.utils.formatUnits(balance)}`);
} catch (error) {
console.error('Error:', error.message);
}
}
// Call the function to get the balance
getBalance();