Search code examples
blockchainsolana

Solana - How to get token balance for a foreign account?


In Solana you can get your own balance with the CLI

$ spl-token accounts

But how do I get the token balance of a foreign account if I have the account ID or his pubkey? When I use the solana explorer I can see the information I need when I search for the foreign account ID and then click on the Tokens tab (next to "History"): https://explorer.solana.com/address/DNuqHBGxzm96VLkLWCUctjYW9CX68DBY6jQ1cVuYP2Ai/tokens?cluster=devnet

So if the explorer website can do it, everybody can, all info on the blockchain is public, right?


Solution

  • That's right, everything is indeed public, so if you want to get the balance for someone else's account, you can simply use getBalance if it's SOL (https://docs.solana.com/developing/clients/jsonrpc-api#getbalance) or getTokenAccountBalance if it's an SPL Token account (https://docs.solana.com/developing/clients/jsonrpc-api#gettokenaccountbalance).