Skip to main content

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.

Version banner. All TypeScript demos target @raydium-io/raydium-sdk-v2@0.2.42-alpha against Solana mainnet-beta, verified 2026-04. The Rust CPI skeleton targets raydium-cp-swap on the master branch, Anchor 0.30.x. Program IDs are pulled via constants from reference/program-addresses.

Prerequisites

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; the GitHub link sits next to each section. Bootstrap follows the demo repo’s config.ts.template (source):
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. It lazily fetches token lists and fee configs from api-v3.raydium.io; you can seed it with your own data in offline environments.

Create a CPMM pool

Source: src/cpmm/createCpmmPool.ts
import { PublicKey } from "@solana/web3.js";
import BN from "bn.js";
import { getCpmmPdas, CREATE_CPMM_POOL_PROGRAM, CREATE_CPMM_POOL_FEE_ACC }
  from "@raydium-io/raydium-sdk-v2";

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.
After confirmation you can fetch the live pool state with:
const { poolKeys, poolInfo, rpcData } = await raydium.cpmm.getPoolInfoFromRpc(
  extInfo.address.poolId,
);

Swap (base-input)

Source: src/cpmm/swap.ts
import { CurveCalculator } from "@raydium-io/raydium-sdk-v2";

const poolId = new PublicKey("<POOL_ID>");

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

const inputMint  = new PublicKey(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. The SDK's CurveCalculator mirrors on-chain math,
//    including Token-2022 transfer fees on either side.
const baseIn = inputMint.equals(new PublicKey(poolInfo.mintA.address));
const swapResult = CurveCalculator.swap(
  amountIn,
  baseIn ? rpcData.baseReserve : rpcData.quoteReserve,
  baseIn ? rpcData.quoteReserve : rpcData.baseReserve,
  rpcData.configInfo!.tradeFeeRate,
);
const minimumAmountOut =
  swapResult.destinationAmountSwapped.muln(1 - slippage * 100).divn(100);

// 3. Build and send.
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
const amountOutWanted = new BN(15_000_000);        // 15 USDC
const slippage        = 0.005;

const baseIn = false; // B is input, A is output? depends on your direction
const swapResult = CurveCalculator.swapBaseOutput(
  amountOutWanted,
  rpcData.baseReserve,
  rpcData.quoteReserve,
  rpcData.configInfo!.tradeFeeRate,
);
const maxAmountIn = swapResult.sourceAmountSwapped.muln(1 + slippage * 100).divn(100);

const { execute } = await raydium.cpmm.swap({
  poolInfo,
  poolKeys,
  inputAmount: maxAmountIn,
  fixedOut:    true,
  amountOut:   amountOutWanted,
  baseIn,
  slippage,
  txVersion:   TxVersion.V0,
});

await execute({ sendAndConfirm: true });

Deposit liquidity

Source: src/cpmm/deposit.ts
const lpAmount = new BN(100_000);           // desired LP mint amount
const slippage = 0.01;

const { execute } = await raydium.cpmm.addLiquidity({
  poolInfo,
  poolKeys,
  lpAmount,
  slippage,
  baseIn: true,           // quote from mintA side
  txVersion: TxVersion.V0,
});

await execute({ sendAndConfirm: true });
The SDK converts lpAmount into needed_token_0 and needed_token_1 using the pool’s current reserves, inflates each by 1 + slippage for the instruction’s maximum_* arguments, and builds the ATA creations if necessary.

Withdraw liquidity

Source: src/cpmm/withdraw.ts
const lpAmount = new BN(100_000);           // LP to burn
const slippage = 0.01;

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, src/cpmm/collectAllCreatorFee.ts These instructions are admin- or creator-gated and typically invoked from a signer held by the Raydium multisig or the pool creator. The SDK surfaces them as raw builders:
import {
  makeCollectProtocolFeeInstruction,
  makeCollectFundFeeInstruction,
  makeCollectCreatorFeeInstruction,
} from "@raydium-io/raydium-sdk-v2";

// The PDAs and authority were set at pool creation; see reference/program-addresses
// for the canonical seeds. The SDK exposes helpers if you prefer.
Off-chain you can read accrued fees directly from PoolState:
const pool = await raydium.cpmm.getRpcPoolInfo(poolId);
console.log("Accrued protocol fee token0:", pool.protocolFeesToken0.toString());
console.log("Accrued protocol fee token1:", pool.protocolFeesToken1.toString());

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.
// Cargo.toml
// raydium-cp-swap = { git = "https://github.com/raydium-io/raydium-cp-swap" }
// anchor-spl       = "0.30"

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(),
    };
    let cpi_ctx = CpiContext::new(
        ctx.accounts.cpmm_program.to_account_info(),
        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 for the status bitmask.

Where to go next

Sources: