---
id: UC0065
title: "Realized gains on disposals"
url: https://carbium.sh/library/usecase/realized-gains-on-disposals
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
---

# Realized gains on disposals

A swap carries its own price in its two legs. Read a wallet's balance deltas from getTransaction, match disposals to first-in first-out lots, and print the implied rate and gain per transaction. History reaches 30 days, so early lots stay missing.

## A disposal in balance deltas

A tax tool needs one fact per event: what the wallet gave up and what it received. On Solana both sit in the transaction's metadata. `getTransaction` returns balances from before and after execution: lamports per account in `preBalances` and `postBalances`, and token amounts per token account in `preTokenBalances` and `postTokenBalances`, each token row with an `owner`. Subtract pre from post for every row the wallet owns and group by mint. A mint whose total fell is a disposal leg. A mint whose total rose is an acquisition leg.

Plain SOL has no token account, so the script reads it from the wallet's own account index and adds the fee back when that wallet pays it. That keeps the fee out of the proceeds. Wrapped SOL is a token account and shows up under its own mint, apart from the SOL row. A token account that opens and stays open takes about 0.002 SOL of rent, which the SOL row shows as a small extra outflow.

## Lots and first-in first-out

A lot is one acquisition: how much of a mint came in, and what went out to get it. A disposal consumes lots oldest first. If a wallet sells 10 units and the oldest lot holds 4, that lot is used up and the other 6 units come from the next lot, with each lot's cost split in proportion to the units taken.

The gain on a disposal is its proceeds for the covered units minus the cost carried by the lots those units came from. The script keeps lots in memory per mint and replays transactions oldest first, so a lot exists before the sale that uses it. A disposal with no lot behind it has no cost to subtract. The script prints how many of the sold units its lots covered and leaves the rest unpriced.

## Pricing from the other leg

Tax tools usually price every asset from an outside feed keyed by timestamp. A swap prices itself. If a wallet gave 2 SOL and received 300 units of a token in one transaction, the rate is 150 tokens per SOL at that slot, and the two legs come from the same record. The lot created for the token carries a cost of 2 SOL. Selling it later for 3 SOL gives a gain of 1 SOL, with no feed in the calculation.

That holds while proceeds and cost are in the same mint. A lot bought with USDC and sold for SOL has its cost in one unit and its proceeds in another, and converting one into the other needs a rate at the time of each leg, from a source you pick. The script prints that case as needing an outside rate. A leg in a dollar-pegged token gives a fiat figure directly, as far as the peg held.

## The script

Run it with a wallet, or with none. With none it takes the newest wrapped SOL mint signature, reads that transaction and uses its fee payer, so a run always has a real wallet. It lists up to 20 of the wallet's newest signatures, drops failed ones and reads at most 5 with `getTransaction` at `maxSupportedTransactionVersion: 1`. Every call sets finalized, and each read is settled on its own, so one failure prints as a line and the rest continue. Per transaction it prints the mints that fell and rose, and for a one-for-one swap the implied rate, how many sold units its lots cover, and the gain.

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

```ts
// UC0065 · Realized gains on disposals
// https://carbium.sh/library/usecase/realized-gains-on-disposals
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Read-only: realized gain per swap from a wallet's own transactions, with first-in first-out lots.
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 url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";
const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));

const WSOL = "So11111111111111111111111111111111111111112";
const cfg = { commitment: "finalized", encoding: "jsonParsed", maxSupportedTransactionVersion: 1 } as const;
type Bal = { owner?: string; mint: string; uiTokenAmount: { amount: string; decimals: number } };
type Tx = { meta: { fee: bigint | number; preBalances: (bigint | number)[]; postBalances: (bigint | number)[];
  preTokenBalances?: Bal[]; postTokenBalances?: Bal[] } | null;
  transaction: { message: { accountKeys: ({ pubkey: string } | string)[] } } };
type Leg = { d: bigint; dec: number };
type Lot = { qty: bigint; left: bigint; cost: bigint; costMint: string };

async function newest(addr: string, limit: number) {
  const all = await rpc.getSignaturesForAddress(address(addr), { limit, commitment: "finalized" }).send();
  return all.filter((s) => s.err === null);
}

// Balance change per mint for one owner: post minus pre, SOL from the account index with the fee added back.
function deltas(tx: Tx, owner: string): Map<string, Leg> {
  const out = new Map<string, Leg>();
  const add = (mint: string, v: bigint, dec: number) => out.set(mint, { d: (out.get(mint)?.d ?? 0n) + v, dec });
  const m = tx.meta!;
  const keys = tx.transaction.message.accountKeys.map((k) => (typeof k === "string" ? k : k.pubkey));
  const i = keys.indexOf(owner);
  if (i >= 0) add("SOL", BigInt(m.postBalances[i]) - BigInt(m.preBalances[i]) + (i === 0 ? BigInt(m.fee) : 0n), 9);
  for (const b of m.preTokenBalances ?? []) if (b.owner === owner) add(b.mint, -BigInt(b.uiTokenAmount.amount), b.uiTokenAmount.decimals);
  for (const b of m.postTokenBalances ?? []) if (b.owner === owner) add(b.mint, BigInt(b.uiTokenAmount.amount), b.uiTokenAmount.decimals);
  for (const [k, l] of out) if (l.d === 0n) out.delete(k);
  return out;
}

let wallet = process.argv[2];
if (!wallet) { // no argument: use the fee payer of the newest wrapped SOL transaction
  const [s] = await newest(WSOL, 10);
  const first = s ? ((await rpc.getTransaction(s.signature, cfg).send()) as unknown as Tx | null) : null;
  const k = first?.transaction.message.accountKeys[0];
  if (!s || !k) { console.error("No wrapped SOL transaction found; pass a wallet."); process.exit(1); }
  wallet = typeof k === "string" ? k : k.pubkey;
  console.log(`no wallet given, using the payer of ${s.signature.slice(0, 8)}: ${wallet}`);
}
const owner = wallet;
const sigs = (await newest(owner, 20)).slice(0, 5);
const got = await Promise.allSettled(sigs.map(
  (s) => rpc.getTransaction(s.signature, cfg).send() as unknown as Promise<Tx | null>));

const lots = new Map<string, Lot[]>();
const ui = (v: bigint, dec: number) => Number(v) / 10 ** dec;
const show = ([m, l]: [string, Leg]) => `${m.slice(0, 4)} ${ui(l.d, l.dec)}`;

for (let i = got.length - 1; i >= 0; i--) { // oldest first, so a lot exists before the sale that uses it
  const tag = sigs[i].signature.slice(0, 8);
  const r = got[i];
  if (r.status === "rejected") { console.log(`${tag} read failed: ${String(r.reason).slice(0, 80)}`); continue; }
  if (!r.value?.meta) { console.log(`${tag} null: older than the ledger the node serves`); continue; }
  const legs = deltas(r.value, owner);
  const fell = [...legs].filter(([, l]) => l.d < 0n);
  const rose = [...legs].filter(([, l]) => l.d > 0n);
  console.log(`${tag} fell: ${fell.map(show).join(", ") || "-"}  rose: ${rose.map(show).join(", ") || "-"}`);
  if (fell.length !== 1 || rose.length !== 1) { console.log("  not a one-for-one swap, no rate"); continue; }
  const [fm, f] = fell[0];
  const [rm, g] = rose[0];
  const sold = -f.d;
  let need = sold, gain = 0n, mixed = false;
  for (const lot of lots.get(fm) ?? []) { // first in, first out
    if (need === 0n) break;
    if (lot.left === 0n) continue;
    const p = lot.left < need ? lot.left : need;
    if (lot.costMint === rm) gain += (g.d * p) / sold - (lot.cost * p) / lot.qty; else mixed = true;
    lot.left -= p;
    need -= p;
  }
  lots.set(rm, [...(lots.get(rm) ?? []), { qty: g.d, left: g.d, cost: sold, costMint: fm }]);
  const verdict = mixed ? "gain needs an outside rate" : need === sold ? "no lot seen" : `gain ${ui(gain, g.dec)} ${rm.slice(0, 4)}`;
  console.log(`  rate ${ui(g.d, g.dec) / ui(sold, f.dec)} ${rm.slice(0, 4)} per ${fm.slice(0, 4)}, lots cover ${ui(sold - need, f.dec)} of ${ui(sold, f.dec)}, ${verdict}`);
}
```

Amounts stay integers in base units until display. Splitting a lot's cost uses integer division, which can drop up to one base unit per lot. A transaction with several falling or rising mints, as a routed swap can have, prints its legs and gets no rate. Without the version setting a v1 transaction answers [-32015](https://carbium.sh/docs#errors) and the read yields nothing, as [Transaction version error -32015](https://carbium.sh/library/howsolana/transaction-version-error-32015) shows.

The listing and each transaction read cost [50 cells](https://carbium.sh/docs#rpc). getTransaction runs at 0.24, 1.2, 5 and 25 req/s on Free, Dev, Business and Pro, and the listing at 0.24, 1.2, 100 and 500. A rate class absorbs a [burst](https://carbium.sh/docs#limits) of at least 1,024 cells, so one listing and five reads fit inside one burst. A long backfill needs a higher plan or a paced loop.

## How far back it reads

`getSignaturesForAddress` on Carbium comes from [its own address index](https://carbium.sh/docs#migrate) that keeps up to 30 days. An empty page past 30 days is the index's age limit, and the wallet may have older transactions this read cannot list. Its pages also reach below the validator's ledger floor, so `getTransaction` can answer null for a signature the listing returned. The script prints the null and moves on. It never treats a null as a transaction with no balance change.

To go past the first page, pass the oldest signature of a page as `before`; [Signature history pagination](https://carbium.sh/library/howsolana/signature-history-pagination) covers the loop. Each transaction read costs 50 cells, so a wallet with 2,000 transactions in the window costs 100,000 cells to replay, and the plan's req/s sets how long that takes. Replay once, store the rows in your own database and read only newer signatures afterwards.

## Where it ends

- No tax advice: first-in first-out is one lot method. Whether a swap is taxable, which method applies, how fees and holding periods count and how income is treated depend on the jurisdiction and the taxpayer. The output is a record of facts for an accountant to apply rules to, and it states no tax conclusion.
- Missing early lots: lots from before the 30-day window never reach the script, so a disposal of an older holding shows less than full cover. Load opening lots from your own records or an export into the lot map first.
- Single-leg changes: a rise with no fall could be a transfer from your other wallet, an airdrop or a payment received, and a fall with no rise could be a transfer out. The script cannot tell which and prints no rate for them.
- Same asset, two rows: SOL and wrapped SOL are separate mints in the deltas. A swap that wraps SOL and closes the account in the same transaction shows the SOL row, and one that keeps the account shows the wrapped SOL mint. Merge them in your ledger.
- Fees and rent: network fees stay outside the proceeds, and rent for token accounts that stay open shows as a small SOL outflow. Book both on their own lines.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| getTransaction answers -32015 on some signatures. | Send maxSupportedTransactionVersion: 1 with an encoding on every getTransaction. Absent or 0 fails for a v1 transaction, and the failed call is uncharged. |
| getTransaction returns null for a signature the listing just gave. | The 30-day address index reaches below the validator's ledger floor. Record the signature as a gap in the ledger and never as a zero change. |
| A disposal prints no gain although lots exist. | Check the lot's cost mint. A gain needs proceeds and cost in one mint, so a lot bought with USDC and sold for SOL needs an outside rate. |
| A swap shows a tiny SOL change beside a large token change. | The SOL leg went through a wrapped SOL account. Treat SOL and wrapped SOL as one asset in the ledger and book the rent on its own line. |
| A backfill on a Free key gets 429 on getTransaction. | getTransaction runs at 0.24 req/s on Free. Pace the reads to the retry-after hint, or move up a plan for a long replay. |

## Questions

### Do I need a price feed for a tax calculator?

A swap between two tokens prices itself from its own legs, and a lot's gain needs no feed while cost and proceeds share a mint. Fiat figures for a SOL leg need a SOL price at that time from a source you choose.

### Can I use a lot method other than first-in first-out?

Yes. Only the loop that picks lots changes, for example ordering by highest cost first. Which method you may use depends on your jurisdiction, so ask your accountant before you switch.

### How far back can a wallet's gains be rebuilt?

The signature listing reaches 30 days at most, and getTransaction can answer null for the oldest ones it lists. Earlier lots have to come from your own records.

### How do I load opening lots from an export before the replay?

Fill the lot map before the replay loop, one entry per mint holding `qty`, `left`, `cost` and `costMint`, oldest first. Set `costMint` to the mint the export says you paid with, because a gain only prints when it matches the mint the sale pays out in.

### Is a move between my own wallets a disposal?

That is a rule of your jurisdiction. The script sees only a fall in one wallet, so match it against your own wallet list before it counts as a disposal.

## Related

- [Signature history pagination](https://carbium.sh/library/howsolana/signature-history-pagination) (How to use Solana, HS0034)
- [Transaction version error -32015](https://carbium.sh/library/howsolana/transaction-version-error-32015) (How to use Solana, HS0012)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#migrate](https://carbium.sh/docs#migrate)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
