A reliable ERC20 token balance API is a tool every blockchain developer must utilize. Are you looking for such a tool? Look no further! With Moralis’ ERC20 token balance API endpoint, you can get a wallet’s native crypto balance using a short code snippet:
const response = await Moralis.EvmApi.balance.getNativeBalance(options)
Also, with the following endpoint, you can get the token balance:
const response = await Moralis.EvmApi.token.getWalletTokenBalances(options)
If you’ve used Moralis before, you know exactly how to implement the above lines of code to make the most out of the best token API. However, if this is the first time you have heard about the market’s leading Web3 provider, create your free Moralis account and follow our lead as we tackle today’s tutorial.
Overview
There are countless opportunities at your disposal once you learn how to make the most of Moralis’ ERC20 token balance API, and today’s article will help you get started with confidence.
Moving forward, we’ll first make sure you all know what an API for ERC20 tokens is. Next, we’ll explain how this tool can be helpful. Then, we’ll properly introduce you to the best ERC20 token balance API brought to you by Moralis’ Token API. Last but not least, we’ll take you through a simple example project where you’ll have a chance to put one of the above Token API endpoints to use. Moreover, by following our lead, you’ll also get to create a simple dapp.
ERC20 Token Balance API – What is it?
An ERC20 token API is a specific Web3 API that revolves around on-chain data regarding ERC20 tokens. You probably know that “application programming interfaces” (APIs) have been an important part of the legacy development space. After all, APIs have facilitated communication between different software pieces by translating instructions for correlative understanding. Also, APIs enable reliable programming in secure and controlled development environments. Similarly, Web3 APIs do the same things but for crypto. Accordingly, Web3 APIs facilitate communication between blockchain nodes and the backend of decentralized applications (dapps). Essentially, Web3 APIs empower blockchain developers to build dapps!
Furthermore, most fungible tokens live on the Ethereum network, where they follow the ERC20 standard. This is where tokens get their name from. It’s also worth noting that ERC20 is short for “Ethereum Request for Comments 20”. This comment/proposal was presented and accepted at the end of 2015. Since its implementation, all fungible tokens minted on Ethereum have the exact same basic qualities that follow ether’s (Ethereum’s native token) example. All ERC20 tokens are created with ERC20 smart contracts. After minting, the token’s smart contract address stores all tokens. However, as tokens are distributed, other blockchain addresses or Web3 wallets get involved. That is why a proper ERC20 token balance API plays an important role – it helps fetch those balances effortlessly.
How Can an API for Displaying ERC20 Token Balances Be Useful?
Just like ERC20 tokens can serve many different purposes, so can an API for displaying ERC20 token balances. Basically, this sort of API is the tool to use when you want your dapp to display or utilize ERC20 balances on the backend. If there are ERC20 tokens involved, whether as utility tokens, governance tokens, or currencies, a reliable ERC20 token balance API makes your life a lot simpler. With this tool, you can fetch on-chain details about the fungible tokens and use the available data to trigger a specific functionality. Additionally, among more advanced and complex features, a token API lets you display ERC20 balances for your dapp’s users.
So, whenever you decide to build a dapp on top of Ethereum or other EVM-compatible chains, a reliable token API should be in your toolbox. With it, you can even build DeFi platforms or incorporate ERC20 tokens in a Web3 game without breaking a sweat. Nonetheless, a high-quality API also enables you to save a ton of time and resources. After all, instead of building your own infrastructure, you simply use short snippets of code like those presented in the intro.
Introducing the Best ERC20 Token Balance API
At this point, you already know that the best ERC20 token balance API is brought to you by Moralis. However, the Token API is just one of many products that this enterprise-grade Web3 API provider offers. When you combine it with the Auth API, Streams API, and NFT API, you can create any kind of dapp easily. Moreover, Moralis is a Web2-Web3 bridge, enabling you to use your favorite legacy dev platforms, programming languages, and frameworks to join the Web3 revolution. Furthermore, you can use Moralis’ cross-platform interoperability to create multi-chain dapps. After all, Moralis supports all leading programmable blockchains. Hence, make sure to explore the full scope of Moralis’ power.
However, let’s go back to the Token API. It enables you to integrate real-time token data into your dapp in a straightforward way. Plus, it helps you fetch more than just token balances but also token prices, ownership, and transfer data across all supported blockchains. To make all this as simple as possible, the Token API provides many endpoints, which you can explore inside the token API documentation. However, in this article, we’ll focus on the “getWalletTokenBalances” and “getNativeBalance” endpoints. After all, they are the key players of the lines of code presented at the top of this article.
The “getWalletTokenBalances” Endpoint
The “getWalletTokenBalances” endpoint is the key to effortlessly fetching wallets’ token balances and is an essential part of Moralis’ ERC20 token balance API. Thus, we ought to take a closer look at the get balance by wallet documentation page:
As you can see above, this endpoint requires the “address” parameter to let the function know which address to focus on. Moreover, when fetching token balances with “getWalletTokenBalances“, you can include other optional parameters:
- “chain” – The chain to query.
- “subdomain” – Use it when selecting local dev/test chains.
- “to_block” – It enables you to check balances for past blocks.
- “token_addresses” – This parameter lets you filter the results to a specific list of addresses.
Moralis’ API reference documentation pages allow you to test the endpoints. So, if you look at the above screenshot again, you can see that you just need to paste in an address you want to query. Then, select the programming language you prefer and hit the “Try It!” button. Nonetheless, you can simply copy the code snippet from the “request” section and paste it into your scripts. Then you use the “getWalletTokenBalances” endpoint to fetch the balance of ERC20 tokens for a specific wallet address for your dapps.
The “getNativeBalance” Endpoint
If you paid attention to the snippets of code provided in the intro, you might have noticed that the “getNativeBalance” endpoint is technically part of the Balance API. However, since this is the endpoint you want to use to get the native balance of an ERC20 token vault, it deserves our attention. Plus, it is the endpoint that we’ll use in the upcoming tutorial. That said, make sure to visit the “getNativeBalance” endpoint’s documentation page:
Just like “getWalletTokenBalances“, “getNativeBalance” also requires the “address” parameter. In addition, it takes in the following three optional parameters:
- “chain” – The chain to query.
- “providerUrl” – You can use this parameter to determine the Web3 provider URL when using local dev chains.
- “to_block” – It enables you to check balances for past blocks.
Use Moralis’ API to Get the Balance of ERC20 Tokens
At this point, you know more than enough about the best ERC20 token balance API to see it in action. As such, we invite you to roll up your sleeves and complete these three steps following our lead:
- Create a NodeJS Backend Dapp
- Initialize Moralis
- Create a ReactJS Frontend Dapp
By completing the above three steps, you’ll have your own instance of our “Get Wallet Native Balance” example dapp:
The above screenshot shows the gist of what you’ll be building. However, if you want a more detailed demo, make sure to use the video at the bottom of this article (0:15).
Create a NodeJS Backend Dapp – Step 1
If this is your first time creating a NodeJS application, make sure to complete the initial setup by following the “NodeJS” page in Moralis’ docs. The latter will show you how to properly install the required dependencies and set up and run an Express server.
Once you have your NodeJS application ready and running on an Express server, you can focus on creating an “index.js” script. There, you’ll use the best ERC20 token balance API. Start by defining the required constants at the top of the file:
const express = require("express"); const Moralis = require("moralis").default; const app = express(); const cors = require("cors"); const port = 3000;
Also, make sure that your dapp uses “cors” and “express”:
app.use(cors()); app.use(express.json());
With the above lines of code in place, create the “get” endpoint to the “balance” route. With a simple “if-else” statement, you ensure that the “getNativeBalance” endpoint accepts its parameters. Ultimately, you need to expand your “index.js” file with these lines of code:
app.get("/balance", async (req, res) => { try { const { query } = req; let balance; if (query.toBlock) { balance = await Moralis.EvmApi.balance.getNativeBalance({ address: query.address, chain: query.chain, toBlock: query.toBlock }); }else{ balance = await Moralis.EvmApi.balance.getNativeBalance({ address: query.address, chain: query.chain, }); } const result = balance.raw; return res.status(200).json({ result }); } catch (e) { console.log(e); console.log("something went wrong"); return res.status(400).json(); } });
The above code will enable your NodeJS dapp to query the details from the entry fields. This will operate correctly once you link it to your frontend, where you’ll create the “Get Balance” button.
Initialize Moralis – Step 2
To initialize Moralis, you need to populate the above-created “index.js” script with the following lines:
Moralis.start({ apiKey: "MORALIS_API_KEY", }).then(() => { app.listen(port, () => { console.log(`Listening for API Calls`); }); });
As you can see, the “MORALIS_API_KEY” placeholder is in the code above. So, to access the power of Moralis’ ERC20 token balance API, you need to replace it with your actual Web3 API key. Once you have your free Moralis account up and running, you get to obtain your Web3 API key in two clicks from your admin area:
Note: The complete “index.js” script awaits you on GitHub.
Create a ReactJS Frontend Dapp – Step 3
You probably have experience creating ReactJS applications and would be more than capable of creating the above-demonstrated frontend yourself. However, you can save some time by using our GitHub repo. Nonetheless, let’s look at the core function of our dapp’s frontend – coded inside the “App.js” script. Here are the details of the “fetchBalance” function, which is triggered by the “Get Balance” button:
async function fetchBalance() { let res; if(toBlock){ res = await axios.get(`http://localhost:3000/balance`, { params: { address: address, chain: chain, toBlock: toBlock }, }); }else{ res = await axios.get(`http://localhost:3000/balance`, { params: { address: address, chain: chain }, }); } console.log(res); setBalance((res.data.result.balance / 1E18).toFixed(2)) }
The lines of code above show you that our dapp provides our backend with the required and optional parameters. Moreover, it takes the raw balance, which includes eighteen decimals, and rounds it to two decimal places.
In case you want more detailed guidance, use the video below. Aside from the demonstration of the “Get Wallet Native Balance” dapp, it also walks you through other core scripts:
- 3:54 – Details of the Core Backend Script (“index.js”)
- 5:24 – The “App.js” Script
With this example dapp in place, we encourage you to try using different wallet addresses and chains. Also, feel free to explore past balances by using different block numbers. In addition, you may also be willing to use the above-presented scripts for “getWalletTokenBalances“. To do this, you’ll need to replace “balance.getNativeBalance” with “token.getWalletTokenBalances“.
Finally, here’s the video tutorial with all the details:
The Best ERC20 Token Balance API for Dapp Development – Summary
In today’s article, you learned what the best ERC20 token balance API for dapp development is and how to use it. As such, you now know that this excellent tool comes from Moralis’ Token API and Balance API. You also had a chance to follow our steps and complete an example dapp that fetches native token balances. With some minor tweaks to the code, this same dapp can be used to fetch ERC20 token balances. Moreover, if you took on today’s tutorial, you learned how to obtain your Web3 API key. Hence, you are now equipped to take advantage of Moralis’ other Web3 APIs.
We believe in learning by taking action. Thus, we recommend you focus on completing as many tutorials as possible that await you in the Moralis docs. In addition, make sure to continue your free blockchain development education by exploring the Moralis YouTube channel and our crypto blog. These two outlets cover a wide range of useful topics. For instance, some of the latest articles focus on Web3 AWS Lambda, Python Web3 development, NFT metadata, blockchain infrastructure, and much more. Nonetheless, you can also become blockchain certified by completing courses offered by Moralis Academy. To even better understand programmable chains, you can start with Ethereum fundamentals.
Read More: moralis.io