Token flow forensics graph
A Node script reads an address's newest transactions, turns balance changes into SOL and token flow edges, prints a Graphviz graph and ranks the counterparties. Each link comes with a reading of how much weight it can carry and where the evidence runs out.
Flows from balance changes
A flow graph has wallets as nodes and value moves as edges. Each transaction records every touched account's balance before and after, and edges are derived from those. An edge comes from one transaction and one asset: the owners whose balance fell sent, the owners whose balance rose received.
SOL balances come as two lamport arrays that line up with the transaction's account list. The fee payer's drop includes the fee, so the script adds the fee back to that one entry. Token balances come as two more lists, and each entry names the mint, the amount and the owning wallet. Those lists matter because a token transfer instruction names the two token accounts and the sender's authority, never the receiving wallet. Working from instructions loses the receiver. Working from the balance lists keeps it, and it also catches transfers made inside other programs.
A wallet can own several token accounts for one mint, so the script sums changes per owner and mint before it compares anyone. When a transaction has several senders and several receivers, no single pairing is recorded. The script splits each receiver's gain across the senders in proportion to what each gave up. For a plain transfer that is exact. For a multi-party transaction it is a reading, and the output should be labelled that way.
The reads and their cost
Two methods do the work. getSignaturesForAddress lists the newest signatures that touch the address, and getTransaction returns each one with its balance lists. The script asks for jsonParsed encoding so account keys and token owners arrive as readable fields.
Mainnet carries v1 transactions, and getTransaction answers -32015 for one unless the call sets maxSupportedTransactionVersion: 1. The script sets it on every call. The -32015 entry shows what the error looks like when it is missing.
Each of the two methods costs 50 cells, so a run with an address passed costs 550 cells: one listing plus 10 transactions. A run with no argument adds one more listing and up to 5 reads, which makes up to 850 cells, 750 of them getTransaction, still inside the 1,024-cell burst their rate class absorbs. A longer pull is paced by the getTransaction rate: 0.24, 1.2, 5 and 25 req/s on Free, Dev, Business and Pro. Size the history you pull per address against that rate before you wire the script into a case queue.
A script in one file
Pass an address, or pass nothing. With no argument the script reads the newest signatures of a busy swap program, takes the first successful transaction it can read and uses its fee payer, so a run always has a wallet with recent activity. It reads the 10 newest transactions of the address, skips failed ones, builds the edges and prints three things: a count line that reports read, null and failed transactions separately, the eight counterparties with the most edges, and a Graphviz digraph of the first 30 edges that touch the address. Each transaction read is settled on its own, so one failed read is printed and the rest still count. It signs and sends nothing.
// UC0041 · Token flow forensics graph// https://carbium.sh/library/usecase/token-flow-forensics-graph// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: builds a one-hop token flow graph for an address from its newest transactions.import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, 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 url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));type Bal = { owner?: string; mint: string; uiTokenAmount: { amount: string; decimals: number } };type Tx = { meta: { err: unknown; fee: number | bigint; preBalances: (number | bigint)[]; postBalances: (number | bigint)[]; preTokenBalances?: Bal[]; postTokenBalances?: Bal[] } | null; transaction: { message: { accountKeys: { pubkey: string }[] } };};async function getTx(sig: string): Promise<Tx | null> { const res = await rpc .getTransaction(signature(sig), { commitment: "confirmed", encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }) .send(); return res as unknown as Tx | null;}// mint -> owner -> balance change in display units (SOL under "SOL"), summed per owner.function changes(tx: Tx): Map<string, Map<string, number>> { const out = new Map<string, Map<string, number>>(); const add = (mint: string, owner: string, d: number) => { const m = out.get(mint) ?? new Map<string, number>(); m.set(owner, (m.get(owner) ?? 0) + d); out.set(mint, m); }; const meta = tx.meta!; // kit returns lamports as bigint: convert before any arithmetic with numbers tx.transaction.message.accountKeys.forEach((k, i) => add("SOL", k.pubkey, (Number(meta.postBalances[i]) - Number(meta.preBalances[i]) + (i === 0 ? Number(meta.fee) : 0)) / 1e9)); for (const [list, sign] of [[meta.preTokenBalances, -1], [meta.postTokenBalances, 1]] as const) { for (const b of list ?? []) { if (b.owner) add(b.mint, b.owner, (sign * Number(b.uiTokenAmount.amount)) / 10 ** b.uiTokenAmount.decimals); } } return out;}let target = process.argv[2];if (!target) { // no argument: take the fee payer of a recent successful transaction of a busy swap program const recent = await rpc.getSignaturesForAddress(address("JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4"), { limit: 5, commitment: "confirmed" }).send(); for (const s of recent) { const tx = await getTx(s.signature).catch(() => null); if (tx?.meta && !tx.meta.err) { target = tx.transaction.message.accountKeys[0].pubkey; break; } } if (!target) { console.error("No wallet found; pass an address."); process.exit(1); }}const sigs = await rpc.getSignaturesForAddress(address(target), { limit: 10, commitment: "confirmed" }).send();const txs = await Promise.allSettled(sigs.map((s) => getTx(s.signature)));const edges = new Map<string, number>(); // "from to mint" -> amountlet read = 0, nulls = 0, failed = 0, errors = 0;for (const [i, r] of txs.entries()) { if (r.status === "rejected") { errors++; console.error(`${sigs[i].signature.slice(0, 12)} failed: ${String(r.reason)}`); continue; } if (!r.value?.meta) { nulls++; continue; } if (r.value.meta.err) { failed++; continue; } read++; for (const [mint, owners] of changes(r.value)) { const out = [...owners].filter(([, d]) => d < -1e-9); const inn = [...owners].filter(([, d]) => d > 1e-9); const sent = out.reduce((s, [, d]) => s - d, 0); for (const [from, a] of out) for (const [to, b] of inn) { const k = `${from} ${to} ${mint}`; edges.set(k, (edges.get(k) ?? 0) + b * (-a / sent)); // split each gain across senders by share } }}const rows = [...edges].map(([k, amount]) => { const [from, to, mint] = k.split(" "); return { from, to, mint, amount }; }) .filter((e) => e.from === target || e.to === target);const linked = new Map<string, number>();for (const e of rows) { const o = e.from === target ? e.to : e.from; linked.set(o, (linked.get(o) ?? 0) + 1); }console.log(`${target}: ${read} of ${sigs.length} transactions read (${nulls} null, ${failed} failed, ${errors} errors), ${rows.length} edges touch it`);console.log("Linked wallets, by number of edges:");for (const [w, n] of [...linked].sort((a, b) => b[1] - a[1]).slice(0, 8)) console.log(` ${w} ${n}`);console.log("digraph flow {");for (const e of rows.slice(0, 30)) console.log(` "${e.from}" -> "${e.to}" [label="${e.amount.toFixed(4)} ${e.mint === "SOL" ? "SOL" : e.mint.slice(0, 6)}"];`);console.log("}");
run: CARBIUM_KEY=$CARBIUM_KEY node main.ts [address]
Save the digraph block to a file and run dot -Tsvg on it to get a picture, or paste the block into any Graphviz viewer. Amounts are floats in display units, which is fine for a picture and wrong for an audit trail. Keep the raw base-unit strings from the RPC when a finding has to be reproduced.
Reading linked wallets
A link in this output means two addresses moved value in one transaction. It does not say one person controls both. The counterparty list is a starting point for review.
| Pattern in the edges | What it suggests | What it does not show |
|---|---|---|
| Many small inbound edges from one source, then one outbound edge | A funding wallet and a collection wallet around the address | That the same person runs them |
| The same two wallets sending the same mint back and forth | A closed loop between two parties | Why they do it |
| One counterparty on nearly every edge | A venue, a pool vault or a deposit hub | Anything about the people using it |
| Equal amounts to many fresh wallets | A fan-out from a single funder | That the fresh wallets share an owner |
The first filter is what kind of account a counterparty is. A pool vault authority is a program-derived address, so it sits off the ed25519 curve, and the token balance lists name it as the owner, which makes it the hub node in this graph. It often holds lamports under the System Program or has no account at all, so the owner program alone cannot tell it from a wallet. Check each address for an off-curve key, then ask getMultipleAccounts for the owner program of each one. Mark an address as a hub when it is off the curve or when a token program or another program owns it. Send at most 100 pubkeys a call below Pro, where a 100-pubkey call costs 1000 cells (1001 over a 4 KiB body). Pro takes up to 300. Drop the hubs from the linkage and keep them as labelled nodes.
Growing the graph outward
For a second hop, rerun the script on each wallet that survived the filter and merge the edge lists by address, keeping a count of the transactions behind each edge. Each hop repeats the same 50-cell reads, so cap the number of wallets you expand per case before you start, and keep the signature of every transaction that produced an edge so a reviewer can open it in a transaction explainer.
For an address under watch, a logsSubscribe with a mentions filter on the websocket streams the logs of transactions that touch it. A subscription opens at 25 credits for that weight and costs 20 credits per MiB sent after, and a refused one is free. Use the notification as a trigger, then read the transaction with getTransaction instead of parsing log text. accountSubscribe stays silent for a plain SOL wallet, so it cannot do this job.
Where it ends
- Window: getSignaturesForAddress reaches back 30 days at most, from Carbium's own address index. An empty page past that marks the index's age limit, and the address can have older transactions. Funding that happened earlier is invisible here.
- Null transactions: the index reaches below the validator's ledger floor, so getTransaction can answer null for an older signature it listed. The script counts only transactions it could read and reports the null ones on the count line apart from failed ones, which is why the read count can be lower than the listing.
- No identity: the output has addresses and amounts. It has no names, no exchange labels and no clustering. Attribution needs a source you hold yourself, such as your own customer records or a list you maintain.
- Holder lookups: asking which wallets hold a mint needs getTokenLargestAccounts or getProgramAccountsV2. Neither is served and both answer -32601, which is final.
- Approximation: multi-party transactions are split in proportion, and amounts are floats. Both are fine for navigation and neither belongs in evidence.
- Scope: the script reads and draws. Deciding that a pattern is wrongdoing, and any report that follows, stays with the people doing the review.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| getTransaction answers -32015 for some signatures. | Set maxSupportedTransactionVersion: 1 in the config of every getTransaction call. Without it, a v1 transaction is refused. |
| getTransaction returns null for a signature that getSignaturesForAddress just listed. | Treat null as a transaction you cannot read and skip it. The address index reaches below the ledger floor, so older signatures can list without a body. |
| One huge node swallows the graph and every wallet looks linked to every other. | The node is usually a pool vault authority, a program account or a deposit hub. Check each address for an off-curve key and look up its owner with getMultipleAccounts. Mark off-curve addresses and program-owned accounts as hubs and leave them out of the linkage count, since an authority PDA can show up as System-owned or missing. |
| A token transfer shows the sender but no receiving wallet. | Stop reading instructions. Take the owner field of the pre and post token balance lists, which names the wallet that owns each token account. |
| The edge list is empty or shorter than the signature list. | Failed transactions move no value and are skipped on purpose. Check the null and failed counts on the count line, and print the signatures behind them. |
| A call to getTokenLargestAccounts answers -32601 and is retried. | Treat -32601 as final and remove the call. Build holder views from the token accounts you already read. |
Questions
Is there a hosted tool where I paste an address and get the graph?
Carbium serves the chain data: the signature index, transactions and account reads. The graph and the linkage rules are your code, and this script is a starting point that prints Graphviz.
How far back can I trace funds?
As far as the 30-day address index goes. Older history is not served, so an empty page past 30 days means the index ended, and the address may still have older activity.
Why read balances and not the transfer instructions?
Instructions list token accounts and the sender's authority, and the receiving wallet is missing. The balance lists carry the owner, and they also include value moved by inner calls.
Can I run it on a whole case list?
Yes, in a loop with one client. Each address costs one listing and one read per transaction, 50 cells each, so size the loop against the getTransaction req/s of your plan.