library / How to use Solana / HS0048
Largest token holders
One TypeScript file gathers token accounts from recent transactions of a mint, reads their fresh balances in one getMultipleAccounts call, sums them by owner and prints the top 5 with each share of supply. It ranks owners seen in recent transactions.
What a holder is
A token account holds the tokens of one mint, and the holder is the account's owner. Each token account records one mint, one owner and one amount. The mint is the first 32 bytes of the account data, the owner is the next 32, and the amount is a little-endian u64 at offset 64. A ranking of people needs one more step: find who owns each account.
One wallet can own several token accounts for the same mint, the associated one and any it created later. An exchange or a program can own dozens. Ranking token accounts splits a large holder into several small entries, so the code sums by owner before it sorts. Some owners are program derived addresses, so the name at the top of the list may be a vault or a pool and no person at all.
Amounts stay as base units in a bigint. The share is the owner's total over the mint's supply from getTokenSupply, computed in integer basis points. The mint's decimals scale the number only when it is printed.
Gathering candidates
The usual call for this job is getTokenLargestAccounts. On Carbium it answers -32601, as does getProgramAccountsV2, and a -32601 is never worth a retry. So the file builds its own candidate list from methods that are served.
The list comes from recent activity. getSignaturesForAddress on the mint address returns the newest transactions that name the mint, which includes every transferChecked. A few settled ones are read with getTransaction. Each carries the token balances after the transaction, with an owner, a mint and an index into the account keys per entry. The index turns into a token account address, and the mint filter drops the other tokens in a swap.
Mainnet carries v1 transactions, so getTransaction needs maxSupportedTransactionVersion: 1 or it answers -32015 for them. And the signature pages come from an address index that keeps up to 30 days, so some older signatures it lists can return null from getTransaction. The file reads the newest ones and prints any it skips.
Balances inside a transaction are the balances right after it, and they age. The file keeps only the addresses and reads them again in one getMultipleAccounts call with commitment: "confirmed". The account data is decoded by offset, so the owner and the amount are as fresh as that one read.
| Call | Times | Cells each |
|---|---|---|
| getSignaturesForAddress | 1 | 50 |
| getTransaction | 6 | 50 |
| getMultipleAccounts | 1 | 10 per pubkey, 1000 for 100 |
| getTokenSupply | 1 | - |
The code
Install @solana/kit at 8.6.0, export CARBIUM_KEY and run the file with Node 24. The mint is an optional argument and defaults to USDC.
// HS0048 · Largest token holders// https://carbium.sh/library/howsolana/largest-token-holders// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressDecoder, type Address,} 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 mint = address(process.argv[2] ?? USDC);const txConfig = { commitment: "confirmed", encoding: "json", maxSupportedTransactionVersion: 1,} as const;// A failed call prints its name and gives null, so the run can go on without it.const call = <T>(name: string, p: Promise<T>) => p.catch((e) => (console.error(`${name} failed: ${String(e).slice(0, 80)}`), null));type Tx = { transaction?: { message?: { accountKeys?: string[] } }; meta?: { loadedAddresses?: { writable: string[]; readonly: string[] }; postTokenBalances?: { accountIndex: number; mint: string }[]; } | null;} | null;// 1. Candidates: token accounts of this mint in the newest settled transactions that name it.const sigs = await call("getSignaturesForAddress", rpc.getSignaturesForAddress(mint, { limit: 20, commitment: "confirmed" }).send());if (!sigs) process.exit(1);const picked = sigs.filter((s) => s.err === null).slice(0, 6);const txs = await Promise.allSettled(picked.map((s) => rpc.getTransaction(s.signature, txConfig).send()));const accounts = new Set<Address>();let skipped = 0;txs.forEach((r, i) => { const tx = r.status === "fulfilled" ? (r.value as unknown as Tx) : null; const base = tx?.transaction?.message?.accountKeys; if (!tx || !base) { skipped++; console.error(`skipped ${picked[i].signature}: ${r.status === "rejected" ? String(r.reason).slice(0, 80) : "null or unreadable"}`); return; } const loaded = tx.meta?.loadedAddresses; const keys = [...base, ...(loaded?.writable ?? []), ...(loaded?.readonly ?? [])]; for (const b of tx.meta?.postTokenBalances ?? []) { if (b.mint === mint && keys[b.accountIndex]) accounts.add(address(keys[b.accountIndex])); }});const list = [...accounts].slice(0, 100);if (list.length === 0) { console.error("No token accounts found for this mint in the newest transactions."); process.exit(1);}// 2. Fresh amounts: owner at offset 32, amount (u64) at offset 64, summed by owner.const res = await call("getMultipleAccounts", rpc.getMultipleAccounts(list, { encoding: "base64", commitment: "confirmed" }).send());if (!res) process.exit(1);const decoder = getAddressDecoder();const byOwner = new Map<Address, bigint>();for (const acc of res.value) { if (!acc) continue; const d = Buffer.from(acc.data[0], "base64"); if (d.length < 165 || decoder.decode(d.subarray(0, 32)) !== mint) continue; const owner = decoder.decode(d.subarray(32, 64)); byOwner.set(owner, (byOwner.get(owner) ?? 0n) + d.readBigUInt64LE(64));}// 3. Top 5 by owner; shares in basis points when the supply read works.const sup = await call("getTokenSupply", rpc.getTokenSupply(mint, { commitment: "confirmed" }).send());const total = sup ? BigInt(sup.value.amount) : 0n;const dec = sup?.value.decimals ?? 0;const fmt = (a: bigint) => { const s = a.toString().padStart(dec + 1, "0"); return dec ? `${s.slice(0, -dec)}.${s.slice(-dec)}` : s;};const top = [...byOwner].sort((a, b) => (a[1] === b[1] ? 0 : a[1] > b[1] ? -1 : 1)).slice(0, 5);console.log(`mint ${mint}: ${picked.length - skipped} transactions read, ${accounts.size} token accounts, ${byOwner.size} owners, supply ${sup ? fmt(total) : "unavailable, amounts in base units"}`);top.forEach(([owner, amount], i) => { const bps = total > 0n ? (amount * 10000n) / total : 0n; const share = sup ? ` (${bps / 100n}.${String(bps % 100n).padStart(2, "0")}% of supply)` : ""; console.log(`${i + 1}. ${owner} ${fmt(amount)}${share}`);});
run: node main.ts [mint-address]
The six getTransaction calls run together under Promise.allSettled, so one failure costs a line on stderr and the run goes on. The other three calls each sit behind a small wrapper that prints the name of the call that failed. A failed getSignaturesForAddress or getMultipleAccounts ends the run, and a failed getTokenSupply still prints the owner ranking, in base units and without shares. The transaction JSON is read through a small local type, because a v1 message may lay out its keys differently from the older formats. A transaction whose keys are missing counts as skipped. The first output line prints how many transactions, token accounts and owners went into the ranking, before the ranking itself, so the size of the sample is always on screen.
The full scan filter
The classic answer to this question is a program scan. getProgramAccounts on the token program with two filters returns every token account of one mint: { dataSize: 165 } keeps accounts of the base layout, and { memcmp: { offset: 0, bytes: <mint> } } keeps those whose first 32 bytes are the mint. A dataSlice of { offset: 32, length: 40 } trims each result to owner and amount. Sum by owner, sort, and the ranking is exact.
The cost grows with the mint. A major mint has millions of token accounts, so a node without a mint index walks the whole program's account set to match them and the reply is large. All of a mint's token accounts sit under that mint's own program. A Token-2022 mint takes one scan of the Token-2022 program with the mint filter alone and no dataSize, because accounts with extensions run longer than 165 bytes. It never takes a second scan beside the token program. This file stays with the served calls above.
Where it ends
The output is the top 5 of the candidate set, and the candidate set is a sample of whoever moved this mint recently. Large holders that sit still, such as treasuries, cold wallets and locked vaults, will not appear in six recent transactions, so the true largest holder can be missing. Read the list as the largest active owners in the sample.
getSignaturesForAddress lists a transaction only when it names the mint. A plain transfer does not list the mint, so holders who move the token only that way never reach the sample.
An owner's total can also come up short. The sample may reveal one of an owner's several token accounts, and the file sums only what it found. For an owner you care about, getTokenAccountsByOwner with a mint filter lists every token account that owner holds for the mint, one call per owner.
Shares are against the whole supply, so the five shares do not add to 100. A wider sample costs 50 cells per extra transaction, and the 100-pubkey cap holds the list however many transactions you read. A table you keep up to date from the mint's transfers gives a current ranking, as in Token holder tracker.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| getTokenLargestAccounts answers -32601. | Do not retry. Build a candidate set as above, or keep your own holder table for a current ranking. |
| getTransaction answers -32015. | Pass maxSupportedTransactionVersion: 1. Left out, or set to 0, a v1 transaction is refused. |
| getTransaction returns null for a signature the list gave you. | Signature pages reach below the validator's ledger floor, so an older signature can have no transaction to return. The file prints it as skipped; the newest signatures answer. |
| A getMultipleAccounts call carries more than 100 pubkeys on a plan below Pro. | Send at most 100 pubkeys a call and make several calls. The 300-pubkey call is a Pro limit. |
| The run exits with a message that no token accounts were found. | The newest signatures held no settled transaction with token balances for the mint. Pass a busier mint and raise the slice count of 6, or both that and the signature limit of 20. |
Questions
Why sum by owner and not rank the token accounts?
A wallet can own several token accounts for one mint, so ranking accounts splits one holder into small entries. Summing by owner puts them back together, as far as the sample saw them.
Can I get the exact top 5 from this file?
Not from this candidate set. A table you keep yourself gives a current ranking, as in Token holder tracker. getTokenLargestAccounts is not served.
Why read balances again instead of using the transaction's own?
The balances in a transaction are the amounts right after it ran, and the account may have moved since. One getMultipleAccounts call returns the current amount and owner for every candidate at once.
Does it work for Token-2022 mints?
Yes. The token balances in a transaction list accounts of either program, and an extended account keeps the mint, owner and amount at the same offsets in its first 165 bytes.