メインコンテンツへスキップ

Five Ways to Check the Balance of a Solana SPL Token Account

更新日:
2025年11月26日

読了時間:7分

概要

If you plan to build a DeFi protocol, wallet, NFT platform, or any type of payment application on Solana, you will need to be able to check the balance of a Solana SPL token account. In this guide, we will walk through five easy ways to check the balance of an SPL token account:

必要なもの

依存関係バージョン
solana-cli1.16.14
spl-token-cli3.1.1
node.js16.15
curl8.1.12
@solana/web3.js1.78.5
@solana/spl-token0.3.7
solana-sdk1.16.14
solana-client1.6.14
貨物1.69.0
Solanaの基礎:クラスター

Before querying our token account, let's do a quick recap on Solana's clusters, as we will need to specify a specific cluster when checking a wallet's balance. "A Solana cluster is a set of validators working together to serve client transactions and maintain the integrity of the ledger. Many clusters may coexist." (Source: docs.solana.com/cluster/overview). In fact, Solana maintains three clusters that each serve different purposes:

  • メインネットベータ:実際のトークンが使用される本番環境かつ許可不要な環境
  • Devnet:Solanaアプリケーションをテストするアプリケーション開発者向けのテスト環境(Devnet上のトークンは架空のものであり、金銭的価値はありません)。Devnetでは通常、Mainnet Betaと同じソフトウェアリリースが実行されています。
  • テストネット:Solanaのコアコントリビューターやバリデーターが、ネットワークのパフォーマンス検証に重点を置いて、新しいアップデートや機能のストレステストを行う環境(テストネット上のトークンは実在するものではなく、金銭的価値もありません)

出典:docs.solana.com/clusters

For this guide, we will use メインネット・ベータ, but you should know that a wallet can have a balance on each cluster simultaneously.

Our first method is to check the balance of a wallet using Solana SPL-Token CLI. If you do not already have it installed, follow the instructions for your operating environment at spl.solana.com/token. To make sure your installation was successful, open a new terminal and type:

spl-token --version

次のような画面が表示されるはずです:

「Solana CLI のバージョン確認」

You're ready to go! All you need to do is get your token account address handy--if you do not know your token account address, check out our Guide: Five Ways to Find the Associated Token Address for a Solana Wallet and Mint.

ターミナルで、次のコマンドを入力してウォレットの残高を確認してください:

spl-token balance --address YOUR_TOKEN_ACCOUNT_ADDRESS -um
Solanaの基礎:クラスター

検索条件を変更することで、さまざまなクラスターにおけるそのウォレットの残高を確認できます。 -u (URL for Solana's JSON RPC) option. We have used -um to ensure we are searching on Solana's mainnet. To get a devnet or testnet balance, try:

spl-token balance --address YOUR_TOKEN_ACCOUNT_ADDRESS -u devnet # for Devnet
# or
spl-token balance --address YOUR_TOKEN_ACCOUNT_ADDRESS -u testnet # for Testnet

These default clusters (mainnet-beta, testnet, devnet) are public JSON RPC endpoints. If you plan to do a lot of queries or build on Solana, you will probably want an endpoint of your own.


See why over 50% of projects on Solana choose Quicknode and sign up for a free account here. You will want a mainnet node to query a wallet's true balance:

「Solana メインネットのエンドポイント」

これで、クエリを修正して、ご自身のエンドポイントを使用できるようになりました:

spl-token balance --address YOUR_TOKEN_ACCOUNT_ADDRESS -u https://example.solana.quiknode.pro/000000/

「Solana CLI の結果」

よくやった!

ターミナルで、以下のコマンドを実行して、新しいプロジェクトディレクトリと「balance.js」というファイルを作成してください。

mkdir token-address && cd token-address && echo > balance.js

Solana Web3 の依存関係をインストールします:

yarn init -y
yarn add @solana/web3.js@1

または

npm init -y
npm install --save @solana/web3.js@1

Open balance.js in a code editor of choice, and on line 1, require @solana/web3.js. We will deconstruct the Connection and PublicKey classes from this package.

const { Connection, PublicKey } = require('@solana/web3.js');

On lines 3-5, define your wallet, mint, and the relevant programs (Token Program and Associated Token Program):

const QUICKNODE_RPC = 'https://example.solana.quiknode.pro/000000/'; // 👈 Replace with your Quicknode Endpoint OR clusterApiUrl('mainnet-beta')
const SOLANA_CONNECTION = new Connection(QUICKNODE_RPC);
const TOKEN_ADDRESS = new PublicKey('YOUR_TOKEN_ACCOUNT_ADDRESS'); //👈 Replace with your wallet address

Finally, fetch your address by creating and calling a new function, getTokenBalanceWeb3() that invokes the getTokenAccountBalance method on the 接続 class:

async function getTokenBalanceWeb3(connection, tokenAccount) {
const info = await connection.getTokenAccountBalance(tokenAccount);
if (info.value.uiAmount == null) throw new Error('No balance found');
console.log('Balance (using Solana-Web3.js): ', info.value.uiAmount);
return info.value.uiAmount;
}

getTokenBalanceWeb3(SOLANA_CONNECTION, TOKEN_ADDRESS).catch(err => console.log(err));

The returned value includes 金額 そして uiAmount. その 金額 response includes extra decimals based on the token mint. This is because Solana stores decimals as integers on chain to avoid floating-point math. The uiAmount response is the 金額 divided by the mint decimals. For example, if the 金額 is 1000000000 and the mint decimals value is 9, the uiAmount will be 1. If the 金額 is 1000000000 and the mint decimals value is 6, the uiAmount will be 1000.

コードを実行してください。ターミナルで次のように入力してください。

ノードのバランス

次のような画面が表示されるはずです:

「Solana-Web3.js の結果」

よくやったね!

The Solana SPL Token API makes this process a little easier. Let's look at how we can fetch the address of an associated token account using the SPL Token API.

First, install the SPL Token Program:

yarn add @solana/spl-token

または

npm install --save @solana/spl-token

開く balance.js, and on line 1 (before our previous import), require @solana/spl-token. We will deconstruct the getAccount そして getMint methods from this package.

const { getAccount, getMint } = require('@solana/spl-token');

Now, at the bottom of your script, create and call a new function, getTokenBalanceSpl that will fetch your token account and then fetch the mint associated with that token account (for handling decimals):

async function getTokenBalanceSpl(connection, tokenAccount) {
const info = await getAccount(connection, tokenAccount);
const amount = Number(info.amount);
const mint = await getMint(connection, info.mint);
const balance = amount / (10 ** mint.decimals);
console.log('Balance (using Solana-Web3.js): ', balance);
return balance;
}

getTokenBalanceSpl(SOLANA_CONNECTION, TOKEN_ADDRESS).catch(err => console.log(err));

Though this method is a little more verbose, it is a great way to get the balance of a token account and handle decimals. Note that we must convert the 金額 returned from our getAccount call to a number (as the returned value is a bigint) and that we must fetch our token mint details to get our decimals (which we then use to divide our 金額 by to get our balance).

コードを実行してください。ターミナルで次のように入力してください。

ノードのバランス

You should see both methods return the same balance:

'Solana Token Program Results'

よくやったね!

cURL は、URL を使用してデータを転送するためのコマンドラインツールおよびライブラリです。ほとんどの *nix 系システムでは、cURL が標準でサポートされています。以下のコマンドを実行して、cURL がインストールされているかどうかを確認してください:

curl -h

まだインストールしていない場合は、curl.seにアクセスしてセットアップしてください。

Once you are ready, all you need to do is drop this HTTP request in your terminal (make sure to replace your endpoint and token account address). In your terminal, enter:

curl https://docs-demo.solana-mainnet.quiknode.pro/ \
-X POST \
-H "Content-Type: application/json" \
--data '{"jsonrpc":"2.0", "id":1, "method":"getTokenAccountBalance", "params": ["YOUR_TOKEN_ACCOUNT_ADDRESS"]}'

次のような画面が表示されるはずです:

「SolanaのcURL実行結果」 Note: You may utilize a package like jq to return formatted JSON data if you prefer.

Notice the same balance is returned in the result.value.uiAmount field 🙌. Check out our ドキュメント for more information on the getTokenAccountBalance メソッド。

Rust開発者の方は、Solana Rust SDKも利用できます。プロジェクトフォルダ内で、次のコマンドを実行して新しいプロジェクトを作成してください:

cargo new token-balance

新しく作成したディレクトリに移動します:

cd token-balance

Cargo.tomlファイルに必要な依存関係を追加してください:

[依存関係]
solana-sdk = "1.16.14"
solana-client = "1.6.14"

src/main.rs を開き、1行目で必要なパッケージをインポートします:

use solana_sdk::公開鍵::公開鍵;
use solana_client::rpc_client::RpcClient;
use std::str::FromStr;

On lines 5-6, define your token account address:

const TOKEN_ADDRESS: &str = "YOUR_TOKEN_ADDRESS";

最後に、あなたの メイン function that will fetch your address by passing the public keys of your owner and mint into the get_token_account_balance メソッド:

fn main() {
let associated_token_address = Pubkey::from_str(TOKEN_ADDRESS).unwrap();
let connection = RpcClient::new("https://example.solana.quiknode.pro/000000/".to_string()); // 👈 Replace with your Quicknode Endpoint
let account_data = connection.get_token_account_balance(&associated_token_address).unwrap();
println!("Token Balance (using Rust): {}", account_data.ui_amount_string);
}

コードをコンパイルして実行してください。ターミナルで次のように入力してください。

cargo build
cargo run

And you should see your same token address returned:

'Solana Rust Results'

よくやったね!

まとめ

Nice work! You now have five useful tools for fetching the balance of a Solana SPL Token Account. If you are just getting started with your Solana journey, here are some resources that may be helpful:

皆さんが開発中のプロジェクトについて、ぜひ詳しくお聞かせください。Discordでメッセージを送っていただくか、Twitterをフォローして、最新情報をチェックしてください!

皆様からのフィードバックを心よりお待ちしております!❤️

ご意見や新しいトピックに関するご要望などがありましたら、ぜひお知らせください。皆様からのご連絡を心よりお待ちしております。

このガイドをシェアする