How to Get the Balance of an ERC-20 Token Using Web3.js | QuickNode (2024)

9 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. A token must have a multitude of different methods and properties to meet the ERC20 standard. 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, we will walk you through how to obtain a wallet's current balance of a particular ERC-20 token.

What You Will Need


Dependencies Used in this Guide

DependencyVersion
node.js18.16.0
web3.js4.1.1

Set Up Your QuickNode Ethereum Endpoint

To interact with Ethereum, you'll need an API endpoint to connect with the network. You're welcome to use public nodes or deploy and manage your own infrastructure; however, if you'd like faster response times, you can leave the heavy lifting to us. Sign up for a free account here.

After creating your account, click the Create an Endpoint button. Then, select the chain of your choice. We use Ethereum Mainnet in this guide.

Then, copy your HTTP Provider URL; you'll use it in the following sections to access the Ethereum blockchain.

How to Get the Balance of an ERC-20 Token Using Web3.js | QuickNode (1)

That's it! You now have an endpoint on the Ethereum Mainnet.

Setting up the Project

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

Run the following code in your terminal (i.e., Terminal, Windows PowerShell) to set up the project. Our project folder's name will be ERC20Balance, but you can modify the name as you wish.

mkdir ERC20Balance
cd ERC20Balance

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

Next, install the Web3.js package via npm.

npm init --yes
npm install web3

caution

The code snippets throughout this guide will follow the new 4.1.1 web3.js version, but if you are using the older, still valid version 1.10, refer to Entire Code with Web3.js version 1.10. The steps will be mostly equivalent.

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.

Create index.js file by running the command.

Then, open up your favorite code editor in the ERC20Balance folder.

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 a script that will get you the token balance you're looking for!

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 Endpoint
  2. Write up the ABI (Application Binary Interface) for the smart contract that you 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

Let's start.

Connect to an Ethereum Endpoint

At 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 QuickNode that we gathered earlier. All in all, your code should look as follows:

//index.js
const { Web3 } = require("web3");
const endpointUrl = "QUICKNODE_HTTP_ENDPOINT"
const httpProvider = new Web3.providers.HttpProvider(endpointUrl);
const web3Client = new Web3(httpProvider)

Replace QUICKNODE_HTTP_ENDPOINT with your QuickNode HTTP Provider 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 web3.js methods that are offered by the library.

Write up the ABI

ABI stands for Application Binary Interface. An ABI is like a guidebook that explains how smart contracts can communicate with each other. It outlines the rules for how data should be packaged and sent between these contracts. The ABI helps different smart contracts understand each other's messages.

An ABI outlines which function you would like to use from a smart contract deployed on the Ethereum Virtual Machine.

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 in this guide. 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 the 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. We will use the Basic Attention Token, but you could use any token that follows the ERC20 spec.

To find the contract address,

The Contract Address of BAT is 0x0D8775F648430679A709E98d2b0Cb6250d2887EF, so we will use this contract address in the guide.

How to Get the Balance of an ERC-20 Token Using Web3.js | QuickNode (2)

Find a Wallet Address to Get the Balance Of

To find a wallet address that holds the ERC20 token that you select,


  • Click the Holders tab on the token page
  • Copy the wallet address that you want to get the balance of

How to Get the Balance of an ERC-20 Token Using Web3.js | QuickNode (3)

Entire Code

We now have a connection to an Ethereum node, an ABI, a smart contract address, and a wallet address. With a few Web3.js calls, we can get the amount of BAT that this address holds.

Your entire index.js file will look as follows;

//index.js
const { Web3 } = require("web3");
const endpointUrl = "QUICKNODE_HTTP_ENDPOINT"
const httpProvider = new Web3.providers.HttpProvider(endpointUrl);
const web3Client = new Web3(httpProvider);

const minABI = [
// balanceOf
{
constant: true,
inputs: [{ name: "_owner", type: "address" }],
name: "balanceOf",
outputs: [{ name: "balance", type: "uint256"}],
type: "function",
},
];

const tokenAddress = "0x0d8775f648430679a709e98d2b0cb6250d2887ef";
const walletAddress = "0xfd821d8cea64feacb6ec86d979e37bc64c64a00b";

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

async function getBalance() {
const result = await contract.methods.balanceOf(walletAddress).call();

const resultInEther = web3Client.utils.fromWei(result, "ether");

console.log(`Balance in wei: ${result}`);

console.log(`Balance in ether: ${resultInEther}`);
}

getBalance();

  1. The program starts by importing the Web3 module, which helps in connecting to Ethereum networks. It sets up an Ethereum node's HTTP endpoint using the URL provided.

  2. It creates a new instance of the Web3.providers.HttpProvider using the defined endpoint URL, establishing a connection to the Ethereum network.

  3. The minABI constant is an array of information about an ERC20 token smart contract's functions. It describes the function balanceOf that can be called on the contract. This function allows checking the balance of an Ethereum wallet address. The information includes details like the function's name, inputs, outputs, and their types.

  4. The tokenAddress and walletAddress constants hold Ethereum addresses. The tokenAddress represents the address of an ERC20 token smart contract on the Ethereum network, while the walletAddress represents an Ethereum wallet address to check the balance.

  5. A new contract instance is created using the minABI array and the tokenAddress. This allows the program to interact with the smart contract functions using the contract variable.

  6. The getBalance function is defined with an async keyword, indicating it performs asynchronous operations. Inside this function, the balanceOf function from the smart contract is called with the walletAddress. The await keyword is used to wait for the response from the Ethereum network. The result is the balance of the specified wallet address in the smart contract's token.

  7. The program logs both the original result (in wei) and the converted resultInEther (in ether) to the console.

  8. Lastly, the getBalance function is invoked at the end of the code, triggering the entire process. This results in displaying the balance of the specified wallet address, both in wei and in ether units.

  9. The getBalance function is called at the end of the code, triggering the entire process and displaying the balance of the specified wallet address.

info

Wei is the smallest unit of Ethereum's cryptocurrency, while ether is the larger and more commonly used unit, with 1 ether being equivalent to 10^18 wei.

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. Make sure that you are still in the main project directory.

node index

It should display in your console the amount of BAT in the both formats.

> node index.js
Balance in wei: 176775759650192465574646501
Balance in ether: 176775759.650192465574646501

Entire Code with Web3.js version 1.10

If you are using version 1.10 of Web3.js, refer to this code. If not, you can skip this section.

//index.js

const Web3 = require('web3')

const provider = 'QUICKNODE_HTTP_ENDPOINT'

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 = '0xfd821d8cea64feacb6ec86d979e37bc64c64a00b'

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

async function getBalance() {
const result = await contract.methods.balanceOf(walletAddress).call()

const resultInEther = Web3Client.utils.fromWei(result)

console.log(`Balance in wei: ${result}`);

console.log(`Balance in ether: ${resultInEther}`);
}

getBalance()

Using the QuickNode Token API

Alternatively, you can easily retrieve the balance of an ERC20 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). You can also check out our Token API documentation page.

Please note that this RPC method requires the Token and NFT API v2 bundle add-on enabled on your QuickNode endpoint.

See the following web3.js example below to see how easy it is to get all the token balances with this method:

Create the indexTokenApi.js file by running the command.

echo > indexTokenApi.js

Then, modify the file.

Replace QUICKNODE_HTTP_ENDPOINT with your QuickNode HTTP Provider URL.

const { Web3 } = require("web3");

const endpointUrl =
"QUICKNODE_HTTP_ENDPOINT";
const httpProvider = new Web3.providers.HttpProvider(endpointUrl);
const web3Client = new Web3(httpProvider);

(async () => {
const heads = await web3Client.requestManager.send({
method: "qn_getWalletTokenBalance",
params: [{wallet: "0xfd821d8cea64feacb6ec86d979e37bc64c64a00b"}],
});

console.log(heads);
})();

Finally, run the code.

node indexTokenApi.js

The console output is like the one below. It brings up all the ERC20 balances and a bunch of information easily.

How to Get the Balance of an ERC-20 Token Using Web3.js | QuickNode (4)

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 set up an Ethereum endpoint. 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 encounter any problems or have any questions, we'd love to help you! Find us on Discord or Twitter.

We ❤️ Feedback!

Let us know if you have any feedback or requests for new topics. We'd love to hear from you.

How to Get the Balance of an ERC-20 Token Using Web3.js | QuickNode (2024)

FAQs

How to Get the Balance of an ERC-20 Token Using Web3.js | QuickNode? ›

After detecting that the user has MetaMask installed what we are going to do is instantiate our version of Web3 with the provider information from the global object. Once we did that, we are already connected to the wallet, which means that we can access the current balance. var accounts = await web3. eth.

How to check ERC20 token balance? ›

Retrieve the balance of an ERC-20 token
  1. Create a project directory​ Create a new directory for your project. ...
  2. Install required packages​ Install the web3 package in the project directory:
  3. Set up the script​ ...
  4. Set the ABI​ ...
  5. Select a token address​ ...
  6. Request the token balance​ ...
  7. Convert the token units​ ...
  8. Run the script​
Sep 5, 2024

How to read the balance of your MetaMask wallet with web3 JS? ›

After detecting that the user has MetaMask installed what we are going to do is instantiate our version of Web3 with the provider information from the global object. Once we did that, we are already connected to the wallet, which means that we can access the current balance. var accounts = await web3. eth.

How do I convert my ERC-20 tokens to cash? ›

Safely exchange your ERC20 tokens through Ledger

In the Ledger Live app Swap tab, select any ERC20 tokens and the accounts of origin and destination. Enter the amount you want to exchange and check the rate. Before confirming the swap, you'll see a summary on Ledger Live.

How do I know if my token is ERC20? ›

You can use a tool or library to call these functions on the target address. Evaluating Return Values: If the function calls succeed and return valid values (e.g., a non-zero balance or a total token supply), it's a strong indication that you're dealing with an ERC20 token contract.

How do I withdraw my ERC20 tokens? ›

Withdraw an ERC20 token
  1. Add the sender and recipient addresses​ Open Ronin Bridge. ...
  2. Choose the token and amount​ ...
  3. Confirm your withdrawal​ ...
  4. Receive the tokens in your Ethereum wallet​
Jun 26, 2024

How to check Ethereum wallet balance? ›

  1. Head to EthVM.
  2. In the search bar, enter your Ethereum public address, (0x…..).
  3. You will be taken to a wallet overview. At the top, the checksummed version of your address will be displayed. Read our article about the differences between checksummed and non-checksummed addresses.

Do ERC-20 tokens have value? ›

The barrier to entry for creating ERC-20 token sets is low (it's really just a matter of deploying a relatively simple 'contract' to the Ethereum network), so the number of sets is measured in the thousands. For this reason, most sets actually have very little value. Some, however, are worth billions.

How do I check my crypto wallet balance? ›

How to check my wallet balance?
  1. Visit the Cryptonow Check Balance page.
  2. Enter your Wallet Public Address. You'll need your wallet's public address for this check. Enter it in the appropriate field.

How do I cash out my web3 wallet? ›

How to withdraw Crypto from Web3 to your primary wallet:
  1. Login to your Mobile App.
  2. Go to the account menu.
  3. Select Web3.
  4. Select the currency you wish to transfer.
  5. Select "Transfer".
  6. Select “Transfer to your primary wallet”.
  7. Enter the amount you wish to transfer or select MAX to transfer all of your selected Crypto.

How to check web3 wallet? ›

Where can I view the assets and balance for my web3 wallet? You can view your balance by selecting your 'web3 wallet' under the My Assets page then navigating to the 'Crypto' tab.

What is the function of web3js? ›

Web3. js enables you to fulfill the second responsibility: developing clients that interact with The Etherem Blockchain. It is a collection of libraries that allow you to perform actions like send Ether from one account to another, read and write data from smart contracts, create smart contracts, and so much more!

How do I access my ERC20 token? ›

Step-by-step guide to using Alchemy to find all ERC-20 tokens owned by an address
  1. Step 1: Install Node and the NPM. Install Node and the Node Package Manager (NPM) on the local machine. ...
  2. Step 2: Sign up for an Alchemy account and create an app. ...
  3. Step 3: Create a Node project. ...
  4. Step 4: Get the token balances of an address.
Mar 13, 2024

How do I transfer my ERC20 token? ›

Sending an ERC-20 token takes only five steps:
  1. Import userop.js and ethers.js. You only need two libraries - ethers and userop. ...
  2. Build account preset. Userop. ...
  3. Import ERC-20 interface. The user operation will call the ERC-20 token's transfer function. ...
  4. Create the user operation. ...
  5. Send the user operation.

Where are ERC-20 tokens stored? ›

ERC 20 tokens can be stored in virtually any cryptocurrency wallet. Importantly, when using them, remember to write down the key phase. This consists of between 12 and 24 words. This is the password for access, in case your funds are lost.

How do I withdraw my Web3 coin? ›

How to withdraw Crypto from Web3 to your primary wallet:
  1. Login to your Mobile App.
  2. Go to the account menu.
  3. Select Web3.
  4. Select the currency you wish to transfer.
  5. Select "Transfer".
  6. Select “Transfer to your primary wallet”.
  7. Enter the amount you wish to transfer or select MAX to transfer all of your selected Crypto.

How do I get my ERC20 token listed on exchange? ›

The Main Requirements to Getting Listed on a Crypto Exchange
  1. Compliance with regulations. The token must adhere to local and international regulatory standards. ...
  2. Technical requirements. Compatibility with the exchange's infrastructure is crucial. ...
  3. Financial audits. ...
  4. Community and marketing. ...
  5. Documentation.
Jun 6, 2024

How do I get ERC20 tokens? ›

Where & How to Buy ERC20 (ERC20) Guide
  1. Download a Trust Wallet Wallet. ...
  2. Set up your Trust Wallet. ...
  3. Buy ETH as Your Base Currency. ...
  4. Send ETH From Binance to Your Crypto Wallet. ...
  5. Choose a Decentralized Exchange (DEX) ...
  6. Connect Your Wallet. ...
  7. Trade Your ETH With the Coin You Want to Get. ...
  8. If ERC20 Doesn't Appear, Find its Smart Contract.

Is API3 an ERC20 token? ›

The API3 token is an ERC-20 token on the Ethereum network with a fixed supply of 130 million units.

Top Articles
Credit Portfolio Management - Open Risk Manual
Can you bring your own paintballs to a paintball field? - Paintball Ruined My Life
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Arielle Torp

Last Updated:

Views: 6020

Rating: 4 / 5 (61 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Arielle Torp

Birthday: 1997-09-20

Address: 87313 Erdman Vista, North Dustinborough, WA 37563

Phone: +97216742823598

Job: Central Technology Officer

Hobby: Taekwondo, Macrame, Foreign language learning, Kite flying, Cooking, Skiing, Computer programming

Introduction: My name is Arielle Torp, I am a comfortable, kind, zealous, lovely, jolly, colorful, adventurous person who loves writing and wants to share my knowledge and understanding with you.