Do you wish to know the way to get all tokens owned by a pockets? If that’s the case, you might be in the fitting place, as this tutorial demonstrates how to take action utilizing Moralis! Because of Moralis’ Token API, you will get all tokens owned by a pockets in 5 simple steps:
- Create a mission
- Set up Moralis by operating the next command within the terminal:
npm set up moralis @moralisweb3/common-evm-utils
- Arrange a brand new file
- Enter the next contents (add a Moralis API key, tackle, and the specified chain):
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();
- Name the ”getWalletTokenBalances” endpoint by operating this system with this terminal command:
node “FILE_NAME”
When you execute this system, you obtain a response containing all tokens owned by the required pockets. It ought to look one thing like this:
{ "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, "stability": "24109691515670000000000" }
For extra info, take a look at the official endpoint documentation to get the stability by pockets!
Overview
Creating decentralized purposes (dapps) and different Web3 initiatives requires related on-chain information. As such, Web3 builders desperately want a fast and efficient technique to question blockchain networks, which is the place Moralis enters the equation. With Moralis’ Web3 APIs, you possibly can seamlessly question any blockchain for information and obtain real-time responses. To reveal the accessibility of Moralis, we’ll on this article present you the way to use the Token API to get all tokens owned by a pockets. If this sounds attention-grabbing, be a part of us on this tutorial, as we’ll cowl this course of from begin to end!
To indicate you ways Moralis’ Token API works in apply, the article demonstrates the way to construct an software the place customers can enter an tackle and click on on a button to question the pockets’s token stability. Nonetheless, earlier than diving deeper into the central half, the article briefly recaps what a token pockets is. So, if you’re already accustomed to token wallets, be at liberty to skip straight into the ”Software Demo” part.
What’s extra, the Token API is just one of many instruments Moralis provides. There are a number of different outstanding options to find, which we suggest you do if you’re critical about moving into Web3 growth. For instance, take a look at the Auth API, permitting you to seamlessly combine blockchain-based authentication into your initiatives with solely single strains of code. If this sounds attention-grabbing, you possibly can, as an example, learn to add an indication in with RainbowKit!
Nonetheless, it doesn’t matter what blockchain growth endeavor you embark on, enroll with Moralis now to leverage the total potential of blockchain know-how!
What’s a Token Pockets?
If you wish to get into the Web3 area, step one is to amass a token pockets. Folks use token wallets to retailer digital belongings corresponding to fungible and non-fungible tokens (NFTs). Together with the power to carry belongings, token wallets additionally typically characteristic further performance. Amongst different issues, this contains sending, shopping for, promoting, and swapping belongings. In flip, you possibly can absolutely handle your digital belongings by a token pockets.
Together with offering a straightforward technique to handle your belongings, token wallets open the door to the blockchain realm. Accordingly, wallets are gateways to the Web3 ecosystem, enabling anybody to work together with dapps and platforms on varied blockchain networks. As such, token wallets play an important position in blockchain!
Listed here are some outstanding examples of token pockets suppliers that you would be able to take into account:
- MetaMask
- Coinbase Pockets
- Phantom
- Argent
- Belief Pockets
What’s extra, if you wish to study extra about token wallets, take a look at our information right here on the Web3 weblog exploring Web3 wallets!
Nonetheless, now that you’re extra accustomed to token wallets, it’s nearly time to dive into the central a part of this tutorial. Nonetheless, earlier than doing so, we offer a fast demo of the applying you’ll study to create on this article!
Get All Tokens Owned by a Pockets – Software Demo
This tutorial teaches you the way to create an easy NextJS software from which customers can get all tokens owned by a pockets. That mentioned, earlier than leaping into the tutorial, this part gives a fast software demo. By masking the intricacies of the app, you achieve a greater understanding of what you might be working in direction of!
Nonetheless, you could find a screenshot of the app’s touchdown web page down beneath:
The appliance options three fundamental parts: a heading, an enter subject, and a ”Submit” button. The sphere takes a Web3 pockets tackle as enter, and when you click on on the ”Submit” button, it returns a desk presenting all tokens owned by the required pockets:
Because the picture above illustrates, the app returns the thumbnail, title, and USD stability for all tokens inside the pockets. Nonetheless, Moralis’ Token API gives further info, corresponding to every token’s tackle and image. (we’ve simply determined to not show this info on the app’s person interface [UI]).
If you wish to learn to construct this software, be a part of us within the following part, the place we present you the way to get all tokens owned by a pockets in solely 5 simple steps!
5-Step Breakdown – How you can Get All Tokens Owned By a Pockets
With a extra profound understanding of what you might be working in direction of, it’s time to present you the way to get all tokens owned by a pockets. Furthermore, to take action, the next sections educate you the way to create an easy NextJS software the place you possibly can enter an tackle and get all tokens from a specified pockets in return. What’s extra, due to Moralis’ Token API, it is possible for you to to create this software in solely 5 straightforwards steps:
- Finishing Conditions and Setting Up a Moralis Account
- Get Your Moralis API Key
- Mission Setup
- Code Breakdown: ”index.js” and ”header.js”
- Code Breakdown: ”fundamental.js”
By finishing the steps above, you’ll find out how Moralis’ Token API works and the way to get all tokens owned by a pockets. By the tip of this tutorial, you’ll have the data so as to add related performance to your future dapps!
Nonetheless, with out additional ado, allow us to soar straight into step one and canopy the required stipulations!
Step 1: Finishing Conditions and Setting Up a Moralis Account
To kick issues off, you initially must cope with a few stipulations on this first step. Particularly, it’s good to guarantee that you’ve got put in NodeJS and npm. You may get these two parts by visiting the NodeJS web site and putting in the latest model.
Together with NodeJS and npm, you have to enroll with Moralis. If in case you have not already, create a Moralis account proper now. Organising an account solely takes a few minutes and is totally free!
Step 2: Get Your Moralis API Key
The principle cause why it’s good to enroll with Moralis is that you just want entry to an API key. As we beforehand talked about, you’ll use Moralis’ Token API to get all tokens owned by a pockets. However, to work together with the assorted endpoints of this API, you want a Moralis Web3 API key. So, the place are you able to get one?
After getting an account at your disposal, log in to the Moralis admin panel. Click on on the ”Web3 APIs” tab and find your API key. What’s extra, go forward and duplicate the API key by clicking on the ”Copy” button, as you want the important thing for the following step:
Step 3: Mission Setup
On this third step, it’s time to arrange the applying. To make this tutorial as accessible as attainable, we’ll use an already pre-made mission. You will see that the entire software code within the GitHub repository down beneath:
Get All Tokens Owned by a Pockets Repo – https://github.com/MoralisWeb3/youtube-tutorials/tree/fundamental/get-any-wallets-token-balance
You’ll be able to open the repository and clone the mission to your native listing. Doing so ought to give you a neighborhood copy of the code, and you must end up with a file construction much like the one within the picture beneath:
From right here, open a brand new terminal, ”cd” into the mission’s root folder, and run the command beneath to put in the Moralis SDK:
npm set up moralis @moralisweb3/common-evm-utils
Subsequent up, create a brand new file referred to as ”.env.native” and add an atmosphere variable on your Moralis API key. It ought to look one thing like this (substitute “YOUR_API_KEY” with the precise key):
NEXT_PUBLIC_MORALIS_API_KEY=”YOUR_API_KEY”
That covers the required steps in making the applying operational. Nonetheless, we have now but to clarify how the applying works or how one can get all tokens. As such, we break down the code within the following two steps and discover the applying logic in additional element. This gives perception into how Moralis’ Token API works, permitting you to make use of the identical elementary ideas for any future Web3 initiatives!
Step 4: Code Breakdown: ”index.js” & ”header.js”
With a neighborhood copy of the mission at your disposal and the required configurations all full, we’ll take the next part to discover two information: ”index.js” and ”header.js”. So, allow us to kick issues off by diving into the code of the ”index.js” file!
- ”index.js” – The code contained inside the ”index.js” file is accountable for rendering the app’s homepage. The contents of the file are comparatively simple, and it seems like this:
import Head from "subsequent/head"; import kinds from "../kinds/House.module.css"; import Header from "../parts/header"; import Essential from "../parts/fundamental"; export default perform House() { return ( <part className={kinds.container}> <Head> <title>Get Token Value</title> <meta title="description" content material="Generated by create subsequent app" /> <hyperlink rel="icon" href="https://moralis.io/favicon.ico" /> </Head> <fundamental className={kinds.fundamental}> <Header /> <Essential /> </fundamental> </part> ); }
On the backside of the file, you can see the code accountable for rendering two parts: ”Header” and ”Essential”, which make up the 2 further information we’ll dive deeper into. So, let’s progress by taking a quick have a look at ”header.js”.
- ”header.js” – The code of the ”header.js” file is sort of simple and is solely accountable for the app’s title and brand displayed on the UI:
import Picture from "subsequent/picture"; import kinds from "../kinds/House.module.css"; import Emblem from "../public/belongings/Moralis_logo.png"; export default perform Header() { return ( <part className={kinds.header}> <Picture src={Emblem} alt="Emblem picture" width="102" top="82" /> <h1 className={kinds.title}>Get Any Pockets's Token Stability</h1> </part> ); }
Within the subsequent step, we’ll dive into ”fundamental.js”, which is the place we discover the applying logic!
Step 5: Code Breakdown: ”fundamental.js”
The ”fundamental.js” file incorporates the logic for the applying and the code enabling us to get all tokens owned by a pockets. This one is sort of intensive if we examine it to the opposite information we noticed within the earlier step. Consequently, we’ll break up the file into smaller sections and give attention to the core elements, making it simpler to observe alongside. So, to start with, allow us to briefly cowl the preliminary 4 strains of the file:
import { useState } from "react"; const Moralis = require("moralis").default; const { EvmChain } = require("@moralisweb3/common-evm-utils"); import kinds from "../kinds/House.module.css";
These preliminary strains are accountable for the required imports. That is additionally the place you put in Moralis and the EVM utils. Following the imports, the rest of the code is the ”header()” perform. This perform does, in flip, characteristic ”handleSubmit()”, containing the logic for buying the tokens owned by a pockets:
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 the ”handleSubmit()” perform, you purchase the pockets tackle from the UI, which we retailer within the ”tackle” variable. Subsequent, the code specifying the ”chain” variable to equal ”evmChain.ETHEREUM” signifies that you just wish to question an tackle on the Ethereum community.
From there, the code initializes Moralis utilizing the ”Moralis.begin()” perform, passing your API key as an argument. Lastly, by the ”getWalletTokenBalances()” perform, you name the Moralis Token API endpoint and retailer the leads to the ”response” variable.
The rest of the code renders the app’s UI components and decides what information to show to the customers:
return ( <part className={kinds.fundamental}> <type className={kinds.getTokenForm} title="create-profile-form" technique="POST" motion="#" > <label className={kinds.label} htmlFor="walletAddress"> Add ERC20 Pockets Tackle </label> <enter className={kinds.walletAddress} sort="textual content" id="walletAddress" title="walletAddress" maxLength="120" required /> </type> <button className={kinds.form_btn} onClick={handleSubmit}> Submit </button> <part className={kinds.outcome}> {showResult && outcome.map((token) => { return ( <part className={kinds.tokenContainer} key={outcome.indexOf(token)} > <img src={token.thumbnail} /> <p className={kinds.title}>{token.title}</p> <p className={kinds.quantity}> {(token.stability / 10 ** token.decimals).toFixed(2)} </p> </part> ); })} </part> </part> );
That covers the central a part of the applying code! For a extra detailed breakdown, take a look at the video from Moralis’ YouTube channel beneath. On this clip, you can see a video tutorial masking your complete course of in additional element:
As well as, take a look at the official “getWalletTokenBalances” endpoint documentation and the entire Token API documentation for extra details about the Token API and the endpoint used on this tutorial!
Get All Tokens Owned by a Pockets – Abstract
On this article, you noticed the way to get all tokens owned by a pockets, due to Moralis’ Token API. To indicate this API in motion, the article demonstrated the way to create an easy NextJS dapp permitting anybody to question a pockets’s token stability based mostly on its tackle. What’s extra, due to the accessibility of Moralis, you had been capable of create this app in solely 5 steps:
- Finishing Conditions and Setting Up a Moralis Account
- Get Your Moralis API Key
- Mission Setup
- Code Breakdown: ”index.js” & ”header.js”
- Code Breakdown: ”fundamental.js”
Should you discovered this text useful, there are different thrilling guides so that you can take a look at on Moralis’ Web3 weblog. For instance, discover the intricacies of Ethereum webhooks or learn to get NFT collections utilizing Python! Furthermore, if Ethereum growth pursuits you probably the most, take a look at our articles exploring the way to get the stability of ERC20 tokens, the last word ERC20 token API, and the very best ERC20 token stability API for dapp growth!
Nonetheless, if you wish to absolutely leverage the facility of blockchain, enroll with Moralis instantly. You’ll be able to arrange your account without spending a dime, and it solely takes seconds, so you don’t have anything to lose!