---
id: SI0056
title: "Inbound transaction triage"
url: https://carbium.sh/library/si/inbound-transaction-triage
collection: AI and blockchain
category: ML classification
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Inbound transaction triage

Reads a wallet's newest transactions through Carbium RPC and prints, for each, who signed, what arrived, how much in the token's own units and how many others were paid, then a class a model can explain.

## What the chain can settle

An unexpected credit raises two questions. The first is what happened, and the chain answers it exactly: which accounts signed, which balances moved and by how much. The second is whether the sender meant well, and no transaction field answers that. A triage step can sort by the shape of the arrival and leave intent to a person.

Shape separates cases that look alike in a wallet app. A payment someone owes you arrives alone, in an amount worth sending. A spray lands in the same transaction as a long list of other recipients, each credited a sliver. Noise is a small credit with few recipients. A credit the wallet signed for is the wallet's own doing, and it is the most common reason a transaction looks unexpected in the first place.

A model is good at explaining these cases once the facts are laid out and poor at deriving them from raw transaction JSON. So the job splits in two. Code computes a short row of inputs per transaction and a class, and the model turns the row into a sentence for the user.

## Four inputs per transaction

- Did the wallet sign. The signers are the first accounts in the message, as many as `numRequiredSignatures` in its header says.
- What arrived for the wallet: a token credit, a SOL credit or nothing, read from balance changes.
- How much, in the asset's own units: the raw token amount divided by ten to the power of its decimals, or lamports divided by 1e9 for SOL.
- How many other recipients the same transaction paid: other owners credited the same mint, or other accounts whose lamports rose.

All four come from one `getTransaction` per signature, so a wallet's newest five transactions cost five calls. The call passes `maxSupportedTransactionVersion: 1` because mainnet carries v1 transactions and an absent or 0 value is refused with -32015 for one. Each call costs [50 cells](https://carbium.sh/docs#rpc).

## The rule table

The rules run top to bottom and the first match wins. Order matters: a transaction the wallet signed never reaches the spray test, and a transaction that paid the wallet nothing never reaches the size test.

| Class | Rule | What the model can say |
|---|---|---|
| skip | Nothing arrived for the wallet | The transaction touched the wallet without paying it, so there is no credit to judge. |
| self-initiated | The wallet signed | You approved this transaction. Check what you approved. |
| spray | Not signed, and 5 or more other recipients | A mass send to many addresses, the usual shape of an advertisement or a lure. |
| noise | Not signed, under 1 token unit or under 0.001 SOL | A small credit from a stranger with no obligation attached. |
| sized | Not signed, at least 1 token unit or 0.001 SOL, fewer than 5 other recipients | A deliberate amount sent to few people. Worth finding out who sent it and why. |

The size test works in each asset's own units. Under one whole token is noise, while native SOL needs only 0.001 to count as sized. The two scales do not line up: half a unit of wrapped SOL is worth far more than 0.001 SOL and still scores as noise. The test sees units and has no price.

Both numbers, 5 recipients and one unit, are hand-set starting points. Once you have a few hundred transactions labelled by people, fit a small decision tree on the same four inputs and compare it with this list before trusting either.

## Finding the wallet in a token credit

A transfer into an existing token account names two token accounts and the sender's authority. The receiving wallet's address appears nowhere in the instruction, so a search of the instruction accounts for it comes back empty and the credit looks like it went to nobody.

The balance lists carry the answer. Every entry in `preTokenBalances` and `postTokenBalances` has an `owner`, a `mint` and a raw `amount` string. Add the post entries and subtract the pre entries for each owner and mint pair. A positive result is a credit to that owner. A wallet can hold several token accounts for one mint, so entries that share an owner and mint are summed before the subtraction.

Raw amounts stay whole numbers until the last division by the decimals. That keeps an unchanged balance at exactly zero, where dividing first can leave a rounding crumb that reads as a credit. SOL works the same way through `preBalances` and `postBalances`, indexed in account order. Addresses loaded from lookup tables follow the static keys in that order, so the file appends them before it looks the wallet up.

## The triage file

One file, with `@solana/kit` as its only dependency, run by Node 24 directly. Set `CARBIUM_KEY` first; the file exits with a message when it is unset, and `CARBIUM_RPC_URL` replaces the default `https://services.carbium.sh`. The key travels in the `x-api-key` header.

`main.ts` (run: `node main.ts`)

```ts
// SI0056 · Inbound transaction triage
// https://carbium.sh/library/si/inbound-transaction-triage
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Inbound transaction triage. Run: CARBIUM_KEY=... node main.ts [wallet]
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, type 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 rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }),
);
const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
const SPRAY = 5, MIN_TOKEN = 1, MIN_SOL = 0.001; // hand-set; tune on your own labels
type Row = { signed: boolean; kind: "token" | "sol" | "none"; amount: number; unit: string; others: number };

const getTx = (sig: Signature): Promise<any> =>
  rpc.getTransaction(sig, { maxSupportedTransactionVersion: 1, encoding: "json", commitment: "confirmed" }).send();

function triage(tx: any, wallet: string): Row {
  const m = tx.transaction.message, meta = tx.meta;
  const keys: string[] = [...(m.accountKeys ?? m.staticAccountKeys ?? []), ...(meta.loadedAddresses?.writable ?? []), ...(meta.loadedAddresses?.readonly ?? [])];
  const signed = keys.slice(0, m.header?.numRequiredSignatures ?? 1).includes(wallet);
  // Token credits: post minus pre per owner and mint, in raw integers.
  const net = new Map<string, { owner: string; mint: string; dec: number; d: number }>();
  const lists: [any[] | null | undefined, number][] = [[meta.postTokenBalances, 1], [meta.preTokenBalances, -1]];
  for (const [list, sign] of lists) {
    for (const b of list ?? []) {
      const id = `${b.owner}:${b.mint}`;
      const e = net.get(id) ?? { owner: b.owner, mint: b.mint, dec: b.uiTokenAmount.decimals, d: 0 };
      e.d += sign * Number(b.uiTokenAmount.amount);
      net.set(id, e);
    }
  }
  const credits = [...net.values()].filter((e) => e.d > 0);
  const mine = credits.filter((e) => e.owner === wallet).sort((a, b) => b.d / 10 ** b.dec - a.d / 10 ** a.dec)[0];
  if (mine) {
    const others = credits.filter((e) => e.mint === mine.mint && e.owner !== wallet).length;
    return { signed, kind: "token", amount: mine.d / 10 ** mine.dec, unit: mine.mint.slice(0, 6), others };
  }
  const i = keys.indexOf(wallet);
  const rise = (j: number): number => Number(meta.postBalances[j]) - Number(meta.preBalances[j]);
  if (i >= 0 && rise(i) > 0) {
    return { signed, kind: "sol", amount: rise(i) / 1e9, unit: "SOL", others: keys.filter((_, j) => j !== i && rise(j) > 0).length };
  }
  return { signed, kind: "none", amount: 0, unit: "-", others: 0 };
}

function classify(r: Row): string {
  if (r.kind === "none") return "skip";
  if (r.signed) return "self-initiated";
  if (r.others >= SPRAY) return "spray";
  return r.amount >= (r.kind === "sol" ? MIN_SOL : MIN_TOKEN) ? "sized" : "noise";
}

async function findWallet(): Promise<string | undefined> {
  const sigs = await rpc.getSignaturesForAddress(address(USDC), { limit: 6, commitment: "confirmed" }).send();
  for (const s of sigs) {
    try {
      const tx = await getTx(s.signature);
      if (!tx?.meta) continue;
      for (const b of tx.meta.postTokenBalances ?? []) {
        const r = b.owner ? triage(tx, b.owner) : undefined;
        if (r && r.kind === "token" && !r.signed) return b.owner;
      }
    } catch (e) {
      console.log("candidate failed:", String(e));
    }
  }
}

const wallet = process.argv[2] ?? (await findWallet());
if (!wallet) { console.error("No wallet found; pass one as the first argument."); process.exit(1); }
const sigs = await rpc.getSignaturesForAddress(address(wallet), { limit: 5, commitment: "confirmed" }).send();
const txs = await Promise.allSettled(sigs.map((s) => getTx(s.signature)));
console.log(`wallet ${wallet}: ${sigs.length} newest signatures`);
txs.forEach((t, i) => {
  const id = String(sigs[i]?.signature).slice(0, 8);
  if (t.status === "rejected") return console.log(`${id}  failed: ${String(t.reason)}`);
  if (!t.value?.meta) return console.log(`${id}  unreadable (null)`);
  try {
    const r = triage(t.value, wallet);
    console.log(`${id}  signed=${r.signed}  ${r.kind}  ${r.amount.toFixed(4)} ${r.unit}  others=${r.others}  ${classify(r)}`);
  } catch (e) {
    console.log(`${id}  failed: ${String(e)}`);
  }
});
```

With a wallet address as the first argument it triages that wallet. With none, it reads the newest signatures of the USDC mint, opens each transaction and takes an account owner whose balance rose and who did not sign. That owner is often a pool's authority account, which has plenty of traffic to read, so pass a real wallet to see ordinary arrivals.

It then lists the wallet's newest five signatures and prints one line each: the signature prefix, whether the wallet signed, the kind of credit, the amount and unit, the count of other recipients and the class. Pass those lines and the rule table to a model and it writes the explanation from the row. A signature whose transaction comes back null prints as unreadable, and a failed call or a row that cannot be scored prints its error beside the others.

A run with no argument makes at most 13 calls of 50 cells each: two signature lists, up to six transactions to find a wallet and five to triage it. That is 650 cells, inside the 1,024-cell [burst](https://carbium.sh/docs#limits) a class absorbs, which matters on a Free key whose steady rate for these calls is 0.24 per second.

## Where it ends

- A class describes the arrival and says nothing about the sender. A sized payment from a stranger can still be a lure, and a spray can be a legitimate airdrop. Address poisoning, where a dust credit plants a lookalike address in your history, is covered by [Address poisoning dust detector](https://carbium.sh/library/usecase/address-poisoning-dust-detector).
- The wallet only counts as paid when something arrived. A transaction the wallet did not pay for but that moves its tokens out, such as a delegate spending an approval, finds no credit and gets skip. The [token delegate exposure scan](https://carbium.sh/library/si/token-delegate-exposure-scan) is the tool for that case.
- The size test sees units and no prices. A token worth nothing can pass as sized with one unit, and a token worth a lot per unit can fall under 1.
- The other-recipient count for SOL includes any account whose lamports rose, so rent paid to new accounts inflates it. For tokens it counts owners credited the same mint.
- A wallet that signed gets self-initiated even when a dishonest app asked for the signature. The class says who signed, and what the wallet approved still needs a read of the instructions.
- History comes from an address index that keeps up to 30 days, and it can list a signature whose transaction is no longer readable, which the file prints as unreadable. Only the newest five transactions are scored.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| `getTransaction` answers -32015 for some signatures. | Pass `maxSupportedTransactionVersion: 1`. Mainnet carries v1 transactions, and an absent or 0 value is refused for one. |
| `getTransaction` answers null for a signature the address index just listed. | Print it as unreadable and go on. The index reaches below the validator's ledger floor, so an older signature can be listed and still have no body. Triage the newest signatures. |
| The receiving wallet is searched for in the transfer instruction and never found. | Compare `preTokenBalances` and `postTokenBalances` by owner and mint, as the token credit section describes. |
| Half a unit of wrapped SOL lands as noise next to a sized native SOL payment. | Expected, because the size test counts units. Set a threshold per mint, or put a price on the amount before the rule runs. |
| A payroll batch or a legitimate airdrop with six recipients reads as spray. | Raise the recipient limit, or check the sender against a list you maintain before the rule runs. |
| A balance that did not change shows as a tiny credit. | Subtract raw integer amounts and divide by the decimals last. Dividing each entry first leaves rounding crumbs. |

## Questions

### Can the assistant tell me a transaction is legit?

It can tell you who signed, what arrived and how many others were paid. Intent is not on chain, so the answer stays a description of the arrival that a person judges.

### Why does the file ask who signed before anything else?

Most unexpected transactions turn out to be ones the wallet or one of its apps signed. Settling that first keeps the size and spray tests for credits a stranger sent.

### What happens when someone spends my tokens through an approval?

No credit reaches the wallet, so the class is skip. The [token delegate exposure scan](https://carbium.sh/library/si/token-delegate-exposure-scan) lists those approvals.

### How do I tune the thresholds?

Label a few hundred transactions yourself, then move the recipient limit and the unit sizes until the classes match your labels. A small decision tree on the same four inputs is the next step.

### Can I run it on a wallet with heavy traffic?

Yes, but it scores only the newest five signatures per run, 50 cells each. Raise the limit in steps and watch the 1,024-cell burst on a Free key.

## Related

- [Address poisoning dust detector](https://carbium.sh/library/usecase/address-poisoning-dust-detector) (Use cases, UC0030)
- [Plain-English balance comparison](https://carbium.sh/library/si/plain-english-balance-comparison) (AI and blockchain, SI0032)
- [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)
