library / Blockchain ideas / BI0060
30-day SOL balance chart
A wallet app can draw 30 days of SOL balance from three RPC methods. The chart is rebuilt from each transaction's postBalances at the wallet's account index, bucketed by UTC day and anchored on today's getBalance.
What the chart needs
A wallet screen that draws 30 days of SOL balance needs one number per day: what the account held when that day ended. No RPC method returns a past balance. getBalance answers for the present, and getAccountInfo does the same. The history has to be rebuilt from the transactions that touched the wallet.
Every transaction records, in postBalances, the lamport balance of each account it loaded, taken after it ran. Find the wallet's position in the transaction's account list and that array gives the wallet's balance right after the transaction. That is one point per transaction, and one point per day comes out by keeping the last one of each day.
| Piece | Call | What it gives |
|---|---|---|
| Transactions, newest first | getSignaturesForAddress | signature, blockTime and err for each row |
| Balance after each one | getTransaction | postBalances, slot, blockTime and the loaded addresses |
| Anchor | getBalance | the balance now |
Run node main.ts with no argument and it picks the fee payer of one of the newest System Program transactions, reads that wallet's newest five transactions and prints a line per point. Pass an address to chart your own wallet. Everything goes to services.carbium.sh with one key, and nothing is signed or sent.
Walking signatures newest to oldest
getSignaturesForAddress returns the signatures that mention one address, newest first. A page holds up to 1,000 rows. To go further back, pass the last signature of a page as before and ask again. The walk stops when a row's blockTime falls before the 30-day cutoff or when a page comes back empty. Signature history pagination covers the paging in detail.
Failed transactions stay in the list. When the wallet is the fee payer, a failed transaction still charges the fee, so the balance dropped and its postBalances shows the drop. The code keeps every row and never looks at err.
Each call in the file names confirmed. Kit would fill in the same level when a call leaves it out, while the server's own default is finalized. Using one level for the signature pages, the transaction reads and getBalance keeps the three in agreement, so the last point and the anchor are comparable.
The code reads at most 5 transactions, set by MAX, so a run finishes in seconds. Raise it to cover the whole 30 days, and set RATE to the plan's getTransaction rate from the cost table, because the loop sends one read per 1 / RATE seconds.
Reading the balance after each transaction
getTransaction takes a config with maxSupportedTransactionVersion: 1 and an encoding, here json. Mainnet carries v1 transactions, and a call without the version answers -32015 for one, so the point is lost. Set the version on every call, as Transaction version error -32015 shows.
The wallet's balance sits at the wallet's index in the full account list. That list is the message's static accountKeys, then the writable addresses loaded from lookup tables, then the readonly ones, and meta.postBalances follows the same order. A wallet that a transaction reaches only through a lookup table sits past the static keys, so a search of accountKeys alone misses it. The code joins the three lists from meta.loadedAddresses and takes indexOf.
Each point holds three values: blockTime, slot and the lamport balance. A lamport is one billionth of a SOL, so the chart divides by 1,000,000,000. The reads go out one at a time in a loop spaced by RATE, and each call sits in its own try, so one failed lookup costs one point and prints a skip line while the rest finish.
// BI0060 · 30-day SOL balance chart// https://carbium.sh/library/blockchainideas/30-day-sol-balance-chart// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";import type { Signature } 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 rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key }, }),);const DAYS = 30; // the address index keeps up to 30 daysconst MAX = 5; // transactions to read; raise it for the whole windowconst RATE = 1.2; // getTransaction calls per second; set it to your plan's rateconst SYSTEM = address("11111111111111111111111111111111");const cfg = { encoding: "json", maxSupportedTransactionVersion: 1, commitment: "confirmed" } as const;type Tx = { slot: bigint; blockTime: bigint | null; meta: { postBalances: (bigint | number)[]; loadedAddresses?: { writable: string[]; readonly: string[] } } | null; transaction: { message: { accountKeys?: string[] } };};const getTx = async (sig: Signature) => (await rpc.getTransaction(sig, cfg).send()) as unknown as Tx | null;const sol = (lamports: bigint) => (Number(lamports) / 1e9).toFixed(6);async function newestPayer(): Promise<string> { const rows = await rpc.getSignaturesForAddress(SYSTEM, { limit: 5, commitment: "confirmed" }).send(); for (const r of rows) { const payer = (await getTx(r.signature))?.transaction.message.accountKeys?.[0]; if (payer) return payer; } throw new Error("no fee payer found on the newest System Program transactions");}async function main(): Promise<void> { const wallet = address(process.argv[2] ?? (await newestPayer())); const cutoff = Date.now() / 1000 - DAYS * 86400; const sigs: Signature[] = []; let before: Signature | undefined; while (sigs.length < MAX) { const page = await rpc .getSignaturesForAddress(wallet, { limit: Math.min(1000, MAX - sigs.length), before, commitment: "confirmed" }) .send(); const inside = page.filter((r) => r.blockTime === null || Number(r.blockTime) >= cutoff); sigs.push(...inside.map((r) => r.signature)); if (page.length === 0 || inside.length < page.length) break; before = page[page.length - 1].signature; } const points: { time: number; slot: bigint; bal: bigint }[] = []; for (const [i, sig] of sigs.entries()) { if (i > 0) await new Promise((r) => setTimeout(r, 1000 / RATE)); try { const tx = await getTx(sig); if (!tx?.meta || tx.blockTime == null) throw new Error("no transaction body or block time"); const { loadedAddresses: la, postBalances } = tx.meta; const keys = [...(tx.transaction.message.accountKeys ?? []), ...(la?.writable ?? []), ...(la?.readonly ?? [])]; const at = keys.indexOf(wallet); if (at < 0) throw new Error("wallet not in the account list"); points.push({ time: Number(tx.blockTime), slot: tx.slot, bal: BigInt(postBalances[at]) }); } catch (e) { console.error(`skip ${sig}: ${e instanceof Error ? e.message : e}`); } } const days = new Map<string, bigint>(); for (const p of points) { const iso = new Date(p.time * 1000).toISOString(); console.log(`${iso} slot ${p.slot} ${sol(p.bal)} SOL`); if (!days.has(iso.slice(0, 10))) days.set(iso.slice(0, 10), p.bal); // newest first: a day's first point closes it } for (const [day, bal] of days) console.log(`close ${day} ${sol(bal)} SOL`); try { const { value } = await rpc.getBalance(wallet, { commitment: "confirmed" }).send(); console.log(`now ${sol(value)} SOL (${wallet})`); } catch (e) { console.error("getBalance failed:", e instanceof Error ? e.message : e); }}main().catch((e) => { console.error(e instanceof Error ? e.message : e); process.exit(1);});
run: CARBIUM_KEY=<YOUR_KEY> node main.ts [WALLET_ADDRESS]
Bucketing by day and anchoring on now
Points arrive newest first. Group them by UTC day and keep the first point seen for each day. That is the day's last transaction, and its postBalances value is the closing balance. A day with no transaction has no point, and the chart carries the closing balance of the nearest older day across it as a flat stretch.
Today's value comes from getBalance. A wallet with no transaction today still ends the line on the right number, and a wallet that moved a moment after the walk started shows the difference. When the anchor equals the newest point, the series is consistent. When it differs, a transaction landed between the first call and the balance read, or a credit with no transaction, such as a leader's fee reward paid to a validator identity account, arrived. Add the anchor as a last point in either case, and walk once more only for the first cause.
Buckets use UTC days. A wallet app that shows local days shifts the cut by the user's offset, and the same list of points rebuckets without any new call.
What it costs
Two methods carry the walk. A getSignaturesForAddress page costs 50 cells and each getTransaction costs 50 cells. Cells are the admission charge per call, and each plan sets a calls-per-second ceiling for the method a row names.
| Plan | Price per month | getSignaturesForAddress | getTransaction |
|---|---|---|---|
| Free | $0 | 0.24 req/s | 0.24 req/s |
| Dev | $20 | 1.2 req/s | 1.2 req/s |
| Business | $250 | 100 req/s | 5 req/s |
| Pro | $500 | 500 req/s | 25 req/s |
Take a wallet with 300 transactions in 30 days. The walk makes one signature page and 300 getTransaction calls. A burst of up to 1,024 cells absorbs the first 20 of those calls at once. The client paces the rest at the plan's rate, which takes about a minute on Business at 5 req/s and about 4 minutes on Dev at 1.2 req/s. The 0.24 req/s on Free is the rate for both methods, one call about every 4 seconds, so a Free key suits a quiet wallet or a walk that runs as a background job.
Limits are per account, and its keys share one budget. A nightly walk and the live app draw on the same rate. A wallet app should walk once, write the points to node:sqlite, and from then on ask for signatures newer than the newest stored one with until. A daily refresh then costs a handful of calls.
Where it ends
- The chart reaches back 30 days at most, because getSignaturesForAddress reads Carbium's own address index. An empty page past that is the index's age limit, and the wallet may have older transactions. A 90-day chart needs your own table, filled from today.
- getTransaction can answer null for a signature the index lists, since its pages reach below the validator's ledger floor. Those points are missing, so the oldest days of a long walk can show gaps. The code prints a skip line for each.
- One point is one transaction. Rows that share a second share a blockTime, and the order of the list says which one came last.
- The line holds lamports in the wallet account only. Balances in token accounts, wrapped SOL included, sit elsewhere, as Wrapped SOL account reader shows.
- Credits that reach a system account with no transaction, such as a leader's fee reward paid to its validator identity account, appear in no signature list. The first point after one reads its own postBalances and the jump shows up there.
- The walk charts one wallet. Several wallets need one walk each, and the rate table above applies to the sum.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| getTransaction answers -32015 for some signatures. | The config lacks maxSupportedTransactionVersion: 1, or holds 0. Mainnet carries v1 transactions, so set 1 on every call. The reply is uncharged. |
| The oldest days of the chart have no points. | getTransaction answered null for signatures the index still lists, since its pages reach below the validator's ledger floor. Skip them, show the gap, and keep your own points for later windows. |
| The last point and the getBalance line disagree. | A transaction landed after the walk began, or the calls used different commitment levels. Name the same level on every call and add the anchor as the final point. |
| Lines say wallet not in the account list. | The account list was built from static keys only. Add meta.loadedAddresses.writable and readonly after them, in that order, before taking the index. |
| The walk answers 429 midway. | The loop ran faster than the plan's rate for getTransaction. Slow the loop by lowering RATE to the rate in the cost table and honour the retry-after hint. Limits are shared by every key on the account. |
| A wallet returns an empty first page. | It has no transaction in 30 days. The chart is a flat line at the getBalance value. |
Questions
Is there a method that returns the balance at a past slot?
No. getBalance reads the present state, so the chart rebuilds the past from the postBalances of each transaction that touched the wallet.
Why postBalances and not preBalances plus arithmetic?
postBalances already includes the fee and every transfer in the transaction, so the value is the balance after it ran.
Can I chart 90 days from Carbium?
Not from one walk. The address index keeps up to 30 days. Write each point to a table as you read it, and a longer chart builds up from today.
Why set maxSupportedTransactionVersion to 1?
Mainnet carries v1 transactions, and a call that leaves the version out or sets 0 answers -32015 for one. With 1 the same call reads every version.
How do I keep the chart fresh without rewalking?
Store the points, then call getSignaturesForAddress with until set to the newest stored signature. Only the new transactions come back.