services
Get a key

library / AI and blockchain / SI0012

Swap transaction decoder

You get a read-only script that takes a swap signature, or an address with steady swap activity, and prints whether it was a swap, the two assets that moved with their amounts, the fee, the slot and the programs that ran.

By Carbium · Swap assistants · SI0012 · updated 2026-11-22

01

What makes a transaction a swap

Solana has no swap transaction type. A transaction is a list of instructions, and it counts as a swap when the wallet that signed it ends with less of one asset and more of another. One pool, a split over several pools and an aggregator route through four venues all leave that footprint.

The decoder skips each venue's instruction layout, which differs per program and shifts when a program upgrades, and reads the outcome. getTransaction with jsonParsed encoding returns balances before and after in meta, for native SOL and for every token account the transaction touched. Subtract the first from the second per asset for the fee payer and the verdict follows.

A clean swap has exactly one asset that went down and exactly one that went up. Everything else prints as not a clean swap, with its legs, so you can see why. A plain transfer moves one asset out and none in. Adding liquidity moves two out and one in. A route that ends in the asset it started with nets to one leg or none.

02

Which fields carry the answer

FieldWhat the decoder takes from it
transaction.message.accountKeys[0]the fee payer, the wallet whose legs are read
meta.preBalances, meta.postBalancesnative SOL change of the payer, in lamports
meta.feeadded back to that change so the fee is not read as part of the swap
meta.preTokenBalances, meta.postTokenBalancestoken legs for accounts the payer owns, grouped by mint
message.instructions, meta.innerInstructionsthe program ids that ran, including those called inside another program
slotthe slot the transaction landed in

Wrapped SOL and native SOL are one asset to the person swapping, so the file adds the wrapped-SOL token leg to the native change and reports both as SOL. Token amounts stay integers in base units and print with the mint's decimals, so a leg never passes through a float.

Receiving a new asset can open a token account, which takes a rent deposit of 2,039,280 lamports from the native balance. A SOL leg under 0.005 SOL is dropped as dust so that deposit does not show up as a second asset going down. The cut-off is the DUST constant.

03

The decoder file

One file on @solana/kit alone. Node 24 strips the types and runs it. Set CARBIUM_KEY first; the file exits with a message when it is missing. CARBIUM_RPC_URL overrides the endpoint, which defaults to https://services.carbium.sh.

main.ts
// SI0012 · Swap transaction decoder// https://carbium.sh/library/si/swap-transaction-decoder// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Swap transaction decoder. Run: CARBIUM_KEY=... node main.ts <signature or address>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 } }));const WSOL = "So11111111111111111111111111111111111111112";// Compute budget, system, token, token-2022, associated token account and memo programs.const PLUMBING = new Set([  "ComputeBudget111111111111111111111111111111", "11111111111111111111111111111111",  "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb",  "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL", "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr",]);const ZERO = BigInt(0);const DUST = BigInt(5_000_000); // lamports: above one token-account deposit (2,039,280)const abs = (n: bigint) => (n < ZERO ? -n : n);function fmt(n: bigint, decimals: number): string {  const s = abs(n).toString().padStart(decimals + 1, "0");  return (n < ZERO ? "-" : "+") + (decimals ? `${s.slice(0, -decimals)}.${s.slice(-decimals)}` : s);}// Net movement of the fee payer's assets, read from the balances before and after.function decode(tx: any) {  const { meta, transaction: { message } } = tx;  const payer: string = message.accountKeys[0].pubkey;  const moves = new Map<string, { delta: bigint; decimals: number }>();  const add = (asset: string, delta: bigint, decimals: number) =>    moves.set(asset, { delta: (moves.get(asset)?.delta ?? ZERO) + delta, decimals });  add("SOL", BigInt(meta.postBalances[0]) - BigInt(meta.preBalances[0]) + BigInt(meta.fee), 9);  for (const [sign, list] of [[-1, meta.preTokenBalances], [1, meta.postTokenBalances]] as const) {    for (const b of list ?? []) {      if (b.owner !== payer) continue;      add(b.mint === WSOL ? "SOL" : b.mint, BigInt(sign) * BigInt(b.uiTokenAmount.amount), b.uiTokenAmount.decimals);    }  }  const legs = [...moves].filter(([asset, m]) => m.delta !== ZERO && (asset !== "SOL" || abs(m.delta) > DUST));  const ran = [...message.instructions, ...(meta.innerInstructions ?? []).flatMap((i: any) => i.instructions)];  const programs = [...new Set<string>(ran.map((i: any) => i.programId))].filter((p) => !PLUMBING.has(p));  const down = legs.filter(([, m]) => m.delta < ZERO).length;  const up = legs.filter(([, m]) => m.delta > ZERO).length;  return { payer, legs, programs, swap: down === 1 && up === 1 };}function show(sig: string, tx: any): boolean {  const d = decode(tx);  console.log(`${sig} slot ${tx.slot} fee ${tx.meta.fee} lamports ${d.swap ? "SWAP" : "not a clean swap"}`);  for (const [asset, m] of d.legs) console.log(`  ${asset} ${fmt(m.delta, m.decimals)}`);  console.log(`  payer ${d.payer}`);  console.log(`  programs ${d.programs.join(" ") || "none"}`);  return d.swap;}const input = process.argv[2];if (!input) {  console.error("Pass a transaction signature or an address with swap activity.");  process.exit(1);}// Mainnet carries v1 transactions; with this absent or 0, getTransaction answers -32015 for one.const config: any = { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 };const sigs: string[] = input.length > 50  ? [input]  : (await rpc.getSignaturesForAddress(address(input), { limit: 8 }).send()).filter((s) => !s.err).map((s) => s.signature);for (const sig of sigs.slice(0, 5)) {  try {    const tx: any = await rpc.getTransaction(signature(sig), config).send();    if (!tx) console.log(`${sig} not found at this commitment`);    else if (show(sig, tx)) break;  } catch (e) {    const message = (e as Error).message;    console.log(`${sig} ${message}`);    if (/\b429\b/.test(message)) break;  }}

run: node main.ts <signature or address>

Pass a signature and it decodes that one transaction. Pass an address with steady activity and it takes the latest eight signatures, drops the failed ones, fetches at most five transactions and stops at the first clean swap. A string longer than 50 characters counts as a signature. Every block has the signature, the slot, the fee in lamports, the verdict, one line per asset with a signed amount, the payer and the program ids. Mint addresses print in full so you can look them up.

LineShape
First<signature> slot <slot> fee <lamports> lamports SWAP
Asset out<asset> -<amount>
Asset in<asset> +<amount>
Payerpayer <address>
Programsprograms <program id> <program id>

A swap shows the word SWAP and two asset lines, one with a minus sign and one with a plus sign. The programs line holds the venue programs. Compute budget, system, token, associated token account and memo programs are filtered out.

04

Calls and cost

An address run makes one getSignaturesForAddress call and up to five getTransaction calls, and a signature run makes a single getTransaction call, because the file skips the listing when it gets a signature. Each call costs 50 cells, so a full address run is at most 300 cells.

CallCellsFree req/sDev req/sBusiness req/sPro req/s
getSignaturesForAddress500.241.2100500
getTransaction500.241.2525

Limits are per account, so every key on the account draws on one budget. A class absorbs bursts up to 1,024 cells or one second of its rate, whichever is larger, so a full 300-cell run fits on every plan. The file stops on a 429. Any other error on one transaction prints its message and the run goes on to the next signature.

The file makes its calls one at a time. For a list of signatures you already hold, a JSON-RPC batch carries up to 100 calls in one request, but each call in it pays its own 50 cells against the same 1,024-cell burst. A getTransaction batch therefore fits at 20 calls, or 25 on Pro, and sending 100 at once draws a 429 on every plan.

05

Decoding swaps as they happen

To catch swaps as they land, open a WebSocket on wss://services.carbium.sh, or the address in CARBIUM_WS_URL, and subscribe with logsSubscribe, which streams transaction logs, all or by mention. Filter by mention of a program or wallet, and hand each signature that arrives to the same decoder.

A subscription opens at a credit price set by filter weight, 25 credits for a mention filter and 200 for all logs, then costs 20 credits per MiB sent. Free carries 5 sockets. A mention filter on a busy program sends a lot, so decode in a worker and skip signatures you have seen.

After you send a swap yourself, signatureSubscribe sends one confirmation for your signature and the subscription ends. Fetch and decode when it fires. A swap built through the quote and swap methods on the RPC endpoint comes back as one unsigned transaction that your software signs and sends. The quote's platformFee is 5 bps and sits inside that transaction on chain, so the net legs the decoder prints already include it.

06

Where it ends

  • Legs are read for the first account key, the fee payer. When a relayer pays fees for a user, the legs printed are the relayer's, and the user's wallet needs its own read by owner.
  • The file reports net movement. It shows no hop-by-hop route, no pool and no price. Divide the two amounts yourself for an effective rate, and keep a table that maps program ids to venue names.
  • The clean-swap test is a heuristic. A route that ends in its starting asset, a swap that pays out to a second wallet, or a SOL leg under the 0.005 SOL cut-off reads as not a clean swap or shows a missing leg.
  • The SOL leg, in either direction, also includes any token-account rent deposits, refunds from closed accounts and tips the payer sent in the same transaction.
  • Listing by address stops at the 30-day address index. An empty page past that points at the index's age limit; it says nothing about when the address first appeared.
07

When it goes wrong

what goes wrongwhat to do
A real swap prints as not a clean swap.Read the asset lines. Two assets down point to a liquidity add or a second input, and a route that returns to its starting asset nets to one leg or none. Check whether the SOL leg fell under the DUST cut-off.
A new token account makes SOL look like a second outgoing asset.The rent deposit is 2,039,280 lamports per account opened. Keep DUST above the deposits a route can open, or compare token legs only.
getTransaction fails with "Transaction version (1) is not supported by the requesting client".Mainnet carries v1 transactions, and with maxSupportedTransactionVersion absent or 0, getTransaction answers -32015, uncharged. Pass maxSupportedTransactionVersion: 1, as the file does.
A 429 in a decode loop, or with the account's budget already spent.A single run fits the 1,024-cell burst, so a 429 points at a drained budget (a loop, other keys on the account) or, on Free, the network's shared budget. Space the getTransaction calls to your plan's rate, or decode fewer transactions per second.
getTransaction returns null for a signature you just sent.The signature is not visible to the node yet. The file's getTransaction runs at confirmed, the commitment @solana/kit fills in. Subscribe with signatureSubscribe at confirmed or finalized and wait for it to fire, so the fetch after it finds the transaction.
An address returns no signatures for an old swap.getSignaturesForAddress reaches back 30 days at most and older history is not served, so keep the signatures you need when you first see them.
08

Questions

How do I tell which exchange handled the swap?

The programs line lists every program that ran, minus compute budget, system, token, associated token account and memo. Match those ids to a table of venues you keep. An aggregator route lists the aggregator and each venue behind it.

Can I identify a swap from the logs alone?

The logs name programs and sometimes print amounts, in a format that differs per program. Balance changes read the same for every venue, which is why the file uses them. Use logsSubscribe to learn that something happened and read the balances after.

What does the decoder print for a failed transaction?

Its balances do not move apart from the fee, and the file adds the fee back, so it prints no asset lines and calls it not a clean swap.

How many transactions can I decode per second?

getTransaction costs 50 cells, which allows 0.24, 1.2, 5 and 25 requests a second on Free, Dev, Business and Pro.