How to Get the Balance of an ERC-20 Token Using Web3.js

·

Interacting with blockchain networks requires precise tools and accurate data handling—especially when retrieving token balances. In this guide, you’ll learn how to get the balance of an ERC-20 token using Web3.js, a widely used JavaScript library for Ethereum development. While newer alternatives like Ethers.js and Viem are now recommended for new projects, understanding Web3.js remains valuable for maintaining legacy systems or exploring foundational blockchain interactions.

We’ll walk through setting up your environment, connecting to an Ethereum node via QuickNode, crafting a minimal ABI, and fetching a wallet’s token balance—specifically focusing on the Basic Attention Token (BAT) as an example.


Understanding ERC-20 Tokens and Balance Retrieval

ERC-20 is the most widely adopted token standard on the Ethereum network. It defines a common set of rules that all fungible tokens must follow, enabling seamless integration across wallets, exchanges, and dApps. One of its core functions is balanceOf, which allows anyone to query how many tokens a given wallet address holds.

To retrieve this balance programmatically, you need:

👉 Discover how blockchain APIs simplify real-time token data access.


Prerequisites for Development

Before diving into code, ensure your development environment meets these requirements:

These tools form the foundation for any Ethereum-based application. Web3.js acts as your bridge between JavaScript and the Ethereum Virtual Machine (EVM), allowing you to send transactions, read smart contract data, and more.


Step 1: Set Up Your Ethereum Endpoint with QuickNode

To interact with Ethereum, you need reliable node access. While public nodes exist, they often suffer from rate limits and latency. Using a dedicated provider like QuickNode ensures fast, stable connections.

  1. Sign up for a free QuickNode account.
  2. Create a new endpoint for Ethereum Mainnet.
  3. Copy your HTTP Provider URL—you’ll use it in your script.

This endpoint serves as your gateway to the Ethereum blockchain, enabling real-time queries without running your own node.


Step 2: Initialize Your Project

Start by creating a new project directory and installing Web3.js:

mkdir ERC20Balance
cd ERC20Balance
npm init -y
npm install web3

This sets up a package.json, installs Web3.js, and prepares your workspace. Next, create an index.js file where all logic will reside.


Step 3: Connect to Ethereum Using Web3.js

At the top of your index.js, import Web3 and connect to your endpoint:

const { Web3 } = require("web3");
const endpointUrl = "YOUR_QUICKNODE_HTTP_ENDPOINT";
const httpProvider = new Web3.providers.HttpProvider(endpointUrl);
const web3Client = new Web3(httpProvider);

Replace YOUR_QUICKNODE_HTTP_ENDPOINT with your actual URL. Now, web3Client is ready to make calls to the Ethereum network.


Step 4: Define the Minimal ABI

An Application Binary Interface (ABI) tells Web3.js how to interact with a smart contract. For balance checks, you only need the balanceOf function:

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

This compact ABI reduces overhead while still enabling interaction with any ERC-20 contract.


Step 5: Specify Token and Wallet Addresses

Choose an ERC-20 token—here, we use BAT with contract address:

0x0d8775f648430679a709e98d2b0cb6250d2887ef

Then pick a wallet holding BAT. You can find active holders on Etherscan under the Holders tab. For this example:

Wallet Address: 0xfd821d8cea64feacb6ec86d979e37bc64c64a00b

Store both in constants:

const tokenAddress = "0x0d8775f648430679a709e98d2b0cb6250d2887ef";
const walletAddress = "0xfd821d8cea64feacb6ec86d979e37bc64c64a00b";

Step 6: Fetch and Display the Token Balance

Create a contract instance and call balanceOf:

const contract = new web3Client.eth.Contract(minABI, tokenAddress);

async function getBalance() {
  const result = await contract.methods.balanceOf(walletAddress).call();
  const resultInEther = web3Client.utils.fromWei(result, "ether");

  console.log(`Balance in wei: ${result}`);
  console.log(`Balance in ether: ${resultInEther}`);
}

getBalance();

Run the script:

node index.js

Output:

Balance in wei: 176775759650192465574646501
Balance in ether: 176775759.650192465574646501
Note: Wei is Ethereum’s smallest unit—1 ETH equals 10^18 wei.

👉 Learn how advanced blockchain tools streamline dApp development workflows.


Alternative: Use QuickNode’s Token API

For faster, aggregated results, consider QuickNode’s Token API, which retrieves all ERC-20 balances for a wallet in one call:

const { Web3 } = require("web3");
const endpointUrl = "YOUR_QUICKNODE_HTTP_ENDPOINT";
const httpProvider = new Web3.providers.HttpProvider(endpointUrl);
const web3Client = new Web3(httpProvider);

(async () => {
  const response = await web3Client.requestManager.send({
    method: "qn_getWalletTokenBalance",
    params: [{ wallet: "0xfd821d8cea64feacb6ec86d979e37bc64c64a00b" }],
  });
  console.log(response);
})();

This method returns metadata, decimals, and balances across multiple tokens—ideal for dashboards or analytics platforms.

⚠️ Requires the Token and NFT API v2 add-on enabled on your endpoint.

Core Keywords for SEO

This guide targets developers seeking practical blockchain solutions. Key terms include:

These keywords naturally appear throughout the content, enhancing search visibility without compromising readability.


Frequently Asked Questions

Q: Is Web3.js still supported?
A: Web3.js is no longer actively maintained. For new projects, consider using Ethers.js or Viem, which offer better performance and active community support.

Q: Can I use this method for other ERC-20 tokens?
A: Yes! Simply replace the contract address with any valid ERC-20 token on Ethereum.

Q: Why do I need an ABI?
A: The ABI defines how your code interacts with a smart contract. Without it, Web3.js wouldn’t know which functions are available or how to encode calls.

Q: What if the balance returns zero?
A: Double-check the wallet address and ensure it actually holds the token. Also verify the contract address is correct and matches the network (Mainnet vs. testnet).

Q: Can I run this in a browser?
A: Yes, but you’ll need to bundle the code using tools like Webpack or Vite. For frontend apps, consider using Ethers.js due to its smaller bundle size.

Q: Are there rate limits on QuickNode endpoints?
A: Free-tier endpoints have usage limits. Paid plans offer higher throughput and access to advanced features like log streaming and private nodes.


By following this guide, you’ve learned how to retrieve ERC-20 token balances using Web3.js, set up a reliable Ethereum connection, and explored alternative API-driven approaches. Whether building a wallet interface or analyzing holdings, these skills are essential for modern blockchain development.

👉 Access powerful blockchain tools to accelerate your next project.