Saturday, August 9, 2025
No Result
View All Result
Crypeto News
Smarter_way_USA
  • Home
  • Bitcoin
  • Crypto Updates
    • General
    • Blockchain
    • Ethereum
    • Altcoin
    • Mining
    • Crypto Exchanges
  • NFT
  • DeFi
  • Web3
  • Metaverse
  • Analysis
  • Regulations
  • Scam Alert
  • Videos
CRYPTO MARKETCAP
  • Home
  • Bitcoin
  • Crypto Updates
    • General
    • Blockchain
    • Ethereum
    • Altcoin
    • Mining
    • Crypto Exchanges
  • NFT
  • DeFi
  • Web3
  • Metaverse
  • Analysis
  • Regulations
  • Scam Alert
  • Videos
CRYPTO MARKETCAP
Crypeto News
No Result
View All Result

How to Get the Token Balance of an Address – Moralis Web3

by crypetonews
December 12, 2022
in Web3
Reading Time: 12 mins read
0 0
A A
0
Home Web3
Share on FacebookShare on Twitter


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: 

metamask user interface showing token balance address

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! 

three coins falling from the sky, ethereum, solana, and bitcoin

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 DemoPrerequisites and Moralis SetupHow to Set Up the ApplicationApplication 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! 

moralis

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: 

application landing page with the title get any wallets token balance

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

application page showing input field to enter in a wallet address and also showing the submit button

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: 

web3 api page on the moralis admin panel

Go ahead and copy the API key, as you need to add it to the code later on in this tutorial: 

arrow pointing at the copy button for a user api key

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: 

code structure inside visual studio code

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 DemoPrerequisites and Moralis SetupHow to Set Up the ApplicationApplication 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! 

moralis blog landing page

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!



Source link

Tags: AddressBalanceMoralisTokenWeb3
Previous Post

Decentralized Finance Protocols Flounder as Value Locked in Defi Shed More Than 25% Since FTX Collapsed – Defi Bitcoin News

Next Post

Thoma Bravo Acquires Business Spend Management Firm Coupa Software for $8 Billion

Related Posts

Ronin API – Build on Ronin with Moralis
Web3

Ronin API – Build on Ronin with Moralis

May 28, 2025
How to Build NFT Apps on Solana
Web3

How to Build NFT Apps on Solana

May 23, 2025
Solana NFT API – Exploring the Top 2025 NFT API for Solana
Web3

Solana NFT API – Exploring the Top 2025 NFT API for Solana

May 21, 2025
Get Solana Whales – How to Fetch Top Whales of a Solana Token
Web3

Get Solana Whales – How to Fetch Top Whales of a Solana Token

May 19, 2025
Neobank App Development – How to Build a Web3 Neobank
Web3

Neobank App Development – How to Build a Web3 Neobank

May 16, 2025
How to Get Top Solana Token Holders
Web3

How to Get Top Solana Token Holders

May 14, 2025
Next Post
Thoma Bravo Acquires Business Spend Management Firm Coupa Software for  Billion

Thoma Bravo Acquires Business Spend Management Firm Coupa Software for $8 Billion

🥵Binance क्या money laundering करता है? 🙄बंद की खबर 😳| Binance News Today | Cryptocurrency

🥵Binance क्या money laundering करता है? 🙄बंद की खबर 😳| Binance News Today | Cryptocurrency

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

RECOMMENDED

Power to the people: London’s National Gallery seeks public panel to help shape its future – The Art Newspaper
NFT

Power to the people: London’s National Gallery seeks public panel to help shape its future – The Art Newspaper

by crypetonews
August 6, 2025
0

The National Gallery in London is transforming its governance model by introducing a citizens' assembly made up of members of...

Analyst Shares Where Bitcoin, Ethereum, And XRP Prices Will Be By 2032

Analyst Shares Where Bitcoin, Ethereum, And XRP Prices Will Be By 2032

August 8, 2025
Clearing, trend-setting gallery with New York and Los Angeles locations, will close – The Art Newspaper

Clearing, trend-setting gallery with New York and Los Angeles locations, will close – The Art Newspaper

August 7, 2025
Whale Buys 300 Bitcoins Daily Despite Market Crash

Whale Buys 300 Bitcoins Daily Despite Market Crash

August 3, 2025
Financial Officers At Billion-Dollar Firms Are Planning To Adopt Crypto — Here are The Stats

Financial Officers At Billion-Dollar Firms Are Planning To Adopt Crypto — Here are The Stats

August 2, 2025
US Bitcoin miners face 21% rig cost surge after Trump’s tariff goes live

US Bitcoin miners face 21% rig cost surge after Trump’s tariff goes live

August 7, 2025

Please enter CoinGecko Free Api Key to get this plugin works.
  • Trending
  • Comments
  • Latest
Top 10 NFTs to Watch in 2025 for High-Return Investments

Top 10 NFTs to Watch in 2025 for High-Return Investments

November 22, 2024
Uniswap v4 Teases Major Updates for 2025

Uniswap v4 Teases Major Updates for 2025

January 2, 2025
Enforceable Human-Readable Transactions: Can They Prevent Bybit-Style Hacks?

Enforceable Human-Readable Transactions: Can They Prevent Bybit-Style Hacks?

February 27, 2025
Best Cryptocurrency Portfolio Tracker Apps to Use in 2025

Best Cryptocurrency Portfolio Tracker Apps to Use in 2025

April 24, 2025
What’s the Difference Between Polygon PoS vs Polygon zkEVM?

What’s the Difference Between Polygon PoS vs Polygon zkEVM?

November 20, 2023
FTT jumps 7% as Backpack launches platform to help FTX victims liquidate claims

FTT jumps 7% as Backpack launches platform to help FTX victims liquidate claims

July 18, 2025
XRP Official CRYPTO VOTE LIVE NEWS!🔴GENIUS, CLARITY Act

XRP Official CRYPTO VOTE LIVE NEWS!🔴GENIUS, CLARITY Act

46
IMP UPDATE : BILLS PASSED || BITCOIN DOMINANCE FALLING

IMP UPDATE : BILLS PASSED || BITCOIN DOMINANCE FALLING

38
🚨BIG UPDATE ON WAZIRX || ALT COIN PORTFOLIO NO 1

🚨BIG UPDATE ON WAZIRX || ALT COIN PORTFOLIO NO 1

37
BITCOIN: IT'S HAPPENING NOW (Urgent Update)!!! Bitcoin News Today, Ethereum, Solana, XRP & Chainlink

BITCOIN: IT'S HAPPENING NOW (Urgent Update)!!! Bitcoin News Today, Ethereum, Solana, XRP & Chainlink

33
JUST IN XRP RIPPLE DUBAI NEWS!

JUST IN XRP RIPPLE DUBAI NEWS!

25
Flash USDT | How It Became the Biggest Crypto Scam Worldwide

Flash USDT | How It Became the Biggest Crypto Scam Worldwide

31
Ethereum Price Watch: Market Eyes Breakout Toward ,500 Target

Ethereum Price Watch: Market Eyes Breakout Toward $4,500 Target

August 9, 2025
Bitcoin–S&P 500 Correlation Hits 80%, Tying Crypto To Stocks

Bitcoin–S&P 500 Correlation Hits 80%, Tying Crypto To Stocks

August 9, 2025
Harvard Reveals 7M BlackRock Bitcoin ETF Stake In SEC Filing – Details

Harvard Reveals $117M BlackRock Bitcoin ETF Stake In SEC Filing – Details

August 9, 2025
CoinDesk Data: TRON Surpasses 0B in Monthly Stablecoin Transfers

CoinDesk Data: TRON Surpasses $600B in Monthly Stablecoin Transfers

August 9, 2025
SBI Clarifies XRP ETF Status With Filing Timed For Regulatory Breakthrough

SBI Clarifies XRP ETF Status With Filing Timed For Regulatory Breakthrough

August 9, 2025
I Asked ChatGPT’s New Agent What to Post Next — It Got 50,000 Views in 48 Hours

I Asked ChatGPT’s New Agent What to Post Next — It Got 50,000 Views in 48 Hours

August 9, 2025
Crypeto News

Find the latest Bitcoin, Ethereum, blockchain, crypto, Business, Fintech News, interviews, and price analysis at Crypeto News.

CATEGORIES

  • Altcoin
  • Analysis
  • Bitcoin
  • Blockchain
  • Crypto Exchanges
  • Crypto Updates
  • DeFi
  • Ethereum
  • Metaverse
  • Mining
  • NFT
  • Regulations
  • Scam Alert
  • Uncategorized
  • Videos
  • Web3

LATEST UPDATES

  • Ethereum Price Watch: Market Eyes Breakout Toward $4,500 Target
  • Bitcoin–S&P 500 Correlation Hits 80%, Tying Crypto To Stocks
  • Harvard Reveals $117M BlackRock Bitcoin ETF Stake In SEC Filing – Details
  • Disclaimer
  • Privacy Policy
  • DMCA
  • Cookie Privacy Policy
  • Terms and Conditions
  • Contact us

Copyright © 2022 Crypeto News.
Crypeto News is not responsible for the content of external sites.

No Result
View All Result
  • Home
  • Bitcoin
  • Crypto Updates
    • General
    • Blockchain
    • Ethereum
    • Altcoin
    • Mining
    • Crypto Exchanges
  • NFT
  • DeFi
  • Web3
  • Metaverse
  • Analysis
  • Regulations
  • Scam Alert
  • Videos

Copyright © 2022 Crypeto News.
Crypeto News is not responsible for the content of external sites.

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In