---
id: HS0026
title: "Token balance diff from simulation"
url: https://carbium.sh/library/howsolana/token-balance-diff-from-simulation
collection: How to use Solana
category: Build, sign and send transactions
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Token balance diff from simulation

A TypeScript file shows how to turn simulateTransaction's post-run accounts into a per-token-account diff, with before, after and delta in base units. Run against a busy mint, it proves the same diff on three landed transactions' pre and post token balances.

## The two snapshots

A balance preview is one subtraction between two snapshots of the same token accounts. The before snapshot is a read of those accounts ahead of the run. The after snapshot is the state the run would leave behind. Both are maps from a token account address to a mint and an integer amount in base units, and one function subtracts them.

Key the maps by token account address. When tokens move between existing accounts, the receiving wallet's address never shows in the account list, only its token account does, and one wallet may hold several accounts of a mint. A map keyed by wallet would merge accounts the transaction treats separately.

The before snapshot comes from `getMultipleAccounts` with `jsonParsed` encoding on the token accounts you plan to touch. A [same-slot snapshot](https://carbium.sh/library/howsolana/same-slot-multi-account-snapshot) shows how to read them consistently. The call charges 10 cells per pubkey, so below Pro send at most 100 addresses a call.

> Amounts stay integers in base units from the first read to the last printed row. A float loses digits on a large balance, and the decimals of the mint matter only when a person reads the number.

## Mapping the simulation accounts

`simulateTransaction` takes an `accounts` option with the addresses to return and an `encoding`. Its reply carries `value.accounts`, one entry per address in the order you asked, each holding the account's state after the run. Ask for `jsonParsed` and a live token account arrives with `data.parsed.info.mint` and `data.parsed.info.tokenAmount.amount`, the amount as a string. Read `value.err` first: a run that failed has no balances worth previewing.

Accounts the run closes need care. The post-run state of a closed token account comes back as an entry with 0 lamports, owned by the system program, with no parsed data. An address that holds nothing comes back as `null`. Both mean a zero balance, so the mapper counts a `null` entry, and an entry with 0 lamports and no `parsed` field, as zero. A test for `null` alone lets a closed account fall through to a read of `data.parsed` that is not there.

| Entry in value.accounts | Amount the diff reads |
|---|---|
| Live token account, parsed | data.parsed.info.tokenAmount.amount |
| null | 0 |
| 0 lamports, system-owned, no parsed data | 0 |

A closed account's after entry has no mint either, so the diff takes the mint from whichever snapshot carries one.

## The code

Export `CARBIUM_KEY` and run the file with Node 24 and `@solana/kit` 8.6.0. The first argument is a mint and defaults to USDC. The second is an optional smallest delta to print, in base units. It is checked as digits before the first call goes out.

`main.ts` (run: `node main.ts [mint] [min-delta-in-base-units]`)

```ts
// HS0026 · Token balance diff from simulation
// https://carbium.sh/library/howsolana/token-balance-diff-from-simulation
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

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 USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
const [mintArg = USDC, minArg = "0"] = process.argv.slice(2);
if (!/^\d+$/.test(minArg)) {
  console.error("Usage: node main.ts [mint] [min-delta-in-base-units, digits only]");
  process.exit(1);
}
const mint = address(mintArg);
const min = BigInt(minArg);

type Snap = Map<string, { mint: string; amount: bigint }>;
type Entry = { data?: { parsed?: { info?: { mint?: string; tokenAmount?: { amount?: string } } } } } | null;
type Bal = { accountIndex: number; mint: string; uiTokenAmount: { amount: string } };
type Tx = {
  slot: number | bigint;
  transaction: { message: { accountKeys: { pubkey: string }[] } };
  meta: { preTokenBalances?: Bal[] | null; postTokenBalances?: Bal[] | null } | null;
};

// simulateTransaction's value.accounts, jsonParsed, in the order of addrs. A null entry or an
// empty one (0 lamports, system-owned, no parsed data) has no amount and reads as zero.
function fromAccounts(addrs: string[], entries: readonly Entry[]): Snap {
  const snap: Snap = new Map();
  addrs.forEach((a, i) => {
    const info = entries[i]?.data?.parsed?.info;
    snap.set(a, { mint: info?.mint ?? "", amount: BigInt(info?.tokenAmount?.amount ?? "0") });
  });
  return snap;
}
// A landed transaction's token balances, keyed by the token account at accountIndex.
function fromMeta(keys: string[], bals?: Bal[] | null): Snap {
  const snap: Snap = new Map();
  for (const b of bals ?? []) snap.set(keys[b.accountIndex], { mint: b.mint, amount: BigInt(b.uiTokenAmount.amount) });
  return snap;
}

function show(label: string, before: Snap, after: Snap) {
  console.log(label);
  let rows = 0;
  for (const account of new Set([...before.keys(), ...after.keys()])) {
    const was = before.get(account), now = after.get(account);
    const b = was?.amount ?? 0n, a = now?.amount ?? 0n;
    const delta = a - b;
    const size = delta < 0n ? -delta : delta;
    if (size === 0n || size < min) continue;
    rows++;
    console.log(`  ${account} mint=${now?.mint || was?.mint || "?"} before=${b} after=${a} delta=${delta > 0n ? "+" : ""}${delta}`);
  }
  if (!rows) console.log("  no balance change");
}

// A simulation-shaped reply: acctB comes back null, acctC comes back empty.
const live = (amount: string): Entry => ({ data: { parsed: { info: { mint: USDC, tokenAmount: { amount } } } } });
const addrs = ["acctA", "acctB", "acctC"];
show("fixture", fromAccounts(addrs, [live("5000000"), live("700"), live("42")]), fromAccounts(addrs, [live("2000000"), null, {}]));

const listed = await rpc.getSignaturesForAddress(mint, { limit: 10, commitment: "confirmed" }).send();
const sigs = listed.filter((s) => s.err === null).slice(0, 3);
console.log(`${mint}: reading ${sigs.length} landed transactions`);
for (const { signature } of sigs) {
  try {
    const tx = (await rpc
      .getTransaction(signature, { commitment: "confirmed", encoding: "jsonParsed", maxSupportedTransactionVersion: 1 })
      .send()) as unknown as Tx | null;
    if (!tx?.meta) {
      console.log(`${signature}: no transaction returned`);
      continue;
    }
    const keys = tx.transaction.message.accountKeys.map((k) => k.pubkey);
    show(`${signature} slot ${tx.slot}`, fromMeta(keys, tx.meta.preTokenBalances), fromMeta(keys, tx.meta.postTokenBalances));
  } catch (e) {
    console.error(`${signature}: ${e instanceof Error ? e.message : String(e)}`);
  }
}
```

`fromAccounts` is the simulation side. You hand it the addresses you asked for and `value.accounts` from your own `simulateTransaction` reply. The file never sends that call, so a fixture of three accounts stands in for the reply: one balance that drops, one `null` entry and one empty entry. `fromMeta` is the landed side. It turns `preTokenBalances` and `postTokenBalances` into the same maps, and `show` diffs whichever pair it gets.

The live part lists the mint's newest signatures with `getSignaturesForAddress`, skips failed ones and reads three with `getTransaction` at `confirmed`, each in its own `try`. One null or one error prints a line and the loop goes on. `maxSupportedTransactionVersion: 1` lets a v1 transaction through. The `jsonParsed` account list already includes addresses loaded from lookup tables, which is the list `accountIndex` counts into.

## Reading the rows

Each row reads `account mint=... before=... after=... delta=...`, all in base units. USDC has 6 decimals, so a delta of -3000000 is 3 USDC leaving the account. Divide by `10 ** decimals` when you show the number to a person, and format from the `BigInt`.

A token account the transaction creates has no entry before, and one it closes has none after. The diff reads the missing side as 0, so the delta is the whole balance. A swap shows one row down and one row up on different mints, plus rows for accounts that belong to the pool. The rows for your own token accounts are the preview.

To trust a preview, compare it with a landed transaction: simulate, send, then diff `preTokenBalances` against `postTokenBalances` for the landed signature. Matching rows mean the preview held. A difference means state moved between the simulation and the landing.

## Where it ends

A preview is the state at the simulation slot. Pools move between the simulation and the landing, so a landed delta can differ from the previewed one. The diff reads token amounts only. SOL moving in or out of a wallet, and the fee, are lamport changes it does not report.

The live part is meant for recent history. `getSignaturesForAddress` keeps up to 30 days, and its pages reach below the validator's ledger floor, so `getTransaction` can answer null for an older signature it lists. The file prints a line for that and moves on.

A run costs 50 cells for the list and 150 for three reads. On a Free key the [`getTransaction` class](https://carbium.sh/docs/limits) holds 1,024 cells, which is 20 reads back to back, and then refills 0.24 reads a second, about one read every four seconds.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| Error -32015 on a getTransaction read. | Pass `maxSupportedTransactionVersion: 1`. Absent or 0, a v1 transaction answers -32015, and so does a block that holds one. [Transaction version error -32015](https://carbium.sh/library/howsolana/transaction-version-error-32015) walks through it. |
| A signature prints `no transaction returned`. | `getSignaturesForAddress` lists signatures below the validator's ledger floor, so `getTransaction` can answer null for an older one. Diff the newest signatures. |
| The mapper throws on a closed account, on a read of `parsed` from an empty entry. | Use optional chaining down to `tokenAmount.amount` and default to "0". A `null` entry and an empty system-owned entry then both read as zero. |
| A row shows the whole balance as the delta for an account that existed before. | The two snapshots were keyed differently, or `accountIndex` was counted against a key list without the lookup-table addresses. Key both by token account address and take the keys from the `jsonParsed` account list. |
| HTTP 429 after about 20 reads fired back to back on a Free key. | Space the reads out to about one every four seconds, or move to a plan with a higher `getTransaction` rate: 1.2, 5 and 25 requests a second on Dev, Business and Pro. |
| The usage message prints for the second argument. | Pass the smallest delta as digits only: base units, no decimal point and no sign. |

## Questions

### What key should the two snapshots share?

The token account address. One wallet can hold several accounts of a mint, and a transaction lists token accounts, so that address is the one key both snapshots carry.

### How do I read the amount of a closed account in a simulation reply?

Count it as zero. Test for a `null` entry and for an entry with 0 lamports and no `parsed` field. The optional chaining in `fromAccounts` covers both.

### Can one run diff more than one mint?

Yes. Each map entry carries its own mint, so rows for several mints print together. For a long list of token accounts, read the before snapshot in one `getMultipleAccounts` call of at most 100 addresses below Pro.

### Why print base units?

Integers stay exact, and a float drops digits on a large balance. Divide by `10 ** decimals` at display time, with the decimals read from the mint.

### Does a landed transaction use the same diff?

Yes. `fromMeta` builds the same maps from `preTokenBalances` and `postTokenBalances`, so a landed row and a previewed row compare directly.

## Related

- [Same-slot multi-account snapshot](https://carbium.sh/library/howsolana/same-slot-multi-account-snapshot) (How to use Solana, HS0045)
- [Fee-payer lamport delta check](https://carbium.sh/library/si/fee-payer-lamport-delta-check) (AI and blockchain, SI0064)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/errors](https://carbium.sh/docs/errors)
- [carbium.sh/docs/endpoints](https://carbium.sh/docs/endpoints)
