> ## Documentation Index
> Fetch the complete documentation index at: https://docs.raydium.io/llms.txt
> Use this file to discover all available pages before exploring further.

# CPMM code demos

> End-to-end TypeScript examples for every CPMM operation — create pool, swap, deposit, withdraw, collect fees — plus a minimal Rust CPI skeleton.

> [!NOTE]
>
> **Version banner.** All TypeScript demos target `@raydium-io/raydium-sdk-v2@0.2.64-alpha`; they were last executed against `0.2.42-alpha` (2026-04) and their call signatures re-checked against the `0.2.64-alpha` source on 2026-09-09, against Solana mainnet-beta. The Rust CPI skeleton targets `raydium-cp-swap` on `master`, Anchor `1.0.2`. Program IDs are pulled via constants from [`reference/program-addresses`](https://docs.raydium.io/reference/program-addresses).

## Prerequisites

```bash theme={null}
npm install @raydium-io/raydium-sdk-v2 @solana/web3.js @solana/spl-token bn.js decimal.js
```

Every demo on this page mirrors a file in [`raydium-sdk-V2-demo/src/cpmm`](https://github.com/raydium-io/raydium-sdk-V2-demo/tree/master/src/cpmm); the GitHub link sits next to each section. Bootstrap follows the demo repo's `config.ts.template` ([source](https://github.com/raydium-io/raydium-sdk-V2-demo/blob/master/src/config.ts.template)):

```ts theme={null}
import { Connection, Keypair, clusterApiUrl } from "@solana/web3.js";
import { Raydium, TxVersion } from "@raydium-io/raydium-sdk-v2";
import fs from "node:fs";

const connection = new Connection(process.env.RPC_URL ?? clusterApiUrl("mainnet-beta"));
const owner = Keypair.fromSecretKey(
  new Uint8Array(JSON.parse(fs.readFileSync(process.env.KEYPAIR!, "utf8"))),
);

const raydium = await Raydium.load({
  owner,
  connection,
  cluster: "mainnet",
  disableFeatureCheck: true,
  blockhashCommitment: "finalized",
});
```

The `Raydium` instance is the SDK's facade — every demo below uses it. `Raydium.load` is async because it loads the token list by default; pass `disableLoadToken: true` to skip that fetch. The availability feature-check is already skipped unless you pass `disableFeatureCheck: false`. Fee configs are fetched lazily on first use via `raydium.api.getCpmmConfigs()`.

## Create a CPMM pool

Source: [`src/cpmm/createCpmmPool.ts`](https://github.com/raydium-io/raydium-sdk-V2-demo/blob/master/src/cpmm/createCpmmPool.ts)

```ts theme={null}
import { PublicKey } from "@solana/web3.js";
import BN from "bn.js";
import { CREATE_CPMM_POOL_PROGRAM, CREATE_CPMM_POOL_FEE_ACC }
  from "@raydium-io/raydium-sdk-v2";
// (If you need every pool PDA at once, the exported helper is `getCreatePoolKeys`.
//  There is no `getCpmmPdas`.)

const mintA = new PublicKey("So11111111111111111111111111111111111111112"); // wSOL
const mintB = new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"); // USDC

// 1. Pick a fee config. index=0 is the 0.25% tier.
const feeConfigs = await raydium.api.getCpmmConfigs();
const feeConfig  = feeConfigs.find((c) => c.index === 0)!;

// 2. Pull mint metadata so the SDK can handle Token-2022 extensions.
const mintAInfo = await raydium.token.getTokenInfo(mintA);
const mintBInfo = await raydium.token.getTokenInfo(mintB);

// 3. Build the transaction.
const { execute, extInfo } = await raydium.cpmm.createPool({
  programId:       CREATE_CPMM_POOL_PROGRAM,
  poolFeeAccount:  CREATE_CPMM_POOL_FEE_ACC,
  mintA:           mintAInfo,
  mintB:           mintBInfo,
  mintAAmount:     new BN(1_000_000_000),   // 1 SOL (assuming 9 decimals)
  mintBAmount:     new BN(   160_000_000),  // 160 USDC (at 160/SOL)
  startTime:       new BN(0),               // open immediately
  feeConfig,
  associatedOnly:  false,
  ownerInfo:       { useSOLBalance: true },
  txVersion:       TxVersion.V0,
});

const { txId } = await execute({ sendAndConfirm: true });
console.log("Pool created at", extInfo.address.poolId.toBase58());
console.log("Tx:", txId);
```

A few things the SDK quietly takes care of:

* Sorting the mints into token0/token1 order before deriving the PDA.
* Paying the one-time `create_pool_fee` to `poolFeeAccount`.
* Creating the caller's associated token accounts if missing.
* Choosing the right token program (SPL Token vs Token-2022) per side.

> [!NOTE]
>
> **`createPool` builds `Initialize`, so the pool's creator fee is off.** To create a pool with the creator fee enabled, use `InitializeV2` (added in the 2026-10-30 program upgrade). Its first 19 accounts match `Initialize`. It drops `rent` and takes one more argument, `creator_fee_on: Option<CreatorFeeOn>`. The `0.2.64-alpha` pin on this page predates the instruction. Until your SDK version ships a builder, encode it from the refreshed IDL. See [`products/cpmm/instructions`](https://docs.raydium.io/products/cpmm/instructions#initializev2).

After confirmation you can fetch the live pool state with:

```ts theme={null}
// getPoolInfoFromRpc takes a positional base58 string, not a PublicKey and not an object.
const { poolKeys, poolInfo, rpcData } = await raydium.cpmm.getPoolInfoFromRpc(
  extInfo.address.poolId.toBase58(),
);
```

## Swap (base-input)

Source: [`src/cpmm/swap.ts`](https://github.com/raydium-io/raydium-sdk-V2-demo/blob/master/src/cpmm/swap.ts)

```ts theme={null}
import { CurveCalculator, FeeOn } from "@raydium-io/raydium-sdk-v2";

const POOL_ID = "<POOL_ID>";   // base58 string

// 1. Load current pool state directly from an RPC (not from the API).
const { poolInfo, poolKeys, rpcData } = await raydium.cpmm.getPoolInfoFromRpc(POOL_ID);

const inputMint  = poolInfo.mintA.address;                // swap A → B
const amountIn   = new BN(100_000_000);                   // 0.1 SOL
const slippage   = 0.005;                                 // 0.5%

// 2. Quote locally. CurveCalculator mirrors on-chain math, including
//    Token-2022 transfer fees on either side. All eight arguments are required.
const baseIn = inputMint === poolInfo.mintA.address;
const swapResult = CurveCalculator.swapBaseInput(
  amountIn,
  baseIn ? rpcData.baseReserve : rpcData.quoteReserve,
  baseIn ? rpcData.quoteReserve : rpcData.baseReserve,
  rpcData.configInfo!.tradeFeeRate,
  rpcData.configInfo!.creatorFeeRate,
  rpcData.configInfo!.protocolFeeRate,
  rpcData.configInfo!.fundFeeRate,
  rpcData.feeOn === FeeOn.BothToken || rpcData.feeOn === FeeOn.OnlyTokenB,
);
// swapResult fields are inputAmount / outputAmount / tradeFee / protocolFee /
// fundFee / creatorFee / newInputVaultAmount / newOutputVaultAmount.
// There is no destinationAmountSwapped or sourceAmountSwapped.

// 3. Build and send. Passing `slippage` here is what applies the bound —
//    no manual minimum-out arithmetic is needed.
const { execute } = await raydium.cpmm.swap({
  poolInfo,
  poolKeys,
  inputAmount: amountIn,
  swapResult,
  slippage,
  baseIn,
  txVersion: TxVersion.V0,
});

const { txId } = await execute({ sendAndConfirm: true });
console.log("Swap tx:", txId);
```

Note: the SDK **always** re-fetches the pool state from an RPC inside `getPoolInfoFromRpc`. Do not quote off `api-v3.raydium.io` for a transaction you are about to sign — a quote that is one block stale can slip into `ExceededSlippage` at land time.

## Swap (base-output)

Source: [`src/cpmm/swapBaseOut.ts`](https://github.com/raydium-io/raydium-sdk-V2-demo/blob/master/src/cpmm/swapBaseOut.ts)

```ts theme={null}
const amountOutWanted = new BN(15_000_000);        // 15 USDC
const slippage        = 0.005;

const baseIn = false; // false → mintB is the input side
const swapResult = CurveCalculator.swapBaseOutput(
  amountOutWanted,
  baseIn ? rpcData.baseReserve : rpcData.quoteReserve,
  baseIn ? rpcData.quoteReserve : rpcData.baseReserve,
  rpcData.configInfo!.tradeFeeRate,
  rpcData.configInfo!.creatorFeeRate,
  rpcData.configInfo!.protocolFeeRate,
  rpcData.configInfo!.fundFeeRate,
  rpcData.feeOn === FeeOn.BothToken || rpcData.feeOn === FeeOn.OnlyTokenB,
);
// swapResult.inputAmount is the required input; there is no sourceAmountSwapped.

const { execute } = await raydium.cpmm.swap({
  poolInfo,
  poolKeys,
  inputAmount: new BN(0),   // unused when fixedOut — the amount comes from swapResult
  fixedOut:    true,
  swapResult,               // required, and it carries the target output amount
  baseIn,
  slippage,
  txVersion:   TxVersion.V0,
});

await execute({ sendAndConfirm: true });
```

## Deposit liquidity

Source: [`src/cpmm/deposit.ts`](https://github.com/raydium-io/raydium-sdk-V2-demo/blob/master/src/cpmm/deposit.ts)

```ts theme={null}
import { Percent } from "@raydium-io/raydium-sdk-v2";
import Decimal from "decimal.js";

// addLiquidity is driven by an INPUT amount, not an LP amount.
const uiInputAmount = "0.0001";
const inputAmount = new BN(
  new Decimal(uiInputAmount).mul(10 ** poolInfo.mintA.decimals).toFixed(0),
);
const slippage = new Percent(1, 100);   // a Percent, not a number

const { execute } = await raydium.cpmm.addLiquidity({
  poolInfo,
  poolKeys,
  inputAmount,
  baseIn: true,           // inputAmount is denominated in mintA
  slippage,
  txVersion: TxVersion.V0,
});

await execute({ sendAndConfirm: true });
```

The SDK derives the paired amount from the pool's current reserves, inflates each side by the slippage for the instruction's `maximum_*` arguments, and builds the ATA creations if necessary. `raydium.cpmm.computePairAmount({ ... })` returns the same numbers if you want them for a UI preview.

## Withdraw liquidity

Source: [`src/cpmm/withdraw.ts`](https://github.com/raydium-io/raydium-sdk-V2-demo/blob/master/src/cpmm/withdraw.ts)

```ts theme={null}
import { Percent } from "@raydium-io/raydium-sdk-v2";

const lpAmount = new BN(100_000);           // LP to burn
const slippage = new Percent(1, 100);       // a Percent, not a number

const { execute } = await raydium.cpmm.withdrawLiquidity({
  poolInfo,
  poolKeys,
  lpAmount,
  slippage,
  txVersion: TxVersion.V0,
});

await execute({ sendAndConfirm: true });
```

## Collect protocol/fund/creator fees

Source: [`src/cpmm/collectCreatorFee.ts`](https://github.com/raydium-io/raydium-sdk-V2-demo/blob/master/src/cpmm/collectCreatorFee.ts), [`src/cpmm/collectAllCreatorFee.ts`](https://github.com/raydium-io/raydium-sdk-V2-demo/blob/master/src/cpmm/collectAllCreatorFee.ts)

Protocol and fund collection remain authority-gated. Creator fees have two paths: the creator-signed `CollectCreatorFee`, and the additive `CollectCreatorFeePermissionless`, which any payer can invoke but which can transfer only to the creator's canonical ATAs. `0.2.64-alpha` ships module-level builders for both creator paths:

```ts theme={null}
// creator-signed
const { execute } = await raydium.cpmm.collectCreatorFees({
  poolInfo,
  poolKeys,
  txVersion: TxVersion.V0,
});

// permissionless — any payer; proceeds go to the creator's canonical ATAs
const { execute } = await raydium.cpmm.collectCreatorFeesPermissionless({
  poolInfo,
  poolKeys,
  txVersion: TxVersion.V0,
});

// several pools at once, creator-signed
await raydium.cpmm.collectMultiCreatorFees({ poolInfoList, txVersion: TxVersion.V0 });
```

> [!WARNING]
>
> **Both creator instructions changed their account lists in the 2026-09-19 program upgrade.** Each
> now takes a `creator_fee_share` PDA at `["creator_fee_share", creator, ammConfig]`, and the
> permissionless one takes `amm_config` as well — both **appended after `system_program`** rather
> than inserted, so the accounts that were already there keep their positions. A builder pinned to
> an SDK release that predates the upgrade emits the shorter list and the transaction is rejected
> for missing accounts. Check that the version you install carries the new accounts before using
> these helpers against the upgraded program, and refresh the IDL if you generate clients from it.
>
> Passing the PDA is mandatory even when it has never been created — derive it and pass it; the
> program falls back to `AmmConfig.creator_fee_share_rate` when the account is empty.

> [!NOTE]
>
> The two creator instructions have **different discriminators and account layouts** — the
> permissionless one replaces the creator signer with a separate `payer` and a non-signing
> `creator`. Use the matching builder rather than hand-swapping accounts on the other one.
>
> There is no protocol- or fund-fee builder in the SDK (`makeCollectProtocolFeeInstruction` and
> `makeCollectFundFeeInstruction` do not exist under any name) — those are admin paths, and so are
> `CreateCreatorFeeShare` / `CloseCreatorFeeShare`, which have no builder either. The low-level
> instruction builders that *do* exist are `collectCpFeeInstruction`,
> `makeCollectCreatorFeeInstruction` and `collectCreatorFeePermissionlessInInstruction`.

Off-chain you can read accrued fees directly from `PoolState`:

```ts theme={null}
const pool = await raydium.cpmm.getRpcPoolInfo(POOL_ID);   // base58 string
console.log("Accrued protocol fee mintA:", pool.protocolFeesMintA.toString());
console.log("Accrued protocol fee mintB:", pool.protocolFeesMintB.toString());
// The CpmmPoolInfoLayout fields are protocolFeesMintA/B, fundFeesMintA/B and
// creatorFeesMintA/B — there are no ...Token0/...Token1 fields.
//
// creatorFeesMintA/B is the *gross* accrual. The creator receives it minus the
// protocol share resolved at collection time; protocolFeesMintA/B receives that
// share, so it also grows on creator-fee collections, not only on swaps.
// See products/cpmm/fees#protocol-share-of-the-creator-fee.
```

## Rust CPI skeleton

If you want to invoke CPMM from your own Anchor program — for example, a vault that swaps on behalf of its depositors — the CPI context looks like this. Account ordering follows [`products/cpmm/instructions`](https://docs.raydium.io/products/cpmm/instructions).

```rust theme={null}
// Cargo.toml — `master` pins anchor-lang =1.0.2.
// raydium-cp-swap = { git = "https://github.com/raydium-io/raydium-cp-swap",
//                     branch = "master", features = ["cpi"] }
// anchor-lang      = "=1.0.2"   // must match what raydium-cp-swap pins
// anchor-spl       = "=1.0.2"
//
// The `cpi` feature is required — the `raydium_cp_swap::cpi` module only exists
// under it. The CLMM sample in products/clmm/code-demos pins the same
// =1.0.2 on its own `master`, so the two can share a program.

use anchor_lang::prelude::*;
use anchor_spl::token_interface::{TokenAccount, TokenInterface, Mint};
use raydium_cp_swap::cpi::accounts::Swap;
use raydium_cp_swap::cpi;
use raydium_cp_swap::program::RaydiumCpSwap;

#[derive(Accounts)]
pub struct ProxySwap<'info> {
    #[account(mut)]
    pub payer: Signer<'info>,

    /// CHECK: validated by the CPMM program
    pub authority:     UncheckedAccount<'info>,
    /// CHECK:
    pub amm_config:    UncheckedAccount<'info>,
    #[account(mut)]
    /// CHECK:
    pub pool_state:    UncheckedAccount<'info>,

    #[account(mut)]
    pub input_token_account:  InterfaceAccount<'info, TokenAccount>,
    #[account(mut)]
    pub output_token_account: InterfaceAccount<'info, TokenAccount>,

    #[account(mut)]
    pub input_vault:  InterfaceAccount<'info, TokenAccount>,
    #[account(mut)]
    pub output_vault: InterfaceAccount<'info, TokenAccount>,

    pub input_token_program:  Interface<'info, TokenInterface>,
    pub output_token_program: Interface<'info, TokenInterface>,

    pub input_token_mint:  InterfaceAccount<'info, Mint>,
    pub output_token_mint: InterfaceAccount<'info, Mint>,

    #[account(mut)]
    /// CHECK: ring buffer
    pub observation_state: UncheckedAccount<'info>,

    pub cpmm_program: Program<'info, RaydiumCpSwap>,
}

pub fn proxy_swap_base_input(
    ctx: Context<ProxySwap>,
    amount_in: u64,
    minimum_amount_out: u64,
) -> Result<()> {
    let cpi_accounts = Swap {
        payer:                ctx.accounts.payer.to_account_info(),
        authority:            ctx.accounts.authority.to_account_info(),
        amm_config:           ctx.accounts.amm_config.to_account_info(),
        pool_state:           ctx.accounts.pool_state.to_account_info(),
        input_token_account:  ctx.accounts.input_token_account.to_account_info(),
        output_token_account: ctx.accounts.output_token_account.to_account_info(),
        input_vault:          ctx.accounts.input_vault.to_account_info(),
        output_vault:         ctx.accounts.output_vault.to_account_info(),
        input_token_program:  ctx.accounts.input_token_program.to_account_info(),
        output_token_program: ctx.accounts.output_token_program.to_account_info(),
        input_token_mint:     ctx.accounts.input_token_mint.to_account_info(),
        output_token_mint:    ctx.accounts.output_token_mint.to_account_info(),
        observation_state:    ctx.accounts.observation_state.to_account_info(),
    };
    // Anchor 1.0 takes the program's Pubkey here, not its AccountInfo.
    let cpi_ctx = CpiContext::new(
        *ctx.accounts.cpmm_program.key,
        cpi_accounts,
    );
    cpi::swap_base_input(cpi_ctx, amount_in, minimum_amount_out)
}
```

If your CPI signs as a PDA (e.g., you manage a vault on behalf of depositors), swap `CpiContext::new` for `CpiContext::new_with_signer` and pass your seeds.

## Common pitfalls

A short checklist before opening a support ticket:

* **Sorted mints.** If your derived `poolState` PDA does not match the on-chain pool, you probably forgot to sort the mints.
* **Stale API quote.** Never pass a reserve value from `api-v3.raydium.io` into `CurveCalculator.swap`. Fetch from an RPC.
* **Wrong token program.** A Token-2022 mint's vault is owned by the Token-2022 program, not by SPL Token. Always use the pool's `token_0_program` / `token_1_program` fields.
* **Slippage under-denominated for transfer-fee mints.** If either side of the pool is a Token-2022 transfer-fee mint, your `minimum_amount_out` must be denominated in what the user actually receives, not in what the vault sends.
* **`NotApproved` on a swap.** Check `PoolState.status` — the admin may have paused swaps on that pool. See [`products/cpmm/instructions`](https://docs.raydium.io/products/cpmm/instructions) for the status bitmask.

## Where to go next

* [`sdk-api/typescript-sdk`](https://docs.raydium.io/sdk-api/typescript-sdk) — full SDK reference.
* [`sdk-api/rest-api`](https://docs.raydium.io/sdk-api/rest-api) — quote and pool-metadata endpoints.
* [`user-flows/create-cpmm-pool`](https://docs.raydium.io/user-flows/create-cpmm-pool) — the non-code walkthrough of the same flow.
* [`integration-guides/aggregator`](https://docs.raydium.io/integration-guides/aggregator) — if you are routing CPMM as part of a multi-hop path.

Sources:

* [Raydium SDK v2 — `@raydium-io/raydium-sdk-v2`](https://github.com/raydium-io/raydium-sdk-V2)
* [Raydium SDK v2 demos — `raydium-sdk-v2-demo`](https://github.com/raydium-io/raydium-sdk-V2-demo)
* [`raydium-io/raydium-cp-swap`](https://github.com/raydium-io/raydium-cp-swap)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.