---
id: UC0007
title: "Wallet balance reconciliation"
url: https://carbium.sh/library/usecase/wallet-balance-reconciliation
collection: Use cases
category: Portfolio, tax and accounting
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Wallet balance reconciliation

Rebuild an address's SOL balance from its transactions and tie it to getBalance. You get the usual causes of a gap, a Node script that checks the balance chain transaction by transaction, and what the check costs in cells.

## Two numbers that should match

getBalance returns the lamports one account holds at one slot, at the commitment you ask for. A sum over history is a different object. It equals the balance only when the transaction list is complete, each amount is the amount the account really moved, and nothing changed the account outside a transaction.

Most gaps break one of those three conditions. The reliable fix reads the balance each transaction recorded for the address, then checks that the records join up. A node returns `preBalances` and `postBalances` for every account in a transaction, with fees and rent already inside them, so one transaction's effect on the address is its post minus its pre.

> Keep amounts as integer lamports, where 1 SOL is 1,000,000,000 lamports. A running float sum of SOL amounts drifts by a few lamports and looks like a discrepancy.

## Where the gap comes from

| Cause | What you see | Fix |
|---|---|---|
| Transfers summed from instructions | The sum is off by fees, rent and any transfer made inside another program's call: fees make it too high, rent and inner transfers move it either way | Read the address's `preBalances` and `postBalances` from `meta` |
| Failed transactions dropped | The balance is lower than your sum by the fees of the failed transactions the address paid for | getSignaturesForAddress lists failed transactions with an `err` value. Keep them, since a failed transaction still pays its fee |
| History cut short | Your sum starts at zero, but the account held lamports before the first transaction you fetched | Start from the oldest `preBalances` you have and check the links between transactions |
| Versioned transactions | getTransaction answers error -32015 for the signature, or the address is missing from the account list | Set `maxSupportedTransactionVersion: 1` and add `meta.loadedAddresses` to the account keys before looking up the address |
| Different slots | The balance is newer or older than the last transaction in your list | Use one commitment value on every call and drop transactions after the balance's `context.slot` |
| Wrapped SOL | A token account holds lamports as rent plus the wrapped amount, and the wallet's own balance leaves them out | Reconcile the token account as its own address |
| Protocol credits | The balance rose and no transaction in the list explains it | Rewards credited by the protocol, such as block rewards to a validator identity account, appear in the rewards list getBlock returns and carry no signature for the address |

The JSON-RPC server defaults to finalized, but @solana/kit 8.6.0 fills in confirmed when a call leaves commitment out, so two clients on one address can read different slots. The script passes `finalized` on every call. For the choice between levels, see [Solana commitment levels](https://carbium.sh/library/howsolana/solana-commitment-levels).

## Reconcile with a chain check

Matching one total proves little, because two errors can cancel. The chain check is stricter. Walking from newest to oldest, each transaction's pre-balance for the address must equal the post-balance of the transaction before it. A missing transaction, a dropped failed one or an unindexed range shows up as a link that does not join, at a named slot.

The check assumes signatures inside one slot come back newest first in block order. If two entries in one slot come back swapped, the break between them is an ordering artefact.

The script reads `getBalance` once, then `getSignaturesForAddress`, which returns newest first. It drops signatures from slots after the balance's `context.slot`, since those landed after the balance was read. It then calls getTransaction once per signature, finds the address among the account keys and records its pre and post. Last it prints each effect, every broken link and a verdict.

`main.ts` (run: `CARBIUM_KEY=$CARBIUM_KEY node main.ts <address> 8`)

```ts
// UC0007 · Wallet balance reconciliation
// https://carbium.sh/library/usecase/wallet-balance-reconciliation
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Read-only: rebuilds an address's SOL balance from its transactions and compares it with getBalance.
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } 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 target = process.argv[2];
if (!target) { console.error("Usage: node main.ts <address> [count]"); process.exit(1); }
const count = Number(process.argv[3] ?? 8);
const url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";
const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));
const owner = address(target);
const commitment = "finalized";
const AHEAD = 10; // extra signatures to read, for those that land after the balance read
const deadline = Date.now() + 20_000; // the whole run; each call gets at most 8 s of it
const within = () => AbortSignal.timeout(Math.max(1_000, Math.min(8_000, deadline - Date.now())));

type Tx = {
  meta: { preBalances: (bigint | number)[]; postBalances: (bigint | number)[];
    loadedAddresses?: { writable: string[]; readonly: string[] } } | null;
  transaction: { message: { accountKeys: string[] } };
};
type Step = { slot: bigint; failed: boolean; pre: bigint; post: bigint };

const sol = (v: bigint) => {
  const a = v < 0n ? -v : v;
  return `${v < 0n ? "-" : ""}${a / 1_000_000_000n}.${String(a % 1_000_000_000n).padStart(9, "0")}`;
};

try {
  const bal = await rpc.getBalance(owner, { commitment }).send({ abortSignal: within() });
  const page = await rpc.getSignaturesForAddress(owner, { limit: count + AHEAD, commitment }).send({ abortSignal: within() });
  const sigs = page.filter((s) => s.slot <= bal.context.slot).slice(0, count);
  const steps: Step[] = [];
  for (const s of sigs) {
    if (Date.now() >= deadline) { console.log(`time budget used: stopping with ${steps.length} transactions`); break; }
    let tx: Tx | null;
    try {
      tx = (await rpc.getTransaction(s.signature, { encoding: "json", maxSupportedTransactionVersion: 1, commitment }).send({ abortSignal: within() })) as unknown as Tx | null;
    } catch (e) {
      console.log(`${s.signature.slice(0, 8)}: ${e instanceof Error ? e.message : e}; stopping with ${steps.length} transactions`);
      break;
    }
    if (!tx?.meta) { console.log(`${s.signature.slice(0, 8)}: no transaction returned`); continue; }
    const loaded = tx.meta.loadedAddresses;
    const keys = [...tx.transaction.message.accountKeys, ...(loaded?.writable ?? []), ...(loaded?.readonly ?? [])];
    const i = keys.indexOf(owner);
    if (i < 0) { console.log(`${s.signature.slice(0, 8)}: address not among the account keys`); continue; }
    steps.push({ slot: s.slot, failed: s.err !== null, pre: BigInt(tx.meta.preBalances[i]!), post: BigInt(tx.meta.postBalances[i]!) });
  }

  // Newest first: this entry's pre must equal the post of the next (older) entry.
  const gap = (n: number) => n + 1 < steps.length && steps[n + 1]!.post !== steps[n]!.pre;
  steps.forEach((r, n) => {
    const note = gap(n) ? `  BROKEN: older entry ends at ${sol(steps[n + 1]!.post)}, this one starts at ${sol(r.pre)}` : "";
    console.log(`slot ${r.slot} ${r.failed ? "failed" : "ok"} ${sol(r.post - r.pre)} SOL${note}`);
  });

  const newest = steps[0];
  console.log(`getBalance at slot ${bal.context.slot}: ${sol(bal.value)} SOL`);
  if (!newest) console.log("no transactions in the address index for this window");
  else {
    const links = steps.filter((_, n) => gap(n)).length;
    console.log(`newest post-balance ${sol(newest.post)} SOL, ${links} broken link(s) in ${steps.length} transactions`);
    console.log(newest.post === bal.value && links === 0 ? "RECONCILED" : "DISCREPANCY: see the broken links above, or a change no transaction carries");
  }
} catch (e) {
  console.error("failed:", e instanceof Error ? e.message : e);
  process.exitCode = 1;
}
process.exit();
```

Run it with an address and a count. It fetches one transaction at a time with no pause between calls. On Free, a window of 8 fits inside the burst. It signs and sends nothing. Each call has 8 seconds and the whole run has 20, and when a lookup fails or times out the script stops there and reports the newest transactions it already has.

- Reconciled: the newest post-balance equals getBalance and no link broke. The window explains the balance from its opening value.
- A broken link at a slot: a transaction between those two entries is missing from your list, or a protocol credit fell between them. Fetch more signatures with `before`, and check that you kept failed transactions.
- Links intact but the newest post-balance differs from getBalance: the balance moved after the newest transaction, for example a protocol credit, or by another change no transaction carries.
- Everything matches but your own total differs: the error is in your sum. Compare your per-transaction numbers with the printed effects.

## What the check costs

A run is one getBalance, one getSignaturesForAddress and one getTransaction per transaction. The two methods [cost 50 cells each](https://carbium.sh/docs#rpc), so a window of 8 transactions is 450 cells plus the getBalance call. The request rates for those two methods differ by plan.

| Plan | getTransaction req/s | getSignaturesForAddress req/s |
|---|---|---|
| Free | 0.24 | 0.24 |
| Dev | 1.2 | 1.2 |
| Business | 5 | 100 |
| Pro | 25 | 500 |

For 50 lookups, the first 20 ride the 1,024-cell burst. The other 30 take about 25 s on Dev at 1.2 req/s and about 6 s on Business at 5 req/s. A Free key gets through about 20 lookups per class on its burst, then each further 50-cell call needs about 4 s of refill at 0.24 req/s.

A finalized transaction never changes, so store each address's pre and post by signature. The next run asks getSignaturesForAddress with `until` set to the newest stored signature, fetches only what is new and extends the chain.

## Keeping it current

Polling a live wallet wastes calls. On Carbium accountSubscribe stays silent for a plain SOL wallet, so subscribe with [`logsSubscribe` and a mentions filter](https://carbium.sh/docs#websocket) on the address, and call getBalance when a log arrives. The notification carries the signature. Fetch that transaction, append its pre and post to your stored chain and check that its pre equals your last post.

A logs subscription with a mentions filter opens at 25 credits, then costs 20 credits per MiB sent, and a refused subscription is free.

## Where it ends

- Reach: getSignaturesForAddress pages come from [Carbium's own address index](https://carbium.sh/docs#migrate), which keeps up to 30 days. Those pages reach below the validator's ledger floor, so getTransaction can return null for an older listed signature, and the check then shows a broken link there. An empty page past 30 days means the index ran out of age, and the address may have older transactions, with an opening balance the index cannot show. Keep your own store from your first run onward.
- The check proves a window. It shows that the transactions in the window join up and match the balance. It cannot prove the opening value of the window.
- Protocol credits carry no transaction. A credit that falls inside the window shows as a broken link at its slot. One that lands after the newest transaction shows as an intact chain with a getBalance mismatch. Block data is the place to look.
- The script reconciles SOL lamports only. Token balances live in token accounts with their own history; see [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance).
- It reads one page of at most the count you pass. For a longer window, store pre and post by signature and page with `before`.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| getTransaction errors on some signatures. | Mainnet carries v1 transactions, and a call with `maxSupportedTransactionVersion` absent or 0 answers -32015 for them. Set `maxSupportedTransactionVersion: 1` on the call, as the script does, and add the loaded addresses to the account keys. |
| The rebuilt balance comes out higher than getBalance by about one fee per transaction. | Instruction amounts leave out the fee the address paid, so a sum of them is too high by about one fee per transaction it paid for. Rent can move it either way. Use the address's post minus pre from `meta`. |
| The newest post-balance differs from getBalance and no link is broken. | Either a transaction landed after the balance read or the address received a protocol credit after its newest transaction. The script already drops signatures after the balance slot, so a remaining difference is a change no transaction carries. Check first for a "no transaction returned" or "address not among the account keys" line, since a skipped newest signature also leaves an intact chain with a mismatch. |
| A 429 stops the run partway through a window. | Rerun with a smaller count. Store finalized pre and post by signature so a rerun fetches only new ones. A Free key past 20 lookups needs about 4 s per call. |
| Two clients report different balances for the same address. | They read different commitments. Set one commitment explicitly in every call. |
| getBalance reads 0 for an address that has history. | The account may have been closed. The last post-balance in its chain is then 0, and the chain check still applies. |

## Questions

### Why does summing transfer amounts rarely match getBalance?

Transfer amounts leave out the fees and rent a transaction moves, and any transfer a program makes inside another call. Post minus pre from the transaction's `meta` includes all of them. An address that only receives plain transfers and never pays a fee can match.

### Should I read finalized or confirmed?

Pick one and pass it on every call. The script uses finalized.

### How far back can I reconcile on Carbium?

getSignaturesForAddress reaches back 30 days at most, from Carbium's own address index. For older history you need records you stored yourself.

### Can I include token balances in the same check?

Reconcile each token account as its own address, since its balance is in the account's data and wallet lamports do not include it. See [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance).

## Related

- [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) (How to use Solana, HS0001)
- [Solana commitment levels](https://carbium.sh/library/howsolana/solana-commitment-levels) (How to use Solana, HS0003)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
- [carbium.sh/docs#migrate](https://carbium.sh/docs#migrate)
