Sunday, March 26, 2023
No Result
View All Result
Blockchain Daily Report
Advertisement
  • HOME
  • BITCOIN
  • CRYPTO UPDATES
    • GENERAL
    • ALTCOINS
    • ETHEREUM
    • CRYPTO EXCHANGES
    • CRYPTO MINING
  • BLOCKCHAIN
  • NFT
  • DEFI
  • METAVERSE
  • WEB3
  • SCAM ALERT
  • REGULATIONS
  • ANALYSIS
Crypto Marketcap
  • HOME
  • BITCOIN
  • CRYPTO UPDATES
    • GENERAL
    • ALTCOINS
    • ETHEREUM
    • CRYPTO EXCHANGES
    • CRYPTO MINING
  • BLOCKCHAIN
  • NFT
  • DEFI
  • METAVERSE
  • WEB3
  • SCAM ALERT
  • REGULATIONS
  • ANALYSIS
Crypto Marketcap
Logo
No Result
View All Result
Home Web3

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

by Blockchain Daily Report
December 13, 2022
in Web3
Reading Time: 12 mins read
A A
0
How to Get the Token Balance of an Address – Moralis Web3
Share on FacebookShare on Twitter


Be part of us on this tutorial as we present you probably the most accessible technique to get the token steadiness of an tackle! In reality, with Moralis and the Token API, you’ll be able to question an tackle’ ERC-20 token steadiness in three steps: 

Create a undertaking and set up the Moralis SDK with the next terminal command:npm set up moralis @moralisweb3/common-evm-utils Arrange a brand new file and name the ”getWalletTokenBalances” endpoint with the next code (add your Moralis API key, an tackle, and the chain you need to question): const Moralis = require(‘moralis’).default;
const { EvmChain } = require(‘@moralisweb3/common-evm-utils’);

const runApp = async () => {
await Moralis.begin({
apiKey: “YOUR_API_KEY”,
// …and another configuration
});

const tackle=”0xBf6521AF44F5D56813A93dCE548E6594Daa00794″;

const chain = EvmChain.ETHEREUM;

const response = await Moralis.EvmApi.token.getWalletTokenBalances({
tackle,
chain,
});

console.log(response.toJSON());
}

runApp(); Execute this system by working the next command: node “FILE_NAME”

Should you comply with the steps above, it’s best to obtain a response much like the one proven under: 

{
“token_address”: “0xff20817765cb7f73d4bde2e66e067e58d11095c2”,
“title”: “Amp”,
“image”: “AMP”,
“brand”: “https://cdn.moralis.io/eth/0xff20817765cb7f73d4bde2e66e067e58d11095c2.png”,
“thumbnail”: “https://cdn.moralis.io/eth/0xff20817765cb7f73d4bde2e66e067e58d11095c2_thumb.png”,
“decimals”: 18,
“steadiness”: “24109691515670000000000”
}

For extra data concerning the ”getWalletTokenBalances” endpoint, take a look at Moralis’ official get steadiness by pockets documentation! 

Overview

On-chain information related to pockets addresses is significant data relating to Web3 growth. Many decentralized purposes (dapps) and platforms, together with DEXs, wallets, and many others., depend on data similar to token balances. Consequently, Web3 builders require straightforward and environment friendly methods to acquire such a blockchain information, which is the place Moralis enters the image! With Moralis’ Token API, you’ll be able to simply get the token steadiness of an tackle with only some strains of code. If you wish to study extra about this, be a part of us on this tutorial as we present you the simplest technique to question the ERC-20 steadiness of a pockets tackle! 

To start with, the article appears on the fundamentals to briefly define what a pockets tackle is and what the token steadiness of an tackle refers to. When you grasp these two simple ideas, we’ll leap straight into the central a part of this tutorial. From there, we’ll present you easy methods to create an utility for querying an tackle’ token steadiness! 

All through this tutorial, you’ll familiarize your self with the Token API. Nonetheless, that is merely one among Moralis’ varied Web3 APIs. One other outstanding instance you would possibly discover attention-grabbing is the Streams API. With this device, you’ll be able to effortlessly stream on-chain information into the backend of your Web3 tasks by way of Moralis webhooks. That mentioned, for this tutorial, you want a Moralis account. Thus, earlier than you progress ahead, enroll with Moralis instantly! 

What’s a Pockets Deal with? 

For the uninitiated, the preliminary two sections of this text will briefly discover the essential ideas of a pockets tackle and the token steadiness of an tackle. As such, if you’re already accustomed to these two parts, be at liberty to skip straight into the ”How you can Get the Token Steadiness of an Deal with…” part. In any other case, be a part of us as we begin this information by answering the query, ”what’s a pockets tackle?”.

A pockets tackle is a randomly generated string of letters and numbers related to a Web3 pockets. Pockets addresses are additionally usually known as public keys and could be shared, very similar to an electronic mail tackle. Furthermore, all blockchain wallets have distinctive addresses, appearing like account numbers the place different customers can ship property. Accordingly, it’s by way of pockets addresses that cryptocurrencies and NFTs could be despatched from one account to a different on blockchains. 

You’ll be able to usually discover your pockets tackle fairly simply by way of your pockets supplier’s consumer interface (UI), and so they can look one thing like this: ”0xd06Ffc9107649344e7….”. For instance, let’s take a fast take a look at MetaMask, one among at present’s most vital pockets suppliers. By logging in to your MetaMask account, you’ll be able to simply copy your pockets tackle by clicking on the button on the prime of the UI: 

metamask user interface showing token balance address

What’s the Token Steadiness of an Deal with? 

As this tutorial teaches you easy methods to get the token steadiness of an tackle, you could additionally perceive what an tackle’ token steadiness is. Happily, this isn’t that obscure, because it merely refers back to the tokens held by a pockets. Accordingly, the token steadiness of an tackle is all of the NFTs and fungible tokens held by the pockets to which the tackle refers! 

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

However, now that you’ve familiarized your self with what the token steadiness of an tackle refers to, it’s time to discover the central a part of this text. As such, be a part of us within the subsequent part, the place we illustrate easy methods to get the token steadiness of an tackle! 

How you can Get the Token Steadiness of an Deal with Utilizing Moralis’ Token API 

Within the following sections, you’ll discover ways to get the token steadiness of an tackle utilizing Moralis’ Token API. To display the accessibility of Moralis, we’ll present easy methods to arrange a simple NextJS utility implementing this performance. Consequently, by way of the app’s UI, you’ll be able to enter an tackle and question its ERC-20 token steadiness with the clicking of a button. What’s extra, to make the tutorial as straightforward as doable to comply with, it has been divided into the next 4 sections: 

Software DemoPrerequisites and Moralis SetupHow to Set Up the ApplicationApplication Code Breakdown

By the tip of this tutorial, you should have discovered easy methods to get the token steadiness of an tackle utilizing Moralis’ Token API. From there, you’ll be able to apply the identical elementary rules to future blockchain tasks to simply implement related performance! 

moralis

Should you would quite watch a video tutorial of the method, you’ll be able to take a look at the next clip from the Moralis YouTube channel. Within the video, a Moralis software program engineer walks you thru the complete course of and offers an in depth breakdown of the code: 

It’s also possible to be a part of us right here as we begin with a demo to point out you ways the appliance works! 

Software Demo 

To kick issues off, this part of the tutorial offers a quick demo of the appliance. Doing so will provide you with a extra profound understanding of what you’re working in the direction of. However, right here is the appliance’s touchdown web page: 

application landing page with the title get any wallets token balance

The consumer interface (UI) is comparatively simple. It comprises a heading, an enter discipline, and a ”Submit” button. To make use of the appliance, all that you must do is enter a sound pockets tackle into the enter discipline and hit ”Submit”. Doing so will generate a response much like the one under (relying on the pockets’s tokens):

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

Consequently, on this occasion, the appliance makes use of Moralis’ Token API to get the token steadiness of the tackle you provided and shows the tokens’ thumbnails, names, and balances in USD. Along with these parts, the API offers different varieties of information, such because the tokens’ addresses, symbols, and many others. Nonetheless, these are usually not displayed on the UI. 

If you wish to discover ways to create this utility, be a part of us within the following sections, the place we offer a complete walkthrough of the complete course of!

Stipulations and Moralis Setup 

Earlier than diving into the appliance code, there are a couple of stipulations that you must cope with. To start with, guarantee that you’ve NodeJS and npm arrange. Should you need assistance with this, go to the next web page to put in the most recent model of Node.js: https://nodejs.org/en/. 

Upon getting arrange NodeJS and npm, you could register for a Moralis account. So, you probably have not already, be a part of Moralis instantly. Becoming a member of Moralis is fully free and solely takes a few seconds. Nonetheless, you would possibly surprise, ”why do I would like a Moralis account?”. With a purpose to work together with the Token API and make calls, you want a Moralis API key. You could 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 forward and replica the API key, as that you must add it to the code afterward on this tutorial: 

arrow pointing at the copy button for a user api key

That covers the stipulations. From right here, it’s time to dive deeper into the appliance code!  

How you can Set Up the Software 

We are going to use an already pre-made utility template to make this tutorial as simple as doable. You could find the entire GitHub repository for the undertaking down under: 

Get Any Pockets Token Steadiness App Repo – https://github.com/MoralisWeb3/youtube-tutorials/tree/primary/get-any-wallets-token-balance

So, to start with, open the repository above and clone the undertaking to your native listing. With an area copy of the appliance, it’s best to now have a file construction much like the one proven under: 

code structure inside visual studio code

Should you examine your native listing, you’ll rapidly discover that the ”.env.native” file is lacking. Thus, be sure you create this file and add the contents under and substitute ”YOUR_API_KEY” with the important thing you copied within the earlier part:

NEXT_PUBLIC_MORALIS_API_KEY=”YOUR_API_KEY”

Lastly, run the next command to put in the Moralis SDK: 

npm set up moralis @moralisweb3/common-evm-utils

That’s truly all that you must do to make the appliance operational. Nonetheless, within the following part, we’ll break down the code to elucidate the logic in additional element. By instructing you ways the appliance works, you’ll be able to apply related rules in future growth endeavors. 

Software Code Breakdown 

This part will break down the important components of the code, together with the logic for easy methods to get the token steadiness of an tackle. Particularly, we’ll give attention to the next three recordsdata: ”index.js”, ”header.js”, and ”primary.js”.

”index.js” – The ”index.js” file comprises the code for the appliance’s homepage. It appears like this: import Head from “subsequent/head”;
import types from “../types/Dwelling.module.css”;

import Header from “../parts/header”;
import Foremost from “../parts/primary”;

export default operate Dwelling() {
return (
<part className={types.container}>
<Head>
<title>Get Token Worth</title>
<meta title=”description” content material=”Generated by create subsequent app” />
<hyperlink rel=”icon” href=”https://moralis.io/favicon.ico” />
</Head>

<primary className={types.primary}>
<Header />
<Foremost />
</primary>
</part>
);
}

As you’ll be able to see on the backside of the file, the code right here is answerable for rendering two parts, ”Header” and ”Foremost”: 

<primary className={types.primary}>
<Header />
<Foremost />
</primary>
</part>

Now, allow us to take a quick take a look at ”header.js”. 

”header.js” – This file is comparatively simple and comprises the code for the title and brand on the prime left of the appliance’s UI:import Picture from “subsequent/picture”;
import types from “../types/Dwelling.module.css”;

import Brand from “../public/property/Moralis_logo.png”;

export default operate Header() {
return (
<part className={types.header}>
<Picture src={Brand} alt=”Brand picture” width=”102″ top=”82″ />
<h1 className={types.title}>Get Any Pockets’s Token Steadiness</h1>
</part>
);
}

Lastly, we have now the ”primary.js” file. Nonetheless, this file is sort of in depth in comparison with the others, and that is the place we discover a lot of the logic wanted to get the token steadiness of an tackle. As such, this file deserves its personal sub-section! 

The ”primary.js” File   

In comparison with the 2 earlier recordsdata, ”primary.js” is comparatively in depth. Due to this fact, we’ve cut up the code into smaller components to make it simpler to comply with together with. As such, allow us to initially take a better take a look at the primary 4 strains of code: 

import { useState } from “react”;
const Moralis = require(“moralis”).default;
const { EvmChain } = require(“@moralisweb3/common-evm-utils”);
import types from “../types/Dwelling.module.css”;

This half is answerable for the required imports. That is additionally the place we set up Moralis and the widespread EVM utils. Furthermore, the rest of the code is the ”Header()” operate. That is the place the central logic for getting the token steadiness of an tackle is discovered within the ”handleSubmit()” operate: 

const handleSubmit = async () => {
tackle = doc.querySelector(“#walletAddress”).worth;
const chain = EvmChain.ETHEREUM;

await Moralis.begin({
apiKey: course of.env.NEXT_PUBLIC_MORALIS_API_KEY,
});

const response = await Moralis.EvmApi.token.getWalletTokenBalances({
tackle,
chain,
});

console.log(response.toJSON());
setResult(response.toJSON());
setShowResult(true);
doc.querySelector(“#walletAddress”).worth = “”;
};

Within the first a part of this operate, we get the tackle from the UI and retailer it within the ”tackle” variable. From there, we set the ”chain” variable to Ethereum. Subsequent up, we initialize Moralis with the ”Moralis.begin()” operate utilizing the API key from the ”.env.native” file. Lastly, we name Moralis’ ”getWalletTokenBalances()” operate, passing the ”tackle” and ”chain” variables as arguments. The returned data is saved within the ”response” variable, offering entry to all of the tokens held by the pockets tackle inputted by the consumer. 

From there, the final a part of the code is answerable for rendering the weather of the UI. That is additionally the place we determine what data to show to the consumer:  

return (
<part className={types.primary}>
<type
className={types.getTokenForm}
title=”create-profile-form”
technique=”POST”
motion=”#”
>
<label className={types.label} htmlFor=”walletAddress”>
Add ERC20 Pockets Deal with
</label>
<enter
className={types.walletAddress}
kind=”textual content”
id=”walletAddress”
title=”walletAddress”
maxLength=”120″
required
/>
</type>
<button className={types.form_btn} onClick={handleSubmit}>
Submit
</button>
<part className={types.outcome}>
{showResult &&
outcome.map((token) => {
return (
<part
className={types.tokenContainer}
key={outcome.indexOf(token)}
>
<img src={token.thumbnail} />
<p className={types.title}>{token.title}</p>
<p className={types.quantity}>
{(token.steadiness / 10 ** token.decimals).toFixed(2)}
</p>
</part>
);
})}
</part>
</part>
);

However, that covers the whole thing of the code and this utility. For a extra detailed code breakdown, please take a look at the video from the ”How you can Get the Token Steadiness of an Deal with Utilizing Moralis’ Token API” part. Moreover, if you wish to study extra in regards to the Token API and the Moralis Token API endpoint used on this tutorial, please go to its official documentation web page! Additionally, make sure that to take a look at the Token API documentation web page!

Abstract – How you can Get the Token Steadiness of an Deal with

On this article, you discovered easy methods to get the token steadiness of an tackle. We additionally confirmed you easy methods to create a simple utility from which customers may enter an tackle and obtain its token steadiness in return. Moreover, because of Moralis’ Token API, you have been capable of question the ERC-20 token steadiness of an tackle with solely a few strains of code! 

Furthermore, we divided the tutorial into 4 primary sections: 

Software DemoPrerequisites and Moralis SetupHow to Set Up the ApplicationApplication Code Breakdown

By protecting every half, you could possibly arrange the appliance permitting you to get the token steadiness of an tackle! 

Should you discovered this tutorial attention-grabbing, take a look at further content material right here on the Moralis Web3 weblog. For subjects much like this text, learn our articles on easy methods to get all tokens owned by a pockets and get the steadiness of an ERC20 token. Additionally, discover the final word ERC20 token API and the perfect ERC20 token steadiness API! As well as, learn the way Web3 information storage works or learn up on all that you must find out about ethers.js! 

moralis blog landing page

What’s extra, if you’re severe about entering into Web3 growth, enroll with Moralis immediately. With Moralis and instruments similar to Moralis’ Web3 APIs, you’ll be able to leverage the ability of blockchain expertise to its fullest!



Source link

Tags: AddressBalanceMoralistokenWeb3
Share76Tweet47

Related Posts

Hong Kong blockchain initiatives natural evolution for finance hub, says Signum Digital CEO

Hong Kong blockchain initiatives natural evolution for finance hub, says Signum Digital CEO

by Blockchain Daily Report
March 24, 2023
0

After the worldwide crypto failures and bankruptcies in 2022 and China’s recognized distaste for cryptocurrencies, Hong Kong regulators stunned with...

Hong Kong poised for ambitious changes

Hong Kong poised for ambitious changes

by Blockchain Daily Report
March 23, 2023
0

Welcome to Future Guidelines, March 23, 2023 – introduced by Joel Flynn.2023 is shaping as much as be a yr...

How DAOs can be remade to be more successful

How DAOs can be remade to be more successful

by Blockchain Daily Report
March 23, 2023
0

Centralized crypto finance took a beating over the past 12 months.However the folks and buyers who relied on centralized constructions...

How to Get a Wallet Balance on Aptos

How to Get a Wallet Balance on Aptos

by Blockchain Daily Report
March 23, 2023
0

Discover the best method to get a pockets steadiness on Aptos with the Web3 Information API from Moralis. With this...

Get Crypto Data Using a Python API for Cryptocurrency

Get Crypto Data Using a Python API for Cryptocurrency

by Blockchain Daily Report
March 22, 2023
0

This tutorial will educate you to make use of the Python-compatible Web3 Knowledge API from Moralis to tug cryptocurrency costs,...

Load More
  • Trending
  • Comments
  • Latest
Mine CLORE Coins Used by the CLORE.AI Distributed Computing Platform

Mine CLORE Coins Used by the CLORE.AI Distributed Computing Platform

January 23, 2023
WildRig Multi 0.36.4 beta Now With Faster NEXA Performance and Lower Fee

WildRig Multi 0.36.4 beta Now With Faster NEXA Performance and Lower Fee

January 23, 2023
Credit Suisse, UBS, Other Banks Facing Russia Sanctions Probe in US, Report – Bitcoin News

Credit Suisse, UBS, Other Banks Facing Russia Sanctions Probe in US, Report – Bitcoin News

March 25, 2023
Arbitrum’s Governance Token ARB Ranks Within Top 40 Market Capitalizations Following Airdrop – Bitcoin News

Arbitrum’s Governance Token ARB Ranks Within Top 40 Market Capitalizations Following Airdrop – Bitcoin News

March 25, 2023
Bitcoin Hashrate Hits 400 EH/s As Miners Profit From Bull Market

Bitcoin Hashrate Hits 400 EH/s As Miners Profit From Bull Market

March 25, 2023
Bitcoin Difficulty Increases for Third Time in Six Weeks, Miners Remain Undeterred With High Hashrate – Mining Bitcoin News

Bitcoin Difficulty Increases for Third Time in Six Weeks, Miners Remain Undeterred With High Hashrate – Mining Bitcoin News

March 25, 2023
RIP WRAPPED PUNK 685 | NFT CULTURE | NFT News | Web3 Culture

RIP WRAPPED PUNK 685 | NFT CULTURE | NFT News | Web3 Culture

March 25, 2023
Billionaire VC Tim Draper Tells Businesses To Keep Payroll In Bitcoin

Billionaire VC Tim Draper Tells Businesses To Keep Payroll In Bitcoin

March 25, 2023
BTC Fall Towards $27,000 to Start the Weekend – Market Updates Bitcoin News

BTC Fall Towards $27,000 to Start the Weekend – Market Updates Bitcoin News

March 25, 2023
Crypto scams, exploits down 71% YoY as $370M lost since January

Crypto scams, exploits down 71% YoY as $370M lost since January

March 25, 2023
Facebook Twitter Instagram Youtube RSS

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

CATEGORIES

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

SITE MAP

  • Disclaimer
  • Privacy Policy
  • DMCA
  • Cookie Privacy Policy
  • Terms and Conditions
  • Contact us

Copyright © 2022 Blockchain Daily Report.
Blockchain Daily Report is not responsible for the content of external sites.

No Result
View All Result
  • HOME
  • BITCOIN
  • CRYPTO UPDATES
    • GENERAL
    • ALTCOINS
    • ETHEREUM
    • CRYPTO EXCHANGES
    • CRYPTO MINING
  • BLOCKCHAIN
  • NFT
  • DEFI
  • METAVERSE
  • WEB3
  • SCAM ALERT
  • REGULATIONS
  • ANALYSIS

Copyright © 2022 Blockchain Daily Report.
Blockchain Daily Report is not responsible for the content of external sites.

  • bitcoinBitcoin(BTC)$27,797.000.69%
  • ethereumEthereum(ETH)$1,764.810.24%
  • USDEXUSDEX(USDEX)$1.07-0.53%
  • tetherTether(USDT)$1.010.08%
  • binancecoinBNB(BNB)$325.980.40%
  • usd-coinUSD Coin(USDC)$1.010.30%
  • rippleXRP(XRP)$0.4529286.43%
  • cardanoCardano(ADA)$0.355838-1.62%
  • dogecoinDogecoin(DOGE)$0.074819-0.58%
  • staked-etherLido Staked Ether(STETH)$1,762.630.20%