November 17, 2022

Balance of ERC20 – How to Get Balance of an ERC20 Token from Address

Table of Contents

With a proper Web3 API endpoint, you can fetch any balance of ERC20 using a single line of code. In fact, take a look at the following code snippet provided by Moralis to get the balance of an ERC20 token effortlessly:

const response = await Moralis.EvmApi.token.getWalletTokenBalances({

The above line of code fetches ERC20 balances of any wallet, which makes it a valuable tool when creating all sorts of dapps. Whether creating a portfolio tracking dapp, a wallet dapp, or a more advanced dapp that incorporates EVM-compatible fungible tokens, it’s crucial that the dapp’s backend knows and showcases the balance of ERC20 tokens. Moreover, if you’ve worked with Moralis before, you already have some ideas on how to implement the above snippet of code to make the most out of it. On the other hand, if you’re new to Web3 development, make sure to complete today’s tutorial. As a result, you’ll learn how to get balance of ERC20 token without breaking a sweat. You’ll just need a free Moralis account and know some JavaScript basics.

Unlock the Power of Blockchain with Moralis

Overview

If you decide to dive into today’s topic, you’ll first learn all you need to know about ERC20 tokens. We’ll also mention some other ERC token standards and quickly compare them to ERC20. Next, we’ll explore the ultimate tool to get balance of ERC20 token. This is where you’ll have a chance to get acquainted with Moralis and this ultimate Web3 API provider’s Token API. After all, the latter is the toolbox that offers the above-provided “getWalletTokenBalances” endpoint. In addition, we’ll also take a closer look at this endpoint and show you how you can explore it in more detail yourself. 

Multiple ERC20 tokens floating inside the metaverse.

Furthermore, you’ll also find out how to get the lines of code that include this endpoint for your favorite legacy programming language/framework. Last but not least, we’ll take you through a simple three-step tutorial that will teach you how to use JavaScript to get the ERC20 balance of any wallet address.      

List of a wallet's balance of ERC20 tokens, including BNT, ETH, MANA, etc.

Exploring ERC20

Unless you are new to the crypto realm, you know that there are many crypto tokens or cryptocurrencies available. However, many don’t know that most of these tokens were created on top of Ethereum, following the ERC20 standard. That said, what is ERC20?

ERC20, or “Ethereum Request for Comments 20”, was proposed by Fabian Vogelsteller back in November 2015. The community accepted it; in turn, devs set it in place, ensuring all tokens created on Ethereum maintain the same essential qualities. Basically, all ERC20 tokens follow Ethereum coin’s (native token) specifics. Furthermore, all ERC20 tokens minted (created) using the same smart contract always have the same characteristics and are completely interchangeable (fungible).

Many times, Web3 devs refer to the ERC20 standard as an “ERC20 contract”. This is because smart contracts are used to implement this standard. Every time someone decides to create ERC20 tokens, a smart contract that incorporates the ERC20 standard must be used. Furthermore, the smart contract used to mint the token ensures that all transfers regarding those tokens follow predefined rules. So, it’s safe to say that the ERC20 contract standard imposes proper rules when ERC20 tokens are created and handled. As such, contracts also ensure that every balance of ERC20 tokens adheres to the token’s tokenomics. In addition, these rules enable developers to accurately predict how their new ERC20 tokens will function within Ethereum’s ecosystem. Also, thanks to the automated nature of smart contracts, those rules get implemented automatically. 

Some of the most popular ERC20 tokens include “Basic Attention Token” (BAT), “Maker” (MKR), “OMG Network” (OMG), and “Augur” (REP). 

Magnifying glass inspecting the ERC20 standard.

ERC20 Rules and Guidelines

The two core pieces of information of every ERC20 smart contract are its blockchain address and the total supply of the ERC20 tokens it governs. In addition to these two required parameters, there are other optional components that ERC20 smart contracts may include. Ultimately, the following are the parameters of ERC20 tokens:

  • Contract address (essential)
  • Total supply of tokens (essential)
  • Token name (optional)
  • Token symbol (the ticker [optional])
  • Number of decimals for the token (optional)

Note: As we show you how to get balance of ERC20 token below, you’ll be able to see the above components in your terminal. Moreover, if you want to explore the above-listed ERC20 contract parameters further, check out our “Exploring the ERC-20 Token Standard” article. 

Leaderboard showing ERC20 vs ERC721 vs ERC1155.

ERC20 vs Other Ethereum Standards

The above-covered details are more than enough to create killer dapps that fetch ERC20 balances of wallet addresses. However, it’s important to be aware of other Ethereum token standards. For instance, you’ve probably heard of ERC721 and ERC1155 tokens. After all, these are the two leading standards for non-fungible tokens (NFTs). As such, these smart contracts include different components – the ones that help ensure uniqueness.

Two other popular Ethereum standards include ERC223 and ERC777. The former is a protocol upgrade for the ERC20 protocol that allows users to transmit tokens to a digital wallet more safely. On the other hand, the ERC777 standard for fungible tokens focuses on ensuring interoperability with existing decentralized exchanges. It relates to Ethereum’s blockchain protocol, which defines the types of tokens that are interoperable with ETH.

In addition, several other token standards, such as ERC677, govern the popular LINK token. Furthermore, as mentioned previously, in order to create killer dapps that get ERC20 balance of wallets, you do not need to dive any deeper into these standards. However, in case you decide to mint your own tokens on Ethereum, make sure to study all available standards more closely.          

Wizard pointing at a sign that says Balance of ERC20.

Ultimate Tool to Get Balance of ERC20 Token

Unless you’ve been living under a rock, odds are you know that Moralis is the Web2-Web3 bridge that enables you to use legacy dev platforms and frameworks to join the Web3 revolution. Aside from being cross-platform interoperable, Moralis also supports all leading programmable blockchains. As such, you can create dapps on Ethereum, all leading EVM-compatible chains, and even Solana in minutes. Furthermore, this cross-chain interoperability also future-proofs your work as you never get stuck to any particular chain.

Graph showing Moralis' supported networks.

Moralis provides several products, including the ultimate Web3 Auth API, NFT API, Streams API, and Token API. While you’ll want to use all of these tools as you start creating more advanced dapps, the Moralis Token API enables you to get ERC20 balance of wallets effortlessly. As such, we’ll focus on the latter herein.  

Moralis’ Token API lets you integrate real-time token data into your applications without breaking a sweat. Moreover, it enables you to get full access to token prices, ownership, and transfer data across all major blockchains. Of course, it also lets you get ERC20 balance of wallets across all supported chains. 

The “getWalletTokenBalances” Endpoint

By now, you know that fetching wallets’ token balances is possible thanks to the “getWalletTokenBalances” endpoint. As such, let’s together look at the endpoint’s get balance by wallet documentation page:

The get balance by wallet endpoint documentation page.

Looking at the above screenshot, you can see that this endpoint takes in the “address” parameter, which is also the only required parameter. After all, the endpoint needs to know which address to focus on when fetching token balances. In addition, “getWalletTokenBalances” includes some optional parameters. These are as follows:

  • chain” – The chain to query.
  • subdomain” – To use when selecting local dev/test chains.
  • to_block” – To check balances for past blocks.
  • token_addresses” – To filter the results to a specific list of addresses.

You can use the above-presented documentation page to test the endpoint. All you need to do is paste in an address you want to query and hit the “Try It!” button. Furthermore, by using the top-right side of the above page, you can select the programming language you want to use. Then, you simply copy the snippet of code from the “request” section and paste it into your scripts. 

Red letters stating Tutorial.

How to Get Balance of ERC20 with Moralis

Now that you know which the ultimate tool to get balance of ERC20 token is, it’s time to roll up your sleeves and follow our lead. However, before we take you through this three-step process, make sure to complete the following prerequisites:

  • Install Node v.14 or higher.
  • Prepare your favorite code editor or IDE. We tend to use Visual Studio Code (VSC).
  • Install your favorite package manager (“npm”, “yarn”, or “pnpm”).
Moralis' homepage pointing at the Start for Free button.

Step 1: Moralis Setup  

Any balance of ERC20 tokens will be at your disposal once you install the Moralis SDK and obtain your Web3 API key. Hence, make sure you create your free Moralis account to access your admin area. Once you have your account up and running and are inside your Moralis admin area, complete the following two steps, as seen in the image:

Step 1, click on Web3 APIs. Step 2, click on the copy icon next to your API key.

Hold on to your API key for now and focus on installing the Moralis SDK in your project. Fortunately, you just need to run the correct command to do that. So, use one of the following commands (depending on the package manager that you are using):

npm install moralis
yarn add moralis
pnpm add moralis

Step 2: An Example Script that Gets Balance of ERC20 Tokens

Now that you’ve successfully installed the Moralis SDK, it’s time to use the right lines of code to get balances of fungible tokens. However, you don’t need to code a script from scratch; instead, you can simply copy and paste the following lines of code into an “index.js” file:

const Moralis = require('moralis').default;
const { EvmChain } = require('@moralisweb3/evm-utils');

const runApp = async () => {
  await Moralis.start({
    apiKey: "YOUR_API_KEY",
    // ...and any other configuration
  });
  
  const address = '0xd8da6bf26964af9d7eed9e03e53415d37aa96045';

  const chain = EvmChain.ETHEREUM;

  const response = await Moralis.EvmApi.token.getWalletTokenBalances({
    address,
    chain,
  });
  
  console.log(response.toJSON());
}

runApp();

Note: The above lines of code focus on using JavaScript. However, you may want to use TypeScript. In that case, access the “How to Get All ERC20 Tokens Owned by an Address” docs page and choose “index.ts”.

Looking at the above example script, you can see “EvmChain.ETHEREUM“. The latter defines the chain. So, if you were to fetch token balances on other supported chains, you’d need to replace “ETHEREUM” accordingly. 

Nonetheless, the “YOUR_API_KEY” placeholder indicates the spot where you need to paste your Moralis Web3 API key:

Showing the apiKey variable and the field where a user should enter their API key.

Step 3: Execute the Program to Get ERC20 Balance of a Wallet

If you’ve properly followed our lead, you now have your own “index” file ready and equipped with your Web3 API key. As such, you can execute the program. By doing so, you’ll be able to see the balance of ERC20 tokens for the “0xd8da6bf26964af9d7eed9e03e53415d37aa96045” address used above. Of course, feel free to replace this address with any other address.

To execute the program, you need to run one of the following commands:

For JavaScript:

node index.js

For TypeScript: 

node index.ts

After running the appropriate command, you should see the following results in your terminal:

[
  {
    "token_address": "0x351d941fe1bbb94f142d3975da5019593ccd2ecc",
    "name": "PEPSI Metaverse",
    "symbol": "PEPSI",
    "logo": null,
    "thumbnail": null,
    "decimals": 18,
    "balance": "767387143779415173800484933"
  },
  {
    "token_address": "0xbab6f30c81209433a3ced28ca8e19256440547d9",
    "name": "Yu Gi Oh",
    "symbol": "YGO",
    "logo": null,
    "thumbnail": null,
    "decimals": 6,
    "balance": "30000000"
  },
  {
    "token_address": "0x39f21985611480595fa60696e04fe104998771eb",
    "name": "Bone Shiba",
    "symbol": "BONESHIB",
    "logo": null,
    "thumbnail": null,
    "decimals": 18,
    "balance": "50000000000000000000000000"
  }
]

Nonetheless, to get a proper hang of using the “getWalletTokenBalances” endpoint, try running the above script for other addresses and chains. Moreover, feel free to experiment with utilizing other optional parameters (presented previously) of this endpoint.

Balance of ERC20 – How to Get Balance of an ERC20 Token from Address – Summary

If you are familiar with Moralis, you were able to use the code snippet provided in the intro to get the ERC20 token balance right away. However, if you decided to start following along in this article instead, you had a chance first to get better acquainted with the Moralis Token API. Along the way, you explored everything you need to know about the ERC20 token standard to incorporate these kinds of tokens into your dapps. Last but not least, you also had an opportunity to take the “getWalletTokenBalances” endpoint for a spin using our example script. As such, you now know how to get the ERC20 balance of any wallet on any supported blockchain. 

Moving forward, you have two options – if you already have the knowledge and the confidence, start building your own dapps. On the other hand, you may need some additional practice. If so, you should explore other tutorials focusing on numerous powerful Web3 API endpoints. Of course, you may also expand your knowledge of other blockchain development topics. If that interests you, make sure to visit the Moralis YouTube channel or the Moralis blog. Some of the latest topics there focus on WalletConnect integration, the easiest way to create NFTs on Solana, creating a Minecraft Web3 game, NFT metadata storage, and more. 

Furthermore, you may take a more professional approach to your blockchain education by enrolling in Moralis Academy. By completing the courses there, you can become blockchain-certified. The courses range from beginner to advanced level. So, in case you already know blockchain fundamentals, the Blockchain Business Masterclass course might be the right course for you. Not only will you level up your blockchain development knowledge, but you will also increase your chances of landing your dream crypto job.     

Moralis Academy's homepage.
Moralis Money
Stay ahead of the markets with real-time, on-chain data insights. Inform your trades with true market alpha!
Moralis Money
Related Articles
August 28, 2022

How to Set Up a Self-Hosted Parse Server

December 18, 2023

How to Watch On-Chain Transactions – Monitor Crypto Transactions and Events

October 11, 2022

Multichain NFT API – How to Build Cross-Chain NFT Dapps

December 26, 2023

ETH Gas Tracker – Full Ethereum Gas Tracker Guide

April 10, 2024

How to Get All Owners of an ERC20 Token 

November 1, 2022

Web3 Infrastructure – Exploring the Best Solution for Web3 Development

October 2, 2022

Tutorial: How to Connect a Dapp to Polygon Network

November 3, 2023

Free Gnosis API for Creating Gnosis Chain Dapps

February 27, 2024

How to Get the Net Worth of Any ERC20 Wallet via API