March 20, 2023

How to Get an Address’ Token Balance on Solana

Table of Contents
https://www.youtube.com/watch?v=A31n28GjwHE

When you use next-gen Web3 tools, you can effortlessly implement essential features into your Solana dapps. For example, thanks to the Solana API from Moralis, you can get the token balance on Solana for a specific address with just a few lines of code. So, if you’d like to bypass the cumbersome process of coding such a feature from scratch, Moralis is your go-to option! In fact, if you decide to use Moralis, you can use the following core lines of code to get an address’ token balance on Solana:

  • First, you need to initialize Moralis using your Web3 API key:
await Moralis.start({
  apiKey: process.env.MORALIS_API_KEY,
});
  • Second, you need to utilize the getSPL endpoint: 
const data = await Moralis.SolApi.account.getSPL({
  address,
  network,
});

The above two snippets of code are the essence of getting addresses’ token balances on Solana the easy way. Of course, there’s some surrounding code that you need to put in place to make this feature function properly. So, if you wish to learn how to properly implement the getSPL Solana Token API endpoint, follow our lead. You can watch the video at the top or complete the tutorial below, which covers a simple three-step process to get token balance on Solana. Whichever option you choose, you’ll need your Web3 API key, which awaits you in the Moralis admin area. Therefore, make sure to sign up with Moralis now!

get token balance on Solana - sign up with Moralis

Overview

Below, you can find two primary sections: “Tutorial: Get Token Balance on Solana with a Simple Backend Script” and “Get Any Token Balance on Solana with Our Example Dapp”. The first is our three-step tutorial demonstrating how to get SPL token balances with minimum fuss using JavaScript, TypeScript, or Python. 

The three steps are as follows:

  1. Moralis Setup – Here, we look at various commands you can use to set up the Moralis SDK.
  2. Get an Address’ SPL Token Balance – This section presents the parameters and their respective options, whether you want to focus on the mainnet or devnet. In addition, we look at how to get token balance using JavaScript, TypeScript, and Python.
  3. Run Your Script – In this section, you finally get to run your script to get the token balance of a specific Solana address.

On the other hand, the second section focuses on our example project around the primary endpoint. This example project uses the same principles as covered in the tutorial but also includes a simple HTML frontend. The latter enables you to experience the power of the getSPL endpoint in your browser.  

get token balance on Solana - using the getSPL endpoint

Tutorial: Get Token Balance on Solana with a Simple Backend Script

Before we jump into the first step of this tutorial, make sure to take care of the following prerequisites:

  • Download and install NodeJS v.14 or higher if you wish to get a token balance on Solana with JavaScript or TypeScript. You can also install Python if you prefer to work with that language.
  • Install your favorite package manager (NPM, Yarn, or PIP).
  • Make sure you have a reliable code editor ready. We prefer to use Visual Studio Code (VSC).

With the above prerequisites under your belt, you’re ready to jump into the first step of this tutorial. 

Step 1: Moralis Setup 

If you haven’t created your Moralis account yet, do it now. A free account is all you need to complete this tutorial and access all Moralis API endpoints. However, if you are serious about your Web3 development and wish to build dapps that easily support a lot of traffic, you should get a Moralis Pro, Business, or Enterprise plan.

Now that you have your Moralis account ready, you are able to access your admin area. This is where you can visit the “Web3 APIs” page and copy your API key:

Note: For now, hold on to your API key – we’ll tell you where to paste it in the second step.   

To use Moralis, you also need to install the Moralis SDK. So, use one of the following commands that match your package manager:

  • NPM:
npm install moralis @moralisweb3/common-sol-utils
  • Yarn:
yarn add moralis @moralisweb3/common-sol-utils
  • PIP:
pip install moralis

Step 2: Get an Address’ SPL Token Balance

At this point, you already know that the easiest way to get token balance on Solana is by using the getSPL endpoint. As indicated in the snippet of code in the intro, this endpoint takes in two parameters: network and address. The first one has two options: mainnet or devnet – the second one accepts any Solana address. So, for the sake of this tutorial, you can decide to focus either on the Solana mainnet or devnet:

Note: If you are unfamiliar with the Solana devnet, we encourage you to use the link to get some experience with this network.   

As for the Solana address, we recommend going with your Solana wallet address. Of course, feel free to use our example address provided in the upcoming scripts. Moving forward, we will walk you through our JavaScript and Python scripts. The TS script is pretty similar to the JavaScript one. Thus, we will simply provide you with the final code. 

Note: You can explore the details of the “getSPL” endpoint and even take it for a spin by visiting the “Get token balance by wallet” API reference page.    

Get SPL Token Balances with JavaScript

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

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

Next, create a runApp async function. At the top of it, initialize Moralis:

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

Looking at the above code snippet, you can see the YOUR_API_KEY placeholder. Make sure to replace it with the above-obtained API key. 

Note: When creating production-ready dapps, you want to use a “.env” file to store your API key and other environmental variables. In that case, you replace the above apiKey line with apiKey: process.env.MORALIS_API_KEY. You can learn more about that in the video at the top (3:00). 

Within runApp, you also need to define the address and network parameters:

const address = "BWeBmN8zYDXgx2tnGj72cA533GZEWAVeqR9Eu29txaen";

const network = SolNetwork.MAINNET;

Feel free to replace the above address with any Solana address you want. Also, you can replace MAINNET with DEVNET if you wish to focus on the latter. By doing so, you can expect transactions of free testnet assets that you get to obtain from a vetted Solana testnet faucet

Finally, you get to implement the Moralis.SolApi.account.getSPL method from the intro. Below the method, you also need to console-log the response in JSON format and run the runApp function:

const response = await Moralis.SolApi.account.getSPL({
  address,
  network,
});

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

runApp();

So, this is the complete JS script that lets you get token balance on Solana:

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

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

  const address = "BWeBmN8zYDXgx2tnGj72cA533GZEWAVeqR9Eu29txaen";

  const network = SolNetwork.MAINNET;

  const response = await Moralis.SolApi.account.getSPL({
    address,
    network,
  });

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

runApp();

Get SPL Token Balances with TypeScript

The following is the complete TypeScript version of the above script (the only difference is how it imports Moralis [the top two lines]). So, paste it in a new “index.ts” script:

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

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

  const address = "BWeBmN8zYDXgx2tnGj72cA533GZEWAVeqR9Eu29txaen";

  const network = SolNetwork.MAINNET;

  const response = await Moralis.SolApi.account.getSPL({
    address,
    network,
  });

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

runApp();

Get SPL Token Balances with Python

If you decide to use Python to get token balances on Solana, create a new “index.py” file and start by importing Moralis:

from moralis import sol_api

Next, define the api_key variable and the two endpoint parameters:

api_key = "YOUR_API_KEY"
params = {
    "network": "mainnet",
    "address": "BWeBmN8zYDXgx2tnGj72cA533GZEWAVeqR9Eu29txaen",
}

Finally, you call the sol_api.account.get_spl method and assign it to results. Plus, you want to return the results:

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

print(result)

This is the Python script that you get if you put all of the above snippets of code together:

from moralis import sol_api

api_key = "YOUR_API_KEY"
params = {
    "network": "mainnet",
    "address": "BWeBmN8zYDXgx2tnGj72cA533GZEWAVeqR9Eu29txaen",
}

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

print(result)

Step 3: Run Your Script

At this point, you should have one of the above scripts in place. As such, it’s time to run your script and get token balance on Solana for the address you used. So, depending on the programming language, use the matching command:

  • JavaScript:
node index.js
  • TypeScript:
ts-node index.ts
  • Python:
python index.py

After running one of the above commands, look at your terminal for the response. Here’s the JSON response for our example address on the Solana mainnet:

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

Get Any Token Balance on Solana with Our Example Dapp

The above screenshot demonstrates our example dapp’s frontend, having a similar backend as the one presented above. You can see that our frontend has an input field where users get to paste any Solana wallet address. It also allows users to choose whether they want to focus on the Solana mainnet or devnet. With an address in place and a network selected – if you remember from the above tutorial are the two parameters that the getSPL endpoint takes as inputs – users get to click on the “Get Token Balance” button to view the results:

Looking at the above image, you can see that results come in the same format as in the above tutorial. As such, they include the following five details:

  • associatedTokenAddress – A record in the Solana ledger that either holds data or is an executable program (e.g., Solana smart contract) for the token in question.
  • mint – An address that stores the metadata of a token. 
  • amountRaw – The amount of the associated tokens with decimal places included. 
  • amount – The amount of tokens excluding the decimal places.
  • decimals – The number of decimal places. 

Note: The getSPL endpoint also returns the token name and symbol if those details are provided.

To better understand the above results, let’s use Solana Explorer to search for the associatedTokenAddress of the above example’s top result:

As you can see, this is a Solana on-chain account, and its owner address is the wallet address we entered in the search field in the above example. You also see that this account provides details about the number of tokens. To access the token’s metadata, we need to use the mint address:

So, based on the response of the getSPL endpoint, you can access a wide range of details.

Build Your Own Instance of Our Example Dapp and More

If you wish to create your own instance of the above-presented dapp and take it for a spin yourself, access the “solana-api-demo” GitHub repo. Then, you’ll easily cover the three core aspects of creating our example dapp:

  1. Obtaining your Moralis Web3 API key and using it to initialize Moralis.
  2. Using the getSPL endpoint to fetch the latest on-chain data fast.
  3. Define an API route in the backend and call the API route on the frontend.

On the above-linked repo, you’ll find all the frontend and backend scripts enabling you to get token balance on Solana in minutes. When it comes to the backend, you can choose between the Solana Python API and NodeJS. Plus, the scripts there include all other Moralis Solana API endpoints – you can find them listed below: 

  • NFT API:
    • Get NFTs by wallet
    • Get NFT metadata
  • Token API:
    • Get token price
  • Balance API:
    • Get native balance, token balance, and portfolio by wallet

With the above set of Solana API endpoints, you can build all sorts of dapps on this popular network. Some of the most common use cases include NFT marketplaces, crypto wallets, portfolio trackers, auditing and reporting, metaverse gaming, block explorers, token gating (NFT authentication), etc.

How to Get an Address’ Token Balance on Solana – Summary

In today’s article, we focused on the getSPL endpoint, enabling you to get token balance on Solana with minimum effort. By following the three-step process in our beginner-friendly tutorial, you were able to create a simple backend script. Whichever programming languages you focused on, you had to obtain your Moralis Web3 API key, which is your ticket to easy Web3 development. In addition to the tutorial, we also showed you our neat demo dapp. We even provided you with the link to our repo so that you can easily create your own instance of our dapp and test all Moralis Solana API endpoints in your browser.

Herein, you obtained all the information you need to start creating Solana dapps the easy way. With your Web3 API key and the Moralis docs, you are fully equipped to create unique dapps on Solana or any other leading blockchain. After all, Moralis is all about cross-chain interoperability. 

However, if you need some additional inspiration, guidance, or more information about Web3 development, you ought to explore the Moralis YouTube channel and Moralis blog. Aside from countless tutorials, these are the places to get acquainted with blockchain and Web3 concepts. For instance, some of the latest articles explore zk-rollup projects, Alchemy’s Notify Custom Webhooks, how and where to buy ENS domains, and much more. All in all, our videos and articles can help you become a Web3 developer for free. That said, you may be interested in taking a more professional approach to your crypto education. In that case, we recommend enrolling in Moralis Academy. There, you can train your individual skills or your entire team and get blockchain certified!

Moralis Money
Stay ahead of the markets with real-time, on-chain data insights. Inform your trades with true market alpha!
Moralis Money
Related Articles
November 17, 2023

How to Add the Sepolia Network to MetaMask – Full Guide

November 11, 2022

The Easiest Way to Create NFTs on Solana

December 16, 2022

How to Call a Smart Contract Function from JavaScript

September 28, 2023

Full BSC Node Guide – How to Run BNB Smart Chain Nodes

August 12, 2022

Moralis Projects – Web3 Magic Treasure Chest

March 13, 2023

Buy ENS Domain – Where to Buy ETH Domains

February 12, 2024

Build on OP Mainnet – Full 2024 Guide

September 28, 2022

How to Connect MetaMask to Website with NextJS

November 6, 2023

Base Faucet – How to Get Free BASE Crypto Testnet Funds