How to Get the Balance of an ERC-20 Token

·

The Ethereum network widely adopts the ERC-20 token standard, which defines a set of rules for smart contracts to function as interoperable tokens. This guide walks you through retrieving the balance of an ERC-20 token from a specific wallet using Node.js and Web3.js.


Prerequisites


Project Setup

1. Initialize Your Project

Create a project folder and navigate into it:

mkdir ERC20Balance && cd ERC20Balance

2. Install Web3.js

Install the Web3.js library via npm:

npm install web3

This generates package.json and installs dependencies in the node_modules folder.

3. Create an Entry File

Name this file index.js—this will house your balance-fetching logic.


Fetching the Token Balance

Step 1: Connect to an Ethereum Node

Use the Web3.js HTTP provider to link to an Ethereum node. Here’s a snippet for WatchData’s API (replace YOUR_API_KEY):

const Web3 = require('web3');
const provider = 'https://ethereum.api.watchdata.io/node/jsonrpc?api_key=YOUR_API_KEY';
const web3 = new Web3(new Web3.providers.HttpProvider(provider));

Step 2: Define the ABI for balanceOf

The ABI (Application Binary Interface) specifies how to interact with the ERC-20 smart contract. Only the balanceOf function is needed:

const minABI = [
  {
    constant: true,
    inputs: [{ name: "_owner", type: "address" }],
    name: "balanceOf",
    outputs: [{ name: "balance", type: "uint256" }],
    type: "function",
  },
];

Step 3: Identify Token and Wallet Addresses

Step 4: Execute the Balance Query

Combine the components to fetch the balance:

const token = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48';
const wallet = '0x2e91728aF3a54aCDCeD7938fE9016aE2cc5948C9';
const contract = new web3.eth.Contract(minABI, token);

const getBalance = async () => {
  const res = await contract.methods.balanceOf(wallet).call();
  const format = web3.utils.fromWei(res); // Converts wei to ETH units
  console.log(format);
};
getBalance();

Run the script:

node index.js

Key Notes


FAQs

1. What is an ERC-20 token?

ERC-20 is a technical standard for Ethereum-based tokens, ensuring compatibility across wallets and exchanges.

2. Why does the balance show in wei?

Ethereum uses wei for precision in smart contracts. Convert it using web3.utils.fromWei().

3. Can I use this for any ERC-20 token?

Yes, as long as you have the token’s contract address and a valid wallet address.

4. How do I get an API key for WatchData?

👉 Sign up here for a free API key.


Conclusion

This guide simplifies retrieving ERC-20 token balances using Web3.js. For advanced use cases, refer to the official Web3.js documentation. Happy coding!