Skip to content

Instantly share code, notes, and snippets.

@ZacharyCouchman
Last active April 1, 2023 04:08
Show Gist options
  • Save ZacharyCouchman/2933b9a31f6cb29ba5f8882024d10286 to your computer and use it in GitHub Desktop.
Save ZacharyCouchman/2933b9a31f6cb29ba5f8882024d10286 to your computer and use it in GitHub Desktop.
Get ERC20 token balance of a wallet
import { ethers } from "ethers";
import { formatUnits } from "ethers/lib/utils.js";
const walletAddress = ""; // add the wallet address you want to check the balance of
const rpcUrl = "https://eth-mainnet.g.alchemy.com/v2/demo;
const imxERC20TokenAddress = "0xF57e7e7C23978C3cAEC3C3548E3D615c346e79fF"; // Immutable X ERC20 token contract address
const contractABI = [
"function name() view returns (string)",
"function symbol() view returns (string)",
"function decimals() view returns (uint8)",
"function balanceOf(address account) view returns (uint256)"
];
async function getERC20Balance(){
const provider = new ethers.providers.JsonRpcProvider(rpcUrl);
const imxTokenContract = new ethers.Contract(imxERC20TokenAddress, contractABI, provider);
const nameOfIMXToken = await imxTokenContract.name();
const symbolOfIMXToken = await imxTokenContract.symbol();
const decimalsOfIMXToken = await imxTokenContract.decimals();
const balance = await imxTokenContract.balanceOf(walletAddress);
console.log(`The name of ERC20 token is ${nameOfIMXToken} and it's symbol is ${symbolOfIMXToken}.`)
console.log(`The currency has ${decimalsOfIMXToken} decimals.`)
console.log(`The IMX token balance of ${walletAddress} is ${formatUnits(balance, decimalsOfIMXToken)}`)
}
getERC20Balance();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment