---
id: SI0040
title: "Swap price-impact explainer"
url: https://carbium.sh/library/si/swap-price-impact-explainer
collection: AI and blockchain
category: Swap assistants
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Swap price-impact explainer

You get a read-only script that lists the newest swaps touching a token or pool address and prints, for each single-pool swap, the execution price, the pool's price before it, the price impact and the share of the pool's reserve it took.

## Finding a token's latest swaps

Solana keeps no per-token transaction log. `getSignaturesForAddress` lists, newest first, the transactions whose account list includes an address, so the first decision is which address to ask about. A mint address shows up in a transaction only when an instruction passes it in, which `transferChecked` transfers and many aggregator routes do. A swap on one pool always carries that pool's own address, so the pool is the more complete choice when you have it.

The file takes either one. Given a mint, it reads whatever the newest signatures hold and keeps the swaps it can measure. Given a pool address, it reads the newest transactions that name that address and keeps the ones that pass the single-pool test.

The signature list carries no amounts, so each signature needs a `getTransaction` call with `jsonParsed` encoding. The amounts live in `meta`: token balances before and after for every token account the transaction touched, and that includes the pool's vaults.

## How the impact is read

Price impact is the gap between the price the swapper got and the price the pool showed just before the swap. One transaction holds both. The swapper's side is the net movement of the fee payer: one asset down, one up, and the ratio of the two is the execution price. The pool's side is its two vault token accounts, whose reserves sit in `preTokenBalances` before the swap and in `postTokenBalances` after it.

For a constant-product pool the price before the swap is the output reserve divided by the input reserve, and impact is one minus the execution price over that price. The figure includes the pool's own fee, so a tiny swap still reads slightly above zero. For small swaps, impact without the fee sits close to the pool share.

| Quantity | Where it comes from |
|---|---|
| Execution price | payer's net output over net input |
| Price before | output vault reserve over input vault reserve, from the balances before |
| Impact | one minus execution price over price before |
| Pool share | input amount over input vault reserve before |

A swap is measured only when the payer lost exactly one asset and gained exactly one, and exactly two other token accounts moved: one vault of the input asset that gained and one vault of the output asset that lost. Both vaults must share an owner, and the input vault must gain what the payer lost to within 5%. Many AMM programs use one authority for all their pools, so the owner test alone would pass a two-hop route through two of them; the count of moved accounts rejects it, along with any transaction that moved a third mint. Wrapped SOL and native SOL count as one asset, and a SOL leg under 0.005 SOL is dropped as dust. When SOL is the input and the payer also opens a token account in the same transaction, the 2,039,280-lamport rent counts against the 5% vault match, so SOL-in swaps under about 0.04 SOL are dropped. When SOL is the output and the payer closes a wrapped SOL account in the same transaction, the refunded rent adds to the output and the impact reads low.

## The impact reader

One file, on `@solana/kit` and Node's own modules. Set `CARBIUM_KEY` and pass a mint or a pool address. With no argument it reads the Raydium AMM v4 SOL-USDC pool, a constant-product pool. If that pool's list comes back empty, or none of its newest transactions measures, the file lists the newest signatures of the Raydium AMM v4 program (`675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8`), reads five of them, and takes the pool account, the second account of the Raydium instruction, from the first transaction that passes the single-pool test. It then runs the same pass on that pool. An address you pass is never swapped for another.

`main.ts` (run: `node main.ts [mint or pool address]`)

```ts
// SI0040 · Swap price-impact explainer
// https://carbium.sh/library/si/swap-price-impact-explainer
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Price impact of a token's latest swaps. Run: CARBIUM_KEY=... node main.ts [mint or pool 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";
const PROGRAM = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"; // Raydium AMM v4
const target = process.argv[2] ?? "58oQChx4yWmvKD5LrN3iyQSVaTNTDY4ZK1rUJSXjPmqV"; // its SOL-USDC pool
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);
const ui = (n: bigint, d: number) => (Number(n) / 10 ** d).toPrecision(4);

type Acct = { mint: string; owner?: string; decimals: number; pre: bigint; post: bigint };

function priceImpact(tx: any) {
  const { meta, transaction: { message } } = tx;
  if (meta.err) return null;
  const payer: string = message.accountKeys[0].pubkey;
  const accts = new Map<number, Acct>();
  for (const [list, side] of [[meta.preTokenBalances, "pre"], [meta.postTokenBalances, "post"]] as const) {
    for (const b of list ?? []) {
      const a: Acct = accts.get(b.accountIndex) ?? { mint: b.mint, owner: b.owner, decimals: b.uiTokenAmount.decimals, pre: ZERO, post: ZERO };
      a[side] = BigInt(b.uiTokenAmount.amount);
      accts.set(b.accountIndex, a);
    }
  }
  // The payer's net movement per mint; native SOL counts as wrapped SOL, with the fee added back.
  const net = new Map<string, bigint>([[WSOL, BigInt(meta.postBalances[0]) - BigInt(meta.preBalances[0]) + BigInt(meta.fee)]]);
  for (const a of accts.values()) if (a.owner === payer) net.set(a.mint, (net.get(a.mint) ?? ZERO) + a.post - a.pre);
  const legs = [...net].filter(([m, d]) => d !== ZERO && (m !== WSOL || abs(d) > DUST));
  const down = legs.filter(([, d]) => d < ZERO), up = legs.filter(([, d]) => d > ZERO);
  if (down.length !== 1 || up.length !== 1) return null;
  const [[inMint, inD]] = down, [[outMint, outD]] = up;
  // A true single-pool swap moves exactly two accounts besides the payer's: one vault of each mint.
  const movers = [...accts.values()].filter((a) => a.owner !== payer && a.post !== a.pre);
  const ins = movers.filter((a) => a.mint === inMint);
  const outs = movers.filter((a) => a.mint === outMint);
  if (movers.length !== 2 || ins.length !== 1 || outs.length !== 1) return null;
  const [vIn] = ins, [vOut] = outs;
  if (vIn.post < vIn.pre || vOut.post > vOut.pre) return null;
  if (vIn.owner !== vOut.owner || vIn.pre === ZERO || vOut.pre === ZERO) return null;
  if (abs(abs(vIn.post - vIn.pre) - abs(inD)) * BigInt(20) > abs(inD)) return null; // not one pool's swap
  const scale = 10 ** (vIn.decimals - vOut.decimals);
  const exec = (Number(outD) / Number(-inD)) * scale;
  const spot = (Number(vOut.pre) / Number(vIn.pre)) * scale;
  return {
    inMint, outMint, inAmt: -inD, outAmt: outD, inDec: vIn.decimals, outDec: vOut.decimals, reserve: vIn.pre,
    exec, spot, impact: (1 - exec / spot) * 100, share: (Number(-inD) / Number(vIn.pre)) * 100,
  };
}

// Mainnet carries v1 transactions; with this absent or 0, getTransaction answers -32015 for one.
const config = { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 } as const;
const abort = () => ({ abortSignal: AbortSignal.timeout(8_000) }); // one fresh 8 s limit per call
let asked = 0, swaps = 0, nulls = 0, failed = 0;
const fail = (what: string, e: unknown) => { failed++; console.log(`${what} ${(e as Error).message}`); };
const read = (sigs: { signature: string }[]) => Promise.allSettled(sigs.map((s) => rpc.getTransaction(signature(s.signature), config).send(abort())));
async function recent(addr: string, limit: number) { // one retry; two failures leave the pass with nothing to read
  const list = () => rpc.getSignaturesForAddress(address(addr), { limit: 25 }).send(abort());
  try { return (await list().catch(list)).filter((s) => !s.err).slice(0, limit); }
  catch (e) { fail("getSignaturesForAddress failed:", e); return []; }
}
async function scan(addr: string) {
  console.log(`reading the newest signatures of ${addr}`);
  const sigs = await recent(addr, 15); asked += sigs.length;
  (await read(sigs)).forEach((r, i) => {
    const id = sigs[i].signature.slice(0, 12);
    if (r.status === "rejected") return fail(id, r.reason);
    if (!r.value) nulls++;
    const s = r.value && priceImpact(r.value);
    if (!s) return;
    swaps++;
    console.log(`${id} slot ${r.value?.slot} ${ui(s.inAmt, s.inDec)} ${s.inMint.slice(0, 4)} -> ${ui(s.outAmt, s.outDec)} ${s.outMint.slice(0, 4)}`
      + ` exec ${s.exec.toPrecision(5)} spot ${s.spot.toPrecision(5)} impact ${s.impact.toFixed(3)}% pool ${s.share.toFixed(3)}% of ${ui(s.reserve, s.inDec)}`);
  });
}
async function findPool() { // the pool account of the first direct Raydium swap that passes the single-pool test
  for (const r of await read(await recent(PROGRAM, 5))) {
    const tx: any = r.status === "fulfilled" ? r.value : null;
    const ix = tx && priceImpact(tx) && tx.transaction.message.instructions.find((i: any) => i.programId === PROGRAM);
    if (ix) return String(ix.accounts[1]);
  }
}
await scan(target);
const pool = swaps || process.argv[2] ? undefined : await findPool();
if (pool) { console.log(`no swap measured on ${target}; trying ${pool} from the newest Raydium AMM v4 signatures`); await scan(pool); }
console.log(`${asked} transactions asked, ${swaps} single-pool swaps, ${nulls} null, ${failed} failed`);
process.exit(0);
```

Each measured swap prints one line: the first 12 characters of the signature, the slot, the input amount with the first four characters of its mint, the output amount likewise, then `exec` for the execution price in output per input, `spot` for the pool's price before the swap in the same unit, `impact` in percent, and `pool` for the pool share in percent followed by the input reserve that share is taken of. Any line can be checked by hand: impact is `100 * (1 - exec / spot)` and the pool share is `100 * input / reserve`. Amounts and reserves print at four significant digits and exec and spot at five, so a recomputation agrees to within that rounding.

The last line gives the transactions asked for, the single-pool swaps found, the null answers and the failed calls. It adds up every pool the run scanned.

## Calls, cost and commitment

A pass makes one `getSignaturesForAddress` call for 25 signatures, tried a second time if the first fails, and up to 15 `getTransaction` calls on the ones that did not fail. Each costs 50 cells, so a pass is at most 800 cells, or 850 when the list call is retried, 750 of them in the transaction lookup class and under the 1,024 cells a class absorbs as a burst. The reads of a pass go out together. A loop that reads transactions without pause is held to [the per-second rate of that class](https://carbium.sh/docs#rpc), 0.24, 1.2, 5 and 25 req/s on Free, Dev, Business and Pro, and every key on the account shares it. Every call gets its own 8-second abort, so a pass takes 24 seconds at worst: the list call and its retry at 8 seconds each, then the parallel reads together at 8.

When the default pool measures nothing, the busy-pool search adds one list call and up to five reads, 300 cells with 250 in the transaction class, and the second pass adds another 800. If the first pass already made 15 reads, the three stages together go past the burst in the transaction class, so on a key whose bucket has not refilled the later reads can answer 429 and print as failed.

Neither call names a commitment, so `@solana/kit` fills in `confirmed`. The config passes `maxSupportedTransactionVersion: 1`, the value mainnet's v1 transactions need; the error you get without it is covered in [Transaction version error -32015](https://carbium.sh/library/howsolana/transaction-version-error-32015).

## Following new swaps

For a live view, open a WebSocket on `wss://services.carbium.sh` with the key as `?api-key=` and subscribe with `logsSubscribe` on a mention of the pool address. Each notification carries a signature: read it through `getTransaction` first, then pass the transaction it returns to `priceImpact`. A mention subscription costs 25 credits to open and then 20 credits per MiB sent, so a busy pool costs more to watch than a quiet one.

For a swap you have not sent yet, the `quote` method on the RPC endpoint is the place to ask. [Swap transaction decoder](https://carbium.sh/library/si/swap-transaction-decoder) shows how to read the legs of one swap in detail.

## Where it ends

- Only pools priced by their reserve ratio read correctly. Concentrated-liquidity pools spread reserves over price ranges and stable-swap curves do not price by the reserve ratio, so the figure on those is not a price impact and can come out negative or far above the pool share.
- The file measures single-pool swaps only, since one pool's reserves cannot price a multi-hop route or a swap split over several pools. A token traded mostly through multi-hop routes yields a small sample. A swap that pays any fee to a separate token account moves a third account, so the single-pool test drops it.
- The reserves are the balances at the start of the transaction, so an earlier instruction in the same transaction that touches the pool shifts them before the swap runs.
- Listing by address stops at the 30-day address index: older history is not served. An empty page past 30 days is the index's age limit, and the address may have older transactions.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The summary line reports 0 single-pool swaps. | A mint lists only transactions that carry the mint, and many swaps omit it. Pass the pool address instead, or run again a little later against a busier address. |
| Impact comes out negative or far above the pool share. | The pool is not priced by its reserve ratio. Keep to constant-product pools or compare the pool column alone. |
| `getTransaction` fails with "Transaction version (1) is not supported by the requesting client". | Mainnet carries v1 transactions, and with `maxSupportedTransactionVersion` absent or 0 the call answers -32015, uncharged. Pass `maxSupportedTransactionVersion: 1`, as the file does. |
| A signature from the list reads null in `getTransaction`. | Signature pages reach below the validator's ledger floor, so an older signature can be listed but not served. The file counts it as null and moves on. Work from the newest signatures. |
| A repeat run gets 429 on some reads. | The 15 parallel reads take 750 cells of the burst. On Free, at 0.24 req/s and 50 cells a call, the class refills 12 cells a second, so a full refill takes about a minute before a second run reads cleanly. |
| A small SOL swap is not measured. | A SOL leg under 0.005 SOL is dropped as dust, so the swap no longer shows two legs. Lower `DUST` only if you also account for the 2,039,280 lamports a new token account takes. |

## Questions

### What is the difference between price impact and slippage?

Impact is the move the swap itself causes in the pool's price. Slippage is the gap between the price quoted when the swap was built and the price it got, which also takes in other swaps that landed in between. The file compares against the pool's price right before the swap, so it reads impact.

### Can I get the latest swaps of a token without knowing a pool?

Yes, with the mint address, but the list holds only transactions that carry the mint in their account list. Find a pool from a few of those swaps, then list that pool's address for a fuller sample.

### How far back can I read?

`getSignaturesForAddress` reaches back 30 days at most, from the address index. Keep the signatures and results you need when you first read them.

### How many swaps can I measure per second?

Each transaction read is one `getTransaction` call of 50 cells, and the transaction lookup class runs at [0.24, 1.2, 5 and 25 req/s](https://carbium.sh/docs#rpc) on Free, Dev, Business and Pro. Those rates count transactions read, and only the single-pool swaps among them get measured.

## Related

- [Swap transaction decoder](https://carbium.sh/library/si/swap-transaction-decoder) (AI and blockchain, SI0012)
- [Transaction version error -32015](https://carbium.sh/library/howsolana/transaction-version-error-32015) (How to use Solana, HS0012)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
- [carbium.sh/docs#migrate](https://carbium.sh/docs#migrate)
- [carbium.sh/docs#quote](https://carbium.sh/docs#quote)
