How to get the balance of an ERC-20 token

April 12, 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:
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

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.

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

Related articles 54

How to Send a Transaction On Solana Using JavaScript
Apr 13, 2022

Hello reader! Today is an exhilarating day because we are going on an expedition to the Solana Blockchain. Solana is an up-and-coming blockchain seeking to improve upon the current ecosystem's solutions to the complex problem of providing a secure, scalable, decentralized...

Continue reading
How to do a non-custodial transaction with QuickNode
Apr 12, 2022

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

Continue reading
How to connect to Ethereum using .NET (Nethereum)
Apr 12, 2022

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
How to Set Up a Near Project from Scratch
Jan 27, 2022

In this tutorial we will look at how we can setup a basic NEAR project from scratch, installing and configuring dependencies and customizing the project to work well with AssemblyScript.We will first start by initializing our project with a package.json file using...

Continue reading
Como crear y lanzar un ERC-721 (NFT)
Dec 29, 2021

Coleccionables digitales que son compatibles con ERC-721 se han vuelto muy populares desde el lanzamiento de Cryptokitties y han ganado adopción masiva en los últimos meses. Esta guía cubrirá la parte de creación y lanzamiento...

Continue reading
How to connect to Ethereum network using Java / Web3j
Apr 12, 2022

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
How to integrate IPFS with Ethereum
Apr 12, 2022

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
How to Connect to the Ethereum Network using Ruby
Jun 13, 2022

The Ruby programming language has a huge fanbase. Ruby was developed by its creator with an intention to invent a language developers can enjoy learning and using. Ruby has been largely accepted by developers all around the world since its launch, in fact, the biggest...

Continue reading
How to connect to Ethereum network with ethers.js
Apr 12, 2022

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
How to Mint an NFT on Solana
Apr 12, 2022

Updated at: April 10, 2022Welcome to another QuickNode guide on Solana - the up-and-coming blockchain that seeks to solve the scalability issues of Ethereum. We will be walking through step-by-step how to create an NFT on Solana. NFT, short for Non Fungible Token,...

Continue reading
The Web3 Developer Stack
Apr 12, 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 common web developer stacks. Similarly, today we will learn more about the web3...

Continue reading
How to deploy a smart contract with Brownie
Apr 12, 2022

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
How to Get All Tokens Held by a Wallet in Solana
Jun 24, 2022

Hello readers! To kick off Solana Summer and the current whitelist meta, we thought it would be helpful to dig into all of the token accounts you and your users have using the getParsedProgramAccounts method. This tool is convenient for querying different...

Continue reading
Introduction to Scaffold-ETH 🏗
Dec 29, 2021

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 like smart contracts and nodes that allow you to connect to the...

Continue reading
Como crear un NFT en SOLANA
Dec 29, 2021

¡Hola querido lector! Bienvenidos a una nueva guía de Solana.Solana es una blockchain que promete mucho a la hora de intentar resolver los problemas de escalabilidad que podemos apreciar en otras blockchains, como Ethereum por...

Continue reading
How to Get Transaction Logs on Solana
Jun 28, 2022

Ever need to pull all the transactions associated with a Wallet? Want to see all of the mint transactions associated with a Candy Machine? Or maybe see transaction history of an NFT? Solana's getSignaturesForAddress method is a versatile tool that makes...

Continue reading
How to Send an EIP-1559 Transaction
Apr 12, 2022

While Ethereum has been trying to scale, it has encountered some gas price issues. Many layer 2 solutions and sidechains sprang into existence to solve this problem, but Ethereum is the main chain, and at some point, it has to be improved. EIP-1559 was introduced to...

Continue reading
How to Create an Address in Solana using JavaScript
Apr 12, 2022

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
How to create your own DAO with Aragon
Apr 12, 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; it enables various use cases in finance, governance, voting, fundraising, etc....

Continue reading
How to Connect to Terra with JavaScript using Terra.js
Apr 12, 2022

Stablecoins have been bridging the gap between traditional currencies and blockchains. Stablecoins offer stable price tokens pegged by a reserve asset which is often a fiat current like USD, EUR, GBP. The Terra protocol provides a framework to work with stablecoins. This...

Continue reading
How to connect to Ethereum network using Go
Apr 12, 2022

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
How To Fork Ethereum Mainnet with Hardhat
Apr 12, 2022

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
How to connect to Ethereum using PHP
Apr 12, 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 web3.php...

Continue reading
How to use Subspace with QuickNode
Apr 12, 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 websites. JavaScript today has become one of the most used programming languages,...

Continue reading
How to Connect Your Dapp With MetaMask Using Ethers.js
Dec 29, 2021

In our dApp, we will have a simple react user interface that has a material button asking the user to connect to MetaMask. And if they do not have an account, they can create one or log in to their account. They will then view their wallet balance and address displayed on...

Continue reading
How to generate a new Ethereum address in Go
Dec 29, 2021

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
How to generate a new Ethereum address in Python
Dec 29, 2021

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
How to Lazy Mint an NFT on Rarible with Rarepress
Apr 12, 2022

NFTs are great for creators to monetize their artwork and for people to get ownership of an item. But since gas prices are usually high given the highly in-demand space on Ethereum, minting an NFT or an NFT collection can become costly for a creator. Lazy minting solves...

Continue reading