QuickNode Raises $60M Series B!
Read the Letter from our CEO.

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 37

How to Access Bitcoin Mempool
Published: Aug 16, 2021
Updated: Sep 21, 2022

Bitcoin is the father of blockchain technology. With Bitcoin started a new era of blockchain and decentralization. Bitcoin enabled everyone to make the peer-to-peer transactions they enjoy...

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

On Ethereum, when a transaction is sent, before being added to a block, it resides in what is called a Mempool. To receive information about this transaction, the Mempool must be queried. This...

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

A developer stack is a bag of technologies a developer possesses. For example, MEAN (MongoDB, Express.js, AngularJS/Angular, and Node.js) and MERN (MongoDB, Express.js, React, and Node.js) are...

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

Developing applications involves juggling several moving pieces like front-ends, back-ends, and databases. But developing a decentralized application on a blockchain adds a few more elements...

Continue reading
How to create your own DAO with Aragon
Published: Aug 8, 2021
Updated: Sep 9, 2022

Blockchain provides us with the power of decentralization. Decentralization means the transfer of power to users/members rather than having a single centralized authority governing everything;...

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

PHP is a very popular choice among developers and has a vast community due to its long presence in web development. In this guide, we’ll cover how to connect to Ethereum with PHP using the

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

In this guide, we'll understand a bit about reactive development and how to use Subspace with QuickNode.JavaScript is the programming language behind most of the internet apps and...

Continue reading