services
Get a key

library / How to use Solana / SPL tokens / HS0132

Large-wallet token account listing

One TypeScript file lists a wallet's token accounts with getTokenAccountsByOwner under a 20-second deadline, so a large wallet ends in a readable error instead of an open request. It filters by mint or program id, decodes each raw amount, and only reads.

By Carbium · SPL tokens · HS0132 · updated 2026-11-23

01

Why one call gets slow

A wallet that holds thousands of token accounts makes getTokenAccountsByOwner return one large reply. The method takes an owner and a filter, then answers with every token account that owner holds under that filter. Nothing in the call splits the answer into pages. A caller that filters only by program id asks for everything the wallet holds, and the reply grows with each account the wallet has opened. Most of those accounts hold a zero balance, or a token nobody reads.

The symptom is a call that never returns. A reply that size takes time to build and time to send, and the client waits on a response it has not finished reading. The file below sets its own deadline, so a slow read ends with an error the caller can act on. The deadline only ends the wait in your process. It does not shrink the reply.

The fix is to ask for less. A mint filter returns the accounts for one token, and a program filter returns the accounts of one token program. The file takes an optional mint and uses it when one is given. The method is covered in token accounts by owner, and the call itself runs over the RPC endpoint.

02

The code

Install @solana/kit at 8.6.0, export CARBIUM_KEY and run the file with Node 24, which strips the types on its own. The first argument is the owner and the second is an optional mint. The call asks for base64 encoding, so each account arrives as raw bytes. Those bytes follow the same layout the token account decoder reads.

main.ts
// HS0132 · Large-wallet token account listing// https://carbium.sh/library/howsolana/large-wallet-token-account-listing// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport {  address,  createDefaultRpcTransport,  createSolanaRpcFromTransport,  getAddressDecoder,  isSolanaError,  SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,} from "@solana/kit";import { setTimeout as pause } from "node:timers/promises";const env = process.env;const apiKey = env.CARBIUM_KEY ?? "";function fail(message: string): never {  console.error(message);  process.exit(1);}if (apiKey === "") fail("CARBIUM_KEY is not set; export your Carbium API key first.");const transport = createDefaultRpcTransport({  url: env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",  headers: { "x-api-key": apiKey },});const rpc = createSolanaRpcFromTransport(transport);const TOKEN_PROGRAM = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");const LIMIT_MS = 20_000;const [ownerInput = "vines1vzrYbzLMRdu58ou5XTby4qAqVRLmqo36NKPTg", mintInput] = process.argv.slice(2);const owner = address(ownerInput);const scope = mintInput ? { mint: address(mintInput) } : { programId: TOKEN_PROGRAM };const toAddress = getAddressDecoder();type Row = { pubkey: string; mint: string; amount: bigint };async function fetchRows(): Promise<Row[]> {  const { value: accounts } = await rpc    .getTokenAccountsByOwner(owner, scope, { encoding: "base64", commitment: "confirmed" })    .send({ abortSignal: AbortSignal.timeout(LIMIT_MS) });  return accounts.map(({ pubkey, account }) => {    const raw = Buffer.from(account.data[0], "base64");    return {      pubkey,      mint: toAddress.decode(raw.subarray(0, 32)),      amount: raw.readBigUInt64LE(64),    };  });}async function main(): Promise<void> {  const began = performance.now();  let rows: Row[];  try {    rows = await fetchRows();  } catch (err) {    if (isSolanaError(err, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR) && err.context.statusCode === 429) {      const wait = Number(err.context.headers.get("retry-after")) || 1;      console.error(`429: waiting ${wait}s, then one more try`);      await pause(wait * 1000);      rows = await fetchRows();    } else if (err instanceof Error && err.name === "TimeoutError") {      fail(`no reply within ${LIMIT_MS / 1000}s for ${owner}; pass a mint to narrow the reply`);    } else {      throw err;    }  }  const funded = rows.filter((row) => row.amount > 0n);  const elapsed = Math.round(performance.now() - began);  console.log(`owner ${owner}: ${rows.length} token accounts, ${funded.length} with a balance, ${elapsed} ms`);  funded.slice(0, 10).forEach((row) => console.log(`${row.mint} amount=${row.amount} account=${row.pubkey}`));}await main();

run: node main.ts <owner-address> [mint-address]

The transport sends every call to the RPC endpoint with the key in the x-api-key header, as the auth docs describe. The owner and filter go in one call at confirmed commitment. AbortSignal.timeout gives the call 20 seconds. When the deadline passes, the error is a TimeoutError, and the file prints the owner, says what to pass, and exits. A 429 is retried once after the retry-after seconds, because a call over its rate limit waits once and then gets a 429 with that hint.

Amounts stay as BigInt. The mint is the first 32 bytes of each account. The raw amount is the 8-byte little-endian integer at byte 64. The file does not scale that amount by decimals, since decimals belong to the mint. It prints the raw value, and the caller scales it.

03

Reading the reply

FieldWhere it sitsMeaning
pubkeyeach reply entryThe token account address. Pass it to getTokenAccountBalance or getAccountInfo.
mintbytes 0 to 31The mint the account holds, decoded as a base58 address.
amountbytes 64 to 71The raw integer in the token's smallest unit. Keep it as a BigInt.
account.data[1]reply entryThe encoding name, base64 in this file.

The file counts every account in the reply, then counts the accounts with a balance above zero, and prints the first ten of those. Zero-balance accounts still come back, so the second count is the one a wallet view needs. Sum the amounts with BigInt values only. A JavaScript number holds integers exactly only up to 2^53, and a balance with nine decimals passes that line quickly.

$The default owner is only there so the file runs with no arguments. Pass the wallet you are reading.
04

Keeping the reply small

  • Pass a mint when you know the token. The reply then holds the accounts for that one mint, usually one per owner.
  • Run one program filter per token program. Classic SPL tokens sit under TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA, and Token-2022 tokens sit under TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb. A filter on one id does not return the other program's accounts, so a full list needs two calls.
  • Filter zero balances in your own code. The method has no amount filter, so empty accounts stay in the reply until their owner closes them.
05

Where it ends

The method has no cursor. A wallet with very many token accounts gets one reply of that size, and this file cannot split it into pages. Narrow the filter to a mint or a program, or accept the size of the reply for that wallet.

A timeout ends your wait and says nothing about the work the node did for the request. This call only reads, so running it again changes nothing on chain and is safe to retry, within the rate limit.

The default filter covers the classic token program only. A wallet that holds only Token-2022 tokens and no mint argument gets an empty list, and that list is correct for the filter used. The method lists accounts for one owner. It does not rank the holders of a mint: getTokenLargestAccounts is not served on Carbium and answers -32601.

06

When it goes wrong

what goes wrongwhat to do
A TimeoutError after 20 seconds, with no reply.Pass a mint so the reply holds one token's accounts. If that still times out, check the owner address and try again later. The deadline only ends your wait.
HTTP 429 with a retry-after hint, and a second 429 on the retry.The file waits the stated seconds and tries once. If the second call is also refused, slow the loop that calls it, since the rate limits set calls per second for each plan.
An empty list for a wallet that holds a token.The default filter covers the classic token program only. Pass the mint, or make a second call with the Token-2022 program id.
An empty list for an owner you expected to hold accounts, with a token account address in the owner position.The owner argument must be the wallet address. A token account address is a valid address, so it parses and returns an empty list. Check that you passed the wallet. Errors from the error reference are returned in the usual JSON-RPC shape.
07

Questions

Why does getTokenAccountsByOwner hang on my wallet?

A wallet with many token accounts sends one large reply, and the method has no paging. A deadline in the client ends the wait with an error you can handle.

Can I page through the accounts?

No. The method returns the full set for its filter in one reply. Narrow the set with a mint or a program id instead.

Does the timeout cancel the work on the node?

The client cannot see that from its side. The timeout ends your wait only, and retrying this read changes nothing, so it is safe.

Why is my list empty for a token I hold?

The token may be Token-2022, which the classic program filter skips. Pass its mint, or make a second call with the Token-2022 program id.