Join us in this tutorial as we show you the most accessible way to get the token balance of an address! In fact, with Moralis and the Token API, you can query an address’ ERC-20 token balance in three steps:
- Create a project and install the Moralis SDK with the following terminal command:
npm install moralis @moralisweb3/common-evm-utils
- Set up a new file and call the ”getWalletTokenBalances” endpoint with the following code (add your Moralis API key, an address, and the chain you want to query):
const Moralis = require('moralis').default; const { EvmChain } = require('@moralisweb3/common-evm-utils'); const runApp = async () => { await Moralis.start({ apiKey: "YOUR_API_KEY", // ...and any other configuration }); const address="0xBf6521AF44F5D56813A93dCE548E6594Daa00794"; const chain = EvmChain.ETHEREUM; const response = await Moralis.EvmApi.token.getWalletTokenBalances({ address, chain, }); console.log(response.toJSON()); } runApp();
- Execute the program by running the following command:
node “FILE_NAME”
If you follow the steps above, you should receive a response similar to the one shown below:
{ "token_address": "0xff20817765cb7f73d4bde2e66e067e58d11095c2", "name": "Amp", "symbol": "AMP", "logo": "https://cdn.moralis.io/eth/0xff20817765cb7f73d4bde2e66e067e58d11095c2.png", "thumbnail": "https://cdn.moralis.io/eth/0xff20817765cb7f73d4bde2e66e067e58d11095c2_thumb.png", "decimals": 18, "balance": "24109691515670000000000" }
For more information regarding the ”getWalletTokenBalances” endpoint, check out Moralis’ official get balance by wallet documentation!
Overview
On-chain data associated with wallet addresses is vital information when it comes to Web3 development. Many decentralized applications (dapps) and platforms, including DEXs, wallets, etc., rely on information such as token balances. Consequently, Web3 developers require easy and efficient ways to obtain this type of blockchain data, which is where Moralis enters the picture! With Moralis’ Token API, you can easily get the token balance of an address with only a few lines of code. If you want to learn more about this, join us in this tutorial as we show you the easiest way to query the ERC-20 balance of a wallet address!
To begin with, the article looks at the basics to briefly outline what a wallet address is and what the token balance of an address refers to. Once you grasp these two straightforward concepts, we will jump straight into the central part of this tutorial. From there, we will show you how to create an application for querying an address’ token balance!
Throughout this tutorial, you will familiarize yourself with the Token API. However, this is merely one of Moralis’ various Web3 APIs. Another prominent example you might find interesting is the Streams API. With this tool, you can effortlessly stream on-chain data into the backend of your Web3 projects through Moralis webhooks. That said, for this tutorial, you need a Moralis account. Thus, before you move forward, sign up with Moralis immediately!
What is a Wallet Address?
For the uninitiated, the initial two sections of this article will briefly explore the basic concepts of a wallet address and the token balance of an address. As such, if you are already familiar with these two components, feel free to skip straight into the ”How to Get the Token Balance of an Address…” section. Otherwise, join us as we start this guide by answering the question, ”what is a wallet address?”.
A wallet address is a randomly generated string of letters and numbers connected to a Web3 wallet. Wallet addresses are also generally referred to as public keys and can be shared, much like an email address. Moreover, all blockchain wallets have unique addresses, acting like account numbers where other users can send assets. Accordingly, it is through wallet addresses that cryptocurrencies and NFTs can be sent from one account to another on blockchains.
You can generally find your wallet address quite easily through your wallet provider’s user interface (UI), and they can look something like this: ”0xd06Ffc9107649344e7….”. For example, let’s take a quick look at MetaMask, one of today’s most significant wallet providers. By logging in to your MetaMask account, you can easily copy your wallet address by clicking on the button at the top of the UI:
What is the Token Balance of an Address?
As this tutorial teaches you how to get the token balance of an address, you must also understand what an address’ token balance is. Fortunately, this is not that difficult to understand, as it simply refers to the tokens held by a wallet. Accordingly, the token balance of an address is all the NFTs and fungible tokens held by the wallet to which the address refers!
Nevertheless, now that you have familiarized yourself with what the token balance of an address refers to, it is time to explore the central part of this article. As such, join us in the next section, where we illustrate how to get the token balance of an address!
How to Get the Token Balance of an Address Using Moralis’ Token API
In the following sections, you will learn how to get the token balance of an address using Moralis’ Token API. To demonstrate the accessibility of Moralis, we will show how to set up a straightforward NextJS application implementing this functionality. Consequently, through the app’s UI, you can input an address and query its ERC-20 token balance with the click of a button. What’s more, to make the tutorial as easy as possible to follow, it has been divided into the following four sections:
- Application Demo
- Prerequisites and Moralis Setup
- How to Set Up the Application
- Application Code Breakdown
By the end of this tutorial, you will have learned how to get the token balance of an address using Moralis’ Token API. From there, you can apply the same fundamental principles to future blockchain projects to easily implement similar functionality!
If you would rather watch a video tutorial of the process, you can check out the following clip from the Moralis YouTube channel. In the video, a Moralis software engineer walks you through the entire process and provides a detailed breakdown of the code:
You can also join us here as we start with a demo to show you how the application works!
Application Demo
To kick things off, this section of the tutorial provides a brief demo of the application. Doing so will give you a more profound understanding of what you are working towards. Nevertheless, here is the application’s landing page:
The user interface (UI) is relatively straightforward. It contains a heading, an input field, and a ”Submit” button. To use the application, all you need to do is enter a valid wallet address into the input field and hit ”Submit”. Doing so will generate a response similar to the one below (depending on the wallet’s tokens):
Consequently, in this instance, the application uses Moralis’ Token API to get the token balance of the address you supplied and displays the tokens’ thumbnails, names, and balances in USD. In addition to these elements, the API provides other types of data, such as the tokens’ addresses, symbols, etc. However, these are not displayed on the UI.
If you want to learn how to create this application, join us in the following sections, where we provide a comprehensive walkthrough of the entire process!
Prerequisites and Moralis Setup
Before diving into the application code, there are a few prerequisites you need to deal with. To begin with, ensure that you have NodeJS and npm set up. If you need help with this, visit the following page to install the latest version of Node.js: https://nodejs.org/en/.
Once you have set up NodeJS and npm, you must register for a Moralis account. So, if you have not already, join Moralis immediately. Joining Moralis is entirely free and only takes a couple of seconds. However, you might wonder, ”why do I need a Moralis account?”. In order to interact with the Token API and make calls, you need a Moralis API key. You can find this by logging in to the Moralis admin panel and navigating to the ”Web3 APIs” tab:
Go ahead and copy the API key, as you need to add it to the code later on in this tutorial:
That covers the prerequisites. From here, it is time to dive deeper into the application code!
How to Set Up the Application
We will use an already pre-made application template to make this tutorial as straightforward as possible. You can find the complete GitHub repository for the project down below:
Get Any Wallet Token Balance App Repo – https://github.com/MoralisWeb3/youtube-tutorials/tree/main/get-any-wallets-token-balance
So, to begin with, open the repository above and clone the project to your local directory. With a local copy of the application, you should now have a file structure similar to the one shown below:
If you inspect your local directory, you will quickly notice that the ”.env.local” file is missing. Thus, make sure you create this file and add the contents below and replace ”YOUR_API_KEY” with the key you copied in the previous section:
NEXT_PUBLIC_MORALIS_API_KEY=”YOUR_API_KEY”
Finally, run the following command to install the Moralis SDK:
npm install moralis @moralisweb3/common-evm-utils
That’s actually all you need to do to make the application operational. However, in the following section, we will break down the code to explain the logic in further detail. By teaching you how the application works, you can apply similar principles in future development endeavors.
Application Code Breakdown
This section will break down the essential parts of the code, including the logic for how to get the token balance of an address. Specifically, we will focus on the following three files: ”index.js”, ”header.js”, and ”main.js”.
- ”index.js” – The ”index.js” file contains the code for the application’s homepage. It looks like this:
import Head from "next/head"; import styles from "../styles/Home.module.css"; import Header from "../components/header"; import Main from "../components/main"; export default function Home() { return ( <section className={styles.container}> <Head> <title>Get Token Price</title> <meta name="description" content="Generated by create next app" /> <link rel="icon" href="https://moralis.io/favicon.ico" /> </Head> <main className={styles.main}> <Header /> <Main /> </main> </section> ); }
As you can see at the bottom of the file, the code here is responsible for rendering two components, ”Header” and ”Main”:
<main className={styles.main}> <Header /> <Main /> </main> </section>
Now, let us take a brief look at ”header.js”.
- ”header.js” – This file is relatively straightforward and contains the code for the title and logo at the top left of the application’s UI:
import Image from "next/image"; import styles from "../styles/Home.module.css"; import Logo from "../public/assets/Moralis_logo.png"; export default function Header() { return ( <section className={styles.header}> <Image src={Logo} alt="Logo image" width="102" height="82" /> <h1 className={styles.title}>Get Any Wallet's Token Balance</h1> </section> ); }
Finally, we have the ”main.js” file. However, this file is quite extensive compared to the others, and this is where we find most of the logic needed to get the token balance of an address. As such, this file deserves its own sub-section!
The ”main.js” File
Compared to the two previous files, ”main.js” is relatively extensive. Therefore, we’ve split the code into smaller parts to make it easier to follow along with. As such, let us initially take a closer look at the first four lines of code:
import { useState } from "react"; const Moralis = require("moralis").default; const { EvmChain } = require("@moralisweb3/common-evm-utils"); import styles from "../styles/Home.module.css";
This part is responsible for the necessary imports. This is also where we install Moralis and the common EVM utils. Moreover, the remainder of the code is the ”Header()” function. This is where the central logic for getting the token balance of an address is found in the ”handleSubmit()” function:
const handleSubmit = async () => { address = document.querySelector("#walletAddress").value; const chain = EvmChain.ETHEREUM; await Moralis.start({ apiKey: process.env.NEXT_PUBLIC_MORALIS_API_KEY, }); const response = await Moralis.EvmApi.token.getWalletTokenBalances({ address, chain, }); console.log(response.toJSON()); setResult(response.toJSON()); setShowResult(true); document.querySelector("#walletAddress").value = ""; };
In the first part of this function, we get the address from the UI and store it in the ”address” variable. From there, we set the ”chain” variable to Ethereum. Next up, we initialize Moralis with the ”Moralis.start()” function using the API key from the ”.env.local” file. Lastly, we call Moralis’ ”getWalletTokenBalances()” function, passing the ”address” and ”chain” variables as arguments. The returned information is stored in the ”response” variable, providing access to all the tokens held by the wallet address inputted by the user.
From there, the last part of the code is responsible for rendering the elements of the UI. This is also where we decide what information to display to the user:
return ( <section className={styles.main}> <form className={styles.getTokenForm} name="create-profile-form" method="POST" action="#" > <label className={styles.label} htmlFor="walletAddress"> Add ERC20 Wallet Address </label> <input className={styles.walletAddress} type="text" id="walletAddress" name="walletAddress" maxLength="120" required /> </form> <button className={styles.form_btn} onClick={handleSubmit}> Submit </button> <section className={styles.result}> {showResult && result.map((token) => { return ( <section className={styles.tokenContainer} key={result.indexOf(token)} > <img src={token.thumbnail} /> <p className={styles.name}>{token.name}</p> <p className={styles.amount}> {(token.balance / 10 ** token.decimals).toFixed(2)} </p> </section> ); })} </section> </section> );
Nevertheless, that covers the entirety of the code and this application. For a more detailed code breakdown, please check out the video from the ”How to Get the Token Balance of an Address Using Moralis’ Token API” section. Additionally, if you want to learn more about the Token API and the Moralis Token API endpoint used in this tutorial, please visit its official documentation page! Also, make sure to check out the Token API documentation page!
Summary – How to Get the Token Balance of an Address
In this article, you learned how to get the token balance of an address. We also showed you how to create a straightforward application from which users could input an address and receive its token balance in return. Furthermore, thanks to Moralis’ Token API, you were able to query the ERC-20 token balance of an address with only a couple of lines of code!
Moreover, we divided the tutorial into four main sections:
- Application Demo
- Prerequisites and Moralis Setup
- How to Set Up the Application
- Application Code Breakdown
By covering each part, you could set up the application allowing you to get the token balance of an address!
If you found this tutorial interesting, check out additional content here on the Moralis Web3 blog. For topics similar to this article, read our articles on how to get all tokens owned by a wallet and get the balance of an ERC20 token. Also, explore the ultimate ERC20 token API and the best ERC20 token balance API! In addition, learn how Web3 data storage works or read up on all you need to know about ethers.js!
What’s more, if you are serious about getting into Web3 development, sign up with Moralis right away. With Moralis and tools such as Moralis’ Web3 APIs, you can leverage the power of blockchain technology to its fullest!
Read More: moralis.io