---
id: HS0001
title: "SPL token balance"
url: https://carbium.sh/library/howsolana/spl-token-balance
collection: How to use Solana
category: SPL tokens
revision: 2
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# SPL token balance

One TypeScript file takes a wallet address and a mint, derives the wallet's token account offline, and prints amount, decimals and uiAmountString. It only reads: no keypair, no signature, no transaction, no state change.

## What the call reads

A Solana wallet holds SOL directly. Every SPL token it owns sits in a separate token account, a small on-chain account that records the mint, the owner and the amount. `getTokenAccountBalance` takes the address of that token account. Passing the wallet address fails. The job therefore has two steps: find the token account, then read it.

For the main account of a given mint the address is predictable. The associated token account is a program derived address built from three seeds: the owner, the token program id and the mint. Deriving it is local arithmetic, so it makes no network call and needs no key. The `@solana-program/token` package ships `findAssociatedTokenPda` for this step. The file below writes out the three seeds itself, which leaves `@solana/kit` as the only dependency.

The read is a plain JSON-RPC query. You can point it at any wallet address you were given. The one secret in play is your Carbium key, and it comes from the environment.

## The code

Install `@solana/kit` at 8.6.0, export `CARBIUM_KEY` and run the file with Node 24, which strips TypeScript types on its own. The wallet is the first argument. The mint is an optional second argument and defaults to USDC.

`main.ts` (run: `node main.ts <wallet-address> [mint-address]`)

```ts
// HS0001 · SPL token balance
// https://carbium.sh/library/howsolana/spl-token-balance
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { setTimeout as sleep } from "node:timers/promises";
import {
  address,
  createDefaultRpcTransport,
  createSolanaRpcFromTransport,
  getAddressEncoder,
  getProgramDerivedAddress,
  isSolanaError,
  SOLANA_ERROR__JSON_RPC__INVALID_PARAMS,
  SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,
} 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 rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({ url, headers: { "x-api-key": key } }),
);

const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
const TOKEN_PROGRAM = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
const ATA_PROGRAM = address("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");

const [ownerArg, mintArg = USDC] = process.argv.slice(2);
if (!ownerArg) {
  console.error("Usage: node main.ts <wallet-address> [mint-address]");
  process.exit(1);
}
const owner = address(ownerArg);
const mint = address(mintArg);

// Offline: the associated token account is a PDA of (owner, token program, mint).
const enc = getAddressEncoder();
const [ata] = await getProgramDerivedAddress({
  programAddress: ATA_PROGRAM,
  seeds: [enc.encode(owner), enc.encode(TOKEN_PROGRAM), enc.encode(mint)],
});

async function read() {
  const { value: lamports } = await rpc
    .getBalance(owner, { commitment: "confirmed" })
    .send();
  console.log(`wallet ${owner}: ${lamports} lamports`);
  try {
    const { value } = await rpc
      .getTokenAccountBalance(ata, { commitment: "confirmed" })
      .send();
    console.log(`token account ${ata}`);
    console.log(`amount=${value.amount} decimals=${value.decimals} uiAmountString=${value.uiAmountString}`);
  } catch (e) {
    const missing =
      isSolanaError(e, SOLANA_ERROR__JSON_RPC__INVALID_PARAMS) &&
      e.context.__serverMessage.includes("could not find account");
    if (!missing) throw e;
    console.log(`amount=0 (no token account at ${ata} for this wallet and mint)`);
  }
}

try {
  await read();
} catch (e) {
  if (!isSolanaError(e, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR) || e.context.statusCode !== 429) throw e;
  const seconds = Number(e.context.headers.get("retry-after")) || 1;
  console.error(`429: waiting ${seconds}s, then one more try`);
  await sleep(seconds * 1000);
  await read();
}
```

The transport sends every call to `https://services.carbium.sh` with the key from the environment, and the `rpc` object is created once and reused for both reads. `getProgramDerivedAddress` turns owner, token program and mint into the token account address without leaving your process. Both reads pass `commitment: "confirmed"`, so the SOL line and the token line come from the same level.

`getBalance` is the only other method. It returns the wallet's SOL in lamports, where 1 SOL is 1,000,000,000 lamports. It is there so one run answers the two questions a developer usually has about a wallet: how much SOL for fees, and how much of the token. If Carbium answers a call with a 429, the file reads the retry-after header and tries once more. Any other error surfaces at once.

## Reading the answer

| Field | Type | Meaning |
|---|---|---|
| amount | string | The raw balance as an integer, in the token's smallest unit. |
| decimals | number | How many digits sit after the decimal point for this mint. USDC uses 6. |
| uiAmountString | string | The amount scaled by decimals, as exact decimal text, such as 1.234567. |
| uiAmount | number or null | The same value as a float. Do not store it. |

An `amount` of `1234567` with `decimals` of 6 reads as `1.234567`. Keep the strings. A JavaScript number holds integers exactly only up to 2^53, about 9.0 x 10^15. A token with 9 decimals and a supply of one billion has a raw amount near 10^18, so a float rounds the last digits and the sum of two balances can drift from the sum on chain. `amount` and `uiAmountString` are strings and carry every digit. Store `amount` as a `BigInt` or a decimal column, show `uiAmountString` to people, and do any arithmetic on `BigInt(amount)`.

> The token balance and the SOL balance use different units. `getBalance` answers in lamports, while the token answer is scaled by the mint's own decimals.

## On Carbium

`getTokenAccountBalance` is an account read and costs 10 cells, the same as `getAccountInfo` and `getMultipleAccounts`. [Account reads](https://carbium.sh/docs#rpc) run at 0.5 per second on Free, 15 on Dev, 50 on Business and 400 on Pro.

To read many wallets, derive every token account address offline first and pass them to `getMultipleAccounts` with `jsonParsed` encoding. It takes up to 300 pubkeys (100 below Pro) at 10 cells each and returns each `tokenAmount` in one reply, with `null` for an address that holds no account. A JSON-RPC batch is the other route: a raw `fetch` POST of a JSON array of up to 100 calls, because `@solana/kit` has no batch call.

`-32601` means method not found: a misspelt name, or a method Carbium does not serve, so do not retry it.

## Where it ends

A wallet with no token account gets an error instead of a zero. If the wallet has not received this mint, nothing exists at the derived address. The node answers with JSON-RPC code -32602 and the message `Invalid param: could not find account`. The file catches exactly that error, prints `amount=0` with a note, and rethrows everything else. A printed zero can mean the wallet has not held the token or has closed its token account, and the RPC does not say which.

Token-2022 mints use a different program id, `TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb`, and that id is one of the three seeds. With the classic token program in the seed, the file derives a different, empty address and reports a missing account for a wallet that does hold the token. The RPC method is the same for either program. Derive with the right program id, and find out which program owns a mint by calling `getAccountInfo` on the mint address and reading the `owner` field.

The method reads one token account. It does not list what a wallet holds: a wallet can hold hundreds of mints, and a token can sit in an account that is not the associated one. This file looks only at the associated account for the one mint you pass. To see every token account a wallet holds, including a non-associated one for the same mint, list them by owner. `getTokenLargestAccounts`, which ranks the holders of a mint, is not served on Carbium and answers `-32601`.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| Error -32602 `Invalid param: could not find account` for a wallet you know holds the token. | Check the spelling of owner and mint, then check the token program. A Token-2022 mint needs its own program id in the seeds. Call `getAccountInfo` on the mint and read `owner` to see which program it belongs to. |
| Error -32602 ending in `not a Token account`. | You passed the wallet address, or another account that is not a token account, to `getTokenAccountBalance`. Derive the token account address first and pass that. |
| HTTP 429 with a retry-after hint. | Wait for the number of seconds in the header and try once more. If it repeats, slow the loop down or move to a plan with more account reads per second. |
| Error -32601 method not found. | Fix the method name, or use another method. A method Carbium does not serve, such as `getTokenLargestAccounts`, will keep answering -32601, so do not retry it. |
| Totals that differ from the chain in the last digits. | You summed `uiAmount` floats. Add `BigInt(amount)` values instead and format with `decimals` at the end, or keep `uiAmountString` as text. |

## Questions

### Do I need a private key to read a token balance?

No. The call takes a token account address and returns its state. The Carbium key only identifies your account to the RPC.

### Why not call getBalance and be done?

`getBalance` returns SOL in lamports for the wallet. A token balance lives in a separate token account, so you need `getTokenAccountBalance` on that account.

### How do I read many wallets?

Derive each token account address offline, then read them with `getMultipleAccounts` in `jsonParsed` encoding, up to 100 per call below Pro and 300 on Pro. `getMultipleAccounts` charges 10 cells per pubkey, so a 100-pubkey call costs 1,001 cells: 10 per pubkey, plus 1 because its body is over 4 KiB.

### Which commitment should I pass?

`confirmed` suits a balance shown to a user. Use `finalized` when the number triggers something you cannot undo, such as crediting a deposit.

### Does deriving the token account address cost a request?

No. `getProgramDerivedAddress` hashes the seeds in your own process, so no request leaves it for that step.

## Related

- [RPC rate-limit alerts](https://carbium.sh/library/usecase/rpc-rate-limit-alerts) (Use cases, UC0001)
- [Failed-mint monitor](https://carbium.sh/library/blockchainideas/failed-mint-monitor) (Blockchain ideas, BI0001)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
