Sunday, June 4, 2023
  • English (Global)
  • 中文(香港)
SUBSCRIBE TO NEWSLETTER
Crypto News Global
No Result
View All Result
  • HOME
  • BITCOIN
  • CRYPTO UPDATES
    • GENERAL
    • ETHEREUM
    • ALTCOINS
    • CRYPTO EXCHANGES
    • CRYPTO MINING
  • BLOCKCHAIN
  • NFT
  • METAVERSE
  • WEB3
  • ANALYSIS
  • SCAM ALERT
  • REGULATIONS
CRYPTO MARKET CAP
  • HOME
  • BITCOIN
  • CRYPTO UPDATES
    • GENERAL
    • ETHEREUM
    • ALTCOINS
    • CRYPTO EXCHANGES
    • CRYPTO MINING
  • BLOCKCHAIN
  • NFT
  • METAVERSE
  • WEB3
  • ANALYSIS
  • SCAM ALERT
  • REGULATIONS
No Result
View All Result
Crypto News Global
No Result
View All Result
Home Web3

How to Get an Address’ Token Balance on Solana

by Crypto News Global
March 20, 2023
in Web3
Reading Time: 13 mins read
A A
0
Share on FacebookShare on Twitter


If you use next-gen Web3 instruments, you’ll be able to effortlessly implement important options into your Solana dapps. For instance, due to the Solana API from Moralis, you may get the token stability on Solana for a selected deal with with only a few traces of code. So, in case you’d wish to bypass the cumbersome means of coding such a characteristic from scratch, Moralis is your go-to choice! The truth is, in case you determine to make use of Moralis, you should use the next core traces of code to get an deal with’ token stability on Solana:

  • First, it’s essential to initialize Moralis utilizing your Web3 API key:
await Moralis.begin({
  apiKey: course of.env.MORALIS_API_KEY,
});
  • Second, it’s essential to make the most of the getSPL endpoint: 
const information = await Moralis.SolApi.account.getSPL({
  deal with,
  community,
});

The above two snippets of code are the essence of getting addresses’ token balances on Solana the straightforward means. In fact, there’s some surrounding code that it’s essential to put in place to make this characteristic operate correctly. So, in case you want to learn to correctly implement the getSPL Solana Token API endpoint, observe our lead. You may watch the video on the prime or full the tutorial under, which covers a easy three-step course of to get token stability on Solana. Whichever choice you select, you’ll want your Web3 API key, which awaits you within the Moralis admin space. Subsequently, be certain that to enroll with Moralis now!

get token balance on Solana - sign up with Moralis

Overview

Beneath, you’ll find two main sections: “Tutorial: Get Token Steadiness on Solana with a Easy Backend Script” and “Get Any Token Steadiness on Solana with Our Instance Dapp”. The primary is our three-step tutorial demonstrating get SPL token balances with minimal fuss utilizing JavaScript, TypeScript, or Python. 

The three steps are as follows:

  1. Moralis Setup – Right here, we have a look at numerous instructions you should use to arrange the Moralis SDK.
  2. Get an Deal with’ SPL Token Steadiness – This part presents the parameters and their respective choices, whether or not you need to give attention to the mainnet or devnet. As well as, we have a look at get token stability utilizing JavaScript, TypeScript, and Python.
  3. Run Your Script – On this part, you lastly get to run your script to get the token stability of a selected Solana deal with.

Alternatively, the second part focuses on our instance mission across the main endpoint. This instance mission makes use of the identical rules as lined within the tutorial but additionally features a easy HTML frontend. The latter lets you expertise the ability of the getSPL endpoint in your browser.  

get token balance on Solana - using the getSPL endpoint

Tutorial: Get Token Steadiness on Solana with a Easy Backend Script

Earlier than we bounce into step one of this tutorial, be certain that to care for the next conditions:

  • Obtain and set up NodeJS v.14 or increased in case you want to get a token stability on Solana with JavaScript or TypeScript. It’s also possible to set up Python in case you desire to work with that language.
  • Set up your favourite package deal supervisor (NPM, Yarn, or PIP).
  • Ensure you have a dependable code editor prepared. We desire to make use of Visible Studio Code (VSC).

With the above conditions below your belt, you’re prepared to leap into step one of this tutorial. 

Step 1: Moralis Setup 

In the event you haven’t created your Moralis account but, do it now. A free account is all it’s essential to full this tutorial and entry all Moralis API endpoints. Nonetheless, if you’re severe about your Web3 improvement and want to construct dapps that simply assist loads of site visitors, it’s best to get a Moralis Professional, Enterprise, or Enterprise plan.

Now that you’ve your Moralis account prepared, you’ll be able to entry your admin space. That is the place you’ll be able to go to the “Web3 APIs” web page and replica your API key:

Notice: For now, maintain on to your API key – we’ll let you know the place to stick it within the second step.   

To make use of Moralis, you additionally want to put in the Moralis SDK. So, use one of many following instructions that match your package deal supervisor:

npm set up moralis @moralisweb3/common-sol-utils
yarn add moralis @moralisweb3/common-sol-utils
pip set up moralis

Step 2: Get an Deal with’ SPL Token Steadiness

At this level, you already know that the simplest technique to get token stability on Solana is by utilizing the getSPL endpoint. As indicated within the snippet of code within the intro, this endpoint takes in two parameters: community and deal with. The primary one has two choices: mainnet or devnet – the second accepts any Solana deal with. So, for the sake of this tutorial, you’ll be able to determine to focus both on the Solana mainnet or devnet:

Notice: If you’re unfamiliar with the Solana devnet, we encourage you to make use of the hyperlink to get some expertise with this community.   

As for the Solana deal with, we advocate going together with your Solana pockets deal with. In fact, be happy to make use of our instance deal with supplied within the upcoming scripts. Shifting ahead, we are going to stroll you thru our JavaScript and Python scripts. The TS script is fairly much like the JavaScript one. Thus, we are going to merely offer you the ultimate code. 

Notice: You may discover the small print of the “getSPL” endpoint and even take it for a spin by visiting the “Get token stability by pockets” API reference web page.    

Get SPL Token Balances with JavaScript

Create a brand new “index.js” file and first import moralis and sol-utils:

const Moralis = require("moralis").default;
const { SolNetwork } = require("@moralisweb3/common-sol-utils");

Subsequent, create a runApp async operate. On the prime of it, initialize Moralis:

const runApp = async () => {
  await Moralis.begin({
    apiKey: "YOUR_API_KEY",
});

Trying on the above code snippet, you’ll be able to see the YOUR_API_KEY placeholder. Be certain to switch it with the above-obtained API key. 

Notice: When creating production-ready dapps, you need to use a “.env” file to retailer your API key and different environmental variables. In that case, you exchange the above apiKey line with apiKey: course of.env.MORALIS_API_KEY. You may study extra about that within the video on the prime (3:00). 

Inside runApp, you additionally have to outline the deal with and community parameters:

const deal with = "BWeBmN8zYDXgx2tnGj72cA533GZEWAVeqR9Eu29txaen";

const community = SolNetwork.MAINNET;

Be happy to switch the above deal with with any Solana deal with you need. Additionally, you’ll be able to exchange MAINNET with DEVNET in case you want to give attention to the latter. By doing so, you’ll be able to count on transactions of free testnet belongings that you just get to acquire from a vetted Solana testnet faucet. 

Lastly, you get to implement the Moralis.SolApi.account.getSPL technique from the intro. Beneath the tactic, you additionally have to console-log the response in JSON format and run the runApp operate:

const response = await Moralis.SolApi.account.getSPL({
  deal with,
  community,
});

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

runApp();

So, that is the entire JS script that permits you to get token stability on Solana:

const Moralis = require("moralis").default;
const { SolNetwork } = require("@moralisweb3/common-sol-utils");

const runApp = async () => {
  await Moralis.begin({
    apiKey: "YOUR_API_KEY",
  });

  const deal with = "BWeBmN8zYDXgx2tnGj72cA533GZEWAVeqR9Eu29txaen";

  const community = SolNetwork.MAINNET;

  const response = await Moralis.SolApi.account.getSPL({
    deal with,
    community,
  });

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

runApp();

Get SPL Token Balances with TypeScript

The next is the entire TypeScript model of the above script (the one distinction is the way it imports Moralis [the top two lines]). So, paste it in a brand new “index.ts” script:

import Moralis from "moralis";
import { SolNetwork } from "@moralisweb3/common-sol-utils";

const runApp = async () => {
  await Moralis.begin({
    apiKey: "YOUR_API_KEY",
  });

  const deal with = "BWeBmN8zYDXgx2tnGj72cA533GZEWAVeqR9Eu29txaen";

  const community = SolNetwork.MAINNET;

  const response = await Moralis.SolApi.account.getSPL({
    deal with,
    community,
  });

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

runApp();

Get SPL Token Balances with Python

In the event you determine to make use of Python to get token balances on Solana, create a brand new “index.py” file and begin by importing Moralis:

from moralis import sol_api

Subsequent, outline the api_key variable and the 2 endpoint parameters:

api_key = "YOUR_API_KEY"
params = {
    "community": "mainnet",
    "deal with": "BWeBmN8zYDXgx2tnGj72cA533GZEWAVeqR9Eu29txaen",
}

Lastly, you name the sol_api.account.get_spl technique and assign it to outcomes. Plus, you need to return the outcomes:

consequence = sol_api.account.get_spl(
    api_key=api_key,
    params=params,
)

print(consequence)

That is the Python script that you just get in case you put the entire above snippets of code collectively:

from moralis import sol_api

api_key = "YOUR_API_KEY"
params = {
    "community": "mainnet",
    "deal with": "BWeBmN8zYDXgx2tnGj72cA533GZEWAVeqR9Eu29txaen",
}

consequence = sol_api.account.get_spl(
    api_key=api_key,
    params=params,
)

print(consequence)

Step 3: Run Your Script

At this level, it’s best to have one of many above scripts in place. As such, it’s time to run your script and get token stability on Solana for the deal with you used. So, relying on the programming language, use the matching command:

node index.js
ts-node index.ts
python index.py

After working one of many above instructions, have a look at your terminal for the response. Right here’s the JSON response for our instance deal with on the Solana mainnet:

[
  {
    "associatedTokenAddress": "Dpmpwm93Amvj4uEFpYhjv8ZzfpgARq6zxKTi6mrj97gW",
    "mint": "BXWuzb3jEuGsGUe29xdApu8Z3jVgrFbr3wWdsZmLWYk9",
    "amountRaw": "100000000000",
    "amount": "100",
    "decimals": "9"
  }
]

Get Any Token Steadiness on Solana with Our Instance Dapp

The above screenshot demonstrates our instance dapp’s frontend, having the same backend because the one introduced above. You may see that our frontend has an enter area the place customers get to stick any Solana pockets deal with. It additionally permits customers to decide on whether or not they need to give attention to the Solana mainnet or devnet. With an deal with in place and a community chosen – in case you bear in mind from the above tutorial are the 2 parameters that the getSPL endpoint takes as inputs – customers get to click on on the “Get Token Steadiness” button to view the outcomes:

Trying on the above picture, you’ll be able to see that outcomes are available in the identical format as within the above tutorial. As such, they embody the next 5 particulars:

  • associatedTokenAddress – A file within the Solana ledger that both holds information or is an executable program (e.g., Solana good contract) for the token in query.
  • mint – An deal with that shops the metadata of a token. 
  • amountRaw – The quantity of the related tokens with decimal locations included. 
  • quantity – The quantity of tokens excluding the decimal locations.
  • decimals – The variety of decimal locations. 

Notice: The getSPL endpoint additionally returns the token title and image if these particulars are supplied.

To higher perceive the above outcomes, let’s use Solana Explorer to seek for the associatedTokenAddress of the above instance’s prime consequence:

As you’ll be able to see, this can be a Solana on-chain account, and its proprietor deal with is the pockets deal with we entered within the search area within the above instance. You additionally see that this account gives particulars concerning the variety of tokens. To entry the token’s metadata, we have to use the mint deal with:

So, based mostly on the response of the getSPL endpoint, you’ll be able to entry a variety of particulars.

Construct Your Personal Occasion of Our Instance Dapp and Extra

In the event you want to create your personal occasion of the above-presented dapp and take it for a spin your self, entry the “solana-api-demo” GitHub repo. Then, you’ll simply cowl the three core points of making our instance dapp:

  1. Acquiring your Moralis Web3 API key and utilizing it to initialize Moralis.
  2. Utilizing the getSPL endpoint to fetch the newest on-chain information quick.
  3. Outline an API route within the backend and name the API route on the frontend.

On the above-linked repo, you’ll discover all of the frontend and backend scripts enabling you to get token stability on Solana in minutes. With regards to the backend, you’ll be able to select between the Solana Python API and NodeJS. Plus, the scripts there embody all different Moralis Solana API endpoints – you’ll find them listed under: 

  • NFT API:
    • Get NFTs by pockets
    • Get NFT metadata
  • Token API:
  • Steadiness API:
    • Get native stability, token stability, and portfolio by pockets

With the above set of Solana API endpoints, you’ll be able to construct all kinds of dapps on this widespread community. A number of the most typical use circumstances embody NFT marketplaces, crypto wallets, portfolio trackers, auditing and reporting, metaverse gaming, block explorers, token gating (NFT authentication), and many others.

Find out how to Get an Deal with’ Token Steadiness on Solana – Abstract

In at the moment’s article, we targeted on the getSPL endpoint, enabling you to get token stability on Solana with minimal effort. By following the three-step course of in our beginner-friendly tutorial, you have been in a position to create a easy backend script. Whichever programming languages you targeted on, you needed to receive your Moralis Web3 API key, which is your ticket to straightforward Web3 improvement. Along with the tutorial, we additionally confirmed you our neat demo dapp. We even supplied you with the hyperlink to our repo so as to simply create your personal occasion of our dapp and check all Moralis Solana API endpoints in your browser.

Herein, you obtained all the data it’s essential to begin creating Solana dapps the straightforward means. Along with your Web3 API key and the Moralis docs, you might be totally outfitted to create distinctive dapps on Solana or some other main blockchain. In any case, Moralis is all about cross-chain interoperability. 

Nonetheless, in case you want some further inspiration, steerage, or extra details about Web3 improvement, you should discover the Moralis YouTube channel and Moralis weblog. Apart from numerous tutorials, these are the locations to get acquainted with blockchain and Web3 ideas. As an illustration, a few of the newest articles discover zk-rollup tasks, Alchemy’s Notify Customized Webhooks, how and the place to purchase ENS domains, and way more. All in all, our movies and articles will help you grow to be a Web3 developer without cost. That mentioned, it’s possible you’ll be taken with taking a extra skilled strategy to your crypto training. In that case, we advocate enrolling in Moralis Academy. There, you’ll be able to practice your particular person abilities or your complete staff and get blockchain licensed!



Source link

Related articles

Private ID verification wins Binance Web3 reality show

June 2, 2023

Web3 gaming gets competitive edge as Maniac Panda Games joins Cointelegraph Accelerator

June 3, 2023
Tags: AddressBalancebitcoin newscrypto analysisCrypto NewsCrypto News GlobalLaest crypto newsSolanaToken
Share76Tweet47

Related Posts

Private ID verification wins Binance Web3 reality show

by Crypto News Global
June 2, 2023
0

Crypto change Binance has introduced the winner of its Web3 actuality present, titled “Construct the Block,” held within the metaverse....

Web3 gaming gets competitive edge as Maniac Panda Games joins Cointelegraph Accelerator

by Crypto News Global
June 3, 2023
0

Because the Web3 gaming panorama is getting greater by the day, mainstream gamers who get pleasure from taking part in...

Mysten Labs’ Sui network partners with F1 Red Bull racing team

by Crypto News Global
June 3, 2023
0

The Sui community, backed by Mysten Labs, has introduced a multiyear partnership with the Pink Bull Components One Racing crew...

What’s next for crypto miners after US debt ceiling deal?

by Crypto News Global
June 1, 2023
0

On this problemUS crypto mining tax: No dealNFT lending: Awash with competitorsBeijing and Web3: Pink scorching ambitionsFrom the editor’s deskExpensive...

Stop shoving crypto ‘down people’s throats’ — Pudgy Penguins CEO on NFTs

by Crypto News Global
June 1, 2023
0

The CEO of Pudgy Penguins — a nonfungible token undertaking that not too long ago launched a line of “phygitals”...

Load More

Leave a Reply Cancel reply

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

  • Trending
  • Comments
  • Latest

Istituto Marangoni Opens Talent District Metaverse

June 24, 2022

Dave Ramsey Dismisses De-Dollarization Concerns — Says BRICS Currency, Chinese Yuan Can’t Take Down US Dollar – Economics Bitcoin News

May 10, 2023

Coinbase’s Base announces mainnet plans as Aave community expresses interest

May 25, 2023

Big News from XR Awards, Microsoft, Meta, and Sony

May 26, 2023

Palm Beach art dealer sentenced to over two years in prison for blue-chip art fraud scheme

May 31, 2023

NFTs and Big Brands: Exploring new possibilities

June 3, 2023

Polkadot (DOT) Price Prediction 2023 2024 2025 2026

June 4, 2023

Ethereum-Based Cross-Chain Trading Platform Emerges As New Front Runner in Decentralized App Space: DappRadar

June 4, 2023

Musk’s alleged price manipulation, the Satoshi AI chatbot and more

June 3, 2023

Hollywood needs Web3, not vice versa

June 3, 2023

Don’t blame memecoins and degens for crypto’s credibility problem

June 3, 2023

FTX files objection to Genesis after being snubbed in $0.00 claim estimate

June 3, 2023

As DigiToads is On Track to Raise $5 Million in Presale, Aave and Polkadot Struggle for New Investors

June 3, 2023

Bitcoin miner fees stay elevated, boosting daily revenue to $1.8M

June 4, 2023

Get the free newsletter

Facebook Instagram Twitter LinkedIn Tumblr RSS
Crypto News Global

Find the latest Bitcoin, Trending Crypto Updates, Altcoins, Blockchain, NFTs, Crypto Regulations, Interviews, Price Analysis, and more at Crypto News Global.

CATEGORIES

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

SITE MAP

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

Copyright © 2022 - Crypto News Global.
Crypto News Global is not responsible for the content of external sites.

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

Copyright © 2022 - Crypto News Global.
Crypto News Global is not responsible for the content of external sites.