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.
What this does. Loads a CPMM pool from RPC, quotes a swap with 0.5% slippage, builds the transaction, signs with your keypair, and submits it. End-to-end in ~30 lines.
Setup
Make sure you’ve read the Quick start prerequisites and have RPC_URL, KEYPAIR, and the deps installed.
The script
Save as swap.mjs:
// swap.mjs
import { Connection, Keypair, PublicKey } from "@solana/web3.js";
import { Raydium, TxVersion, CurveCalculator } from "@raydium-io/raydium-sdk-v2";
import BN from "bn.js";
import fs from "node:fs";
// ── Config from env ──────────────────────────────────────────────
const RPC_URL = process.env.RPC_URL ?? "https://api.mainnet-beta.solana.com";
const KEYPAIR = process.env.KEYPAIR ?? `${process.env.HOME}/.config/solana/id.json`;
const POOL_ID = process.env.POOL_ID; // required, base58
const INPUT_MINT = process.env.INPUT_MINT; // required, base58
const AMOUNT_RAW = process.env.AMOUNT_RAW; // required, integer in raw units (e.g. 1_000_000_000 for 1 SOL)
if (!POOL_ID || !INPUT_MINT || !AMOUNT_RAW) {
console.error("Set POOL_ID, INPUT_MINT, AMOUNT_RAW env vars.");
process.exit(1);
}
// ── Setup ────────────────────────────────────────────────────────
const connection = new Connection(RPC_URL, "confirmed");
const owner = Keypair.fromSecretKey(
new Uint8Array(JSON.parse(fs.readFileSync(KEYPAIR, "utf8"))),
);
const raydium = await Raydium.load({
owner,
connection,
cluster: "mainnet",
disableFeatureCheck: true,
blockhashCommitment: "finalized",
});
// ── Load pool ────────────────────────────────────────────────────
const { poolInfo, poolKeys, rpcData } =
await raydium.cpmm.getPoolInfoFromRpc(new PublicKey(POOL_ID));
const baseIn = poolInfo.mintA.address === INPUT_MINT;
// ── Quote ────────────────────────────────────────────────────────
const inputAmount = new BN(AMOUNT_RAW);
const swapResult = CurveCalculator.swap(
inputAmount,
baseIn ? rpcData.baseReserve : rpcData.quoteReserve,
baseIn ? rpcData.quoteReserve : rpcData.baseReserve,
rpcData.configInfo.tradeFeeRate,
);
console.log(`Quote: ${inputAmount.toString()} -> ${swapResult.destinationAmountSwapped.toString()}`);
console.log(`Fee: ${swapResult.tradeFee.toString()}`);
// ── Build and execute ────────────────────────────────────────────
const { execute } = await raydium.cpmm.swap({
poolInfo,
poolKeys,
inputAmount,
swapResult,
slippage: 0.005, // 0.5%
baseIn,
txVersion: TxVersion.V0,
computeBudgetConfig: {
units: 250_000,
microLamports: 50_000,
},
});
const { txId } = await execute({ sendAndConfirm: true });
console.log(`Swap landed: https://solscan.io/tx/${txId}`);
Run it
Pick any CPMM pool you have liquidity for. Example with the canonical SOL/USDC CPMM pool:
export POOL_ID="<paste a CPMM pool ID — find one in Raydium UI's Pools tab>"
export INPUT_MINT="So11111111111111111111111111111111111111112"
export AMOUNT_RAW="10000000" # 0.01 SOL
node swap.mjs
Expected output:
Quote: 10000000 -> 1640000
Fee: 25000
Swap landed: https://solscan.io/tx/4Z9...
What just happened
Raydium.load initialised the SDK — fetched the global config, set up your wallet context.
getPoolInfoFromRpc pulled the live pool state directly from RPC (not from the API cache). For high-value swaps you always want fresh state.
CurveCalculator.swap computed the constant-product output net of the pool’s fee. This is the same math the program runs on-chain, so you can compare quotes off- and on-chain.
raydium.cpmm.swap built the transaction with V0 format (address lookup tables enabled) and added an explicit compute-budget config. The compute-budget tip helps the tx land in busy windows.
execute({ sendAndConfirm: true }) signed, sent, and waited for confirmation.
Common errors
Pool not found — Wrong POOL_ID, or you’re pointed at the wrong cluster (mainnet pool ID against a devnet RPC, etc.).
Insufficient funds for transaction — Your wallet doesn’t have enough SOL for the swap input + fees + ATA rent.
Slippage tolerance exceeded — The pool’s price moved between quote and execution. Re-run; or raise the slippage parameter; or use the SDK’s computeAmountOut which always re-fetches reserves.
Token account not initialized — Output token’s ATA didn’t exist and the implicit-create instruction landed but failed for some reason; check your wallet’s SOL balance and try again.
Next