services
Get a key

library / Use cases / UC0005

Wallet token holdings

A wallet's token mints live in its token accounts, under two token programs. Two RPC reads list them and a Node script groups them by mint. The answer counts empty accounts apart and leaves out names, history and live updates.

By Carbium · Wallet products · UC0005 · updated 2026-11-22

01

Mints live in token accounts

A wallet address does not store its tokens. Each token a wallet holds sits in a separate token account that records the mint, the owner and an amount. To list a wallet's mints you list the token accounts it owns and read the mint field of each. A wallet with 40 tokens owns at least 40 token accounts.

Two token programs create these accounts: the original Token program and Token-2022. A mint belongs to one of them, and an account lives under the program of its mint. A listing that asks only the original program misses every Token-2022 mint, and the wallet screen looks short with no error to explain why. So the job is two reads, one per program, merged by mint.

A wallet is free to own more than one account for the same mint. The mint list is therefore a group-by, and the sum of the amounts per mint is the balance.

02

The read and its cost

The method is getTokenAccountsByOwner with the owner and a programId filter. The script asks for jsonParsed encoding, so the mint and the amount come back as fields and nothing needs layout decoding. Every call goes to https://services.carbium.sh with the key in the x-api-key header. The code builds one client from createDefaultRpcTransport and createSolanaRpcFromTransport and reuses it for each read.

Each wallet costs two reads against your plan's req/s, so size that before you put the call behind a page many users open at once. For comparison with other account reads, getAccountInfo and getTokenAccountBalance cost 10 cells each, and getMultipleAccounts charges 10 cells per pubkey and takes up to 300 pubkeys (100 below Pro).

03

A script in one file

Run it with one or more wallet addresses. For each wallet it sends one read per token program in parallel, groups the accounts by mint and sums the amounts as integers. It prints the count of mints with a balance and the count with only empty accounts, then the first 15 mints with a balance. It reads CARBIUM_KEY and exits with a message when it is unset, and it takes an optional CARBIUM_RPC_URL. It signs and sends nothing.

main.ts
// UC0005 · Wallet token holdings// https://carbium.sh/library/usecase/wallet-token-holdings// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: lists the SPL token mints a wallet holds, from its token accounts under both token programs.import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY to your Carbium API key."); process.exit(1); }const url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const owners = process.argv.slice(2);if (owners.length === 0) { console.error("Usage: node main.ts <wallet> [wallet ...]"); process.exit(1); }// One client, reused for every call.const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));// A mint lives under one of two token programs: ask both.const PROGRAMS: Record<string, string> = {  "Token": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",  "Token-2022": "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb",};type Info = { mint: string; tokenAmount: { amount: string; decimals: number } };type Holding = { mint: string; program: string; accounts: number; amount: bigint; decimals: number };async function holdings(owner: string): Promise<Holding[]> {  const reads = await Promise.all(Object.entries(PROGRAMS).map(async ([program, id]) => {    const res = await rpc      .getTokenAccountsByOwner(address(owner), { programId: address(id) }, { commitment: "confirmed", encoding: "jsonParsed" })      .send();    return res.value.map((v) => ({      program,      info: (v.account.data as unknown as { parsed: { info: Info } }).parsed.info,    }));  }));  // Several accounts can hold one mint: group by mint and sum the base units as integers.  const byMint = new Map<string, Holding>();  for (const { program, info } of reads.flat()) {    const h = byMint.get(info.mint) ??      { mint: info.mint, program, accounts: 0, amount: 0n, decimals: info.tokenAmount.decimals };    h.accounts++;    h.amount += BigInt(info.tokenAmount.amount);    byMint.set(info.mint, h);  }  return [...byMint.values()];}for (const owner of owners) {  const all = await holdings(owner);  const held = all.filter((h) => h.amount > 0n);  console.log(`${owner}: ${held.length} mints with a balance, ${all.length - held.length} with only empty accounts`);  for (const h of held.slice(0, 15)) {    console.log(`  ${h.mint}  ${h.program}  accounts ${h.accounts}  ${h.amount} base units, ${h.decimals} decimals`);  }}

run: CARBIUM_KEY=$CARBIUM_KEY node main.ts <wallet1> <wallet2>

Amounts stay as base-unit strings from the RPC, are summed as BigInt and printed next to the mint's decimals. Convert to a display value only on the screen, with the decimals of that mint. A float loses digits once a balance passes 2^53 base units. For one known mint, SPL token balance covers the single read.

04

Reading the answer

  • Empty accounts: a token account stays on chain with an amount of 0 until its owner closes it. The script counts these apart from the mints with a balance. Show them behind a toggle and keep them out of the main list.
  • NFTs: a one-of-one NFT is a mint with 0 decimals and an amount of 1, so it appears in the same list. That pair is a hint only, and a fungible token can match it.
  • Token-2022 extensions: a mint under that program can add behaviour such as a transfer fee. The amount field is the raw balance. Read the mint account when your screen must show what a transfer would deliver.
  • Names and logos: a token account carries the mint, the owner and the amount, and has no name or logo field. Take names and logos from your own token list or metadata source.
05

Keeping the list current

Reading again on page load is the simplest design and fits most wallet products. Cache the result per wallet for a short time so a burst of page loads costs one pair of reads, one per token program. To track the 429s a busy page produces, see the rate-limit watcher.

For push updates, accountSubscribe stays silent for a plain SOL wallet: use logsSubscribe with a mentions filter plus getBalance. A token transfer into the wallet lists the receiving token account, and the wallet address may be absent from the transaction. A subscription opens at 5, 25 or 200 credits by filter weight and then costs 20 credits per MiB sent, and a refused one is free. A logsSubscribe mentions filter takes a single address, so covering the token accounts means one subscription per token account, each opening at the logs-mentions weight. A wallet with hundreds of accounts is better served by rereading on load. On each notification, read the holdings once more instead of parsing log text.

06

Where it ends

  • Current holdings only: a closed account leaves no row, so the list cannot say which mints a wallet held last month. History comes from getSignaturesForAddress, which reaches back 30 days at most from Carbium's own address index, and an empty page past that is the index's age limit. Each signature then needs a getTransaction, and both cost 50 cells, so rebuilding a mint history is the expensive path.
  • Two reverse-lookup methods are not served: getTokenLargestAccounts and getProgramAccountsV2 are among eight methods that answer -32601, and -32601 is final. The mint filter of getTokenAccountsByOwner answers a different question, whether one wallet holds one mint.
  • Size: a wallet with thousands of token accounts returns a large body in one response. Cache it and avoid reading on every render.
  • No values: the list holds amounts and no prices. The quote plane has a prices method, and this script does not call it.
  • Snapshot: the result is the state at the commitment you asked for, at the moment of the read.
07

When it goes wrong

what goes wrongwhat to do
The list misses tokens the wallet clearly holds.Query both token programs. Token-2022 mints sit only under the second one.
The screen shows dozens of tokens with a zero balance.Drop accounts with an amount of 0 from the main list and offer them behind a toggle. They stay on chain until the owner closes them.
Balances are off in the last digits.Sum the base-unit strings as BigInt and divide by the mint's decimals only when you format the value.
getTokenLargestAccounts or getProgramAccountsV2 answers -32601 and the client retries it.Treat -32601 as final and remove the call. For one wallet and one mint, use the mint filter of getTokenAccountsByOwner.
A popular page rereads the same wallet on every load and gets 429.Cache the holdings per wallet for a short time so repeated loads share one pair of reads.
Two numbers on one screen disagree.Use one commitment for every call of the screen. A screen that mixes commitments can show a transfer in one number and miss it in another.
08

Questions

Do I need getProgramAccounts to list a wallet's tokens?

No. getTokenAccountsByOwner takes the owner and a program filter and returns only that wallet's token accounts. getProgramAccountsV2 is not served and answers -32601.

Which commitment should a wallet screen use?

The script uses confirmed. Pick one and use it for every read on the screen.

How do I add the SOL balance?

Plain SOL sits in the wallet account itself and has no token account, so it needs a separate getBalance call. Send it with the same commitment as the token reads.

Can I read many wallets in one request?

A JSON-RPC post can carry a batch of up to 100 calls. Post the batch yourself to the same URL with the same x-api-key header, since the kit client sends one call per request.

Does a closed account still show its mint?

No. Once the owner closes an account it is gone and the mint drops out of the list. Accounts with an amount of 0 remain until closed, which is why the script counts them separately.