'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 1:[1]

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).

Solution 2:[2]

Following code worked to get the balance for SOL after Jon Cinque's answer (maybe helpful for others or future me):

const web3 = require("@solana/web3.js");
const { Keypair, Transaction, SystemProgram, LAMPORTS_PER_SOL, sendAndConfirmTransaction, clusterApiUrl } = require("@solana/web3.js");

let secretKey = Uint8Array.from([233, 65, ... (rest of my secret)]);

let fromKeypair = Keypair.fromSecretKey(secretKey);

let connection = new web3.Connection(clusterApiUrl('devnet'));

(async () => {

    const balance = await connection.getBalance(
        fromKeypair.publicKey
    );
    console.log(balance)
})()

Output: 7912350560 which is correct, since I have 7.912350560 SOL in that account.

But for the SPL Token it didn't work yet...

Solution 3:[3]

To get the list of foreign accounts with their balances, the following CLI command can be used:

$ spl-token accounts --owner <account owner's pubkey>
  • where <account owner's pubkey> is the public key or address of the wallet you want to get the info about.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jon C
Solution 2 G-Unit
Solution 3 Alexey Guryev