Canonical: https://solanashreds.xyz/docs/programs/raydium-cpmm-and-clmm

# Raydium CPMM and CLMM recipe

Raydium's two newer pool programs both publish Anchor IDLs, so one decoder handles their swaps and pool creations. This recipe covers CPMM and CLMM, the LaunchLab graduation that creates CPMM pools, and what a CLMM swap leaves unsaid, tested against real mainnet transactions.

For a Raydium CPMM decode, match top-level instructions to the CPMM program and read them with the IDL Raydium publishes: one swap instruction fixes the input, the other fixes the output, and initialize creates a pool. CLMM swaps decode the same way, but their price depends on tick array state that the instruction only points to.

## Program IDs and IDLs

| What | Value |
| --- | --- |
| CPMM program ID | `CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C` |
| CLMM program ID | `CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK` |
| LaunchLab program ID | `LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj` |
| IDLs | `raydium_cp_swap.json`, `raydium_clmm.json`, `raydium_launchpad.json` from raydium-io/raydium-idl, commit e7e0c96 |
| 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 |

The older Raydium AMM v4 program has no IDL; the [Raydium AMM v4 recipe](https://solanashreds.xyz/docs/programs/raydium-amm) decodes it by hand.

## Swap and pool instructions

| Program, instruction | User fixes | Amount | Limit | User accounts |
| --- | --- | --- | --- | --- |
| CPMM `swap_base_input` | input | `amount_in` | `minimum_amount_out` | `input_token_account`, `output_token_account`, signer `payer` |
| CPMM `swap_base_output` | output | `amount_out` | `max_amount_in` | same |
| CLMM `swap` and `swap_v2` | input when `is_base_input`, else output | `amount` | `other_amount_threshold` | same |
| CPMM `initialize`, `initialize_with_permission` | deposit | `init_amount_0`, `init_amount_1` | none | `creator`, mints `token_0_mint`, `token_1_mint` |
| CLMM `create_pool` | starting price | `sqrt_price_x64` | none | `pool_creator`, mints `token_mint_0`, `token_mint_1` |

CLMM swaps also carry `sqrt_price_limit_x64`, the price beyond which the swap stops. A CLMM pool is created empty: liquidity arrives through separate position instructions, which can sit in the same transaction. The pool creation in the example below is followed by `open_position_with_token22_nft` in the same transaction.

## LaunchLab graduations create CPMM pools

Both CPMM pool creations in our sample were not top-level `initialize` calls. They came from Raydium LaunchLab: a top-level LaunchLab `migrate_to_cpswap`, signed by `RAYpQbFNq9i3mu6cKpTKKRwwHFDeK5AuZz8xvxUrCgw` in both cases, called CPMM `initialize_with_permission` internally. That inner call is invisible in shreds, but `migrate_to_cpswap` names the new pool in its own accounts as `cpswap_pool`, together with `base_mint` and `quote_mint`. In both transactions that account equalled the pool the inner call created.

One graduation also shows why deposits must be checked against balances. Its token used Token-2022, and the pool's vault received 200,693,000,000,000 raw units against the 206,900,000,000,000 the instruction deposited, three percent less. That is a transfer fee, set by the token, not by Raydium. [Token-2022 extensions](https://solanashreds.xyz/learn/token-2022-extensions) explains where such fees come from.

## Why a CLMM swap price needs tick arrays

A CLMM pool keeps its liquidity in ranges, stored in tick array accounts of 60 ticks each. A swap names the pool and lists the tick arrays it may cross after its named accounts: in our sample, 2, 3 or 6 of them. The executed price depends on the pool's current price and the liquidity in those arrays at the moment the swap runs, and none of that is in the instruction. To compute it you must fetch the pool and tick array accounts, and even then later transactions in the same block may have moved them first. [Concentrated liquidity on Solana](https://solanashreds.xyz/learn/concentrated-liquidity-on-solana) explains ticks and arrays.

What the instruction does give is the worst price the user accepted, through `other_amount_threshold` and `sqrt_price_limit_x64`. For a settled price, use the token balance changes after confirmation.

## Steps

1. Keep transactions with a top-level call to CPMM, CLMM or LaunchLab. Resolve [lookup table](https://solanashreds.xyz/docs/decode/resolve-lookup-tables) addresses first for v0 and v1 transactions.
2. Decode CPMM and CLMM calls with `SwapDecoder` and `PoolDecoder` below.
3. For a LaunchLab `migrate_to_cpswap`, decode it with the LaunchLab IDL through `AnchorDecoder` and record `cpswap_pool` with its two mints as a new CPMM pool.
4. Join swaps to pools by pool address; for CLMM, keep the trailing tick array accounts if you plan to price the swap.
5. After confirmation, take outcomes and real amounts from RPC.

## src/swaps.ts

The Raydium CPMM and CLMM entries in `MAPS` are the second and third.

```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)));
}
```

## A real swap and a real pool, decoded

| Field | CPMM swap, slot 470,928,571 | CLMM pool creation, slot 470,742,077 |
| --- | --- | --- |
| `instruction` | `swap_base_input` | `create_pool` |
| `pool` | `2yLFomCTck19BqK7EzJqsUWXPWP3uWGNBSrfKvJzNzp2` | `8k99JKfG2vs3JPXGKvix1KgGkFivu9C8RxxM8MpLpgke` |
| user or creator | `DdMLiWDkV2R3bnNyy6UH9ND1r84wLfyCyoikR59Q4qXR` | `DfreA4EWH5epT7WRd755zjEAfTz9xneeaLGSqys1TkK1` |
| fixed amount | exact in: 38,132,600 | none |
| limit or price | at least 15,445,762,115,675 out | `sqrt_price_x64` 332,213,663,356,585,312,256 |
| mints | not in the swap's own fields | `So11111111111111111111111111111111111111112` and `CT7AsA1nZ9r3JZnU96qDBHGKqCAZwMPbCav9NGj3Qnjz` |

The CLMM starting price works out to about 324.34 raw units of the second mint per raw unit of the first: divide the square root by 2^64 and square it, then adjust for decimals before showing it.

## How this code was tested

| Check | Result |
| --- | --- |
| Swaps decoded (successful transactions) | CPMM `swap_base_input` 15, CLMM `swap_v2` 6 |
| The user signed | every one |
| Exact side equals the user's balance change, where no other instruction touched that account | 7/7 CPMM, 4/4 CLMM |
| Limit respected, same condition | 11/11 CPMM, 4/4 CLMM |
| Pool creations: decoded pool equals the pool the sample was found by; vault balances | CPMM 2/2, deposit lands 2/2 (one with a Token-2022 fee); CLMM 1/1 |
| LaunchLab `migrate_to_cpswap` names the CPMM pool it creates | 2/2 |
| Not seen in our sample, so mapped from the IDL but not tested on real data | CPMM `swap_base_output`, CLMM `swap` (v1) |

The tests are `test-swaps.ts` and `test-pools.ts` in the examples' `test-all.sh`.

## What the instructions cannot tell you

A swap names the user's token accounts and the pool, not the mints, and not the amount it received. CLMM prices need account state at execution time. LaunchLab creations are visible only through `migrate_to_cpswap`, and swaps made through a router are inner instructions that shreds never carry. We only tested `swap_base_input` and `swap_v2` on real data; treat the other two swap forms with care until you have seen your own.

## The rest of Raydium and its neighbours

For AMM v4, see the [Raydium AMM v4 recipe](https://solanashreds.xyz/docs/programs/raydium-amm); for the other concentrated designs, the [Orca Whirlpool recipe](https://solanashreds.xyz/docs/programs/orca-whirlpool) and the [Meteora recipe](https://solanashreds.xyz/docs/programs/meteora). [PumpSwap](https://solanashreds.xyz/docs/programs/pumpswap) uses the same decoder. To watch new Raydium pools appear, [see pricing](https://solanashreds.xyz/pricing).
