Skip to main content

How to get the balance of an ERC-20 token

Updated on
Feb 28, 2023

How to get the balance of an ERC-20 token

7 min read

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.

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:

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:

//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:

//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.

//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

//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:

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.

Using the QuickNode Token API

Alternatively, you can easily retrieve the balance of an ERC-20 token using the QuickNode Token API. The Token API allows users to easily retrieve aggregated token data such as balances by wallet, token transfers, and token details (such as metadata and decimal places).

See the following ethers.js example:

const ethers = require("ethers");
(async () => {
const provider = new ethers.providers.JsonRpcProvider("QUICKNODE_HTTP_ENDPOINT");
provider.connection.headers = { "x-qn-api-version": 1 };
const heads = await provider.send("qn_getWalletTokenBalance", {
wallet: "0x7108936BE5cFF94D5d949255A35358eb09332C27",
contracts: [
'0x0d8775f648430679a709e98d2b0cb6250d2887ef', //BAT
]
});
const balance = heads.assets.map(bal => bal.amount);
console.log(balance);
})();

Sign up for free access to the Quicknode Token API. You can also check out our Token API documentation page and a sample dApp.

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 :)

Share this guide