services
Get a key

library / Use cases / UC0036

Cost basis capture at receipt

A tax report needs the time and price of every receipt. A Node script records each SOL and token receipt of a wallet as a lot in SQLite, with slot, time and signature, ready for a price.

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

01

Why the receipt is the record

A tax report for a Solana wallet starts from lots. A lot is one receipt of an asset: how much arrived, when, and what it was worth in your reporting currency at that moment. When the asset is later sold or sent on, the report matches that disposal against lots, and the difference is the gain or loss. Your jurisdiction and your accountant choose the matching order (first in first out, specific lots, or an average), and the lots have to exist whichever wins.

Chain history is permanent in principle, but the signatures of an address come from an index that keeps up to 30 days. An empty page past that is the index's age limit, and the address may have older transactions. A year-end report built by walking an address back to January cannot be served from it. A job that captures lots as they arrive never needs to look back further than its own last run.

A transaction carries amounts and a block time and no fiat value, so something has to write the price down, and the easiest time is while the receipt is new.

02

What one lot holds

The script stores one row per receipt and per asset. Every field is read from the transaction, except the price, which stays empty until a pricing step fills it.

FieldWhere it comes fromWhy it is kept
signatureThe transaction's signatureThe audit trail from a report line back to the chain
assetSOL, or the token mintSOL sits in the wallet account and a token sits in a token account that names a mint
amount, decimalsThe change in lamports or token base units, as integer textExact arithmetic when lots are summed
slot, block_timeThe transaction's slot and blockTime, empty when the node has no block timeThe slot orders two receipts in one second and the time picks the price
unit_price_usdEmpty at captureFilled later by the pricing step

Amounts go into SQLite as text and are summed as BigInt. A SQLite integer is a signed 64-bit value, a token amount can reach the full unsigned 64-bit range, and a float loses digits past 2^53 base units.

03

The capture script

Run it with a wallet address, or with none: it then looks at the newest transactions of a busy program and picks a wallet that just received something. It reads the wallet's token accounts with getTokenAccountsByOwner for both token programs, lists the 4 newest signatures of the wallet and of its first 3 token accounts at confirmed commitment, and merges them by signature. It keeps the 4 newest by slot, fetches each with getTransaction and inserts a lot for every positive change of the wallet's SOL or token balance, printing each lot as it is written. It writes lots.db in the working directory and signs and sends nothing. Calls run one after another and each stops after 5 s. No call runs past 24 s, so a run ends inside 30 s. Each call is settled on its own, so one failure prints and the rest continue.

main.ts
// UC0036 · Cost basis capture at receipt// https://carbium.sh/library/usecase/cost-basis-capture-at-receipt// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: records what a wallet received in its newest transactions as cost basis lots in SQLite.import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, signature } from "@solana/kit";import { DatabaseSync } from "node:sqlite";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 BUSY_PROGRAM = "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4"; // only used to find a wallet when none is givenconst TOKEN_PROGRAMS = ["TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"];const LIMIT = 4; // signatures read per runconst end = Date.now() + 24_000; // no call starts or runs past this, so the run ends inside 30 sconst opt = () => ({ abortSignal: AbortSignal.timeout(Math.max(1, Math.min(5_000, end - Date.now()))) });console.log(`start: reading ${LIMIT} signatures from ${url}`);type Bal = { owner?: string; mint: string; uiTokenAmount: { amount: string; decimals: number } };type Tx = { slot: bigint; blockTime: bigint | number | null; transaction: { message: { accountKeys: { pubkey: string; signer?: boolean }[] } };  meta: { err: unknown; fee: bigint; preBalances: bigint[]; postBalances: bigint[]; preTokenBalances?: Bal[]; postTokenBalances?: Bal[] } | null };type Lot = { asset: string; amount: bigint; decimals: number };const getTx = async (sig: string) => (await rpc.getTransaction(signature(sig), { commitment: "confirmed", encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send(opt())) as unknown as Tx | null;// Positive balance changes of one wallet in one transaction: SOL first, then each token mint.function receipts(wallet: string, t: Tx): Lot[] {  const m = t.meta;  if (!m || m.err) return [];  const lots: Lot[] = [];  const i = t.transaction.message.accountKeys.findIndex((k) => k.pubkey === wallet);  if (i >= 0) {    // The fee payer's change includes the fee it paid: add it back.    const d = BigInt(m.postBalances[i]) - BigInt(m.preBalances[i]) + (i === 0 ? BigInt(m.fee) : 0n);    if (d > 0n) lots.push({ asset: "SOL", amount: d, decimals: 9 });  }  const net = new Map<string, Lot>();  for (const [list, sign] of [[m.preTokenBalances, -1n], [m.postTokenBalances, 1n]] as const) {    for (const b of list ?? []) {      if (b.owner !== wallet) continue; // match on the owner field, not on instruction accounts      const lot = net.get(b.mint) ?? { asset: b.mint, amount: 0n, decimals: b.uiTokenAmount.decimals };      lot.amount += sign * BigInt(b.uiTokenAmount.amount);      net.set(b.mint, lot);    }  }  return [...lots, ...[...net.values()].filter((l) => l.amount > 0n)];}// First signer or token owner whose SOL or token balance rose in one of the busy program's newest successful transactions.async function discover(): Promise<string | null> {  const sigs = await rpc.getSignaturesForAddress(address(BUSY_PROGRAM), { limit: 25, commitment: "confirmed" }).send(opt()).catch((e) => { console.log(`busy program: listing failed, ${String(e).slice(0, 80)}`); return []; });  for (const s of sigs) {    if (s.err) continue; // successful transactions only    if (Date.now() >= end - 10_000) break; // leave time for the capture itself    try {      const t = await getTx(s.signature);      if (!t) continue;      const cands = [...t.transaction.message.accountKeys.filter((k) => k.signer).map((k) => k.pubkey), ...(t.meta?.postTokenBalances ?? []).map((b) => b.owner ?? "")];      const found = cands.find((o) => o !== "" && receipts(o, t).length > 0);      if (found) return found;    } catch (e) { console.log(`${s.signature.slice(0, 12)}: failed, ${String(e).slice(0, 80)}`); }  }  return null;}const wallet = process.argv[2] ?? await discover();if (!wallet) { console.log("no receiving wallet found in the newest transactions of the busy program; pass a wallet address"); process.exit(1); }console.log(`wallet ${wallet}`);const db = new DatabaseSync("lots.db");db.exec("CREATE TABLE IF NOT EXISTS lots (wallet TEXT, signature TEXT, asset TEXT, amount TEXT, decimals INTEGER, slot TEXT, block_time INTEGER, unit_price_usd REAL, PRIMARY KEY (signature, asset, wallet))");const insert = db.prepare("INSERT OR IGNORE INTO lots (wallet, signature, asset, amount, decimals, slot, block_time) VALUES (?, ?, ?, ?, ?, ?, ?)");// A transfer into an existing token account never names the wallet: list the first 3 token accounts' signatures too.const addrs: string[] = [wallet];for (const p of TOKEN_PROGRAMS) {  try { addrs.push(...(await rpc.getTokenAccountsByOwner(address(wallet), { programId: address(p) }, { encoding: "base64", commitment: "confirmed" }).send(opt())).value.map((a) => a.pubkey)); }  catch (e) { console.log(`token accounts: failed, ${String(e).slice(0, 80)}`); }}const listed = addrs.slice(0, 4);const bySig = new Map<string, bigint>();for (const a of listed) {  try { for (const s of await rpc.getSignaturesForAddress(address(a), { limit: LIMIT, commitment: "confirmed" }).send(opt())) bySig.set(s.signature, s.slot); }  catch (e) { console.log(`${a.slice(0, 8)}: listing failed, ${String(e).slice(0, 80)}`); }}const sigs = [...bySig].sort((x, y) => Number(y[1] - x[1])).slice(0, LIMIT).map(([s]) => s);let added = 0;for (const sig of sigs) {  if (Date.now() >= end) { console.log("time budget reached, stopping"); break; }  try {    const t = await getTx(sig);    if (!t) { console.log(`${sig.slice(0, 12)}: null, older than the ledger the node holds`); continue; }    const time = t.blockTime == null ? null : Number(t.blockTime); // null keeps the lot out of the pricing step    for (const l of receipts(wallet, t)) {      added += Number(insert.run(wallet, sig, l.asset, l.amount.toString(), l.decimals, String(t.slot), time).changes);      console.log(`${sig.slice(0, 12)}  ${l.asset}  +${l.amount} base units, ${l.decimals} decimals, block time ${time}`);    }  } catch (e) { console.log(`${sig.slice(0, 12)}: failed, ${String(e).slice(0, 80)}`); }}console.log(`${wallet}: ${added} new lots from ${sigs.length} signatures across ${listed.length} addresses, stored in lots.db`);

run: CARBIUM_KEY=$CARBIUM_KEY node main.ts [wallet]

The primary key is wallet, signature and asset, so a rerun over the same signatures inserts nothing twice. A scheduled job can overlap its own previous window without care.

  • SOL: the wallet's balance after minus before, read at its index in the account keys. When the wallet pays the fee, the fee is added back, so a small receipt is not hidden by the fee of its own transaction. Only a positive result becomes a lot.
  • Tokens: the sum of the wallet's token accounts for a mint after the transaction minus the sum before. A wallet can own more than one token account for one mint, and a transfer to an existing token account lists the token accounts and the sender's authority and never the receiving wallet. That is why the script lists signatures for each token account as well as for the wallet. It then reads the owner field of each token balance entry in the transaction metadata and never looks for the wallet among the instruction accounts.
  • Failed transactions: skipped. A failed transaction moved nothing but its fee.
  • Versions: mainnet carries v1 transactions. getTransaction answers the transaction version error, -32015, uncharged, when maxSupportedTransactionVersion is absent or 0. The script passes 1.
  • Commitment: every call asks for confirmed.
04

Cost and the price column

A capture reads the token accounts once per token program, then costs one getSignaturesForAddress read for the wallet and for each of its first 3 token accounts, and one getTransaction per signature, 50 cells each. A wallet with 3 token accounts and four signatures is 2 token account reads, 4 listings and 4 fetches: 10 calls in all, and 400 cells for the listings and fetches. getTransaction runs at 0.24, 1.2, 5 and 25 req/s on Free, Dev, Business and Pro, and getSignaturesForAddress at 0.24, 1.2, 100 and 500.

A rate class absorbs bursts up to 1,024 cells or one second of its rate, whichever is larger. On Free that covers about 20 getTransaction calls. A run with no wallet argument first spends 1 listing and up to 25 getTransaction fetches on discovery, which is more than that Free burst. The budget is shared by all keys of the account. A backfill of a busy wallet belongs on a paid plan, run in sequence with a short pause between calls. A JSON-RPC post can also carry a batch of up to 100 calls, which saves round trips on a backfill.

The price column stays empty at capture on purpose. A pricing step is a separate job: it selects the lots where unit_price_usd is null, asks the price source your accountant accepts for the block_time of each, and updates the row. A lot with no block time is skipped, so it never gets a price for 1970. Write the source name and the read time beside the number, because a report is checked against them. The RPC endpoint answers a prices method among its quote methods.

05

Capturing as receipts land

A schedule is the simplest design. Run the script per wallet and let each run read the newest signatures. Size the interval so the receipts between two runs stay under the page, and page back with the before option until the job meets a signature it already stored. The page of 4 here is small so that one run stays inside its time limit.

For a live ledger, accountSubscribe sends nothing for a plain SOL wallet, so open one logsSubscribe per address, the wallet and each of its token accounts, because a mentions filter takes exactly one address. Each opens at 25 credits as a logs mentions subscription and then costs 20 credits per MiB sent. Call getTransaction on each notification. A mention of the wallet alone catches SOL receipts and only the token receipts that name the wallet, and it misses a transfer into an existing token account. With all of them, the rows match the script's, because the notification only tells you which signature to read. For a pattern that watches many addresses for incoming transfers, see Exchange deposit alerts.

06

Where it ends

  • Scope: the lots cover the addresses you pass in. An exchange account, another chain and a wallet you forgot are outside them.
  • Token accounts: the script lists only the wallet's first 3 token accounts. A tax job has to list every token account the wallet owns, one getSignaturesForAddress each, or it misses receipts that land in the rest.
  • Own transfers: a move between two wallets you own shows as a receipt in the second one. The script cannot know ownership, so mark those rows before the report treats them as a purchase.
  • Kind: a payment, an airdrop, a reward and a refund look the same in a balance change. Closing a token account returns its rent to the wallet, and that shows as a SOL receipt. The script records the amount and leaves classification and tax treatment to you and your accountant.
  • History: with no job running at the time, a receipt older than 30 days is not listed. A signature that is listed below the validator's ledger floor can still make getTransaction answer null, and the script prints those and moves on.
  • Token-2022 fees: the lot is what arrived after any transfer fee, and the sender's figure can be larger.
  • No gain math: the script stores lots. Matching sales to lots and computing gains is the report's job, and the rules differ by country.
07

When it goes wrong

what goes wrongwhat to do
A small SOL receipt is missing from the lots.When the wallet is the fee payer, its balance change includes the fee. Add the fee back, as the script does for account index 0.
getTransaction answers -32015 for some signatures.Pass maxSupportedTransactionVersion: 1 with an encoding. The error means a v1 transaction was read with the value absent or 0.
getTransaction answers null for a signature the address listing returned.The listing reaches below the validator's ledger floor. Handle null and capture on a schedule so receipts are read while they are new.
A rerun doubles the lots.Key the table on wallet, signature and asset and use INSERT OR IGNORE, so a repeated read changes nothing.
A token receipt is missing although the wallet got the tokens.The transaction was most likely never listed, because a transfer into an existing token account does not name the wallet. List the signatures of the wallet's token accounts too, as the script does. If the signature is listed, read the owner field of the pre and post token balances.
Totals are off in the last digits.Store base units as text, sum them as BigInt, and divide by the decimals only when the report formats a value.
08

Questions

Which cost basis method do these lots support?

All of them. A lot holds the amount, the time and the price, and first in first out, specific lots or an average is applied at report time. Which one is allowed depends on your jurisdiction, so ask your accountant.

Can I fill in lots for last year after the fact?

Only from a job that ran at the time or from records you hold elsewhere, since the address index keeps up to 30 days.

Why store both the slot and the block time?

The block time is a Unix second and a slot lasts about 200 ms, so the slot orders two receipts in the same second. The time is what a price is looked up by.

Do I need a WebSocket for this?

No. A scheduled run reads new signatures and is enough for a report. Use logsSubscribe when a screen must show a lot as it lands.

How do I capture several wallets?

Loop over the wallets in sequence and keep the same table, since the wallet is part of the key. Keep to your plan's getTransaction rate.