services
Get a key

library / Use cases / UC0037

Wallet journal entries export

Accounting software wants one flat list per wallet. The script reads a wallet's newest transactions, subtracts the before and after balances for SOL and each token, and writes a CSV of signed amounts, fees and status.

By Carbium · Portfolio, tax and accounting · UC0037 · updated 2026-11-22

01

What the books need from a wallet

Accounting software for a Solana wallet starts from one flat list. Each line carries a time, a transaction signature, an asset, a signed amount and the fee paid. The chain does not store history in that shape. A transaction is a bundle of instructions, and the amounts that matter sit in the balance snapshots the runtime records before and after it ran.

The journal reads those snapshots and skips the instructions. Instruction layouts differ for every program, while the snapshot arrays look the same for a plain transfer, a swap through a router and a mint you have never seen. For one wallet the rule is short: subtract the pre balance from the post balance, once for SOL and once for each mint the wallet holds tokens of. A change of zero produces no line.

The result is one row per asset per transaction, written to journal.csv. Your accountant maps rows to ledger accounts, and a price source adds fiat values.

02

Two reads feed every line

getSignaturesForAddress lists the newest signatures that mention the wallet, and getTransaction returns the full record of each. Both go to the RPC endpoint https://services.carbium.sh with the key in the `x-api-key` header, and each call costs 50 cells.

The signature list comes from an address index that keeps up to 30 days, so an export built here covers the last 30 days at most. A signature near the old edge can be listed while getTransaction answers null for it, because the list reaches below the validator's ledger floor. The script reads the finalized slot with getSlot, keeps only the listed signatures at or below that slot, and reads those at finalized commitment. It retries each null once after two seconds, then counts it as a gap and moves on.

Pass maxSupportedTransactionVersion: 1 together with an encoding. Mainnet carries v1 transactions, and a call without the option, or with 0, answers -32015 for one of them, uncharged, and that row is lost (Transaction version error -32015 covers it). The script asks for jsonParsed, which resolves address lookup tables, so the account keys line up by index with the balance arrays.

The script makes at most about 1,000 cells of calls. Eight transactions cost 400 cells, and a retry of every one of them would add another 400, so reads that succeed on the first try spend none of it. The wallet list costs 50 and the slot read 1. Picking a busy wallet when none is given adds a slot read, a list, a read and a retry for at most 151. That fits inside the 1,024 cells a rate class absorbs as a burst, so the script sends the eight reads at once. A larger page needs spacing between reads, sized to your plan's req/s.

03

The script

Run it with node main.ts after exporting CARBIUM_KEY. A wallet address added after the command is optional. Without one, the script takes the newest finalized signature of a busy program, reads that transaction and uses its fee payer as the wallet, so the wallet it exports has just been active. It exits with a message when the key is unset, and it takes optional CARBIUM_RPC_URL. Each read settles on its own: a failed one prints its signature and the rest still reach the file. It signs and sends nothing.

main.ts
// UC0037 · Wallet journal entries export// https://carbium.sh/library/usecase/wallet-journal-entries-export// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: turns a wallet's newest transactions into journal lines, one per asset changed, and writes journal.csv.import { writeFileSync } from "node:fs";import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, 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 url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));const commitment = "finalized" as const; // lists are cut at the finalized slot, and the reads use the same commitment// Worst case in cells: wallet list 50, slot 1, 8 reads 400, 8 retries 400, busy-wallet pick 151 = 1,002, inside the 1,024 burst.const LIMIT = 8;type Bal = { owner?: string; mint: string; uiTokenAmount: { amount: string; decimals: number } };type Tx = {  blockTime: number | bigint | null;  transaction: { message: { accountKeys: { pubkey: string }[] } };  meta: { err: unknown; fee: number | bigint; preBalances: (number | bigint)[]; postBalances: (number | bigint)[];    preTokenBalances?: Bal[]; postTokenBalances?: Bal[] } | null;};// A null gets one retry after a wait before it counts as a gap.async function readTx(sig: string): Promise<Tx | null> {  const get = async () => (await rpc.getTransaction(signature(sig), { commitment, encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send()) as unknown as Tx | null;  const first = await get();  if (first) return first;  await new Promise((resolve) => setTimeout(resolve, 2000));  return get();}// The newest signatures of an address, keeping only those at or below the finalized slot.async function recent(addr: string, limit: number) {  const slot = await rpc.getSlot({ commitment }).send();  const list = await rpc.getSignaturesForAddress(address(addr), { limit, commitment }).send();  return list.filter((s) => s.slot <= slot);}// One row per asset the wallet's balance moved in: [time, signature, status, asset, change, decimals, fee].function lines(wallet: string, sig: string, t: Tx): string[][] {  const m = t.meta;  if (!m) return [];  const when = t.blockTime == null ? "" : new Date(Number(t.blockTime) * 1000).toISOString();  const status = m.err ? "failed" : "ok";  const rows: string[][] = [];  const i = t.transaction.message.accountKeys.findIndex((k) => k.pubkey === wallet);  if (i >= 0) {    const fee = i === 0 ? BigInt(m.fee) : 0n; // the fee payer is the first account    const moved = BigInt(m.postBalances[i]) - BigInt(m.preBalances[i]) + fee;    if (moved !== 0n || fee > 0n) rows.push([when, sig, status, "SOL", String(moved), "9", String(fee)]);  }  const net = new Map<string, { change: bigint; decimals: number }>();  const add = (list: Bal[] | undefined, sign: bigint) => {    for (const b of list ?? []) {      if (b.owner !== wallet) continue; // the owner field holds the wallet      const e = net.get(b.mint) ?? { change: 0n, decimals: b.uiTokenAmount.decimals };      e.change += sign * BigInt(b.uiTokenAmount.amount);      net.set(b.mint, e);    }  };  add(m.preTokenBalances, -1n);  add(m.postTokenBalances, 1n);  for (const [mint, e] of net) if (e.change !== 0n) rows.push([when, sig, status, mint, String(e.change), String(e.decimals), "0"]);  return rows;}let wallet = process.argv[2];if (!wallet) {  // No argument: borrow a busy wallet, the fee payer of a busy program's newest finalized transaction.  const [s] = await recent("JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4", 3);  const t = s ? await readTx(s.signature) : null;  if (!t) { console.error("No wallet given and none found; pass one."); process.exit(1); }  wallet = t.transaction.message.accountKeys[0].pubkey;}const owner: string = wallet;const sigs = await recent(owner, LIMIT);const reads = await Promise.allSettled(sigs.map((s) => readTx(s.signature)));const rows: string[][] = [];let missing = 0;reads.forEach((r, n) => {  const sig = sigs[n].signature;  if (r.status === "rejected") { console.error(`read failed ${sig}: ${String(r.reason).slice(0, 120)}`); missing++; }  else if (r.value === null) { console.error(`no record for ${sig}`); missing++; }  else rows.push(...lines(owner, sig, r.value));});rows.reverse(); // oldest firstconst header = "time,signature,status,asset,change,decimals,fee_lamports";writeFileSync("journal.csv", [header, ...rows.map((r) => r.join(","))].join("\n") + "\n");console.log(`${owner}: ${sigs.length} signatures, ${rows.length} journal lines, ${missing} unreadable, written to journal.csv`);for (const r of rows.slice(0, 8)) console.log("  " + r.join(" "));

run: node main.ts

Amounts stay as integers in base units: lamports for SOL, the mint's smallest unit for tokens, with the decimals in their own column. Divide in the spreadsheet, per row, using that column. When the wallet pays the fee, the SOL line excludes it and the fee sits in its own column, so a swap and its fee show apart.

04

Reading the columns

ColumnMeaningSource field
timeBlock time as an ISO timestampblockTime
signatureThe transaction the line belongs tothe listed signature
statusok, or failed when the transaction erroredmeta.err
assetSOL, or the mint address of a tokentoken balance mint
changeSigned base units; for SOL the fee is not in itpost minus pre balance
decimals9 for SOL, the mint's decimals for a tokentoken balance decimals
fee_lamportsThe fee when the wallet is the fee payer, else 0meta.fee
  • A failed transaction still charges its fee. It appears as a SOL line with a change of 0 and the fee filled in.
  • Token lines match on the owner field of the token balance, so a wallet with two token accounts for one mint gets one net line.
  • Opening a token account moves rent out of the wallet. It shows as a SOL change in that transaction, and your accountant books it as a deposit that returns when the account closes.
  • A swap that wraps SOL shows a SOL line and, when the wallet keeps a wrapped SOL token account, a line for the wrapped SOL mint. Book that pair as one movement. A temporary wrapped SOL account opened and closed inside the swap leaves no token balance, so it produces only the SOL line.
05

Covering the whole 30 days

To page further, pass before with the oldest signature of the last page and repeat until a page comes back empty. One getSignaturesForAddress call returns up to 1,000 signatures, and every signature you keep then needs its own getTransaction. A POST can carry a batch of up to 100 calls, which cuts round trips for those reads. Each call in a batch still costs its 50 cells against the same burst, so a batch of getTransaction calls stays at about 20 below Pro.

A wallet's own address misses one kind of transaction. A token transfer to an existing token account lists the token accounts and the sender's authority, and never the receiving wallet, so the receiving side stays out of the wallet's signature list. Cover it by listing the wallet's token accounts with getTokenAccountsByOwner (the read in Wallet token holdings), listing signatures for each token account address as well, and removing duplicates by signature before the transaction reads. Each extra address adds one 50-cell list call.

Run the export on a schedule and keep the rows in a table keyed by signature and asset, so a rerun inserts only what is new. node:sqlite does it with INSERT OR IGNORE. The index forgets after 30 days, so a schedule that skips a stretch longer than that leaves a gap nobody can fill later.

06

Where it ends

  • Thirty days at most: older history is not served, and an empty page past the index's age limit says nothing about whether older transactions exist. Your own stored export becomes the record from the first run onward.
  • No labels: the file records what moved, and deciding whether a line is a payment, a swap or income is left to your accountant's rules.
  • No fiat values and no cost basis: amounts are base units. Prices and tax treatment belong to the next stage.
  • Net per transaction: a wallet that sends and receives the same mint inside one transaction shows only the difference.
  • Wallet-mentioned transactions only: incoming token transfers need the token account step above.
  • Gaps are counted: unreadable and null reads print with their signatures, and a rerun fills a gap only while that signature is still in the newest page, or when you page back to it with before.
07

When it goes wrong

what goes wrongwhat to do
The newest transactions are missing from the file and the log shows -32015.Send maxSupportedTransactionVersion: 1 with an encoding on getTransaction. Without it, v1 transactions answer -32015.
getTransaction answers null for a signature the list returned.The signature sits below the validator's ledger floor, which the 30-day address index reaches past, so no record exists for it. Print it and count it as a gap, as the script does. Export a wallet with activity in the last few minutes to confirm the code on the newest signatures, and keep your stored rows for the older ones.
Incoming token transfers are absent from the journal.The receiving wallet is not in such a transaction. Add each token account of the wallet as a signature source and deduplicate by signature.
A swap shows a SOL line but no token line.Compare the wallet with the owner field of each token balance. Matching the token account's own address against the wallet finds nothing, because that address is a different account.
SOL totals differ from the wallet balance by small amounts.The wallet's SOL movement is the change column minus the fee column. Token account rent already sits in the change column. Any remaining gap comes from unreadable rows or from transactions outside the exported page.
A larger page fails partway with 429.Send fewer reads at once, wait the retry-after the response names, and rerun. The script rewrites journal.csv from the newest page on every run. A rerun fills only the missing rows once you keep rows in a table keyed by signature and asset.
08

Questions

How far back can I export a wallet?

Up to 30 days, the reach of the address index behind getSignaturesForAddress. Run the export on a schedule and keep the rows yourself, since the index does not hold older transactions.

How do I book rent and wrapped SOL?

Rent for a new token account shows as a SOL change and returns when the account closes, so book it as a deposit. A wrapped SOL line pairs with the SOL line only when the wallet keeps a wrapped SOL token account; a temporary one closed inside the swap leaves only the SOL line.

Can I export many wallets?

Run the script once per wallet and merge the files by signature and asset. Within a wallet, a POST can carry a batch of up to 100 calls, but each call still costs 50 cells against the 1,024-cell burst, so below Pro a batch of transaction reads stays near 20 calls and inside your plan's req/s.

Why does a failed transaction appear in the journal?

The fee is charged even when the transaction errors. The line has a change of 0, the status failed and the fee in lamports.

Does the file include prices?

No. It holds base-unit amounts and decimals. Add fiat values in the next stage from your own price source and the date of each row.