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.
Voraussetzungen
npm install @raydium-io/raydium-sdk-v2 @solana/web3.js @solana/spl-token bn.js decimal.js
Jedes Beispiel auf dieser Seite entspricht einer Datei in raydium-sdk-V2-demo/src/cpmm; der GitHub-Link befindet sich neben jedem Abschnitt. Die Bootstrap-Initialisierung folgt der Datei config.ts.template des Demo-Repositories (Quelle):
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",
});
Die Raydium-Instanz ist die Fassade des SDK — jedes Beispiel unten verwendet sie. Sie lädt Token-Listen und Gebührenkonfigurationen lazy von api-v3.raydium.io ab; Sie können sie in Offline-Umgebungen mit eigenen Daten vorinitialisieren.
Erstellen eines CPMM-Pools
Quelle: 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. Gebührenkonfiguration auswählen. index=0 ist die 0,25%-Klasse.
const feeConfigs = await raydium.api.getCpmmConfigs();
const feeConfig = feeConfigs.find((c) => c.index === 0)!;
// 2. Mint-Metadaten abrufen, damit das SDK Token-2022-Erweiterungen handhaben kann.
const mintAInfo = await raydium.token.getTokenInfo(mintA);
const mintBInfo = await raydium.token.getTokenInfo(mintB);
// 3. Transaktion erstellen.
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 (angenommene 9 Dezimalstellen)
mintBAmount: new BN( 160_000_000), // 160 USDC (bei 160/SOL)
startTime: new BN(0), // sofort öffnen
feeConfig,
associatedOnly: false,
ownerInfo: { useSOLBalance: true },
txVersion: TxVersion.V0,
});
const { txId } = await execute({ sendAndConfirm: true });
console.log("Pool erstellt unter", extInfo.address.poolId.toBase58());
console.log("Tx:", txId);
Einige Dinge, die das SDK stillschweigend übernimmt:
- Mints in Token0/Token1-Reihenfolge sortieren, bevor das PDA abgeleitet wird.
- Die einmalige
create_pool_fee an poolFeeAccount zahlen.
- Die zugehörigen Token-Konten des Aufrufers erstellen, falls fehlend.
- Das richtige Token-Programm (SPL Token vs. Token-2022) pro Seite auswählen.
Nach der Bestätigung können Sie den Live-Pool-Status abrufen mit:
const { poolKeys, poolInfo, rpcData } = await raydium.cpmm.getPoolInfoFromRpc(
extInfo.address.poolId,
);
Quelle: src/cpmm/swap.ts
import { CurveCalculator } from "@raydium-io/raydium-sdk-v2";
const poolId = new PublicKey("<POOL_ID>");
// 1. Aktuellen Pool-Status direkt von einem RPC laden (nicht von der API).
const { poolInfo, poolKeys, rpcData } = await raydium.cpmm.getPoolInfoFromRpc(poolId);
const inputMint = new PublicKey(poolInfo.mintA.address); // A → B swappen
const amountIn = new BN(100_000_000); // 0,1 SOL
const slippage = 0.005; // 0,5%
// 2. Lokal quotieren. Der CurveCalculator des SDK spiegelt die On-Chain-Mathematik,
// einschließlich Token-2022-Transfergebühren auf beiden Seiten.
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. Erstellen und senden.
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);
Hinweis: Das SDK ruft den Pool-Status immer innerhalb von getPoolInfoFromRpc von einem RPC ab. Quotieren Sie nicht über api-v3.raydium.io für eine Transaktion, die Sie gerade signieren — ein Quote, der einen Block alt ist, kann bei der Landung in ExceededSlippage verfallen.
Swap (Basis-Output)
Quelle: src/cpmm/swapBaseOut.ts
const amountOutWanted = new BN(15_000_000); // 15 USDC
const slippage = 0.005;
const baseIn = false; // B ist Input, A ist Output? hängt von Ihrer Richtung ab
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 });
Liquidität einzahlen
Quelle: src/cpmm/deposit.ts
const lpAmount = new BN(100_000); // gewünschte LP-Mint-Menge
const slippage = 0.01;
const { execute } = await raydium.cpmm.addLiquidity({
poolInfo,
poolKeys,
lpAmount,
slippage,
baseIn: true, // von mintA-Seite quotieren
txVersion: TxVersion.V0,
});
await execute({ sendAndConfirm: true });
Das SDK konvertiert lpAmount in needed_token_0 und needed_token_1 anhand der aktuellen Pool-Reserven, bläst jeden um 1 + slippage für die maximum_*-Argumente der Anweisung auf und erstellt die ATA-Kreationen bei Bedarf.
Liquidität abheben
Quelle: src/cpmm/withdraw.ts
const lpAmount = new BN(100_000); // LP zum Verbrennen
const slippage = 0.01;
const { execute } = await raydium.cpmm.withdrawLiquidity({
poolInfo,
poolKeys,
lpAmount,
slippage,
txVersion: TxVersion.V0,
});
await execute({ sendAndConfirm: true });
Protokoll-/Fonds-/Creator-Gebühren einziehen
Quelle: src/cpmm/collectCreatorFee.ts, src/cpmm/collectAllCreatorFee.ts
Diese Anweisungen sind Admin- oder Creator-gated und werden typischerweise von einem Signer aufgerufen, der vom Raydium-Multisig oder dem Pool-Creator gehalten wird. Das SDK stellt sie als rohe Builder bereit:
import {
makeCollectProtocolFeeInstruction,
makeCollectFundFeeInstruction,
makeCollectCreatorFeeInstruction,
} from "@raydium-io/raydium-sdk-v2";
// Die PDAs und der Authority wurden bei der Pool-Erstellung gesetzt; siehe reference/program-addresses
// für die kanonischen Seeds. Das SDK stellt Hilfsfunktionen zur Verfügung, falls Sie diese bevorzugen.
Off-Chain können Sie aufgelaufene Gebühren direkt aus PoolState lesen:
const pool = await raydium.cpmm.getRpcPoolInfo(poolId);
console.log("Aufgelaufene Protokollgebühr Token0:", pool.protocolFeesToken0.toString());
console.log("Aufgelaufene Protokollgebühr Token1:", pool.protocolFeesToken1.toString());
Rust-CPI-Grundgerüst
Wenn Sie CPMM aus Ihrem eigenen Anchor-Programm aufrufen möchten — beispielsweise ein Vault, das im Namen seiner Depositors swapped — sieht der CPI-Kontext wie folgt aus. Die Kontenreihenfolge folgt 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: vom CPMM-Programm validiert
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)
}
Wenn Ihr CPI als PDA signiert (z. B. Sie verwalten einen Vault im Namen von Depositors), swappen Sie CpiContext::new gegen CpiContext::new_with_signer und übergeben Sie Ihre Seeds.
Häufige Fallstricke
Eine kurze Checkliste, bevor Sie ein Support-Ticket öffnen:
- Sortierte Mints. Wenn Ihr abgeleitetes
poolState-PDA nicht mit dem On-Chain-Pool übereinstimmt, haben Sie die Mints wahrscheinlich nicht sortiert.
- Veraltetes API-Quote. Übergeben Sie niemals einen Reservewert von
api-v3.raydium.io an CurveCalculator.swap. Rufen Sie den RPC auf.
- Falsches Token-Programm. Der Vault eines Token-2022-Mints wird von dem Token-2022-Programm besessen, nicht von SPL Token. Verwenden Sie immer die Felder
token_0_program / token_1_program des Pools.
- Slippage unter-denominiert für Transfer-Fee-Mints. Wenn eine Seite des Pools ein Token-2022-Transfer-Fee-Mint ist, muss Ihr
minimum_amount_out in dem ausgedrückt sein, was der Benutzer tatsächlich erhält, nicht in dem, was der Vault sendet.
NotApproved bei einem Swap. Überprüfen Sie PoolState.status — der Admin kann die Swaps auf diesem Pool pausiert haben. Siehe products/cpmm/instructions für die Status-Bitmaske.
Wo geht es als Nächstes hin?
Quellen: