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

# Token accounts by owner

One TypeScript file takes a wallet address, or picks an active one when you pass none, reads its token accounts under the Token program and Token-2022, and prints one line per mint. It only reads and needs no keypair.

## The two methods

The two names in the query are `@solana/web3.js` 1.x helpers. `Parsed` means the node decodes the account data into named fields (`jsonParsed`) where the plain call returns base64 bytes. `@solana/kit` has no separate parsed methods: you call `getProgramAccounts` or `getTokenAccountsByOwner` and pass `encoding: "jsonParsed"`. That leaves a choice between the two underlying methods, and only one of them fits a wallet lookup.

`getProgramAccounts` takes a program id and returns every account that program owns, narrowed by the filters you send. It covers one program per call, so a query on the Token program never returns Token-2022 accounts. For the Token program the query reaches every token account of every holder, so a wallet lookup needs a `dataSize` filter of 165 and a `memcmp` filter at byte offset 32, where a token account stores its owner. A second call to Token-2022 needs a different shape: every associated token account there carries the ImmutableOwner extension and is longer than 165 bytes, so the 165 filter would drop it. That call keeps the `memcmp` at offset 32 and drops `dataSize`.

`getTokenAccountsByOwner` takes the wallet and one filter, either a `mint` or a `programId`, and returns that wallet's token accounts. It exists for this lookup, so you write no byte offsets and no size filters. It covers one token program per call, which means two calls for a full picture.

| Question | getProgramAccounts | getTokenAccountsByOwner |
|---|---|---|
| Takes | A program id plus filters | A wallet plus a mint or a program id |
| Searches | Every account the program owns, narrowed by your filters | The wallet's token accounts |
| Filters you write | `dataSize` 165 and `memcmp` at offset 32 on the Token program | No byte offsets or sizes |
| Token-2022 | A second call to that program with `memcmp` at offset 32 and no `dataSize` | A second call with the Token-2022 program id |
| Fits | Every holder of a mint, or program-wide data | One wallet's holdings |

## The code

Install `@solana/kit` at 8.6.0, export `CARBIUM_KEY` and run the file with Node 24, which strips TypeScript types on load. The wallet address is the only argument and it is optional. With none, `find` reads the newest signatures of the Token program, collects the owners named in those transactions' token balances, and the file tries up to five of them until one lists at least one token account. A failed `getTransaction` prints its name and the run moves on to the next signature, while a failed `getSignaturesForAddress` leaves no candidates and the file ends with "No wallet found to list."

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

```ts
// HS0017 · Token accounts by owner
// https://carbium.sh/library/howsolana/token-accounts-by-owner
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { setTimeout as sleep } from "node:timers/promises";
import {
  address, type Address, createDefaultRpcTransport, createSolanaRpcFromTransport,
  isSolanaError, 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 PROGRAMS = {
  token: address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"),
  "token-2022": address("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"),
};
type Info = { mint: string; tokenAmount: { amount: string; decimals: number } };

async function list(owner: Address, program: string, programId: Address) {
  const { value } = await rpc
    .getTokenAccountsByOwner(owner, { programId }, { encoding: "jsonParsed", commitment: "confirmed" })
    .send();
  return value.map((a) => ({ program, ...(a.account.data as unknown as { parsed: { info: Info } }).parsed.info }));
}

async function retry<T>(f: () => Promise<T>): Promise<T> {
  try {
    return await f();
  } 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);
    return f();
  }
}

async function find() {
  const owners = new Set<Address>();
  try {
    const sigs = await retry(() => rpc.getSignaturesForAddress(PROGRAMS.token, { limit: 3 }).send());
    for (const { signature } of sigs) {
      if (owners.size >= 5) break;
      try {
        const tx = await retry(() => rpc.getTransaction(signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send());
        for (const b of tx?.meta?.postTokenBalances ?? []) if (b.owner) owners.add(b.owner);
      } catch (e) { console.error(`failed getTransaction ${signature}: ${(e as Error).message}`); }
    }
  } catch (e) { console.error(`failed getSignaturesForAddress: ${(e as Error).message}`); }
  return [...owners];
}

function fmt(raw: bigint, decimals: number) {
  const s = raw.toString().padStart(decimals + 1, "0");
  return decimals ? `${s.slice(0, -decimals)}.${s.slice(-decimals)}` : s;
}

const ownerArg = process.argv[2];
const candidates = ownerArg ? [address(ownerArg)] : await find();
let shown = false;
for (const owner of candidates.slice(0, 5)) {
  const results = await Promise.allSettled(Object.entries(PROGRAMS).map(([name, id]) => retry(() => list(owner, name, id))));
  const accounts = results.flatMap((r) => (r.status === "fulfilled" ? r.value : []));
  const failed = results.flatMap((r, i) => r.status === "rejected" ? [`${Object.keys(PROGRAMS)[i]}: ${(r.reason as Error).message}`] : []);
  failed.forEach((f) => console.error(`failed ${f}`));
  if (!ownerArg && (failed.length > 0 || accounts.length === 0)) continue;
  if (failed.length > 0) process.exitCode = 1;

  const byMint = new Map<string, { program: string; decimals: number; raw: bigint; accounts: number }>();
  let empty = 0;
  for (const { program, mint, tokenAmount } of accounts) {
    const raw = BigInt(tokenAmount.amount);
    if (raw === 0n) { empty++; continue; }
    const row = byMint.get(mint) ?? { program, decimals: tokenAmount.decimals, raw: 0n, accounts: 0 };
    row.raw += raw;
    row.accounts++;
    byMint.set(mint, row);
  }
  console.log(`wallet ${owner}: ${accounts.length} token accounts, ${byMint.size} mints with a balance, ${empty} empty`);
  for (const [mint, r] of byMint) console.log(`${mint} ${r.program} accounts=${r.accounts} amount=${fmt(r.raw, r.decimals)}`);
  shown = true;
  break;
}
if (!shown) {
  console.error("No wallet found to list.");
  process.exitCode = 1;
}
```

`list` calls `getTokenAccountsByOwner` with `{ programId }` and `encoding: "jsonParsed"`. The two calls, one for the Token program and one for Token-2022, run together and are settled on their own, so one that fails prints its message and the other still lists. The loop then groups accounts by mint and adds the raw `amount` strings as `BigInt`, so a wallet with two accounts for one mint gets one line. `fmt` puts the decimal point back using the mint's `decimals`.

## Reading the answer

Each entry in `value` is one token account. The fields the file uses sit under `account.data.parsed.info`, and the account's own address is `pubkey`.

- `mint`: the token's mint address.
- `owner`: the wallet you asked about.
- `tokenAmount.amount`: the raw balance as an integer string, in the token's smallest unit.
- `tokenAmount.decimals` and `tokenAmount.uiAmountString`: the scale of the mint and the amount as exact decimal text.
- `state`: `initialized` or `frozen`.

A wallet can hold several token accounts for one mint, because the associated token account is only the default one, so sum by mint. Accounts at zero stay on chain until their owner closes them, and the call returns them. The file counts them and leaves them out of the list. NFTs show up the same way, as an account with `decimals` of 0 and an `amount` of 1.

Add `BigInt(amount)` values and never `uiAmount` floats. A float holds integers exactly only up to 2^53, and a mint with 9 decimals reaches that raw value at about 9 million tokens.

> Both calls read at confirmed commitment.

## On Carbium

Each run with a wallet address sends two calls. Without one, the file first adds a `getSignaturesForAddress` call and up to three `getTransaction` reads to find a wallet, then makes two `getTokenAccountsByOwner` calls for each candidate it tries, up to five candidates. [Budgets belong to the account](https://carbium.sh/docs#limits): every key on it draws from the same pool.

When the mints are known up front, skip the listing. Derive each associated token account address offline, as [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) shows, then read the lot with `getMultipleAccounts`: 10 cells per pubkey, up to 300 pubkeys per call, though the 1024-cell burst caps one call at 100 pubkeys on every plan below Pro. Account reads run at 0.5 req/s on Free, 15 on Dev, 50 on Business and 400 on Pro.

`getProgramAccountsV2` is not served. It answers `-32601`, method not found, and retrying cannot change that. Build a lookup on a served method such as [getTokenAccountsByOwner](https://carbium.sh/docs#rpc), which this file calls.

## Where it ends

The reply describes token accounts and says nothing about the tokens. A mint's name and symbol live in a metadata account or, for Token-2022, in the mint's own `tokenMetadata` extension behind a `metadataPointer`, and either one is a separate read. The SOL balance comes from `getBalance`, and no price comes with any of it.

The method has no paging. A wallet with a very large number of token accounts gets them in one large reply, and for such wallets the way out is to ask per mint with `{ mint }` in place of `{ programId }`. When the file picks a wallet itself, it skips any candidate whose call fails or lists no accounts. A wallet that holds nothing gets an empty `value`, which is a valid answer. A program-wide question, such as every holder of a mint, is what a filtered `getProgramAccounts` is for, and that is a heavy read for any node.

The two calls are two reads and can differ by a slot. Each mint belongs to one token program, so nothing is counted twice, but the Token line and the Token-2022 line may come from slightly different moments.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| HTTP 429 with a retry-after hint. | Sleep for the seconds in the header and send the call once more, which is what `retry` does. If it repeats, slow the loop or move to a plan with more requests per second for [this method](https://carbium.sh/docs#rpc). |
| Error -32601 method not found. | Correct the method name or choose another method. `getProgramAccountsV2` and the other methods Carbium does not serve keep answering -32601, so do not retry them. |
| An empty list for a wallet you know holds tokens. | Check that the address is the owner wallet and not a token account address. A call for one token program misses the other, so the file asks the Token program and Token-2022. |
| Totals that differ from the chain in the last digits. | You summed `uiAmount` floats. Add `BigInt(amount)` values and format with `decimals` at the end. |
| A wallet total from `getProgramAccounts` that is lower than the wallet's real holdings. | The call reaches one program only, so Token-2022 holdings are missing from the total. Add a second Token-2022 call without the 165-byte size filter, or use `getTokenAccountsByOwner` once per program id. |

## Questions

### Is there a getParsedTokenAccountsByOwner in @solana/kit?

No. It is the web3.js 1.x name for `getTokenAccountsByOwner` called with `jsonParsed` encoding. In kit you call `getTokenAccountsByOwner` and pass `encoding: "jsonParsed"` in the config.

### Why not use getProgramAccounts with filters for a wallet?

It makes the node search every account the program owns, and one call reaches one program, so Token-2022 holdings need a separate request with a different filter set. `getTokenAccountsByOwner` takes the wallet directly and needs only the other program id for Token-2022.

### Do I need a private key to list a wallet's tokens?

No. The call reads state for an address. The Carbium key identifies your account and signs nothing.

### Does the reply include SOL?

No. SOL sits on the wallet account itself. Read it with `getBalance`, which returns lamports.

### How do I get a token's name or symbol?

Not from this reply, which holds the mint address, owner, amount and state. [Token-2022 metadata lookup](https://carbium.sh/library/howsolana/token-2022-metadata-lookup) shows the separate read.

## Related

- [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) (How to use Solana, HS0001)
- [Wallet token holdings](https://carbium.sh/library/usecase/wallet-token-holdings) (Use cases, UC0005)
- [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)
