Canonical: https://solanashreds.xyz/docs/programs/orca-whirlpool

# Orca Whirlpool recipe: swaps and new pools

Orca Whirlpool names its accounts by token A and token B, so the direction of a swap is a flag rather than an account order. This recipe decodes swaps and pool creations with Orca's published IDL, walks one real swap from bytes to balances, and lists what the bytes leave open.

For an Orca Whirlpool swap decode, match top-level instructions to the Whirlpool program and decode them with Orca's published IDL. The data holds the amount, a threshold on the other side, a price limit and two flags: whether the amount is the input, and whether tokens move from A to B. The flags, not account order, give the direction.

## Program ID and IDL

| What | Value |
| --- | --- |
| Program ID | `whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc` |
| IDL | `whirlpool.json` shipped in the npm package @orca-so/whirlpools-sdk 0.22.0 |
| Decoder | `anchor.ts` from the [Anchor decoding guide](https://solanashreds.xyz/docs/decode/anchor-instructions), plus the two files below |
| Runtime | Node 24, no dependencies |

Every pool belongs to a WhirlpoolsConfig account, stored right after the 8-byte discriminator of the pool account. Both new pools in our sample belonged to the same config account as the first existing pool we read, which is how we found them: by listing that config account's recent transactions.

## The swap and pool instructions

| Instruction | Arguments | Accounts that matter |
| --- | --- | --- |
| `swap_v2` | `amount`, `other_amount_threshold`, `sqrt_price_limit`, `amount_specified_is_input`, `a_to_b`, optional `remaining_accounts_info` | `token_authority` (signer), `whirlpool`, `token_mint_a`, `token_mint_b`, `token_owner_account_a` and `_b`, `tick_array_0` to `_2` |
| `swap` | the same five values | as above, but with one `token_program` and no mint accounts |
| `initialize_pool_v2` | `tick_spacing`, `initial_sqrt_price` | `whirlpools_config`, `token_mint_a`, `token_mint_b`, `funder`, `whirlpool` |
| `initialize_pool` | `bumps`, `tick_spacing`, `initial_sqrt_price` | same |

Unlike most DEX swaps, `swap_v2` names both mints, so you can label a swap without looking up the pool. A pool is created empty, at the starting price; liquidity comes through separate position instructions.

## Direction, threshold and price limit

`a_to_b` true means token A leaves `token_owner_account_a` and token B arrives in `token_owner_account_b`; false means the reverse. `amount_specified_is_input` decides what `amount` is: the exact input when true, the exact output when false. `other_amount_threshold` is then the least the user will accept out, or the most they will pay in.

`sqrt_price_limit` is the price at which the swap stops, in the same square-root 64.64 format as the pool's price. Many swaps set it to the bound of the program's range, which means no limit at all: the source fixes those bounds at `4295048016` and `79226673515401279992447579055`. The example below uses one less than the upper bound.

The three named tick arrays let a swap cross up to three arrays of 88 ticks; supplemental arrays and transfer-hook accounts follow in the remaining accounts, described by `remaining_accounts_info`. The source marks the `oracle` account as currently unused. [Concentrated liquidity on Solana](https://solanashreds.xyz/learn/concentrated-liquidity-on-solana) compares this layout with the other designs.

## Steps

1. Keep transactions with a top-level call to the Whirlpool program, resolving [lookup tables](https://solanashreds.xyz/docs/decode/resolve-lookup-tables) first for v0 and v1.
2. Decode with `SwapDecoder` and `PoolDecoder` below; for the mints of a swap, read `token_mint_a` and `token_mint_b` from `AnchorDecoder.decodeWithAccounts`.
3. Map source and destination with `a_to_b`, and exact side with `amount_specified_is_input`. `swaps.ts` does both.
4. After confirmation, read the real amounts from the token balance changes of the two user accounts.

## src/swaps.ts

The Orca Whirlpool entry in `MAPS` is the fourth.

```typescript file="src/swaps.ts"
// One shape for swaps on PumpSwap, Raydium CPMM and CLMM, Orca Whirlpool and Meteora DLMM and DAMM v2, decoded with
// each program's published IDL (fixtures/idls/SOURCES.tsv) through anchor.ts. Names on the right are the IDLs' own.
import { AnchorDecoder } from "./anchor.ts";

export type Swap = {
  program: string; instruction: string;
  pool: string; user: string;                    // the pool traded against and the signer that owns the user accounts
  source: string; destination: string;           // the user's token accounts: tokens leave source, arrive in destination
  exact: "in" | "out";                           // which side the user fixed
  amount: bigint;                                // the fixed side: exact input, or exact output
  limit: bigint;                                 // exact in: least output accepted; exact out: most input accepted
  partial: boolean;                              // true only for DAMM v2 PartialFill: up to `amount` in may be spent
};

export const DEX = {
  pumpswap: "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA",
  raydiumCpmm: "CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C",
  raydiumClmm: "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK",
  orcaWhirlpool: "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc",
  meteoraDlmm: "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo",
  meteoraDammV2: "cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG",
} as const;

type Map = (name: string, x: Record<string, any>, a: Record<string, string | null>) => Omit<Swap, "program" | "instruction" | "partial"> | null;

const MAPS: Record<string, Map> = {
  // PumpSwap: buy fixes the base tokens out; buy_exact_quote_in fixes the quote in; sell fixes the base tokens in.
  [DEX.pumpswap]: (n, x, a) => {
    const base = { pool: a.pool!, user: a.user! };
    if (n === "buy" || n === "buy_v2") return { ...base, source: a.user_quote_token_account!, destination: a.user_base_token_account!, exact: "out", amount: x.base_amount_out, limit: x.max_quote_amount_in };
    if (n.startsWith("buy_exact_quote_in")) return { ...base, source: a.user_quote_token_account!, destination: a.user_base_token_account!, exact: "in", amount: x.spendable_quote_in, limit: x.min_base_amount_out };
    if (n === "sell" || n === "sell_v2") return { ...base, source: a.user_base_token_account!, destination: a.user_quote_token_account!, exact: "in", amount: x.base_amount_in, limit: x.min_quote_amount_out };
    return null;
  },
  // Raydium CPMM: one instruction per direction of exactness.
  [DEX.raydiumCpmm]: (n, x, a) => {
    const base = { pool: a.pool_state!, user: a.payer!, source: a.input_token_account!, destination: a.output_token_account! };
    if (n === "swap_base_input") return { ...base, exact: "in", amount: x.amount_in, limit: x.minimum_amount_out };
    if (n === "swap_base_output") return { ...base, exact: "out", amount: x.amount_out, limit: x.max_amount_in };
    return null;
  },
  // Raydium CLMM: a flag says which side `amount` is; `other_amount_threshold` is the limit on the other side.
  [DEX.raydiumClmm]: (n, x, a) => n === "swap" || n === "swap_v2"
    ? { pool: a.pool_state!, user: a.payer!, source: a.input_token_account!, destination: a.output_token_account!,
        exact: x.is_base_input ? "in" : "out", amount: x.amount, limit: x.other_amount_threshold } : null,
  // Orca Whirlpool: accounts are named by token A and B, so direction comes from `a_to_b`.
  [DEX.orcaWhirlpool]: (n, x, a) => n === "swap" || n === "swap_v2"
    ? { pool: a.whirlpool!, user: a.token_authority!,
        source: (x.a_to_b ? a.token_owner_account_a : a.token_owner_account_b)!, destination: (x.a_to_b ? a.token_owner_account_b : a.token_owner_account_a)!,
        exact: x.amount_specified_is_input ? "in" : "out", amount: x.amount, limit: x.other_amount_threshold } : null,
  // Meteora DLMM: separate exact-in and exact-out instructions, each with a "2" variant that adds remaining accounts.
  [DEX.meteoraDlmm]: (n, x, a) => {
    const base = { pool: a.lb_pair!, user: a.user!, source: a.user_token_in!, destination: a.user_token_out! };
    if (n === "swap" || n === "swap2") return { ...base, exact: "in", amount: x.amount_in, limit: x.min_amount_out };
    if (n === "swap_exact_out" || n === "swap_exact_out2") return { ...base, exact: "out", amount: x.out_amount, limit: x.max_in_amount };
    return null;
  },
  // Meteora DAMM v2: swap is exact in; swap2 carries a mode byte (damm-v2 ix_swap.rs SwapMode: 0 ExactIn, 1 PartialFill, 2 ExactOut).
  [DEX.meteoraDammV2]: (n, x, a) => {
    const base = { pool: a.pool!, user: a.payer!, source: a.input_token_account!, destination: a.output_token_account! };
    const p = x._params;
    if (n === "swap") return { ...base, exact: "in", amount: p.amount_in, limit: p.minimum_amount_out };
    if (n === "swap2") return p.swap_mode === 2 ? { ...base, exact: "out", amount: p.amount_0, limit: p.amount_1 }
      : { ...base, exact: "in", amount: p.amount_0, limit: p.amount_1 }; // PartialFill fills up to amount_0 in
    return null;
  },
};

export class SwapDecoder {
  private decoders = new Map<string, AnchorDecoder>();
  /** idls: program id -> that program's IDL */
  constructor(idls: Record<string, object>) { for (const [p, idl] of Object.entries(idls)) this.decoders.set(p, new AnchorDecoder(idl as any)); }

  decode(programId: string, data: Uint8Array, accounts: string[]): Swap | null {
    const dec = this.decoders.get(programId), map = MAPS[programId];
    if (!dec || !map) return null;
    const d = dec.decodeWithAccounts(data, accounts, programId);
    if (!d) return null;
    const s = map(d.name, d.args as Record<string, any>, d.accounts);
    if (!s) return null;
    const partial = programId === DEX.meteoraDammV2 && d.name === "swap2" && (d.args as any)._params.swap_mode === 1;
    return { program: programId, instruction: d.name, ...s, partial };
  }
}
```

## src/pools.ts

```typescript file="src/pools.ts"
// One shape for new pools on PumpSwap, Raydium CPMM and CLMM, Orca Whirlpool and Meteora DLMM and DAMM v2, decoded
// with each program's published IDL (fixtures/idls/SOURCES.tsv) through anchor.ts. Names on the right are the IDLs' own.
import { AnchorDecoder } from "./anchor.ts";
import { DEX } from "./swaps.ts";

export type PoolCreated = {
  program: string; instruction: string;
  pool: string; creator: string;                 // the new pool account and the account that pays for it
  mintA: string; mintB: string;                  // in the program's own order (base/quote, 0/1, A/B or X/Y)
  amountA: bigint | null; amountB: bigint | null; // initial deposit, when the creation instruction carries one
  sqrtPriceX64: bigint | null;                   // starting price for the sqrt-price designs (Q64.64)
  activeBinId: number | null;                    // starting bin for DLMM
};

type Map = (n: string, x: Record<string, any>, a: Record<string, string | null>) => Omit<PoolCreated, "program" | "instruction"> | null;
const none = { amountA: null, amountB: null, sqrtPriceX64: null, activeBinId: null };

const MAPS: Record<string, Map> = {
  [DEX.pumpswap]: (n, x, a) => n === "create_pool"
    ? { ...none, pool: a.pool!, creator: a.creator!, mintA: a.base_mint!, mintB: a.quote_mint!, amountA: x.base_amount_in, amountB: x.quote_amount_in } : null,
  [DEX.raydiumCpmm]: (n, x, a) => n === "initialize" || n === "initialize_with_permission"
    ? { ...none, pool: a.pool_state!, creator: a.creator!, mintA: a.token_0_mint!, mintB: a.token_1_mint!, amountA: x.init_amount_0, amountB: x.init_amount_1 } : null,
  [DEX.raydiumClmm]: (n, x, a) => n === "create_pool"
    ? { ...none, pool: a.pool_state!, creator: a.pool_creator!, mintA: a.token_mint_0!, mintB: a.token_mint_1!, sqrtPriceX64: x.sqrt_price_x64 } : null,
  [DEX.orcaWhirlpool]: (n, x, a) => n.startsWith("initialize_pool")
    ? { ...none, pool: a.whirlpool!, creator: a.funder!, mintA: a.token_mint_a!, mintB: a.token_mint_b!, sqrtPriceX64: x.initial_sqrt_price } : null,
  [DEX.meteoraDlmm]: (n, x, a) => n === "initialize_lb_pair" || n === "initialize_lb_pair2" || n.startsWith("initialize_customizable_permissionless_lb_pair")
    ? { ...none, pool: a.lb_pair!, creator: a.funder!, mintA: a.token_mint_x!, mintB: a.token_mint_y!, activeBinId: x.active_id ?? x.params.active_id } : null,
  [DEX.meteoraDammV2]: (n, x, a) => n === "initialize_pool" || n === "initialize_customizable_pool" || n === "initialize_pool_with_dynamic_config"
    ? { ...none, pool: a.pool!, creator: a.creator!, mintA: a.token_a_mint!, mintB: a.token_b_mint!, sqrtPriceX64: x.params.sqrt_price } : null,
};

export class PoolDecoder {
  private decoders = new Map<string, AnchorDecoder>();
  /** idls: program id -> that program's IDL */
  constructor(idls: Record<string, object>) { for (const [p, idl] of Object.entries(idls)) this.decoders.set(p, new AnchorDecoder(idl as any)); }

  decode(programId: string, data: Uint8Array, accounts: string[]): PoolCreated | null {
    const dec = this.decoders.get(programId), map = MAPS[programId];
    if (!dec || !map) return null;
    const d = dec.decodeWithAccounts(data, accounts, programId);
    if (!d) return null;
    const p = map(d.name, d.args as Record<string, any>, d.accounts);
    if (!p) return null;
    return { program: programId, instruction: d.name, pool: p.pool, creator: p.creator, mintA: p.mintA, mintB: p.mintB,
      amountA: p.amountA, amountB: p.amountB, sqrtPriceX64: p.sqrtPriceX64, activeBinId: p.activeBinId };
  }
}
```

## src/decode-dex.ts: one transaction

```typescript file="src/decode-dex.ts"
// Print swaps and new pools for one transaction, for the six DEX programs in swaps.ts and pools.ts.
//   node src/decode-dex.ts <idl-dir> <transaction-base64> [loaded-writable,...] [loaded-readonly,...]
import fs from "node:fs";
import { decodeTx } from "./tx.ts";
import { SwapDecoder, DEX } from "./swaps.ts";
import { PoolDecoder } from "./pools.ts";

const [idlDir, txBase64, loadedW = "", loadedR = ""] = process.argv.slice(2);
const idl = (f: string) => JSON.parse(fs.readFileSync(`${idlDir}/${f}`, "utf8"));
const idls = { [DEX.pumpswap]: idl("pump_amm.json"), [DEX.raydiumCpmm]: idl("raydium_cp_swap.json"), [DEX.raydiumClmm]: idl("raydium_clmm.json"),
  [DEX.orcaWhirlpool]: idl("whirlpool.json"), [DEX.meteoraDlmm]: idl("dlmm.json"), [DEX.meteoraDammV2]: idl("cp_amm.json") };
const swaps = new SwapDecoder(idls), pools = new PoolDecoder(idls);
const tx = decodeTx(Buffer.from(txBase64, "base64"));
const keys = [...tx.staticKeys, ...loadedW.split(",").filter(Boolean), ...loadedR.split(",").filter(Boolean)];

for (const ix of tx.instructions) { // top-level calls only: a DEX called by a router or launchpad is a CPI
  const program = keys[ix.programIndex], accounts = ix.accounts.map((i) => keys[i]);
  const event = swaps.decode(program, ix.data, accounts) ?? pools.decode(program, ix.data, accounts);
  if (event) console.log(JSON.stringify({ signature: tx.signatures[0], ...event }, (_k, v) => (typeof v === "bigint" ? v.toString() : v)));
}
```

## One real swap, from bytes to balances

| Field | Value, slot 470,929,912 |
| --- | --- |
| `pool` | `56QW1m7pe5TdbEg9hTqmCB943LT3PSauVyBdnX4UACXH` |
| `user` | `Hasda78TSaT9bjiPxDBvP4GpohFpP3TDTaJEcCYK5kyN` |
| mints | A `TTWofwAge91oFhZs7kpQdyrVRkmevgM88xijGvQFbKo`, B `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` |
| `a_to_b` | false: token B in, token A out |
| `exact`, `amount` | in, 36,851,318 raw units of B |
| `limit` | at least 169,882 raw units of A |
| `sqrt_price_limit` | 79,226,673,515,401,279,992,447,579,054: no effective limit |
| trailing accounts | 2 |
| source balance change, from RPC | minus 36,851,318: exactly the amount |
| destination balance change, from RPC | plus 170,107: above the limit by 225 |

The first five rows come from the instruction; the last two only exist after execution. That gap is the whole difference between what a shred decoder knows early and what a confirmed transaction settles.

## How this code was tested

| Check | Result |
| --- | --- |
| Swaps decoded (successful transactions) | `swap_v2` 7 |
| The user signed | 7/7 |
| Exact side equals the user's balance change, where no other instruction touched that account | 4/4 |
| Limit respected, same condition | 3/3 |
| Pool creations: decoded pool equals the pool the sample was found by; both mints have vaults afterwards | `initialize_pool_v2` 2/2, both with `tick_spacing` 8 |
| Not seen in our sample, so mapped from the IDL but not tested on real data | `swap` (v1), `initialize_pool` (v1) |

Three of the seven swaps moved 1 raw unit with a threshold of 0. They decode like any other swap; decide in your own pipeline whether such tiny swaps matter. The tests are `test-swaps.ts` and `test-pools.ts` in the examples' `test-all.sh`.

## What the swap bytes cannot tell you

The instruction says what the user asked for and the worst outcome they accepted; it does not say what they got, what fee was taken or where the price ended. Those need balances or the pool account after execution. Transfer-hook tokens add accounts whose meaning depends on the token's hook program. A swap made through an aggregator is an inner instruction and never appears in shreds.

## Other concentrated liquidity programs

The [Raydium CPMM and CLMM recipe](https://solanashreds.xyz/docs/programs/raydium-cpmm-and-clmm) and the [Meteora recipe](https://solanashreds.xyz/docs/programs/meteora) use the same decoder for their pools, and [how swaps look as instructions](https://solanashreds.xyz/learn/how-swaps-look-as-instructions) compares all of them. To watch Whirlpool swaps arrive before they are confirmed, [compare the plans](https://solanashreds.xyz/pricing).
