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

# Transaction category classifier

Fetches an address's newest transactions through Carbium RPC, reads the parsed instructions and the fee payer's token balance changes, and labels each one with a category and a score, giving you labelled rows to review or train on.

## Why label transactions first

A transaction arrives as program ids, account lists and balance arrays. A wallet screen, a report or an agent that summarizes activity wants one word for it: swap, transfer, memo. A supervised model on chain data starts from a table of transactions that carry such a word, because it needs labelled rows before it can learn anything.

A small scorer can produce those labels before any training exists. You run it over an address, read the output, correct the rows it got wrong, and keep the corrected table as training data. The scorer here has seven categories and eight yes or no signals, and every label comes with the score that won and the score of the runner-up, so a reviewer sees which rows deserve a second look.

- failed: the transaction landed with an error.
- swap: the fee payer gave up one token and received another.
- token transfer: a token transfer instruction, with no exchange of mints.
- SOL transfer: a system transfer instruction.
- account setup: token account creation or closing.
- memo: a memo instruction.
- program call: an instruction for a program the file cannot read, with no token exchange.

## Eight signals from one parsed transaction

The file asks Carbium RPC for each transaction in `jsonParsed` form. Known programs such as the system program, the token programs and memo come back parsed, under a program name. Everything else comes back with a program id and raw data, and that difference is itself a signal.

| Signal | Read from | Fires when |
|---|---|---|
| err | `meta.err` | the transaction failed |
| swapShape | token balances of the fee payer | one mint went down and another went up |
| tokenMoves | token balances of the fee payer | any mint changed |
| tokenIx | parsed token instructions | a `transfer` or `transferChecked` is present |
| solIx | parsed system instructions | a `transfer` is present |
| memo | parsed instructions | a memo instruction is present |
| setup | parsed instructions | an associated token account is created or an account is closed |
| unknown | top-level instructions | an instruction has no parsed form and is not a compute budget call |

The balance signals use the `owner` field on each token balance entry and sum the amounts per mint before comparing. A wallet can own more than one token account for one mint, and a move between them would otherwise look like a loss and a gain, the swap shape.

The balance signals take the fee payer's point of view, the first account key; the instruction signals read every top-level instruction.

## One weight row per category

Each category owns a row of weights. Its score is the sum of the weights of the signals that fired, plus a bias for the fallback category. The highest score is the label, and a tie goes to the category listed first in `W`. A failed transaction scores 5 for `failed` and loses 5 in every other row, so it can never be called a swap that did not happen.

| Category | Weights |
|---|---|
| failed | err +5 |
| swap | swapShape +3, unknown +1, tokenMoves +0.5, err -5 |
| token transfer | tokenIx +2, tokenMoves +1, swapShape -2, err -5 |
| SOL transfer | solIx +2, tokenMoves -1, swapShape -2, err -5 |
| account setup | setup +2, err -5 |
| memo | memo +2.5, err -5 |
| program call | bias +0.2, unknown +1.5, err -5 |

Take a transaction that creates a token account, calls an unrecognized program and moves USDC out of the payer for another mint back in. Swap scores 3 + 1 + 0.5 = 4.5, program call 1.5 + 0.2 = 1.7 and account setup 2. The label is swap with a margin of 2.5.

These weights are hand-set priors. They state a judgment: a token exchange plus a program the file cannot read is almost always a swap, and a memo outranks a bare SOL transfer because the memo is usually the reason the transfer exists. A memo next to a token transfer that moves the payer's tokens loses to the transfer, 3 against 2.5. Move those numbers once you have labels of your own.

## The classifier

One file with `@solana/kit` as its only dependency. Node 24 runs the TypeScript directly. Set `CARBIUM_KEY` first; the file exits with a message when it is unset, and `CARBIUM_RPC_URL` overrides the default endpoint.

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

```ts
// SI0108 · Transaction category classifier
// https://carbium.sh/library/si/transaction-category-classifier
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Transaction category classifier. Run: CARBIUM_KEY=... node main.ts [address]
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 rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }),
);
const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
const BUDGET = "ComputeBudget111111111111111111111111111111";
// Hand-set priors: one weight row per category over the signals below.
const W: Record<string, Record<string, number>> = {
  failed: { err: 5 },
  swap: { swapShape: 3, unknown: 1, tokenMoves: 0.5, err: -5 },
  "token transfer": { tokenIx: 2, tokenMoves: 1, swapShape: -2, err: -5 },
  "SOL transfer": { solIx: 2, tokenMoves: -1, swapShape: -2, err: -5 },
  "account setup": { setup: 2, err: -5 },
  memo: { memo: 2.5, err: -5 },
  "program call": { bias: 0.2, unknown: 1.5, err: -5 },
};
function signals(tx: any): Record<string, number> {
  const keys: any[] = tx.transaction.message.accountKeys;
  const payer: string = keys[0].pubkey;
  const delta = new Map<string, bigint>();
  const sides: [any[] | null, bigint][] = [[tx.meta.preTokenBalances, -1n], [tx.meta.postTokenBalances, 1n]];
  for (const [list, sign] of sides) {
    for (const b of list ?? []) {
      if (b.owner === payer) delta.set(b.mint, (delta.get(b.mint) ?? 0n) + sign * BigInt(b.uiTokenAmount.amount));
    }
  }
  const d = [...delta.values()];
  const ixs: any[] = tx.transaction.message.instructions;
  const types = (...programs: string[]) => ixs.filter((i) => programs.includes(i.program)).map((i) => String(i.parsed?.type));
  const tokenTypes = types("spl-token", "spl-token-2022");
  return {
    err: tx.meta.err ? 1 : 0,
    swapShape: d.some((x) => x < 0n) && d.some((x) => x > 0n) ? 1 : 0,
    tokenMoves: d.some((x) => x !== 0n) ? 1 : 0,
    tokenIx: tokenTypes.some((t) => t.startsWith("transfer")) ? 1 : 0,
    solIx: types("system").includes("transfer") ? 1 : 0,
    memo: ixs.some((i) => i.program === "spl-memo") ? 1 : 0,
    setup: types("spl-associated-token-account").length > 0 || tokenTypes.includes("closeAccount") ? 1 : 0,
    unknown: ixs.some((i) => !i.parsed && i.programId !== BUDGET) ? 1 : 0,
  };
}
function classify(f: Record<string, number>) {
  const ranked = Object.entries(W)
    .map(([cat, w]) => [cat, Object.entries(w).reduce((s, [k, v]) => s + v * (k === "bias" ? 1 : (f[k] ?? 0)), 0)] as const)
    .sort((a, b) => b[1] - a[1]);
  return { best: ranked[0]!, next: ranked[1]! };
}
const target = process.argv[2] ?? USDC;
const sigs = await rpc.getSignaturesForAddress(address(target), { limit: 10, commitment: "confirmed" }).send();
const counts = new Map<string, number>();
for (const s of sigs) {
  const id = s.signature.slice(0, 8);
  try {
    const tx: any = await rpc.getTransaction(s.signature, { maxSupportedTransactionVersion: 1, encoding: "jsonParsed", commitment: "confirmed" }).send();
    if (!tx) { console.log(`${id}  unreadable (null)`); continue; }
    const { best, next } = classify(signals(tx));
    counts.set(best[0], (counts.get(best[0]) ?? 0) + 1);
    console.log(`${id}  ${best[0].padEnd(14)} ${best[1].toFixed(1)}  next ${next[0]} ${next[1].toFixed(1)}`);
  } catch (e) {
    console.log(`${id}  failed: ${String(e)}`);
  }
}
console.log(`${target.slice(0, 8)}: ${[...counts].map(([c, n]) => `${c} ${n}`).join(", ") || "nothing classified"}`);
```

With no argument it reads the newest ten signatures that touched the USDC mint, a busy address, and classifies each. Pass any address as the first argument to classify its transactions instead. The output has one line per transaction with a short signature, the category, the winning score and the runner-up, then a closing line with the count per category. A transaction that cannot be read prints its own line and the run goes on.

## Reading the transactions

The file calls `getSignaturesForAddress` once, then `getTransaction` once per signature. Both cost 50 cells, so a run of ten transactions spends 550 cells, inside the 1,024-cell burst a rate class absorbs. The calls run one after another on purpose: a larger scan on a small plan should pace itself to the [per-plan rate](https://carbium.sh/docs/limits) or page through addresses over time.

Every `getTransaction` call passes `maxSupportedTransactionVersion: 1`. Mainnet carries v1 transactions, and an absent or 0 value answers -32015 for one.

`getSignaturesForAddress` reads from an address index that keeps up to 30 days. That index reaches below the validator's ledger floor, so `getTransaction` can answer null for an older signature it lists. The file prints a line for a null and moves on. Scan the newest signatures first, and use [Signature history pagination](https://carbium.sh/library/howsolana/signature-history-pagination) when you need to page back through a longer list.

A token transfer to an existing token account lists the token accounts and the sender's authority, never the receiving wallet. That is why the owner field of the balance entries drives the signals. For the typed shape of the parsed response, [Typed jsonParsed transactions](https://carbium.sh/library/howsolana/typed-jsonparsed-transactions) covers the fields this file reads.

## From rules to a trained model

The scorer is a linear model with hand-set weights, so replacing it with a fitted one changes the numbers and nothing else. Run the file over a few dozen addresses of different kinds, print the object `signals(tx)` returns beside each line, write the rows into a table with the eight signals as columns, and correct the label by hand where it is wrong. A few hundred reviewed rows are enough to fit a multinomial logistic regression with any tool you like.

- Keep the corrected table. It is the asset.
- Hold out whole addresses when you test. Rows from one wallet resemble each other and make a model look better than it is.
- Watch the runner-up margin. Rows with a margin under 1 are the ones a reviewer should read first, and the ones a trained model will disagree on.

Once the labels hold up, a language model can write the plain-English line for a transaction from the label and the signals, which keeps it from guessing the category itself. For a sibling classifier over token accounts, see [LP token classifier](https://carbium.sh/library/si/lp-token-classifier).

## Where it ends

- Only the fee payer's side is read. A transaction that pays a wallet but is signed by someone else is classified as the sender's action. To classify for a receiving wallet, set `payer` in `signals` to that wallet's address.
- Seven categories are coarse. Lending, vault deposits, liquidity changes and NFT sales all land in swap or program call. Splitting them needs program ids and instruction layouts for each protocol.
- A swap whose tokens move through accounts the payer does not own shows no payer balance change, so it falls to program call.
- Native SOL has no token balance entry. A swap from SOL that wraps and unwraps inside one transaction shows only the token gained, so it loses the swap label; it reads as a swap when the payer's wrapped SOL account holds a balance before the transaction and less after it.
- Only the top-level instructions are read. A transfer that happens inside another program's call is not seen by the instruction signals, only by the balance signals.
- History stops at the 30-day address index. Older transactions are not served through this method, and a null answer inside the window means the ledger no longer holds the body.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| `getTransaction` answers -32015 for some signatures. | Pass `maxSupportedTransactionVersion: 1` with the encoding. Mainnet carries v1 transactions, and an absent or 0 value is refused for one. |
| `getTransaction` answers null for a signature that `getSignaturesForAddress` just listed. | Skip it and print the signature. The address index reaches below the validator's ledger floor, so an older signature can be listed and still unreadable. Work from the newest signatures. |
| A swap is labelled program call. | The payer's own token accounts did not change: another wallet's tokens moved while the payer only paid the fee, or the route used accounts the payer does not own. Set `payer` in `signals` to the wallet that owns the tokens, or add a signal for the program id. |
| A wallet shows a loss and a gain of the same mint and is labelled swap. | Sum the balance changes per owner and mint before comparing. A wallet can own several token accounts for one mint, and a move between them nets to zero. |
| A memo with a payment is labelled memo instead of SOL transfer. | The weights put the memo above a bare SOL transfer. Lower the memo weight below 2 if you want the payment to win, then recheck your labelled rows. |
| Back-to-back runs on a small plan come back with errors. | Each run spends 550 cells, and once the 1,024-cell burst is spent a small plan refills slowly. Lower the limit or run the scan on a schedule, and read the printed failure lines before trusting the counts. |

## Questions

### Why a weighted scorer and not a neural network?

The inputs are eight yes or no signals, so a linear model fits them, runs in microseconds and explains each label by the signals that fired. A neural network needs far more labelled rows than a first pass will have, and you need the labels either way.

### Can I use the output as training data directly?

Use it as a first draft. Review the rows with a small margin, fix the wrong labels by hand, and keep the corrected table. Training on unreviewed output teaches a model to repeat the scorer's mistakes.

### How many calls does a run make?

One `getSignaturesForAddress` call and one `getTransaction` call per signature, 11 calls at 50 cells each for the default limit of ten. Change `limit` in the file to scan more.

### Does the file ever write or send anything?

No. It reads signatures and transactions only.

## Related

- [LP token classifier](https://carbium.sh/library/si/lp-token-classifier) (AI and blockchain, SI0009)
- [Typed jsonParsed transactions](https://carbium.sh/library/howsolana/typed-jsonparsed-transactions) (How to use Solana, HS0065)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/endpoints](https://carbium.sh/docs/endpoints)
- [carbium.sh/docs/auth](https://carbium.sh/docs/auth)
