June 17, 2021

How to get the balance of an ERC-20 token

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.

Picture of an API node on quicknode.com, with an arrow pointing to the HTTP provider.
 
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:
Etherscan.io with an arrow pointing to the BAT token's contract address

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 you're looking at.

Etherscan.io page with an arrow pointing to a heading that says "Address"

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.

Screenshot of a terminal with the expected output after running the "node index" command.

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 :)
Ready to try QuickNode? Start your 7-day free trial

Related articles 27

Jul 3, 2021 The Web3 Developer Stack

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 common web developer stacks. Similarly, today we will learn more about the web3...

Continue reading
Jun 7, 2021 How to integrate IPFS with Ethereum

It can be costly to store massive files on a blockchain mainnet, and this is where decentralized file storing systems like IPFS can come in handy. Sometimes, NFTs use IPFS as well. In this guide, we’ll cover how we can integrate IPFS with...

Continue reading
Jun 8, 2021 How to generate a new Ethereum address in PHP

PHP is very popular in developing the backend of websites or web applications. PHP has a huge crowd of developers trusting it as their go-to language. In this guide, we will see how we can generate a new Ethereum address in...

Continue reading
Jun 8, 2021 Estimating gas price using pending transactions in Python

To send a transaction on the Ethereum network, you need to pay fees for including the transaction in a block as well as the computation necessary in the transaction; this fee is called gas. The transactions are accepted into the block based on the amount of gas they are...

Continue reading
Jun 8, 2021 How to connect to Ethereum network with ethers.js

When someone thinks of developing a dApp the first tool that comes to their mind is web3.js which is pretty common because of its popularity in the community and wide use cases, dApp development has been consistently growing and there are a lot of developers who want to...

Continue reading
Jun 8, 2021 How to connect to the Ethereum network using Ruby

Ruby has a huge fanbase. Ruby was developed by its creator with an intention to create a language people can have fun using. Ruby has been largely accepted by the developers all around the world since it’s launch, in fact, the biggest tech communities in many cities are...

Continue reading
Jun 8, 2021 How to re-send a transaction with higher gas price using ethers.js

Sometimes, you submit a transaction on Ethereum without enough gas due to network congestion or too many pending transactions offering a higher gas price than you have offered on your transaction. If you have a high priority transaction but low gas, you could end up...

Continue reading
Jun 8, 2021 How to connect to Ethereum network with Web3.js

Libraries and frameworks make the development process a lot easier and faster. When it comes to Ethereum development, Web3.js is the go to library. That's because Web3.js is the official library, from the

Continue reading
Jun 8, 2021 How to generate a new Ethereum address in Ruby

With high usage in web applications and straightforward syntax, Ruby is used by a vast number of people. This guide will cover creating an Ethereum address in Ruby using ruby-eth...

Continue reading
Jun 8, 2021 How to Fork Ethereum Blockchain with Ganache.

Forking and running a local simulated Ethereum environment is essential if you want to work with DeFi or do Ethereum development in general. In this guide, we’ll cover how to fork Ethereum Blockchain with

Continue reading
Jun 8, 2021 How to fetch Ethereum event logs in Ruby

Ethereum log records are very useful to understand and keep track of smart contract events. In this guide, we are going to learn how to fetch ethereum event logs in Ruby using ethereum.rb ruby...

Continue reading
Jun 9, 2021 How to generate a new Ethereum address in Go

Golang is very popular among backend developers for building infrastructures and microservices. Go is a procedural programming language. Developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google, then launched in 2009 as...

Continue reading
Jun 9, 2021 How to generate a new Ethereum address in Python

Python is one of the most versatile programming languages out there with an abundance of use cases; We can build many applications with Python from client-side to back end. In this guide, we will cover creating an Ethereum address in Python using the

Continue reading
Jun 9, 2021 How to generate a new Ethereum address in JavaScript

When it comes to programming, there’s hardly anyone who has not used or heard about JavaScript. JavaScript was initially created for client-side scripting but has become a full-featured Object-Oriented...

Continue reading
Jun 9, 2021 How to connect to Ethereum network using Go

Go helps you make faster scalable backends and this guide will show you how to connect your backend to Ethereum (and make it even faster, more reliable, and globally accessible, all thanks to QuickNode’s global infrastructure). What is...

Continue reading
Jun 9, 2021 How to connect to Ethereum network using Java / Web3j

We can say that Java is one of the most versatile languages out there, and it continues to be relevant in today's time. Java is so popular because of its massive user base and use cases. In this guide/tutorial, we'll learn how to connect to the Ethereum Blockchain network...

Continue reading
Jul 25, 2021 How to Create an Address in Solana using JavaScript

Hello reader! Welcome to QuickNode's first Solana guide. Solana is an up-and-coming blockchain that seeks to solve the scalability issues that Ethereum has been handling. You will walk through step-by-step how to create a Solana address using the @solana/web3.js...

Continue reading
Jun 9, 2021 How to connect to Ethereum using .NET (Nethereum)

Dotnet or .NET is very popular for the development of desktop applications, most Windows desktop applications are built using .NET, and it also contributes largely to web application’s tech stack. In this guide, let’s see how we can connect to Ethereum using .NET and

Continue reading
Jun 15, 2021 How to connect to Ethereum using PHP

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 web3.php...

Continue reading
Jul 15, 2021 How to Setup Local Development Environment for Solidity

The success story of blockchain started with Bitcoin and was given wings by Ethereum. Ethereum was the first blockchain to introduce programmable software to the immutable ledger; these programs that live on the blockchain are called smart contracts. Solidity is the...

Continue reading
Jun 9, 2021 How to use Subspace with QuickNode

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 websites. JavaScript today has become one of the most used programming languages,...

Continue reading
Jun 9, 2021 How to connect to the Ethereum network using Python using Web3.py

You can build Ethereum applications in different programming languages. In this article, we will connect to the Ethereum network using Python.PrerequisiteEthereum Node (We will use QuickNode’s free...

Continue reading
Jul 24, 2021 How to deploy a smart contract with Brownie

Python is one of the most versatile programming languages; from researchers running their test models to developers using it in heavy production environments, it has use cases in every possible technical field. In today's guide, we will learn about Brownie, a Python-based...

Continue reading
Jul 13, 2021 How To Fork Ethereum Mainnet with Hardhat

Forking the chain at an older block of the blockchain is helpful if you want to simulate the blockchain’s state at that block; Hardhat has this functionality built in. In this guide, let’s go through the process of forking the Ethereum Mainnet at an older...

Continue reading
Jun 26, 2021 How to create and deploy a smart contract with Hardhat

Ethereum development environments like Truffle and Hardhat make it easier to work with smart contracts and Ethereum nodes. They provide a set of tools to seamlessly write, test, and deploy...

Continue reading
Jul 2, 2021 How to do a non-custodial transaction with QuickNode

Private keys are one of the most sensitive pieces of data when it comes to cryptography, cryptocurrencies, and blockchain. However, there has always been debate/confusion about choosing between custodial wallets (where the wallet provider has custody of the user’s private...

Continue reading
Jul 2, 2021 How to generate a new Bitcoin address in JavaScript

To do any type of transaction on the Bitcoin blockchain, you’ll need a public key or a Bitcoin address. In this guide, we’ll cover how to generate a new Bitcoin address in JavaScript using CyrptoCoinJS.

Continue reading