Marketplace has launched, further enabling blockchain developers! Learn more

How to get the balance of an ERC-20 token

September 21, 2022

Overview

When a new token is made on the Ethereum network, it usually follows a specification. The most popular of which is the ERC20 specification. To meet this ERC20 standard, one's token must have a multitude of different methods and properties. You could think of it as a standard interface for smart contracts to follow if they are to operate on the Ethereum network as a token.

Today I will walk you through how to obtain a wallet's current balance of a particular ERC-20 token.

Prerequisites:
  • Nodejs install on your system
  • A text editor
  • Terminal/CLI

Setting up a node

You could use any Ethereum client, but for the purpose of this tutorial I'm going to use QuickNode. You can set up a node super easily through here.

First, you will need to create an account.

Secondly, you will need to create a node. Pick a plan that suits whatever needs you may have. For this tutorial I am using a launch plan node.

After filling out your relevant info you will be redirected to your node. You will want the HTTP provider URL for this walkthrough.

A screenshot of the Quicknode endpoint Getting Started page with HTTP link and WSS
 
That's it! You now have a node setup on the Ethereum Mainnet.

Setting up the Project

Now that you've done the legwork to get an ethereum node running, you can now connect to the node via web3js. This is a package on npm that will allow you to easily interface with the Ethereum blockchain.

I am going to set up a folder for our project. Feel free to copy my folder name, or make your own. To do this I am going to open up the command line and run the following commands.

setting up the project

Copy
mkdir ERC20Balance 
cd ERC20Balance

This should create a folder called ERC20Balance and then move the command line into that directory.

Next, you will want to install the web3js package via npm. In order to do this you can run:

setting up the project

Copy
npm install web3

This will create a package.json  and package-lock.json file, along with a node_modules folder. All of this should live in your ERC20Balance folder. 

At this point I believe it would be wise to open up your text editor of choice in this new folder you have created. Once you are done with that you can create a file and name it index.js. This is all the setup you should need to write some JavaScript that will get you the token balance you're looking for!

Getting the ERC20-Token balance of a wallet

Getting the ERC20-Token Balance of a Wallet
With your project all configured, it's time to learn a bit about the Ethereum blockchain. In order to get the ERC-20 Token balance, you will need to do a number of things.
  1. Connect to an Ethereum Node
  2. Write up the ABI for the smart contract that we want to use to interact with the blockchain
  3. Find an ERC20-Token to get the balance of
  4. Find a wallet to get the balance of
  5. Put it all together

I think it would make sense to tackle these in order. 

Connect to an Ethereum node

In the top of your index.js file you will want to import the Web3 library you installed earlier. You can do this like so:

connect to an ethereum node

Copy
//index.js
const Web3 = require("web3");

This allows us to call Web3 methods that are useful for interacting and connecting to the Ethereum blockchain.

To connect to a node we can use the HTTP Provider from QuikNode that we gathered earlier. All in all your code should look as follows:

connect to an ethereum node

Copy
//index.js
const Web3 = require("web3");
const provider = "<YOUR_QUIKNODE_HTTP_PROVIDER_HERE>"
const Web3Client = new Web3(new Web3.providers.HttpProvider(provider));

Replace  <YOUR_QUIKNODE_HTTP_PROVIDER_HERE> with your actual URL

This code will connect you to the QuickNode API that is running the Ethereum client for you. You can now use the Web3Client variable to call any web3js methods that are offered by the library. 

Write up the ABI

ABI is short for Application Binary Interface. It's okay if that doesn't mean too much to you right now.

What an ABI does is outline which function you would like to use from a smart contract that is deployed on the Ethereum Virtual Machine. EVM for short. 

The ERC20 spec is actually a smart contract on Ethereum, and you can see the entire ABI for it here. However, you only need the `balanceOf` method. It seems a bit unnecessary to copy this entire thing over just for the one function. 

Luckily for you, this is completely possible. Out of that huge thing you only need this one piece to use the `balanceOf` method.

write up the abi

Copy
//index.js

// The minimum ABI to get ERC20 Token balance

const minABI = [  
  // balanceOf
  {    
    constant: true,

    inputs: [{ name: "_owner", type: "address" }],

    name: "balanceOf",

    outputs: [{ name: "balance", type: "uint256" }],

    type: "function",
  },

];

Find an ERC20-Token to get the balance of

You will most likely interact with many different ERC20-Tokens over the course of your crypto activities. One such token is the Basic Attention Token. BAT for short. 

BAT will be the token that I showcase, but you could use any token that follows the ERC20 spec.

You will want to head over to Etherscan to find the `contract address`. This is the smart contract that governs how the token functions.

You will want to search for whatever token you are looking for; in my case it's BAT.

You will want to grab the `Contract Address`  , which you can find like so:

Find a wallet address to get the balance of

You can use a similar process from step 3 to find a wallet address.
With the list of Transactions that's underneath all of the token information, I arbitrarily picked one.

From here I clicked on the from address.

When you go to a page on Etherscan it will tell you what address you're looking at.

Put it all together

We now have a connection to an Ethereum Node, an ABI to call, a contract address, and a wallet address. With a few web3js calls we can get the amount of BAT that this address contains.

Your entire index.js file will look as follows

put it all together

Copy
//index.js

const Web3 = require("web3");

const provider =
  "<YOUR_QUIKNODE_HTTP_PROVIDER_HERE>"

const Web3Client = new Web3(new Web3.providers.HttpProvider(provider));

// The minimum ABI required to get the ERC20 Token balance
const minABI = [
  // balanceOf
  {
    constant: true,
    inputs: [{ name: "_owner", type: "address" }],
    name: "balanceOf",
    outputs: [{ name: "balance", type: "uint256" }],
    type: "function",
  },
];
const tokenAddress = "0x0d8775f648430679a709e98d2b0cb6250d2887ef";
const walletAddress = "0x1cf56Fd8e1567f8d663e54050d7e44643aF970Ce";

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

async function getBalance() {
  const result = await contract.methods.balanceOf(walletAddress).call(); // 29803630997051883414242659
  
  const format = Web3Client.utils.fromWei(result); // 29803630.997051883414242659

  console.log(format);
}

getBalance();

All in all about 40 lines of code.

You can see the first half is the code that we already wrote, so I will explain the bottom half to you.

Line 21: This is a string representation of the "Contract Address" from etherscan.

Line 22: This is a string representation of the "Wallet Address" we obtained from etherscan.

Line 24: Invoking the web3 "Contract" method. This takes an ABI and a contract address as arguments.

Since we passed in the "balanceOf" ABI and a contract address- our "contract" constant will use those when making calls to the blockchain.

Line 26: Instantiating an asynchronous function "getBalance"

Line 27:  Declaring the "result" variable that will hold the balance of BAT that this particular walletAddress contains as a string. We obtained the balance using the "balanceOf" method.

However, it will be in the wei format. This is the smallest value that Ethereum supports, so is not indicative of how many whole BAT the wallet contains.

Line 29: Here we use the "fromWei" method in the utilis portion of the web3 library, which takes a number in wei, and converts it to a different format. It defaults to ether, which is the format we wanted in this case.

The last thing to do is run it! The only thing you should need to do at this point is save your index.js file and then in your terminal run:

put it all together

Copy
node index

Make sure that you're still in the correct directory!

It should display in your console the amount of BAT in the correct format.

Conclusion

Having made it to the end, you will have gained some valuable insights. You now know how to navigate etherscan to view token and wallet addresses, what an ABI is, and how to setup an Ethereum node. Then you put all of those things together, and were able to get the amount of BAT that is inside a particular wallet! 

Subscribe to our newsletter for more articles and guides on Ethereum. If you have any feedback, feel free to reach out to us via Twitter. You can always chat with us on our Discord community server, featuring some of the coolest developers you’ll ever meet :)

Related articles 35

How to do a non-custodial transaction with QuickNode
Originally Published On: Jun 19, 2021
Updated On: Sep 9, 2022

Private keys are one of the most... A non-custodial wallet is a... Custodian of Private... At We could use pretty much any... We could use any of the many... Let us create a token transfer... Congratulations on making a...

Continue reading
How to Set Up a Near Project from Scratch
Originally Published On: Jan 27, 2022
Updated On: Sep 9, 2022

In this tutorial we will look at... In this section, we will... In this section, we will look at... In this section, we will look at... When writing smart contracts on... In the last section, we looked... In the last section, we looked... In the last section, we looked... We have finally come to the end...

Continue reading
Estimating gas price using pending transactions in Python
Originally Published On: Feb 20, 2021
Updated On: Sep 9, 2022

To send a transaction on the... Gas is the unit to measure the... Why do we want to estimate gas?... Our first step here would be to... For our purposes today, we could... The first thing we’re going to... Now you know how to estimate gas...

Continue reading
Como crear y lanzar un ERC-721 (NFT)
Originally Published On: Dec 27, 2021
Updated On: Sep 9, 2022

Coleccionables digitales que son... Fungible significa que es lo... ERC es la abreviación para... Ahora que conocemos qué es y... Antes de escribir nuestro... Felicidades por crear tu propio...

Continue reading
How to Access Bitcoin Mempool
Originally Published On: Aug 16, 2021
Updated On: Sep 21, 2022

Bitcoin is the father of... The transactions which are sent... For our purpose today, we need a... We will use Bitcoin RPC methods... Congratulations on mastering the...

Continue reading
How to Mint an NFT on Polygon with Ethers.js
Originally Published On: Mar 28, 2022
Updated On: Sep 9, 2022

This guide demonstrates how to... Ethers.js is a complete Ethereum... As a reminder, the act of... We will deploy our contract on... Time to write the code! Start by... Note, you will need some... That’s it! You have minted an...

Continue reading
How to access Ethereum Mempool
Originally Published On: Oct 15, 2020
Updated On: Sep 15, 2022

On Ethereum, when a transaction... In blockchain terminology, a... For the purpose of this guide,... First, query the Let’s examine how to subscribe... This short guide showed you how...

Continue reading
The Web3 Developer Stack
Originally Published On: Jul 3, 2021
Updated On: Sep 15, 2022

A developer stack is a bag of... If we can imagine web3 as a car... The Chainlink price feed... Head over to the We’ll need a Kovan node to... We’ll now write a short... Congratulations :D You’ve taken...

Continue reading
How to Mint NFTs on the Stacks Blockchain
Originally Published On: Aug 19, 2022
Updated On: Sep 9, 2022

Stacks is an emerging blockchain... The Stacks ecosystem has adopted... Open up a terminal window and... Implementing the SIP-009... This section will demonstrate... The moment you've been waiting... Awesome Work! You’ve learned how...

Continue reading
Introduction to Scaffold-ETH 🏗
Originally Published On: Oct 7, 2021
Updated On: Sep 9, 2022

Developing applications involves... First of all, before getting... Scaffold-ETH comes with a demo... We will set up a QuickNode... Congratulations, and thank you...

Continue reading
How to connect to Ethereum using PHP
Originally Published On: Jun 11, 2021
Updated On: Sep 9, 2022

PHP is a very popular choice... Before installing the web3.php,... We could use pretty much any... Now, make a PHP script file... Congratulations on connecting to...

Continue reading
How to use Subspace with QuickNode
Originally Published On: Sep 8, 2020
Updated On: Sep 9, 2022

In this guide, we'll understand... To install Subspace, we'll need... For our purposes today, we could... Now let's create a short script,... Run the file using the node...

Continue reading
How to Connect Your Dapp With MetaMask Using Ethers.js
Originally Published On: Dec 13, 2021
Updated On: Sep 9, 2022

In our dApp, we will have a... A dApp is an application that... We will need to install the... Ethers.js is a lightweight... With this application, we will... Next, we will create a function... After connecting to MetaMask, we... To handle the wallet address of... This section will show us how to... In this tutorial, we...

Continue reading
How to Lazy Mint an NFT on Rarible with Rarepress
Originally Published On: Feb 23, 2022
Updated On: Sep 9, 2022

NFTs are great for creators to... To mint an NFT, you write data... Lazy Minting is a process in... We will write some JavaScript... Rarepress interacts with the... Now that we have everything in... Congratulations on listing your...

Continue reading