library / How to use Solana / HS0016
SOL balances for many accounts
One TypeScript file takes a list of addresses from the command line or a file, reads their lamports with getMultipleAccounts in chunks of 100, and prints each balance in SOL with a total. It only reads: no keypair, no signature, no transaction.
One call for the whole list
A wallet's SOL balance is the lamports field of its account. The obvious read is getBalance once per address, which for twenty addresses means twenty round trips, each answered from whichever slot the node had reached when your request arrived. getMultipleAccounts takes the whole list in one request, answers in the order you sent, and reports one context.slot that every account in that reply was read at.
Two choices in the file follow from that call. An address that holds no lamports has no account on chain, so its entry in the reply is null and no zero comes back. The file prints it as 0 lamports and counts it separately. The read also asks for a data slice of length 0, so the reply carries balances and no account data. Without the slice, a list that includes a program or a large mint would return the full body of every such account.
The file reads 100 addresses per call. The endpoint takes up to 300 pubkeys per call on Pro and 100 below it, so 100 works on every plan and keeps each retry small.
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. Pass addresses as arguments, or pass --file and the path of a text file with one address per line or separated by spaces.
// HS0016 · SOL balances for many accounts// https://carbium.sh/library/howsolana/sol-balances-for-many-accounts// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { readFileSync } from "node:fs";import { setTimeout as sleep } from "node:timers/promises";import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, isSolanaError, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, 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 args = process.argv.slice(2);const list = args[0] === "--file" ? readFileSync(args[1] ?? "", "utf8").split(/\s+/).filter(Boolean) : args;if (list.length === 0) { console.error("Usage: node main.ts <address> [<address> ...] or node main.ts --file addresses.txt"); process.exit(1);}const accounts: Address[] = list.map((a) => address(a)); // throws on a malformed addressconst CHUNK = 100; // 100 per call on every plan (300 on Pro)function readChunk(chunk: Address[]) { return rpc .getMultipleAccounts(chunk, { commitment: "confirmed", encoding: "base64", dataSlice: { offset: 0, length: 0 }, // balances only, no account data }) .send();}async function readWithRetry(chunk: Address[]) { try { return await readChunk(chunk); } 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 readChunk(chunk); }}const sol = (l: bigint) => `${l / 1_000_000_000n}.${String(l % 1_000_000_000n).padStart(9, "0")}`;let total = 0n;let missing = 0;for (let i = 0; i < accounts.length; i += CHUNK) { const chunk = accounts.slice(i, i + CHUNK); const { context, value } = await readWithRetry(chunk); console.log(`slot ${context.slot}`); value.forEach((acct, j) => { const lamports = acct?.lamports ?? 0n; if (acct === null) missing++; total += lamports; console.log(`${chunk[j]} ${sol(lamports)} SOL (${lamports} lamports)${acct === null ? " no account" : ""}`); });}console.log(`${accounts.length} addresses, ${missing} with no account, total ${sol(total)} SOL`);
run: node main.ts <address> [<address> ...]
The transport sends the key in the x-api-key header to https://services.carbium.sh, and one rpc object serves every chunk. address() validates every string before the first request, so a typo stops the run at once and costs nothing. Each chunk asks for commitment: "confirmed" and encoding: "base64" together with the empty data slice.
The total is a bigint. @solana/kit returns lamports as bigint, so adding thousands of balances stays exact, and the SOL text comes from integer division and a zero-padded remainder with no float anywhere. A 429 on a chunk is retried once after the wait that the retry-after header names.
Reading the answer
| Part of the reply | What it holds |
|---|---|
| context.slot | The slot every account in this reply was read at. |
| value[i] | The account for the i-th address you sent, or null when no account exists there. |
| value[i].lamports | The balance as a bigint. 1 SOL is 1,000,000,000 lamports. |
| value[i].owner | The program that owns the account. A plain wallet shows the System Program, 11111111111111111111111111111111. |
| value[i].data | Empty here, because the data slice has length 0. |
Each chunk comes back as one reply, and the file prints the slot once per chunk, then one line per address in the order you gave them. The owner field is a quick way to tell a plain wallet from a program account or a token account when a list mixes kinds, since the lamports of any of them are read the same way.
On Carbium
getMultipleAccounts charges 10 cells per pubkey. A 100-pubkey call costs 1000 cells, or 1001 when the body is over 4 KiB, and 100 base58 addresses run past 4 KiB, so expect 1001 for each full chunk. Account reads run at 0.5 requests per second on Free, 15 on Dev, 50 on Business and 400 on Pro, so a long list on a small plan reaches the limit sooner.
A second 429 on the same chunk ends the run. Slow the loop down or move to a plan with more account reads per second, and see how the budget is counted to size the pauses.
A JSON-RPC batch is the other route to many answers: one POST holding up to 100 calls. @solana/kit has no batch call, so that route means a raw fetch with a JSON array. For balances, one getMultipleAccounts call per chunk is shorter to write and returns every account at one slot.
Where it ends
The file reads the lamports of the account itself and nothing else. A wallet's SPL tokens sit in separate token accounts, so a USDC balance is not in this output. For that read, see SPL token balance.
It reads the current state once. It polls nothing and does not stream. For live updates, accountSubscribe stays silent for a plain SOL wallet, because the account is not in the stream. The route is logsSubscribe with a mention of the address on wss://services.carbium.sh, and a getBalance call whenever a notification arrives. The websocket methods cover the subscription side.
A balance of 0 and an address with no account look the same in the totals. The file prints no account next to the second kind, and the RPC cannot say whether such an address was never funded or was emptied. Duplicated addresses in the list are read and summed once per occurrence, so remove duplicates first when the total matters.
A list of thousands of addresses is many calls, each at 10 cells per pubkey. The loop runs them one after another and retries a 429 only once per chunk. For a recurring job over a long list, space the chunks out and watch your 429 count. RPC rate-limit alerts covers the alerting side.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The run stops before any output with an error about an invalid address. | address() rejected a string that is not valid base58 for 32 bytes. Check each entry in the list, and look for a stray quote, a trailing character or a copied line number. |
| HTTP 429 with a retry-after hint, and the run ends after one retry. | The chunk was too costly for your plan's account-read rate. Wait for the seconds in the header, lower CHUNK, pause between chunks, or move to a plan with more account reads per second. |
| A chunk size above 100 fails below Pro, and above 300 on Pro. | The endpoint takes up to 300 pubkeys in one getMultipleAccounts call on Pro and 100 below it. Keep CHUNK at 100, or at most 300 on Pro. |
| Every balance prints as 0 with no account. | The addresses hold no lamports on mainnet or are spelled wrong. Check one of them in a block explorer, and check that you did not pass token account addresses from another network. |
| A total that differs by a few lamports from another tool. | The two reads used different slots or commitment levels. Compare at the same commitment, and keep the list in one chunk when you need one slot. |
| Error -32601 method not found. | A misspelt method name, or a method Carbium does not serve. Fix the name. Do not retry it. |
Questions
Why not loop over getBalance?
It works, and it makes one request per address, each read at its own slot. getMultipleAccounts sends the list once per chunk and returns every balance in the chunk from one slot.
How many addresses fit in one call?
Up to 300 pubkeys on Pro and 100 below it, at 10 cells per pubkey. The file uses 100 so that a retry resends a small chunk.
Can I get token balances in the same call?
No. The lamports field is SOL only. A token balance lives in a token account, which you derive and read separately, as in SPL token balance.
Do I need a private key?
No. The call takes public addresses and returns their state. The Carbium key only identifies your account to the RPC.