# Bonding curves Source: https://docs.raydium.io/algorithms/bonding-curves The mathematics behind token-issuance curves — quadratic, linear, and virtual-reserves CPMM variants — derivations for cost / proceeds / spot price, and the graduation-threshold math used by LaunchLab. > [!NOTE] > > This page derives the general bonding-curve mathematics. For LaunchLab's specific implementation, see [`products/launchlab/bonding-curve`](/products/launchlab/bonding-curve). The derivations are given in continuous form; the on-chain code implements the discrete analog in fixed-point arithmetic. ## What a bonding curve is A **bonding curve** is a deterministic price function `p(s)` that relates the price of a token to the amount currently in circulation (`s` for "supply sold"). Buyers purchase by sending collateral to the contract; the contract emits new token units at the marginal price dictated by the curve. Sellers return token units and receive the integrated refund. Two key properties compared to a CPMM pool: * **No counterparty needed.** The issuing contract is the market maker; liquidity exists by fiat. * **Monotonic price.** Price rises with every net-buy and falls with every net-sell. Bonding curves are the standard launch mechanism when the issuing entity does not want to pre-seed an AMM pool with collateral. ## Generic pricing formulas For any continuous price function `p(s)`: **Spot price** at supply `s`: ``` p(s) = the curve formula ``` **Cost to buy** supply from `s_0` to `s_1` (with `s_1 > s_0`): ``` cost(s_0, s_1) = ∫_{s_0}^{s_1} p(s) ds = P(s_1) − P(s_0) ``` where `P(s) = ∫ p(s) ds` is the curve's antiderivative. Geometrically, `cost` is the area under `p` between `s_0` and `s_1`. **Proceeds from selling** supply back from `s_1` to `s_0`: ``` proceeds(s_1, s_0) = cost(s_0, s_1) ``` (Symmetry: buying and selling across the same interval exchanges the same collateral — modulo fees.) **Average price** for the buy: ``` avg = cost(s_0, s_1) / (s_1 − s_0) ``` ## Common curve families ### Linear ``` p(s) = a + b · s ``` ``` P(s) = a·s + (b/2)·s² cost(s_0, s_1) = a·(s_1 − s_0) + (b/2)·(s_1² − s_0²) ``` Price rises proportionally with supply. Used for "steady" launches where the issuer wants a predictable, moderate markup over the lifetime. ### Quadratic ``` p(s) = k · s² // or k · (s / S_max)² for a normalized form ``` ``` // Antiderivative of the normalized form p(s) = k · (s / S_max)² P(s) = (k / (3 · S_max²)) · s³ cost(s_0, s_1) = (k / (3 · S_max²)) · (s_1³ − s_0³) ``` (For the un-normalized `p(s) = k · s²`, drop the `S_max²`: `P(s) = (k/3) · s³`. Pick one convention and stay in it — the worked example below uses the normalized form throughout.) Price rises quadratically. Early buyers get a near-zero price (flat starting region); late buyers pay a steeper premium. > [!NOTE] > > **LaunchLab does not implement a quadratic *price* curve.** Its three curve types are > `0 = ConstantProduct` (the default), `1 = FixedPrice` and `2 = LinearPrice`. The closest shape to > this section is `LinearPrice`, whose price is `p(s) = a·s` and whose *cost* is therefore > quadratic. This section is kept as the general treatment of a polynomial curve. ### Virtual-reserves CPMM (Pump-style) The curve is a standard CPMM with a pretend initial quote reserve `V_q`: ``` effective_y = V_q + collateral_received effective_x = S_max − s (effective_x) · (effective_y) = V_q · S_max // invariant ``` Spot price: ``` p(s) = effective_y / effective_x = V_q · S_max / (S_max − s)² · ... (derivable via implicit differentiation) ``` Cost to move from `s_0` to `s_1`: ``` cost(s_0, s_1) = V_q · S_max / (S_max − s_1) − V_q · S_max / (S_max − s_0) = V_q · (s_1 − s_0) · S_max / ((S_max − s_0) · (S_max − s_1)) ``` This variant has the elegant property that at graduation (where `s = S_graduate`), the marginal price equals the opening price of the downstream CPMM pool seeded with reserves `(S_max − S_graduate, V_q + cost(0, S_graduate))`. Handoff is seamless. LaunchLab exposes this as `curve_type = 0` (`ConstantProduct`) — the default, and the only type with live configs today. ## Discrete implementation On-chain, `s` and `cost` are both integers (smallest-denomination units). The continuous integral `cost(s_0, s_1)` is computed directly from the closed form whenever one exists (linear, quadratic). For curves without a closed-form inverse (quadratic, given `cost`, find `s_1`), Newton iteration is used: ``` # Solve quadratic: (k/3)·s_1³ = (k/3)·s_0³ + cost # Initialize with s_guess ≈ cbrt(3·cost/k + s_0³) for i in 0..MAX_ITER: f = (k/3)·s_guess³ − (k/3)·s_0³ − cost f' = k·s_guess² step = f / f' s_guess -= step if |step| < precision_floor: break ``` > [!NOTE] > > This is the general numerical recipe, not LaunchLab's implementation. LaunchLab has **no Newton > solver and no `NotConverged` error** — none of its three curves needs one. The constant-product > curve inverts in closed form, the fixed-price curve is a division, and the linear-price curve's > quadratic cost inverts with a square root. Even the quadratic-price case above has the exact > closed form `s₁ = ∛(s₀³ + 3·cost/k)`, which is what the snippet uses as its initializer. ## Fee integration Fees are applied on top of the curve cost, not inside it. On buy: ``` cost_curve = cost(base_sold, base_sold + base_out) fee = ceil(cost_curve · buy_numerator / buy_denominator) quote_in = cost_curve + fee ``` On sell: ``` proceeds_curve = cost(base_sold − base_in, base_sold) fee = ceil(proceeds_curve · sell_numerator / sell_denominator) quote_out = proceeds_curve − fee ``` The LP portion of the fee is retained in `quote_vault` and effectively makes the curve stiffer for later buyers — the reserve grows without issuing more supply. The protocol and creator portions are tracked in separate counters for later sweep. ## Graduation threshold A curve "graduates" when it has received enough collateral to seed an external AMM pool at a price matching the current curve price. For a quadratic curve with parameters `(k, S_max, S_graduate)`: ``` quote_to_graduate = cost(0, S_graduate) · (1 + buy_fee_rate) = (k / 3) · S_graduate³ · (1 + f_buy) ``` Once `quote_vault ≥ quote_to_graduate`, the `Graduate` instruction creates a CPMM pool with: ``` cpmm_base_reserve = S_max − S_graduate // unsold curve supply cpmm_quote_reserve = quote_vault − accrued_fee_counters cpmm_initial_price = cpmm_quote_reserve / cpmm_base_reserve ``` For the virtual-reserves curve, by construction: ``` cpmm_initial_price == p(S_graduate) // exact equality ``` For the quadratic this equality does **not** hold: the integrated average price sits strictly above the marginal price, so the CPMM opens above `p(S_graduate)` by a fixed factor (see the worked example). Only the constant-product / virtual-reserves curve — the one LaunchLab actually runs — is price-continuous at handoff. ## Impermanence vs a CPMM pool A pure bonding-curve launch has **no impermanence** in the Uniswap sense: there is no "other side" of the market to rebalance against. The curve issues supply on demand, and the only "LP" is the contract itself. Post-graduation, the resulting CPMM pool behaves like any other CPMM pool — if the LP was not burned, they are subject to the usual impermanent-loss dynamics. This is why the **burn** post-graduation policy is dominant in public launches: it keeps the pool permanent and removes any LP-withdrawal-driven price shocks. ## Worked example Curve: quadratic, `k = 40`, `S_max = 1e9`, `S_graduate = 0.8 · S_max = 8e8`. Buy fee 1%. ### Price at `s = 5e8` ``` p(5e8) = 40 · (5e8 / 1e9)² = 40 · 0.25 = 10 ``` 10 units of quote per base unit. ### Cost of the first buy of 1e6 base ``` cost(0, 1e6) = (40 / (3 · (1e9)²)) · (1e6)³ = (40 / 3e18) · 1e18 ≈ 13.3 (smallest quote units) ``` With 1% fee: ``` quote_in = 13.3 · 1.01 ≈ 13.5 ``` ### Graduation threshold ``` cost(0, 8e8) = (40 / 3e18) · (8e8)³ = (40 / 3e18) · 5.12e26 ≈ 6.827e9 (≈ 6,827 units of a 6-decimal quote mint) quote_to_graduate ≈ 6.827e9 · 1.01 ≈ 6.895e9 ``` ### Price at graduation ``` p(8e8) = 40 · 0.64 = 25.6 ``` ### Post-graduation CPMM reserves ``` cpmm_base = 1e9 − 8e8 = 2e8 cpmm_quote ≈ 6.827e9 (less fee-counter deductions) cpmm_price ≈ 6.827e9 / 2e8 = 34.14 per base ``` > [!WARNING] > > That is **not** `p(8e8) = 25.6` — it is exactly `4/3` of it. For any quadratic-price curve the > integrated average is `p(s)/3 · s / s`, so `cost(0,s)/s = p(s)/3 · ...` works out to `4/3 · p(s)` > once the remaining supply is `1 − 0.8`. The quadratic handoff is therefore **not > price-continuous**. Only the constant-product / virtual-reserves curve has the exact-equality > property described above; a quadratic launch shows a step at graduation. ## Pointers * [`products/launchlab/bonding-curve`](/products/launchlab/bonding-curve) — the on-chain LaunchLab implementation of these formulas. * [`products/launchlab/instructions`](/products/launchlab/instructions) — `Buy`, `Sell`, `Graduate` account-level specs. * [`algorithms/constant-product`](/algorithms/constant-product) — what the post-graduation CPMM does with the reserves. Sources: * Raydium LaunchLab program source (quadratic + virtual-reserves curve implementations). * Bancor white paper (linear bonding curves, historical). * Pump.fun public post-mortems (virtual-reserves variant). # Estimating CLMM APR Source: https://docs.raydium.io/algorithms/clmm-apr How Raydium computes the APR numbers shown on CLMM pools, how to estimate your own APR for a hypothetical range before opening a position, and the edge cases that make trailing APR misleading. > [!NOTE] > > The **APR shown on the Raydium UI** for a CLMM pool is the realised fee APR of the **in-range liquidity** over the past 24 hours, projected to a year. It is not the APR *your position* would have earned — that depends on your range, your time-in-range, and your share of the liquidity that was active during the trading window. ## The headline formula For a CLMM pool, the daily fee APR shown on Raydium is computed as: ``` apr_24h = (fees_24h / tvl_in_range_24h) · 365 ``` Where: * `fees_24h` is the sum of LP-side swap fees accrued in the last 24 hours (in USD). * `tvl_in_range_24h` is the time-weighted average USD value of liquidity that was **in range** during the window. The denominator is what distinguishes CLMM APR from CPMM APR. CPMM uses total pool TVL because every dollar is always contributing. CLMM uses only the in-range subset because out-of-range dollars earn nothing. ## What your APR will actually be The headline APR is a statistic of the pool, not of your position. Your APR depends on four multipliers: ``` your_APR = headline_APR · (your_in_range_fraction / pool_in_range_fraction) # concentration bonus · time_in_range # range discipline · (1 − transfer_fee_haircut) # token-2022 tax · compounding_factor # if you auto-restake ``` * **Concentration bonus.** If your range is tighter than the pool-wide average, every active tick has more of your liquidity per dollar than the average LP's. Tighter = bigger bonus (and proportionally bigger IL amplification). * **Time in range.** If you are in range only 40% of the time, multiply by 0.40. * **Transfer-fee haircut.** For Token-2022 mints with transfer fees, every fee collection hops through a transfer that itself bleeds basis points. * **Compounding.** If you `collectFee` and redeploy into the same range weekly, the effective APR is about `(1 + daily_APR)^365 − 1`. Without compounding it is linear. ### Worked example Suppose a SOL/USDC CLMM pool has: * 24h volume: \$120M * Fee tier: 0.05% (LP share **84%** of fees — every mainnet CLMM `AmmConfig` carries `protocol_fee_rate = 12%` plus `fund_fee_rate = 4%`) * Total TVL: \$40M * In-range TVL: \$18M (45% of pool is currently in range) ``` fees_24h = 120M · 0.0005 · 0.84 = $50,400 apr_24h = (50,400 / 18,000,000) · 365 = 102% ``` The Raydium UI shows **102% APR** for the pool. (This example uses a deep, high-volume pool to keep the numbers concrete; typical CLMM pools display anywhere from 10% to 50% APR, with low-volume pools well under 10%.) Now you are considering opening a position: * Your range: tight enough that you have 2× the average concentration. * Expected time-in-range: 70% (you will check weekly). * No Token-2022 fees. No auto-compounding. ``` your_APR ≈ 102% · 2 · 0.70 = 143% ``` That is an estimate, not a guarantee. Realised volume can halve or double in a week. ## Why trailing APR is a lagging signal CLMM APR moves **fast** relative to CPMM APR because the in-range TVL denominator moves fast: * A large price move pushes chunks of positions out of range, shrinking the denominator. Suddenly your remaining in-range TVL looks "higher APR" — but only because competitors left, and typically volume falls too. * A pool reaching a new ATH can temporarily show 500–1000% APR for an hour as most positions were calibrated for lower prices and only a few aggressive LPs remain in range. * Once the market settles, LPs rebalance and APR mean-reverts. Rules of thumb: * **Ignore sub-24h APR.** Too much noise. * **Prefer 7d and 30d windows.** Raydium exposes both via [`GET /pools/info/ids`](/sdk-api/rest-api) — fields `week.apr` and `month.apr`. * **Backtest your specific range** on historical volume and price data before committing meaningful capital. ## How the math works (single-tick step) Inside a single tick the CLMM behaves like a CPMM on the amount of liquidity `L` active in that tick. Fees accrue in `fee_growth_global_X` and `fee_growth_global_Y` per unit of liquidity. For a position with liquidity `Lₚ` that spans tick ranges `[i_lo, i_hi]`: ``` fees_earned_X = Lₚ · (fee_growth_inside_X(i_lo, i_hi, now) − fee_growth_inside_X(i_lo, i_hi, t_open)) fees_earned_Y = Lₚ · (fee_growth_inside_Y(i_lo, i_hi, now) − fee_growth_inside_Y(i_lo, i_hi, t_open)) ``` Where `fee_growth_inside` subtracts fee growth below `i_lo` and above `i_hi` from the global accumulator. Details in [`algorithms/clmm-math`](/algorithms/clmm-math). To compute *expected* fees over a future period for a prospective range, estimate: ``` expected_fees_per_day = Σ_ticks_in_range (volume_at_tick · fee_rate · your_share_at_tick) ``` Raydium's SDK exposes `PoolUtils.estimateAprsForPriceRangeMultiplier` and `PoolUtils.estimateAprsForPriceRangeDelta` for this estimation. ## SDK helper ```ts theme={null} import { Raydium, PoolUtils } from "@raydium-io/raydium-sdk-v2"; const raydium = await Raydium.load({ owner, connection }); // getPoolInfoFromRpc takes a positional base58 string on the CLMM module. const pool = await raydium.clmm.getPoolInfoFromRpc(POOL_ID); // Synchronous, and it reads the volume/fee stats off poolInfo[aprType]. const apr = PoolUtils.estimateAprsForPriceRangeMultiplier({ poolInfo: pool.poolInfo, aprType: "day", // "day" | "week" | "month" positionTickLowerIndex: -100, // your intended range positionTickUpperIndex: 100, }); console.log(`Expected APR: ${apr.feeApr}% fee-only; rewards: ${apr.rewardsApr.join(", ")}`); ``` The helper returns `{ feeApr, rewardsApr[], apr }` — `rewardsApr` is per reward stream and `apr` is the total. There is no `raydium.clmm.estimatedApr` method. `estimateAprsForPriceRangeDelta` is the same computation parameterized by a ± delta around spot instead of explicit ticks. ## Where farm APR fits in Raydium CLMM pools can have Farm v6 emissions layered on top. Farm rewards are paid in a **reward mint** (often RAY or a partner token) independent of swap fees. The Raydium UI typically shows: ``` Total APR = Fee APR + Farm APR [in $X, Y, Z reward mints] ``` Farm APR is computed similarly but using the reward emission schedule and the current price of the reward mint in USD. Unlike fee APR it is not volatility-dependent — it is a fixed schedule. See [`products/farm-staking/overview`](/products/farm-staking/overview) for farm emission math. ## Common mistakes * **"APR is compounded automatically."** No. Fees must be claimed — via a zero-liquidity `DecreaseLiquidity`, since CLMM has no standalone collect instruction — then manually redeployed. Raydium does not auto-compound CLMM fees. * **"My APR = headline APR."** Only if your concentration is average, your time-in-range is 100%, and you compound at the same cadence. All three are usually false. * **"Higher fee tier = higher APR."** Only if volume survives the higher fee. At 1% a pair may quote 50% APR but do 1/10 the volume; net less than 0.25% at 120% × 0.1 = 12%. * **"Out-of-range positions have zero risk."** They have zero fee income but full IL on the existing token composition — the position is now "100% of whichever side". ## Pointers * [`algorithms/clmm-math`](/algorithms/clmm-math) — full derivation of the fee-growth accumulator. * [`algorithms/impermanent-loss`](/algorithms/impermanent-loss) — the loss side of the LP equation. * [`user-flows/choosing-a-pool-type`](/user-flows/choosing-a-pool-type) — decision framework that uses this APR estimate. * [`sdk-api/rest-api`](/sdk-api/rest-api) — live volume / APR endpoints. Sources: * Raydium SDK v2 `PoolUtils.estimateAprsForPriceRangeMultiplier` / `estimateAprsForPriceRangeDelta` implementations. * Raydium UI pool page (live APR fields). * Uniswap V3 fee-growth derivation. # Concentrated-liquidity math Source: https://docs.raydium.io/algorithms/clmm-math sqrt-price representation, liquidity-to-amount formulas, single-tick and multi-tick swap steps, fee-growth accounting — the math behind Raydium CLMM. > [!NOTE] > > This page consolidates the derivations behind CLMM. For the on-chain implementation, see [`products/clmm/math`](/products/clmm/math) (which cites this page) and [`products/clmm/ticks-and-positions`](/products/clmm/ticks-and-positions) (which motivates the tick lattice). ## Why sqrt-price, not price Uniswap-v3-family CLMMs represent price as its square root, stored in a fixed-point `Q64.64`: ``` sqrt_price_x64 = floor(sqrt(price) · 2^64) ``` Three reasons: 1. **Linear liquidity math.** The amount of token0 or token1 in a price range turns out to be a linear function of `sqrt_price`, not of `price`. Storing `sqrt_price` lets the swap step evaluate those linear formulas without computing a square root. 2. **Overflow control.** `sqrt_price · L` fits in `u256` for all reasonable parameters; `price · L` can overflow much sooner. 3. **Tick math is uniform.** Because ticks are defined as `1.0001^i`, `sqrt(price) = (√1.0001)^i ≈ 1.00005^i` is also an exact geometric ladder. (`√1.0001 = 1.00004999875…`, so treating it as exactly `1.00005` drifts by up to \~0.6% at `MAX_TICK`.) Each tick-cross translates to a small multiplication in `sqrt_price_x64` space. Price and sqrt-price are one-to-one; the conversion is `price = (sqrt_price_x64 / 2^64)^2`. ## Tick lattice Prices are discretized onto a grid: ``` price(tick_i) = 1.0001^i ``` `tick_i` is an `i32`. The live range is `[MIN_TICK, MAX_TICK] = [−443636, 443636]`, giving a price range of roughly `[2^−64, 2^64]` — about `5.4e-20` to `1.8e19`. Each pool's `tick_spacing` is set by its fee tier: smaller spacings for tight pairs (e.g. stablecoin 0.01% tier uses spacing 1), larger spacings for volatile pairs (0.25% tier uses 60, 1% tier uses 120). Positions must have `tick_lower` and `tick_upper` aligned to `tick_spacing`. A pool's active ticks (those with liquidity starting or ending there) are the only ticks the swap step cares about. ## Liquidity-to-amount For a position with liquidity `L` and price range `[sqrt_lo, sqrt_hi]` (all `sqrt_price` values): | Pool state | Amount of token0 | Amount of token1 | | - | - | - | | Price above range (`sqrt_p ≥ sqrt_hi`) | 0 | `L · (sqrt_hi − sqrt_lo)` | | Price in range | `L · (sqrt_hi − sqrt_p) / (sqrt_p · sqrt_hi)` | `L · (sqrt_p − sqrt_lo)` | | Price below range (`sqrt_p ≤ sqrt_lo`) | `L · (sqrt_hi − sqrt_lo) / (sqrt_lo · sqrt_hi)` | 0 | Derivation: differentiate the CPMM invariant locally. Inside any single tick range, the position behaves as a CPMM with virtual reserves `(x_v, y_v)` chosen so the pool's current `(sqrt_p, L)` is consistent with `L = sqrt(x_v · y_v)`. Integrating from `sqrt_p` to the range boundary yields the amounts above. **Inverse formulas** (used when minting a position for a given `amount0` or `amount1`): ``` L_from_amount0(amount0, sqrt_lo, sqrt_hi, sqrt_p) = amount0 · sqrt_p · sqrt_hi / (sqrt_hi − sqrt_p) L_from_amount1(amount1, sqrt_lo, sqrt_hi, sqrt_p) = amount1 / (sqrt_p − sqrt_lo) // For a symmetric deposit into an in-range position, take the min. L = min(L_from_amount0, L_from_amount1) ``` ## Single-tick swap step Within a single tick range the pool behaves like a CPMM. Given current `sqrt_p` and target `sqrt_target`: ``` Δamount0_step = L · (sqrt_target − sqrt_p) / (sqrt_p · sqrt_target) // if swapping for token0 Δamount1_step = L · (sqrt_target − sqrt_p) // if swapping for token1 ``` ### Exact-input step Given `Δin_remaining`: ``` // Candidate new sqrt_p if we filled to the tick boundary: sqrt_after_full = sqrt_target amount_to_full = Δamount_in_to_reach(sqrt_p → sqrt_target) if Δin_remaining ≥ amount_to_full: // consume the rest of the bucket sqrt_p' = sqrt_target Δin_consumed = amount_to_full Δout = amount_out_at_boundary else: // we don't cross; solve for the terminal sqrt_p sqrt_p' = L · sqrt_p / (L + Δin_remaining · sqrt_p) // for 0→1 swaps Δin_consumed = Δin_remaining Δout = L · (sqrt_p − sqrt_p') // proportional to Δsqrt ``` The `0→1` swap lowers `sqrt_p` (price declines as we sell token0 in). A `1→0` swap raises it. The formulas are symmetric with `sqrt_p` and `sqrt_target` swapped. ### Exact-output step Same structure, solving for `Δin` instead. ## Multi-tick swap loop A swap iterates over ticks until the input is exhausted or the price limit is hit: ``` while Δin_remaining > 0 and sqrt_p != sqrt_price_limit: next_tick = find_next_initialized_tick(pool.tick_current, direction) sqrt_target = min(next_tick.sqrt_price, sqrt_price_limit) // directionally (Δin, Δout, sqrt_p') = single_step(sqrt_p, sqrt_target, L, Δin_remaining) Δin_remaining -= Δin accumulated_out += Δout if sqrt_p' == next_tick.sqrt_price: // crossing the tick L += next_tick.liquidity_net * direction_sign flip_fee_growth_outside(next_tick) match_limit_orders_at_tick(next_tick, ...) // see products/clmm/math pool.tick_current = next_tick.tick_index sqrt_p = sqrt_p' ``` Each `single_step` uses the pool's current `L`. `L` changes **only** when crossing an initialized tick. Liquidity between ticks is constant, which is what makes the step math closed-form. `liquidity_net` at a tick is the signed sum of position liquidities that start at that tick minus those that end there. Crossing upward adds `liquidity_net`; crossing downward subtracts it. When the pool has limit orders open at a tick, the cross-tick step also opportunistically consumes part of the swap input to fill those orders (FIFO across cohorts). The matching algorithm and the dynamic-fee surcharge that may apply on top of the base step are documented in [`products/clmm/math`](/products/clmm/math); they don't change the closed-form single-step formulas above. ## Fee-growth accumulators CLMM tracks fees per unit of active liquidity, per side, globally and per tick: ``` fee_growth_global_0_x64 // Q64.64, monotone fee_growth_global_1_x64 tick.fee_growth_outside_0_x64 // "fees accrued while this tick was outside the active range" tick.fee_growth_outside_1_x64 ``` On each `single_step`: ``` step_lp_fee = (Δin · fee_rate) · (1 − protocol_fraction − fund_fraction) fee_growth_global += step_lp_fee · 2^64 / L // only for the input side ``` (The other side's `fee_growth_global` does not move on this step, since no token on that side was paid as input.) When crossing a tick, the program **flips** `fee_growth_outside`: ``` tick.fee_growth_outside_0_x64 = fee_growth_global_0_x64 − tick.fee_growth_outside_0_x64 tick.fee_growth_outside_1_x64 = fee_growth_global_1_x64 − tick.fee_growth_outside_1_x64 ``` "Outside" is relative to `tick_current`. When `tick_current` is above the tick, outside means "below". When `tick_current` is below, outside means "above". The flip swaps the interpretation. ### `fee_growth_inside` for a position Given a position `[tick_lower, tick_upper]` and the current `tick_current`: ``` if tick_current >= tick_upper: inside = tick_upper.fee_growth_outside − tick_lower.fee_growth_outside else if tick_current < tick_lower: inside = tick_lower.fee_growth_outside − tick_upper.fee_growth_outside else: // position is in range inside = fee_growth_global − tick_lower.fee_growth_outside − tick_upper.fee_growth_outside ``` A position's uncollected fees for token side `s` are: ``` tokens_owed_s += L · (fee_growth_inside_s − fee_growth_inside_last_s) / 2^64 fee_growth_inside_last_s = fee_growth_inside_s ``` This update runs on every interaction with the position (`IncreaseLiquidity`, `DecreaseLiquidity`, `CollectFees`). ## Worked example — crossing one tick Pool (simplified): * `sqrt_p_x64 = 2^64 · 1.0 = 2^64` (price = 1.0) * `L = 1_000_000` * `tick_current = 0` * Next initialized tick below: `tick = −60`, `sqrt_price = 1.0001^(−30) ≈ 0.99700`, `liquidity_net = −400_000` (this tick ends a position, so a downward cross removes 400k) * Fee rate: 0.25% Swap: `Δin = 10_000` token0, direction = 0→1. **Step 1 — up to `sqrt_target = 0.99700 · 2^64`**: ``` amount_in_to_target = L · (1/sqrt_target − 1/sqrt_p) = 1_000_000 · (1/0.99700 − 1/1.0) ≈ 1_000_000 · 0.003009 ≈ 3_009 ``` 3,009 \< 10,000, so we fill this step completely: ``` Δin_step = 3_009 / (1 − 0.0025) = 3_017 // gross of fee Δout_step = L · (sqrt_p − sqrt_target) ≈ 1_000_000 · 0.00299 ≈ 2_990 sqrt_p = 0.99700 · 2^64 tick_current = −60 L = 1_000_000 + (−400_000) = 600_000 // crossed the tick fee_growth_outside at tick −60 is flipped Δin_remaining = 10_000 − 3_017 = 6_983 ``` **Step 2 — with new `L = 600_000`**: The next initialized tick (say `tick = −120`) is at `sqrt = 0.99402`. Recompute `amount_in_to_target`: ``` amount_in_to_target = 600_000 · (1/0.99402 − 1/0.99700) ≈ 600_000 · 0.003010 ≈ 1_806 ``` Still less than `Δin_remaining`. Cross again. Continue until `Δin_remaining` reaches zero. The full sequence of `Δout` accumulates to the final swap output. ## Initialization and overflow guards * `MIN_SQRT_PRICE_X64` and `MAX_SQRT_PRICE_X64` correspond to `tick = ±443636`. Any swap that would push `sqrt_p` outside this range reverts. * The user's `sqrt_price_limit` parameter must lie in the same interval; the program checks. * Products of `L · Δsqrt` are computed in `u256` then shifted back to `u128` to avoid overflow. ## Differences vs Uniswap v3 * **Oracle.** Raydium's `ObservationState` ring buffer stores only `(block_timestamp: u32, tick_cumulative: i64)` per slot plus `[u64; 4]` of reserved padding — there is **no** `seconds_per_liquidity_cumulative` field, so Uniswap's liquidity-weighted derivations are not available on-chain. * **Token-2022.** Raydium CLMM supports Token-2022 mints; the transfer-fee variant requires additional pre/post-swap amount adjustments. See [`algorithms/token-2022-transfer-fees`](/algorithms/token-2022-transfer-fees). * **Tick bitmap.** Raydium packs the initialized-tick bitmap into `[u64; 16]` per pool for fast `find_next_initialized_tick`; Uniswap uses a per-word on-chain mapping. The tradeoff is rent vs lookup cost. * **Reward slots.** Raydium supports 3 per-pool reward streams with separate `reward_growth_global_x64` counters; same structure as the fee-growth accumulator. ## Pointers * [`products/clmm/math`](/products/clmm/math) — the on-chain implementation and worked example with actual CLMM struct fields. * [`products/clmm/ticks-and-positions`](/products/clmm/ticks-and-positions) — tick lattice, `liquidity_net`/`gross`, active-range semantics. * [`products/clmm/fees`](/products/clmm/fees) — the fee-growth accumulator in action. Sources: * Uniswap v3 whitepaper (canonical derivation of sqrt-price math). * Raydium CLMM program source. # Constant-product AMM Source: https://docs.raydium.io/algorithms/constant-product The x·y=k invariant, reserve-based pricing, slippage derivation, and the fee handling variants used by Raydium CPMM and AMM v4. This is the reference math page every x·y=k product at Raydium links back to. ## The invariant A constant-product market maker (CPMM) holds two reserves `x` and `y` and enforces: ``` x · y ≥ k (after every trade) ``` where `k` is the product of the reserves before the trade. For a fee-free market, `x · y = k` exactly. With fees, `k` strictly grows (the LP share of the fee is retained in the reserves). The invariant is deliberately geometric: it guarantees that no matter how small one reserve becomes, the other grows unboundedly to match — i.e. the pool can never be drained to zero on either side. ## Pricing ### Spot price The marginal price of `y` denominated in `x` at any instant is the tangent of the curve: ``` p = y / x ``` (derivation: implicit differentiation of `x · y = k` gives `dy/dx = −y/x`; ignoring the sign, `|dy/dx| = y/x`). This is the price that the pool quotes for an infinitesimally small trade. For any finite trade, the realized price is worse due to slippage along the curve. ### Exact-input swap (give `Δx`, receive `Δy`) With fees, let `f` be the fee rate (e.g. `f = 0.0025` for 25 bps). Apply the fee to the input, then use the invariant to solve for the output: ``` Δx_after_fee = Δx · (1 − f) Δy = y · Δx_after_fee / (x + Δx_after_fee) ``` Post-trade reserves: ``` x' = x + Δx y' = y − Δy ``` The full `Δx` enters the reserves. The LP portion of the fee stays in `x'`; the protocol portion is excluded from the curve via a separate accounting step (see [Fee accounting variants](#fee-accounting-variants) below). ### Exact-output swap (receive `Δy`, pay the minimal `Δx`) ``` Δx_after_fee = x · Δy / (y − Δy) Δx = Δx_after_fee / (1 − f) ``` `Δx` is rounded up to ensure the pool does not undercharge. ## Slippage and price impact **Price impact** measures how much the pool's spot price moves as a result of the trade: ``` p_before = y / x p_after = y' / x' = (y − Δy) / (x + Δx) impact = (p_before − p_after) / p_before ``` For small `Δx / x`, a first-order expansion gives: ``` impact ≈ 2 · Δx / x (ignoring fees) ``` Intuition: a 1% swap causes a \~2% price impact. This factor of 2 is the reason CPMM pools quoted for mid-size trades look "thin" compared to orderbook markets — you are not just buying against the current best bid, you are walking up your own marginal price. **Effective price** paid by the swapper: ``` effective = Δx / Δy ``` The spread between `p_before` and `effective` is **slippage**. On-chain `slippage` UI is usually expressed as `(effective − p_before) / p_before`; the SDK's `computeAmountOut` returns both `amountOut` and `priceImpact` for this reason. ## Invariant check in code After a swap, protocols re-verify: ``` k' = x' · y' ≥ k = x · y ``` Any violation is a program bug or an arithmetic overflow. Raydium's swap instructions make this check explicit as a post-condition: ```rust theme={null} let k_before = coin_reserve_before as u128 * pc_reserve_before as u128; let k_after = coin_reserve_after as u128 * pc_reserve_after as u128; require!(k_after >= k_before, ErrorCode::InvariantViolation); ``` ## Fee accounting variants The invariant check assumes the LP fee stays in the reserves. Different Raydium products handle the protocol / fund / creator components differently: ### CPMM convention Fees are `u64` basis-point-like rates on a `1_000_000` denominator. The trade fee is split into `trade_fee_rate` (total) and then subdivided via `protocol_fee_rate`, `fund_fee_rate`, `creator_fee_rate`. On each swap: ``` trade_fee = ceil(Δx · trade_fee_rate / 1_000_000) creator_fee = ceil(Δx · creator_fee_rate / 1_000_000) // its own rate on volume, // NOT a slice of trade_fee protocol_fee = floor(trade_fee · protocol_fee_rate / 1_000_000) fund_fee = floor(trade_fee · fund_fee_rate / 1_000_000) lp_fee = trade_fee − protocol_fee − fund_fee ``` The three non-LP shares accrue into separate counters (`protocol_fees_*`, `fund_fees_*`, `creator_fees_*`) that are **excluded** from the reserves used in the invariant. This is how fees can be swept without moving the curve. See [`products/cpmm/fees`](/products/cpmm/fees). ### AMM v4 convention Fees are `numerator / denominator` ratios on a `10_000` denominator. The split is fixed at pool creation and stored on `AmmInfo.fees`: ``` swap_fee = ceil(Δx · swap_fee_numerator / swap_fee_denominator) // e.g. 0.25% pnl_share = swap_fee · pnl_numerator / pnl_denominator // 12 / 100 = 12% of swap_fee lp_share = swap_fee − pnl_share // 0.22% of volume ``` `pnl_share` accrues into `state_data.need_take_pnl_*` and is excluded from reserves; `lp_share` stays in the vault. See [`products/amm-v4/fees`](/products/amm-v4/fees). Both conventions preserve the invariant the same way — the difference is cosmetic (denominator + number of sub-categories). ## Rounding rules * **Fee calculation rounds up.** Ensures the pool never undercharges on the fee. * **Output amount rounds down.** Ensures the invariant holds strictly (`k' > k` even before the fee is added). * **Exact-output input amount rounds up.** Ensures the user does not underpay. All arithmetic uses `u128` for the intermediate `x · Δx` products to avoid overflow on large reserves. Final results are cast back to `u64` with a saturation check. ## Edge cases ### Empty pool Before the first `Deposit`, `x = y = 0`. Swap instructions reject pre-deposit. ### Zero output If `Δx` is small enough that the rounded-down `Δy` is 0, the instruction reverts with `ZeroTradingTokens`. This prevents extraction of value without payment; also means dust swaps on highly imbalanced pools fail. ### Dust LP The first `Deposit` has special handling: it computes the initial LP supply as `sqrt(x · y)` and burns a small "init burn" amount (usually 100 LP units) to prevent the "first-depositor inflation attack" (where an attacker donates to the vault and inflates the LP token value). Subsequent deposits use pro-rata math. ## Relationship to arbitrage A CPMM pool's price only changes via: 1. Trades through the pool itself (users walking the curve). 2. Donations (sending tokens to the vault without a swap). Because trades move the price deterministically with the curve, any pool whose price diverges from the broader market creates an arbitrage opportunity. Arbitrageurs bring the pool price back toward the market price in expectation. This is why CPMM pools are said to "quote a price without an oracle": the market finds the price through arbitrage rather than the pool reading it externally. The flip side: the pool itself is the arbitrageur's counterparty, so any arbitrage profit is LP impermanent loss (minus the fee captured by LPs). ## Worked examples ### Example 1 — small trade, negligible slippage Pool: `x = 1_000_000, y = 2_000_000, k = 2·10^12`. Fee `f = 0.0025`. Trade `Δx = 1_000`: ``` Δx_after_fee = 1000 · 0.9975 = 997.5 Δy = 2_000_000 · 997.5 / (1_000_000 + 997.5) = 1_995_000_000 / 1_000_997.5 ≈ 1_993.01 ``` Effective price: `1000 / 1993.01 ≈ 0.5018`. Spot before: `0.5`. Slippage vs spot: **\~0.35%**. Price impact — the move in the pool's spot price, per the definition above — is **\~0.20%**. ### Example 2 — mid-size trade, visible slippage Same pool, `Δx = 100_000` (10% of `x`): ``` Δx_after_fee = 100_000 · 0.9975 = 99_750 Δy = 2_000_000 · 99_750 / (1_000_000 + 99_750) = 199_500_000_000 / 1_099_750 ≈ 181_405 ``` Effective: `100_000 / 181_405 ≈ 0.5513`. Slippage vs spot: **\~10.3%**. Price impact: **\~17.3%** — close to the `2 · 10% = 20%` rule of thumb, which the trade fee and the curve inversion pull slightly below. The two numbers are often conflated: slippage is what the swapper pays relative to spot, price impact is how far the pool's own quote moves. ## Pointers * [`products/cpmm/math`](/products/cpmm/math) — CPMM's specific rounding + fee-denominator choices. * [`products/amm-v4/math`](/products/amm-v4/math) — how AMM v4's OpenBook-integrated reserves extend this model. * [`algorithms/slippage-and-price-impact`](/algorithms/slippage-and-price-impact) — dedicated page on slippage tolerance sizing for UIs. Sources: * Uniswap v2 whitepaper — the canonical statement of `x · y = k`. * Raydium CPMM program source. * Raydium AMM v4 program source. # Impermanent loss Source: https://docs.raydium.io/algorithms/impermanent-loss The fundamental LP risk: value lost relative to simply holding the two tokens. Formulas for CPMM (constant-product) and CLMM (concentrated-liquidity) pools, worked examples, and the break-even fee-APR thresholds that matter for LPs. > [!NOTE] > > **Impermanent loss (IL)** is the gap between (a) the value of your LP position and (b) the value you would have had if you had simply held the two tokens from deposit to now. It is "impermanent" in name only — if you withdraw while prices have diverged, the loss is realised. This page gives the formulas, the intuition, and the break-even APRs for CPMM and CLMM. ## The simple case: `xy=k` (CPMM, AMM v4) Suppose at deposit you put in `x₀` tokens of A and `y₀` tokens of B with price `P₀ = y₀ / x₀`. A constant-product pool maintains `x · y = k = x₀ · y₀`. When the external price of A in B moves to `P₁`, arbitrageurs rebalance the pool until marginal price matches, giving: ``` x₁ = √(k / P₁) y₁ = √(k · P₁) ``` Your LP share is worth `x₁ · P₁ + y₁` tokens of B. Compare to simply holding: `x₀ · P₁ + y₀`. The ratio is: ``` V_LP / V_HOLD = 2 · √r / (1 + r) where r = P₁ / P₀ ``` **IL** is `1 − V_LP / V_HOLD`. A few sample values: | Price change `r` | `V_LP / V_HOLD` | IL | | - | - | - | | 1.00× (no change) | 1.0000 | 0.00% | | 1.25× (+25%) | 0.9938 | 0.62% | | 1.50× (+50%) | 0.9798 | 2.02% | | 2.00× (+100%) | 0.9428 | 5.72% | | 3.00× (+200%) | 0.8660 | 13.40% | | 5.00× (+400%) | 0.7454 | 25.46% | | 0.50× (−50%) | 0.9428 | 5.72% | | 0.25× (−75%) | 0.8000 | 20.00% | IL is symmetric in `P₁ / P₀` vs `P₀ / P₁`: doubling and halving produce the same IL. ### Intuition The pool is constantly selling whichever side goes up and buying whichever side goes down, at average prices worse than the new equilibrium. IL is the rebate you pay to arbitrageurs for keeping the pool honest. In exchange, you earn trading fees — the hope is that fees more than offset IL over the holding period. ## Break-even fee APR (CPMM) Given realised volatility `σ` (annualised stdev of log-returns) and no correlation, a rough first-order IL rate is: ``` dIL/dt ≈ σ² / 8 per year ``` So the break-even fee APR for a CPMM LP is approximately `σ² / 8`. | Realised vol (annualised) | IL-per-year | Break-even fee APR | | - | - | - | | 20% | 0.50% | 0.50% | | 40% | 2.00% | 2.00% | | 80% | 8.00% | 8.00% | | 120% | 18.00% | 18.00% | | 200% | 50.00% | 50.00% | A SOL/USDC pair running \~80% annualised vol needs roughly 8% fee APR to break even on IL. If the pool quotes 30% fee APR, the LP is netting \~22% after IL (before SOL-denominated PnL). ### Caveats * This ignores fees compounding into the position. * It assumes continuous rebalancing by perfectly-efficient arbitrage, which overstates IL slightly on Solana where arb has latency. * It assumes the path is log-normal; fat-tailed meme tokens underestimate IL at this formula. ## CLMM-specific IL In a concentrated-liquidity pool you pick a range `[P_lo, P_hi]`. Three things change versus CPMM: 1. **Inside the range, IL is amplified** because you have effectively leveraged your capital. The multiplier is roughly `1 / (1 − √(P_lo/P_hi))`, so a range that goes from −50% to +100% (P\_hi / P\_lo = 4) has a leverage of \~2× and an IL \~2× a CPMM position over the same move. 2. **Outside the range, you hold only one token.** Once price crosses `P_hi`, you hold 100% of the lower-numbered token (typically the "base"); below `P_lo`, you hold 100% quote. No further swaps happen against your position, so IL is bounded but so are fees (zero). 3. **Rebalancing = realising IL + opening a new range** at the new price. Every rebalance locks in the loss to that point and starts fresh. ### IL vs HODL for a CLMM position For a position with range `[P_lo, P_hi]` and current price `P`, with `P₀` the entry price (somewhere in the range), let: ``` √P₀̄ = √P₀ · (bounded by √P_lo, √P_hi) √P̄ = √P · (bounded by √P_lo, √P_hi) ``` The IL relative to holding the entry composition is the standard V\_LP / V\_HOLD formula applied to the *clamped* prices. That is: if price stays inside the range, IL behaves like a CPMM IL on a position leveraged by the range-width factor. If price exits the range, IL is fixed at the single-token composition: all base or all quote, priced at `P` but valued against a portfolio you would have held 50/50 at `P₀`. ### Worked CLMM example Assume you deposit \$10,000 of SOL/USDC into a CLMM at SOL = \$160, range `[$120, $200]`. Note the deposit is **not** 50/50: at that price in that range the position takes 27.54 SOL (\$4,407) and \$5,593 USDC, which fixes `L ≈ 3,300`. The HODL benchmark below is a 50/50 \$5,000 + \$5,000 hold, matching the CPMM comparison. * Range width: `P_hi / P_lo = 200 / 120 ≈ 1.67`. Leverage factor ≈ `1 / (1 − √(120/200)) ≈ 4.4×`. * If SOL moves to \$180 (+12.5%), HODL value = \$10,625; CLMM position ≈ \$10,397; **IL ≈ 2.1%**. * If SOL moves to \$200 (+25%), HODL value = \$11,250; CLMM position is now 100% USDC worth ≈ \$10,520; **IL ≈ 6.5%**. * If SOL moves to \$240 (+50%, outside range), HODL value = \$12,500; CLMM position is still ≈ \$10,520; **IL ≈ 15.8%**. The same capital in a CPMM (no range) would have IL of only \~2.02% at \$240 and would continue earning fees. That gap is the amplification this page opens with: roughly the leverage factor times the CPMM IL while in range. The CLMM position has higher fee capture *while in range* but much worse IL once out of range for an extended period. ## Single-sided deposits Raydium CLMM supports opening a position by depositing only one token if the current price is at or outside the corresponding range boundary. This is equivalent to placing a limit order — the pool will swap your single-side deposit into the other token as price moves through the range. IL on single-sided deposits is calculated the same way but with a different entry composition. ## Mitigations * **Stick to correlated pairs.** Stable/stable and LST/SOL have near-zero IL at realistic horizons. * **Use LaunchLab tokens cautiously.** Newly-launched tokens typically run 200–400% annualised vol, meaning IL eats 20–50% per year. * **Widen CLMM ranges if you won't rebalance.** A 2× wider range has \~half the fee density and \~half the IL amplification — roughly the same IL-per-fee-earned ratio over long horizons. * **Auto-compound fees.** CPMM does this implicitly; CLMM requires manual `collectFee` + re-deposit. Farm-auto-compound vaults (several 3rd-party) automate this. ## Verification tools * [`sdk-api/typescript-sdk`](/sdk-api/typescript-sdk) — `raydium.clmm.getOwnerPositionInfo({ programId })` plus `PoolUtils.getAmountsFromLiquidity(...)` return current exposure; diff against your entry basis. * [`sdk-api/rest-api`](/sdk-api/rest-api) — `/pools/info/ids` returns historical price series for IL backtests. * External: dune.com and defillama.com both host IL simulators that can import a Raydium pool id and replay history. ## Pointers * [`algorithms/constant-product`](/algorithms/constant-product) — the invariant IL is derived from. * [`algorithms/clmm-math`](/algorithms/clmm-math) — liquidity-to-amount conversion used in CLMM IL derivation. * [`algorithms/clmm-apr`](/algorithms/clmm-apr) — fee-side estimate to weigh against IL. * [`user-flows/choosing-a-pool-type`](/user-flows/choosing-a-pool-type) — LP decision guide that uses this page's break-even logic. Sources: * Uniswap V2 whitepaper (CPMM IL derivation). * Uniswap V3 whitepaper (concentrated-liquidity IL amplification). * Panoptic and GFX Labs CLMM IL research, 2024–2025. # Algorithms Source: https://docs.raydium.io/algorithms/index Mathematical deep-dive chapter: the invariants, pricing formulas, and edge cases behind every Raydium product. ## Who this chapter is for Protocol researchers, auditors, and advanced integrators who want to understand the *why* behind the math rather than just call the instructions. Product pages give a summary and defer here for derivations. ## Chapter contents > **[Constant product (xy=k)](/algorithms/constant-product)** > > Invariant, marginal price, swap input/output formulas, slippage as a function of trade size. > **[CLMM math](/algorithms/clmm-math)** > > Sqrt-price representation, liquidity ↔ amount conversion, single-tick swap step, fee-growth accumulator, multi-tick swap iteration. > **[Bonding curves](/algorithms/bonding-curves)** > > LaunchLab's curve formula(s), graduation threshold derivation, continuous vs. discrete pricing. > **[Slippage and price impact](/algorithms/slippage-and-price-impact)** > > Definitions, how SDK computes `minAmountOut`, what "price impact" means across AMM types, MEV considerations. > **[Token-2022 transfer fees](/algorithms/token-2022-transfer-fees)** > > How a transfer-fee-bearing token changes the effective swap input and output amounts, and how the CPMM/CLMM programs handle it. > **[Impermanent loss](/algorithms/impermanent-loss)** > > IL formulas for CPMM and CLMM, worked examples, and the break-even fee APR thresholds every LP should know. > **[Estimating CLMM APR](/algorithms/clmm-apr)** > > How Raydium computes the APR shown on CLMM pools and how to project APR for a prospective range before opening it. ## Writing brief * Use LaTeX-style math sparingly; show formulas as code blocks with inline prose. * Every formula is followed by a worked numeric example. * Every page has a "Where this is implemented" section that points to the relevant line range in the on-chain program source, for auditors. * Do not re-derive the same formulas on product pages — link here. # Slippage and price impact Source: https://docs.raydium.io/algorithms/slippage-and-price-impact Precise definitions of slippage vs price impact, how Raydium's SDK sizes minAmountOut and maxAmountIn, differences across AMM types, and MEV considerations for production routing. ## Two distinct concepts **Price impact** and **slippage** are frequently conflated in UIs but refer to different things. * **Price impact** is a deterministic property of a trade against a specific pool state. Given `(Δin, reserves)`, price impact is fully computable before the trade is submitted. * **Slippage** is the realized difference between the price you *expected* at quote time and the price you *actually got* at execution time. It is a function of latency, concurrent transactions, and block inclusion order — not of the pool math. A 1% quote against an otherwise-idle pool has 0% slippage if it lands in the next block; the 1% was the price impact. That same quote lands 0.2% worse if another trade hits the pool first — the extra 0.2% is slippage. ## Formal definitions ### Price impact ``` p_before = pool.spot_price() p_after = pool.spot_price_if_trade(Δin) applied impact = (p_before − p_after) / p_before // can be signed ``` For a CPMM: `impact ≈ 2 · Δin / reserve_in` for small trades. For CLMM: depends on how many ticks the trade crosses; often flat within the current tick range, jumping at each tick cross. ### Realized slippage ``` quoted_out = amount_out computed at quote time actual_out = amount_out observed on-chain slippage = (quoted_out − actual_out) / quoted_out ``` Slippage is always non-negative (or zero), assuming the quote was honest. A negative value would mean you got *more* than quoted — possible if the pool state moved in your favor between quote and execution. ## Sizing `minAmountOut` and `maxAmountIn` Every Raydium swap takes a slippage-protection bound: * `SwapBaseInput(amount_in, min_amount_out)` — exact-input, lower-bound the output. * `SwapBaseOutput(max_amount_in, amount_out)` — exact-output, upper-bound the input. The SDK computes these per product — the three do **not** share one signature: ```ts theme={null} // AMM v4 — the only module with a method literally called computeAmountOut const computed = raydium.liquidity.computeAmountOut({ poolInfo, // needs baseReserve/quoteReserve/version/status spliced in amountIn, // BN mintIn, mintOut, slippage: 0.005, // 0.5% tolerance, a plain number }); // -> { amountOut, minAmountOut, currentPrice, executionPrice, priceImpact, fee } // all amounts are plain BNs // CPMM const { computePoolInfo } = await raydium.cpmm.getPoolInfoFromRpc(POOL_ID); const cpmmQuote = raydium.cpmm.computeSwapAmount({ pool: computePoolInfo, amountIn, outputMint: mintOut, slippage: 0.005, }); // -> { amountIn, amountOut, minAmountOut, fee, executionPrice, priceImpact, swapResult, allTrade } // CLMM — a PoolUtils static, and it needs the bitmap extension + a block timestamp const clmmQuote = PoolUtils.computeAmountOutFormat({ poolInfo: computeClmmPoolInfo, tickarrayBitmapExtension, tickArrayCache, amountIn, tokenOut, slippage: 0.005, epochInfo: await raydium.fetchEpochInfo(), blockTimestamp: Math.floor(Date.now() / 1000), }); // -> { amountOut, minAmountOut, fee, priceImpact, remainingAccounts, ... } ``` Across all three, `minAmountOut` is `amountOut × (1 − slippage)` and is what goes on-chain as the bound; `priceImpact` is deterministic from pool state alone; `fee` is the total charged. The slippage tolerance is a **buffer around the price impact**, not the price impact itself. A 0.5% tolerance means "accept at most 0.5% worse than my quote" — independent of whether the price impact was 0.01% (a tiny trade) or 2% (a large trade). For a 2% price-impact trade with 0.5% tolerance, `minAmountOut` is `2.5%` below the pre-trade spot — the sum of impact and tolerance, essentially. ## Recommended slippage tolerances There is no single right number; the right bound depends on: 1. **Pair stability.** Stablecoin-stablecoin pools can safely use 0.1%. Volatile meme-pair pools often need 3–5% just to reliably land. 2. **Trade size.** Larger trades have larger price impacts, so tolerance needs to scale with them to avoid reversion. The SDK's auto-slippage defaults around `max(0.5%, 2 × price_impact)` for this reason. 3. **Block inclusion latency.** Transactions that sit in the mempool for multiple blocks are exposed to more concurrent trades. Jito bundles and priority fees reduce this. Rules of thumb (Raydium UI defaults): | Pair type | Default tolerance | | - | - | | Stable-stable (USDC-USDT, USDC-USDS) | 0.1% | | Stable-major (USDC-SOL, USDC-BTC) | 0.5% | | Major-major (SOL-BTC, SOL-ETH) | 1% | | Volatile (meme tokens, illiquid long-tail) | 3–5% | ## Differences across AMM types ### CPMM Price impact is smooth and continuous (closed-form `2 · Δin / reserve_in`). Slippage tolerance scales linearly with trade size. ### AMM v4 Same curve math as CPMM. Since the OpenBook removal, the "effective reserves" are just the two vault balances: * Quote off the raw vault balances. There is no on-book component to add — `Initialize2` writes `AmmInfo.open_orders = Pubkey::default()` on every new pool, and no instruction reads an `OpenOrders` account. * Subtract the accrued protocol PnL (`state_data.need_take_pnl_coin` / `need_take_pnl_pc`) from the vault balances to get the reserves the invariant actually uses. * There is no crank to pre-run: `MonitorStep` now panics with `unimplemented!` and must not be sent. ### CLMM Price impact is **piecewise**. Within the current tick range, impact is approximately linear in `Δin / L`. Crossing a tick boundary can change `L` discretely, causing a sudden jump in the marginal price. A trade that crosses several sparsely-populated ticks can have much higher impact than the `2 · Δin / reserve` rule of thumb suggests. The SDK's CLMM quote iterates the swap step deterministically to return an exact expected `amountOut`, so `minAmountOut = amountOut · (1 − slippage)` is correct. But the **priceImpact** return value should be interpreted as "the spread between pre-trade spot and post-trade spot", which on CLMM can be much larger than the swap's effective slippage for a user who only cares about `amount_out`. ### LaunchLab curve Similar to CPMM but with an asymmetric curve (quadratic or virtual-reserves). Impact grows faster for late buyers as the curve steepens toward graduation. Pre-buyer UIs should warn when a buy is expected to push the curve more than \~5% of `quote_reserve_target` in one transaction. ## MEV considerations On Solana, MEV extraction against swaps mostly takes the form of **sandwich attacks**: a bot places a back-run transaction that trades after yours, plus a front-run that trades before, both at the same slot. Your trade fills at a worse price than it would have absent the sandwich; the back-run captures the difference. Mitigations: 1. **Tight `minAmountOut`.** Aggressive slippage bounds cause the victim transaction to revert if sandwiched heavily, protecting funds (but wasting gas). On Solana this is standard practice — rejection is cheap. 2. **Jito bundles.** Submitting through Jito with a bundled tip excludes middlemen from reordering your tx. Bundles land as atomic blocks. 3. **Priority fees.** A high priority fee increases the chance your trade lands in the current leader's block before a sandwicher can react. Less robust than bundles, more standard. 4. **Private RPC.** Submitting through a private RPC (or via a validator's direct endpoint) reduces the window during which a mempool sandwicher can observe your transaction. Raydium's SDK does not bundle; integrators typically layer Jito on top. See [`integration-guides/routing-and-mev`](/integration-guides/routing-and-mev) for patterns. ## Slippage for multi-hop routes When a swap routes through multiple pools (e.g. `USDC → SOL → RAY`), slippage tolerance should be applied per-hop, not just end-to-end: ```ts theme={null} // Bad: 0.5% applied at the end only, so any intermediate hop sliding fails the second hop. const finalMin = finalAmount * (1 - 0.005); // Better: each hop enforces its own bound. const hop1Min = hop1Amount * (1 - 0.005); const hop2Min = hop2Amount * (1 - 0.005); // End-to-end this is tighter (compound), but atomic — if either hop degrades, the tx reverts early. ``` The SDK's router applies per-hop bounds automatically when you call `raydium.tradeV2.swap`. (The facade is `tradeV2` — `raydium.trade` does not exist.) For custom routers, replicate the pattern. ## Reporting to users Rules-of-thumb for a good swap UI: * Display **both** expected price impact and slippage tolerance separately. * Highlight when price impact exceeds \~2% — "high impact" warning. * Highlight when price impact exceeds tolerance — the transaction is almost certain to revert. * For volatile pairs, offer a "high slippage mode" that relaxes the bound and shows a stronger warning. ## Pointers * [`products/cpmm/math`](/products/cpmm/math), [`products/amm-v4/math`](/products/amm-v4/math), [`products/clmm/math`](/products/clmm/math) — impact derivations per pool type. * [`integration-guides/routing-and-mev`](/integration-guides/routing-and-mev) — multi-hop routing + MEV defenses. * [`integration-guides/priority-fee-tuning`](/integration-guides/priority-fee-tuning) — sizing priority fees to reduce slippage. Sources: * Raydium SDK v2 slippage / impact implementation. * Flashbots / Jito on Solana MEV. # Token-2022 transfer fees in swaps Source: https://docs.raydium.io/algorithms/token-2022-transfer-fees How Token-2022's transfer-fee extension changes the pre/post-swap amount accounting, which Raydium products support it, and the edge cases integrators need to handle (asymmetric fees, fee updates, max-fee caps, non-transferable extensions). > [!NOTE] > > Support matrix: **CPMM** supports Token-2022 fully, including transfer-fee mints. **CLMM** supports Token-2022 with transfer fees via explicit `SwapV2` accounts. **AMM v4** does not support Token-2022 at all. **LaunchLab** creates a classic SPL base mint through `InitializeV2`, but has a dedicated `InitializeWithToken2022` entrypoint that creates a Token-2022 base mint and optionally attaches a `TransferFeeConfig`; its quote side accepts either token program. See [`products/launchlab/platform-config`](/products/launchlab/platform-config#token-2022-transfer-fee-authorities). **Farm v6** supports Token-2022 on both staking and reward mints. ## What a transfer fee is Token-2022 is the second SPL Token program (`TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA` → `TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb`). Among its extensions, the **transfer-fee** extension makes every `TransferChecked` on a token mint deduct a fee from the transferred amount. The fee routes to a recipient designated by the mint authority and can be updated by the authority (within bounds). A mint with transfer fee has two relevant parameters: * **`transfer_fee_basis_points`** — the rate (e.g. 100 = 1%). * **`maximum_fee`** — an absolute cap per transfer (so whales moving huge amounts don't pay unbounded fees). A mint can have **two** active transfer-fee configurations at once: the "newer" one (in effect now) and the "older" one (being scheduled out). This is the "epoch transition" design — transfer fee changes take effect across an epoch boundary to avoid surprising in-flight transactions. ## Why this matters for swaps A pool's vaults hold actual balances. When a user calls a Raydium swap: 1. User sends `amount_in` to the pool vault. If the **in-mint** has a transfer fee, the vault receives `amount_in − fee_in`, not `amount_in`. 2. The swap math operates on the vault-received amount. 3. The pool sends `amount_out` to the user's ATA. If the **out-mint** has a transfer fee, the user receives `amount_out − fee_out`, not `amount_out`. If the swap program is naive and uses the raw `amount_in` argument, the invariant check fails because the vault got less than the program thinks. Conversely, if it computes `amount_out` without subtracting the outbound transfer fee, the user sees a shortfall and blames the program. Raydium CPMM and CLMM (via `SwapV2`) handle this by: * **Pre-swap**: computing `in_after_fee = amount_in − transfer_fee_on(amount_in, in_mint)`, and using `in_after_fee` in the curve math. * **Post-swap**: computing `out_gross = amount_out_from_curve`, sending `out_gross` to the user via `TransferChecked` which the Token-2022 program will itself reduce by the transfer fee. The user's `minAmountOut` slippage bound is checked against `out_gross` (what the pool sends), **not** against what the user receives. This is how every major Solana DEX handles Token-2022, and it matters because: * If the pool checked post-fee, a fee-update between quote and execution would cause the trade to revert. * Checking pre-fee pins the failure to the quote's own quality, not to the user's out-of-band fee changes. UIs should subtract the expected Token-2022 transfer fee when showing "You receive" to the user. ## Computing the Token-2022 fee The SPL Token-2022 program exposes a deterministic helper. In Rust: ```rust theme={null} use spl_token_2022::extension::transfer_fee::TransferFeeConfig; use spl_token_2022::extension::StateWithExtensions; let mint_data = ...; let state = StateWithExtensions::::unpack(&mint_data)?; let config = state.get_extension::()?; let epoch = Clock::get()?.epoch; let fee_bp = config.get_epoch_fee(epoch).transfer_fee_basis_points; let max_fee = u64::from(config.get_epoch_fee(epoch).maximum_fee); let fee = (amount as u128 * fee_bp as u128 / 10_000).min(max_fee as u128) as u64; ``` In TypeScript (via `@solana/spl-token`): ```ts theme={null} import { getTransferFeeConfig, getTransferFeeAmount } from "@solana/spl-token"; const config = getTransferFeeConfig(mintAccount); const currentEpochFee = config.olderTransferFee.epoch <= currentEpoch ? config.newerTransferFee : config.olderTransferFee; const rate = currentEpochFee.transferFeeBasisPoints; const maxFee = currentEpochFee.maximumFee; const fee = Math.min(Math.floor(amount * rate / 10_000), Number(maxFee)); ``` ## Adjusted swap formulas (CPMM, exact-input) Let `f_pool` be the pool fee rate, `f_in` the in-mint transfer fee rate, `max_in` its max cap, `f_out` the out-mint transfer fee rate, `max_out` its max cap. ``` transfer_fee_in = min(amount_in · f_in / 10_000, max_in) vault_received = amount_in − transfer_fee_in pool_fee = ceil(vault_received · f_pool / 1_000_000) amount_after = vault_received − pool_fee amount_out_gross = y · amount_after / (x + amount_after) transfer_fee_out = min(amount_out_gross · f_out / 10_000, max_out) user_receives = amount_out_gross − transfer_fee_out ``` Slippage check: `amount_out_gross ≥ min_amount_out` (not `user_receives ≥ min_amount_out`). The user's `minAmountOut` is set by the SDK to `expected_gross · (1 − slippage)` — keep the bound on the "sent" side, not the "received" side. ## Adjusted formulas (CPMM, exact-output) The SDK iterates to find `amount_in` such that `user_receives = amount_out_exact`: ``` # user wants to receive amount_out_exact after transfer fee amount_out_gross = amount_out_exact + transfer_fee_out_for(amount_out_exact) # then solve CPMM exact-output for amount_after: amount_after = ceil(x · amount_out_gross / (y − amount_out_gross)) # then add pool fee: vault_received = ceil(amount_after · 1_000_000 / (1_000_000 − f_pool)) # then add in transfer fee: amount_in = ceil(vault_received · 10_000 / (10_000 − f_in)) # (or iterate — see fee-cap edge case below) ``` The `max_in` / `max_out` caps make the computation non-linear because once the cap is hit the fee stops growing. The SDK's `computeAmountIn` / `computeAmountOut` handle this by iterating if the naive formula would push past the cap. ## Edge cases ### Asymmetric fees (one side has a fee, the other does not) Common in practice. The formulas above already handle this — if one side has `f_in = 0`, the relevant terms collapse. There is no special case in the program. ### Fee updates mid-swap If the mint's transfer fee changes between quote time and execution time, the swap will either land with slightly worse economics (user bears the difference within the slippage tolerance) or revert (the gross output drops below `minAmountOut`). Slippage bounds absorb this; no additional protection is needed. ### Maximum-fee cap Once the trade is large enough to hit `maximum_fee`, the fee saturates and further growth is zero. This makes the effective rate asymptotic to zero for very large trades, which can cause odd pricing curves on deeply illiquid markets. The SDK's `computeAmountOut` accounts for this. ### Non-transferable extension Some Token-2022 mints use the `NonTransferable` extension, which rejects all `Transfer` calls except to and from the mint authority. Such mints **cannot** be used in a Raydium pool at all. `CreatePool` rejects them at init. ### Interest-bearing mints Token-2022 also supports an `InterestBearingConfig` extension that makes balances appear to grow over time. Raydium's pools read raw vault balances (which ignore the interest accrual), so on a pool with an interest-bearing mint, LPs capture the accrued interest as a pure gift whenever they redeem (the vault balance grew faster than the LP supply representation). Integrators should treat this as a non-issue but document it for the LP side. ### Transfer hooks Token-2022's `TransferHook` extension allows arbitrary CPI on every transfer. Raydium CPMM supports these — the swap instruction forwards the hook accounts — but it adds CU overhead and requires the hook to be well-behaved. CLMM `SwapV2` also supports hooks. AMM v4 does not support Token-2022 at all, so the question does not arise. ## Worked example CPMM pool, `x = 1_000_000 USDY, y = 1_000_000 USDC`, pool fee 0.25%. * USDY has a 1% transfer fee, `max_fee = 10_000` (0.01 USDY with 6 decimals). * USDC has no transfer fee. User swaps `amount_in = 1_000 USDY` for USDC (exact-input). ``` transfer_fee_in = min(1_000 · 100 / 10_000, 10_000) = 10 // 1%, well under cap vault_received = 1_000 − 10 = 990 pool_fee = ceil(990 · 2_500 / 1_000_000) = 3 // 0.25% amount_after = 990 − 3 = 987 amount_out_gross = 1_000_000 · 987 / (1_000_000 + 987) ≈ 986.03 ``` ≈ 986.03 USDC. No outbound transfer fee, so the user receives ≈ 986.03 USDC. ## Pointers * [`products/cpmm/overview`](/products/cpmm/overview) — CPMM Token-2022 support. * [`products/clmm/instructions`](/products/clmm/instructions) — `SwapV2` vs `Swap` for Token-2022 routing. * [`solana-fundamentals/spl-token-and-token-2022`](/solana-fundamentals/spl-token-and-token-2022) — the general Token-2022 extension model. Sources: * [SPL Token-2022 transfer-fee extension docs](https://www.solana-program.com/docs/token-2022/extensions#transfer-fees) * Raydium CPMM program source (`SwapBaseInput` / `SwapBaseOutput` Token-2022 handling). * Raydium CLMM program source (`SwapV2`). # Choosing a wallet Source: https://docs.raydium.io/getting-started/choosing-a-wallet How to pick a Solana wallet for using Raydium: the features that matter, the security choices to make, and what to verify before you sign. > [!NOTE] > > Raydium does not endorse any specific wallet provider. Any reputable, non-custodial Solana wallet that supports versioned (V0) transactions can connect to Raydium and sign swaps, LP actions, and farm operations. This page focuses on **what to look for**, not which one to pick — that decision is yours. ## What a Raydium-compatible wallet must do A wallet is a Raydium-compatible wallet if it can do all of the following: * Hold a Solana keypair locally and **never** transmit the private key off-device. * **Sign versioned (V0) transactions.** Raydium swaps use Address Lookup Tables and require V0 support. Wallets that only sign legacy transactions cannot complete a Raydium swap. * **Connect to dApps via the Wallet Adapter standard.** This is what makes the "Connect Wallet" button on raydium.io work. * **Show a clear transaction preview** before you approve, including the program(s) being called and the token movements. * **Support associated token accounts** (creating an ATA the first time you receive a new mint). These are baseline requirements. Any modern Solana wallet meets them. Anything that does not is unsafe to sign Raydium transactions with — period. ## Features that matter beyond the baseline Once a wallet clears the baseline, the differences come down to your workflow and risk profile. Decide which of the following matter to **you**, and pick a wallet that handles them: | Feature | When it matters | | - | - | | **Hardware-wallet pairing** | You are holding more than a casual amount. The software wallet becomes a transaction builder; the hardware device holds the key and signs. Most reputable Solana wallets pair with at least Ledger; some pair with Keystone, SafePal, or other devices. | | **Mobile dApp browser** | You expect to use Raydium primarily from a phone. The wallet's in-app browser is what loads raydium.io and signs transactions on mobile. | | **Multiple-account management** | You separate funds across hot / cold / experimental wallets and want to switch quickly without juggling extensions. | | **Token-2022 extension awareness** | You will interact with pools that use Token-2022 mints (e.g. transfer-fee tokens). A wallet that surfaces these extensions in the signing UI helps you spot unexpected fees before you sign. | | **Priority-fee display** | You trade during congestion and want to see what the wallet has set for compute-budget price before approving. | | **Solana Actions / Blinks support** | You want to use the one-click swap links Raydium publishes on social media. See [`user-flows/referrals-and-blinks`](/user-flows/referrals-and-blinks). | | **Open-source codebase** | You want to be able to audit the wallet client (or rely on the community having done so). | | **Multi-chain accounts** | You hold assets on chains other than Solana and prefer one wallet for all of them. Verify the multi-chain support is mature for the chains you actually use; it varies. | ## Popular Solana wallets The following are well-known wallet projects with active Solana support. They are listed alphabetically; **inclusion is informational, not an endorsement**, and the list is not exhaustive. Verify the official URL before installing — phishing clones routinely buy sponsored ads against the real domain names. ### Software wallets | Wallet | Where it runs | Official site | | - | - | - | | Phantom | Browser extension, iOS, Android | [phantom.com](https://phantom.com) | | Solflare | Browser extension, iOS, Android, web | [solflare.com](https://solflare.com) | | OKX Wallet | Browser extension, iOS, Android | [web3.okx.com](https://web3.okx.com) | | Backpack | Browser extension, iOS, Android, desktop | [backpack.app](https://backpack.app) | All four are non-custodial, support Wallet Adapter, sign V0 transactions, and pair with at least one mainstream hardware device. Past that, the differences are workflow-specific — use the criteria in the previous section to decide which fits you. ### Hardware wallets A hardware wallet pairs with one of the software wallets above (the software side becomes the transaction builder; the hardware device holds the key and signs). | Device | Type | Official site | | - | - | - | | Ledger | USB / Bluetooth | [ledger.com](https://www.ledger.com) | | Keystone | Air-gapped (QR-code signing) | [keyst.one](https://keyst.one) | Each software wallet documents which hardware devices it supports; check before buying. ## Hot / cold wallet pattern A common practice that works regardless of which wallet you pick: * A **hot wallet** holds a small amount you accept might be lost — for daily swapping and trying things. * A **cold wallet** (paired with a hardware device) holds anything you would be unhappy to lose. Move funds in only when you actively need them in the hot wallet. Raydium treats each wallet as completely independent: separate positions, separate LP tokens, separate farm rewards, separate history. Switching wallets is one click. ## Where to find wallet options The Raydium UI's "Connect Wallet" modal lists every wallet that has integrated with Raydium via the Wallet Adapter. Browse it to see what is currently supported. Solana's official wallet directory ([`solana.com/wallets`](https://solana.com/wallets)) is another neutral starting point — it is filterable by platform, custody model and features. When you evaluate a wallet, run through this checklist: * [ ] Maintained: recent releases, an active issue tracker, a security-disclosure channel. * [ ] Reviewed: a published audit by a reputable firm, or open-source code with an active community. * [ ] V0-transaction support confirmed (test on devnet before transferring real funds). * [ ] If you plan to use a hardware device: the wallet documents which devices it supports and how the pairing works. * [ ] You found the official download via the project's verified domain — **not** via a sponsored ad or a forwarded link. ## Wallet security basics Regardless of which wallet you pick: * **Write down the seed phrase on paper.** Store the paper in two physically separate locations. **Never** type the seed phrase anywhere except during a wallet recovery on a fresh install. * **Use a password manager** for the wallet's unlock password — and keep that password completely separate from the seed. * **Use a dedicated browser profile** for crypto activity, with the minimum number of extensions installed. Phishing extensions are the single largest drain vector. * **Treat every wallet-connect prompt with suspicion.** Read what you are signing. If a transaction transfers all of a token instead of a specific amount, reject it. * **Bookmark `raydium.io`.** Always navigate from the bookmark, never from a search-engine ad. More security guidance is in [`getting-started/trust-and-safety`](/getting-started/trust-and-safety). ## Where to go next * **Prerequisites:** [`getting-started/what-you-need`](/getting-started/what-you-need). * **Fund the wallet:** [`getting-started/funding-your-wallet`](/getting-started/funding-your-wallet). * **First swap:** [`getting-started/first-swap`](/getting-started/first-swap). * **Safety:** [`getting-started/trust-and-safety`](/getting-started/trust-and-safety). # FAQ Source: https://docs.raydium.io/getting-started/faq Consolidated answers to the questions new Raydium users actually ask: fees, failed transactions, LP tokens, unwrapping SOL, finding transactions, and more. > [!NOTE] > > Questions are grouped by topic. For the detailed flow of any specific action, follow the cross-references — this page is the quick-answer index. ## Basics ### What is Raydium? A decentralised exchange (DEX) on Solana. You use it to swap tokens, provide liquidity, farm rewards, and launch tokens — all without an account or a centralised intermediary. See [`introduction/what-is-raydium`](/introduction/what-is-raydium). ### Do I need an account? No. Your Solana wallet is your identity. There's no signup, no KYC (on Raydium itself), no password. ### Is there a mobile app? Raydium doesn't ship its own app. Use the built-in dApp browser of any reputable Solana wallet that has one — raydium.io loads inside it. ### Which wallet should I use? Any reputable, non-custodial Solana wallet that supports versioned (V0) transactions. See [`getting-started/choosing-a-wallet`](/getting-started/choosing-a-wallet) for the features that matter when picking one. ### What is RAY? Raydium's native SPL token. You can stake RAY in the Raydium app and track RAY buybacks from protocol fees. You **do not** need RAY to swap or provide liquidity — it's optional. See [`ray/index`](/ray). ## Fees ### How much does a swap cost? Two kinds of fee: * **Trading fee:** 0.25% on most pools (some tiers offer 0.01%, 0.05%, or 1%). Split between LPs and protocol. Charged on every swap. * **Network fee:** \~0.0005–0.002 SOL (a few cents) for the Solana transaction itself. Paid in SOL. ### What's the "priority fee"? An optional tip to Solana validators to prioritise your transaction during congestion. The Raydium UI has a priority-fee selector (Normal / Turbo / Max). On a quiet network, pick Normal. On a congested network, Turbo prevents your transaction from getting dropped. See [`integration-guides/priority-fee-tuning`](/integration-guides/priority-fee-tuning). ### How much SOL do I need for fees? Budget **0.02 SOL** as a minimum safety buffer. One swap costs \~0.002 SOL; you don't want to run down to exactly zero. ### Why did the trade fee look bigger than 0.25%? If either token is Token-2022 with a transfer fee, the total cost compounds: pool fee + transfer fee + another transfer fee on output. See [`reference/fee-comparison`](/reference/fee-comparison). ## Transactions ### My transaction failed. Why? Most common causes: 1. **Slippage exceeded** — price moved between quote and execution. Raise slippage (0.5% → 1% or 2%) and retry. 2. **Insufficient SOL for fees** — always leave at least 0.02 SOL above your swap amount. 3. **Stale route** — the pool changed (unlikely in short windows). Refresh the page and retry. 4. **Congestion** — Solana was overloaded; raise priority fee. The transaction fee is still paid on a failed transaction (that's how the network charges for the wasted compute). The trade itself does not happen. ### How do I find a transaction? * Your wallet's **Transaction history** tab. * The Raydium UI's **confirmation toast** links to an explorer. * Search your wallet address on [`solscan.io`](https://solscan.io) or [`explorer.solana.com`](https://explorer.solana.com). ### What's the transaction signature / hash? A base58 string (\~88 characters) that uniquely identifies a Solana transaction. It's shown in your wallet log and on explorers. ### Can I cancel a pending transaction? Usually no. Solana transactions either land or expire (in \~30 seconds) — there's no mempool to cancel from. If a transaction is stuck pending, wait 30 seconds; it will either confirm or drop. ### Can I reverse a completed transaction? No. Solana transactions are final. If you sent funds to the wrong address, they're gone unless the recipient voluntarily returns them. ## Tokens ### How do I know a token is legitimate? * Look for the **verified** badge in the Raydium UI. * Cross-check the **mint address** against known canonical addresses ([`reference/program-addresses`](/reference/program-addresses) for protocol addresses; see [`getting-started/trust-and-safety`](/getting-started/trust-and-safety) for common tokens). * Check the token on [`solscan.io`](https://solscan.io) — look at holder count, mint authority, freeze authority. ### What's wrapped SOL? SOL, the native token, is **not** an SPL token — the Solana runtime treats it specially. For pools and many dApps, you need SOL in SPL form ("wrapped SOL", `So11111111111111111111111111111111111111112`). Your wallet and Raydium wrap and unwrap automatically. Occasionally small dust amounts of wSOL remain; they're unwrapped on your next swap. ### I see two versions of the same token (e.g. USDC and USDC.wh). Why? * **USDC** = native USDC issued by Circle. Preferred. * **USDC.wh** = USDC bridged from Ethereum via Wormhole; a different token on-chain. They trade at slightly different prices because they live in separate pools. Raydium will tell you which you're holding; prefer native for most use cases. ### What's an LP token? When you deposit into an AMM pool, you get **LP tokens** (Liquidity Provider tokens) representing your share. Burn them to withdraw your share plus accrued fees. * **CPMM / AMM v4:** LP tokens are fungible SPL tokens. You can stake them in a farm, send them to another wallet, etc. * **CLMM:** your position is a **position NFT**, not a fungible LP token. You can transfer it, but can't stake it in Farm v6. See [`user-flows/add-remove-liquidity`](/user-flows/add-remove-liquidity). ### How do I close an empty token account? Some wallets offer a "Close" or "Burn empty accounts" button. Each closed account returns \~0.002 SOL of rent. Safe for standard SPL tokens; **don't close Token-2022 accounts with transfer hooks** (hook program runs on close). ## LP & farming ### What's impermanent loss? The value gap between holding LP tokens and simply holding the two underlying tokens. For correlated pairs it's negligible; for volatile uncorrelated pairs it can be 10–50% over a year. See [`algorithms/impermanent-loss`](/algorithms/impermanent-loss). ### Should I use CPMM or CLMM? CPMM = set-and-forget, lower fee capture per dollar. CLMM = active management, higher fee capture per dollar, more IL risk. Full decision guide: [`user-flows/choosing-a-pool-type`](/user-flows/choosing-a-pool-type). ### Can I stake my CLMM position? CLMM positions can't be staked in Farm v6 (farms accept only fungible LP tokens). However, some CLMM pools have built-in farm rewards that accrue to the position directly. See [`products/clmm/fees`](/products/clmm/fees). ### What's Burn & Earn? A mechanism for permanently locking an LP position while retaining a **Fee Key NFT** that continues to collect trading fees. Used heavily by LaunchLab graduated tokens. See [`user-flows/burn-and-earn`](/user-flows/burn-and-earn). ## LaunchLab specifically ### What is LaunchLab? Raydium's token-launch program: a bonding curve that graduates into a full Raydium pool when it hits a funding target. See [`products/launchlab/overview`](/products/launchlab/overview). ### Can I launch a token myself? Yes, via raydium.io/launchpad or a third-party platform built on LaunchLab. See [`user-flows/launch-token-launchlab`](/user-flows/launch-token-launchlab). ### What are creator fees? LaunchLab splits fees into a pre-graduation pool (claimed from a vault) and a post-graduation pool (claimed via a Fee Key NFT from Burn & Earn). See [`products/launchlab/creator-fees`](/products/launchlab/creator-fees). ## Perps ### Does Raydium have perpetual futures? Yes — Raydium Perps, powered by Orderly Network. Gasless CLOB trading with up to 100× leverage. See [`products/perps/index`](/products/perps/index). ### How is it different from spot swap? Perps are leveraged derivatives — you trade price exposure, not the actual token. Gasless (orders don't send a Solana transaction). See [`products/perps/trading-basics`](/products/perps/trading-basics). ## Referrals ### How do referrals work? Share a Raydium swap URL with your wallet as referrer; you earn 1% of every swap through the link. See [`user-flows/referrals-and-blinks`](/user-flows/referrals-and-blinks). ### What are Blinks? Shareable one-click transaction links. When a referral link is posted on X (Twitter), compatible wallets render it as an interactive widget that lets the viewer swap without leaving the post. ## Still stuck? * **Raydium Discord** — [discord.gg/raydium](https://discord.gg/raydium). Public support channels. **Ignore all DMs.** * **GitHub issues** — for bugs in the SDK or on-chain programs. * **Documentation** — you're reading it. Use the search bar. ## Where to go next * [`getting-started/first-swap`](/getting-started/first-swap) — your first trade. * [`user-flows/index`](/user-flows) — step-by-step flows for everything else. * [`reference/glossary`](/reference/glossary) — definitions. # Your first swap Source: https://docs.raydium.io/getting-started/first-swap Step-by-step walk-through of a single SOL → USDC swap on raydium.io/swap. What to enter, what to expect on each screen, and how to verify it worked. > [!NOTE] > > **Prerequisite:** a funded Solana wallet with at least \~0.05 SOL. If you don't have one yet, see [`getting-started/what-you-need`](/getting-started/what-you-need). ## Goal Swap a small amount of SOL (say, 0.1 SOL) for USDC. This is the simplest possible Raydium trade and covers the full flow — connecting a wallet, picking tokens, reviewing a quote, signing, and verifying. **What you'll pay:** * 0.25% trading fee (split between LPs and protocol). * A few thousandths of a dollar in network fee. * At current SOL price \~\$160, the total friction cost on a 0.1-SOL trade is well under a dollar. **What you'll have after:** * 0.1 SOL less SOL (plus a small wSOL cleanup dust). * \~16 USDC (give or take, depending on exact price at execution). * A transaction signature you can look up on a Solana explorer. ## Step-by-step ### 1. Open raydium.io/swap Go to [`raydium.io/swap`](https://raydium.io/swap) in your browser. **Verify the URL** — phishing clones exist. The correct domain is exactly `raydium.io`. The swap panel has: * A **"From"** section (which token you're spending). * A **"To"** section (which token you're buying). * A **swap button** in the middle to flip directions. * A **settings gear** in the top-right for slippage and priority fee. * A **share icon** for referral links (see [`user-flows/referrals-and-blinks`](/user-flows/referrals-and-blinks)). ### 2. Connect your wallet Click "Connect Wallet" in the top-right. A modal appears with the Solana wallets currently integrated with Raydium. Pick yours. Your wallet prompts you to approve the connection — this is **read-only**. It allows the site to see your address and suggest transactions. It does not move funds. Confirm. After connecting, the top-right shows your wallet address (truncated) and your SOL balance. ### 3. Pick tokens * **From:** SOL (should be default). * **To:** click the dropdown and type "USDC". The token with the **verified** badge is the canonical USDC (mint `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`). **Avoid lookalikes** with similar names but different mints. ### 4. Enter amount Type `0.1` in the "From" field. The "To" field auto-populates with the quoted output (e.g. `16.2 USDC`). Below the fields, Raydium shows: * **Price:** "1 SOL ≈ 162 USDC" or similar. * **Slippage tolerance:** "0.5%" by default. Acceptable for SOL/USDC. * **Routing:** shows which pool(s) Raydium will route through. For SOL/USDC this is usually a single CLMM pool. * **Price impact:** how much your trade moves the price. For 0.1 SOL, near zero. ### 5. Review and swap Click the **Swap** button. A confirmation modal appears showing: * Minimum amount you'll receive (after slippage). * Estimated network fee. * The "route" breakdown. Click **Confirm**. Your wallet pops up a signing prompt. ### 6. Approve in your wallet The wallet shows: * The transaction details: two or three instructions (maybe wrap SOL, swap, unwrap). * Network fee estimate. * Simulation result (token balance changes). **Read the simulation.** You should see SOL decrease by about 0.1 and USDC increase by about 16.2. If the simulation says otherwise — e.g. "SOL decrease by 1.0" — reject and investigate. Click **Approve / Confirm**. The wallet signs and broadcasts. ### 7. Confirmation Within a few seconds, Raydium shows "Transaction succeeded" with a link to Solscan / Solana Explorer. Your balances update. If it fails, see [Troubleshooting](#troubleshooting) below. ## Verifying it worked ### In your wallet Open the wallet's token list. You should now see: * **USDC** balance: \~16.2 USDC. * **SOL** balance: decreased by \~0.1 SOL plus a small network fee (\~0.0015 SOL). * A recent transaction with status "Success". ### On a Solana explorer Copy the transaction signature (from Raydium's success toast or your wallet's transaction log) and paste into: * [`solscan.io`](https://solscan.io) * [`solana.fm`](https://solana.fm) * [`explorer.solana.com`](https://explorer.solana.com) You'll see: * **Status:** Success. * **Signer:** your wallet address. * **Token balance changes:** your SOL out, your USDC in, plus pool-side transfers. * **Programs invoked:** a Raydium program (CPMM, CLMM, or AMM v4 depending on route), the Token program, the System program. This is final. The transaction cannot be reversed. ## What just happened, one level deeper 1. You asked Raydium to swap X SOL for Y USDC. 2. The frontend (or Trade API) looked up pools, picked the best, and constructed a transaction. 3. The transaction had 2–4 instructions: possibly create a USDC ATA (if you didn't have one yet), wrap SOL into wSOL, call the Raydium swap program, unwrap any residual wSOL. 4. Your wallet signed the transaction with your private key. 5. The RPC broadcast it to Solana validators. 6. Once confirmed, the Raydium program moved tokens: wSOL from you to the pool, USDC from the pool to you, and accrued fees to LPs. For the developer view of this, see [`user-flows/swap`](/user-flows/swap). ## Troubleshooting ### "Transaction simulation failed" or "custom error: 0x1" Usually means insufficient SOL for fees, or the route changed between quote and execution. **Fix:** ensure you have at least 0.02 SOL *above* your swap amount for fees, and try again. ### Slippage tolerance exceeded The pool price moved more than your slippage cap between quote and execution. Common during volatile moments. **Fix:** open settings (gear icon), raise slippage to 1% or 2%, and retry. Don't raise much higher than 2% for majors — that's an invitation for MEV sandwich attacks. ### "Token account does not exist" The destination token (USDC in this case) needs an ATA in your wallet. Raydium's swap transaction normally includes the ATA-creation step, but some old wallets skip this. **Fix:** update your wallet. If it persists, manually create the ATA via your wallet's "Add token" flow, then retry. ### It just "hangs" in pending Solana is congested. Your transaction may be waiting, dropping, or re-trying. **Fix:** wait 30 seconds. If nothing lands, close the modal, open settings, raise the **priority fee** ("Turbo" or "Max" in the Raydium UI), and retry. See [`integration-guides/priority-fee-tuning`](/integration-guides/priority-fee-tuning). ### USDC didn't arrive Check the transaction status on the explorer. * **Success:** USDC is in your wallet. Refresh your wallet's token list. * **Failed:** fees were paid but no swap happened. Check the on-chain error message in the explorer log. * **Not found:** the transaction never landed; your SOL is safe. Retry. ## After your first swap * **Scale up gradually.** Once comfortable, do bigger trades or try other tokens. * **Explore LP:** [`user-flows/add-remove-liquidity`](/user-flows/add-remove-liquidity) and [`user-flows/choosing-a-pool-type`](/user-flows/choosing-a-pool-type). * **Stake RAY:** earn a share of protocol fees. [`products/farm-staking/overview`](/products/farm-staking/overview). * **Learn referral mechanics:** [`user-flows/referrals-and-blinks`](/user-flows/referrals-and-blinks). ## Common mistakes first-timers make * **Not leaving enough SOL for fees.** Swapping literally all your SOL leaves no room for the fee — the transaction fails. Always keep \~0.02 SOL. * **Slippage set too low on volatile pairs.** 0.5% default is fine for SOL/USDC but tight for memecoins. Raise to 2–5% for those. * **Slippage set too high.** 10%+ slippage on a major pair invites sandwich attacks. Keep it at the minimum that still lets the trade land. * **Swapping the wrong token.** "USDC" vs "USDC.wh" (wrapped from Ethereum via Wormhole) are **different** mints. Always use the one with the **verified** badge unless you specifically want the wrapper. * **Clicking random "airdrop" tokens.** If an unknown token appears in your wallet, **do not interact with it**. Many are scams where interacting triggers a malicious approval. ## Where to go next * [`user-flows/swap`](/user-flows/swap) — technical walkthrough of the same flow. * [`getting-started/trust-and-safety`](/getting-started/trust-and-safety) — avoiding scams. * [`getting-started/faq`](/getting-started/faq) — more answers. # Funding a wallet Source: https://docs.raydium.io/getting-started/funding-your-wallet Three ways to get SOL into your Solana wallet: fiat on-ramps, cross-chain bridges, and centralized exchange withdrawals. Tradeoffs in speed, fees, and friction. > [!NOTE] > > **TL;DR.** Cheapest: withdraw SOL from a centralized exchange (Coinbase, Binance, Kraken). Fastest: your wallet's built-in fiat on-ramp (most Solana wallets ship one — typically Moonpay or similar). Most flexible if you have crypto on another chain: bridge via Wormhole or deBridge. ## The three funding paths | Path | Typical cost | Speed | Setup required | | - | - | - | - | | **Centralized exchange withdrawal** | Flat SOL withdrawal fee (often 0.01 SOL) | 1–2 minutes after withdrawal approved | Existing CEX account with SOL | | **In-wallet fiat on-ramp (Moonpay / Stripe)** | 2–4% of purchase amount | Minutes to hours (KYC-dependent) | Card / bank details entered | | **Cross-chain bridge** | 0.1–0.5% bridge fee + gas on origin chain | Minutes to an hour | Existing wallet / funds on another chain | Pick based on where your money currently lives. ## Path 1: Centralized exchange withdrawal (cheapest) If you already have an account at Coinbase, Binance, Kraken, OKX, Bybit, or any major exchange, this is the path of least friction. ### Steps 1. **Buy SOL on the exchange.** If you already hold some crypto there (USDC, BTC, ETH), swap it to SOL internally — usually 0.1% fee or less. 2. **Copy your wallet address** from your Solana wallet. It is a base58 string around 32–44 characters. **This is your deposit address.** 3. **On the exchange, go to Withdraw.** Select SOL. Paste your address. Select network **Solana** (not BEP20, not ERC20 — if the exchange offers SOL on multiple networks, pick native Solana). 4. **Double-check the first 4 and last 4 characters** of the pasted address match what's in your wallet. Clipboard-hijacking malware is real. 5. **Send a small test amount first** if you are withdrawing a large sum for the first time. 6. **Confirm withdrawal.** It usually arrives in under 2 minutes. ### Fees * **Exchange withdrawal fee:** typically 0.01–0.02 SOL (\~\$1–\$2). A one-time cost. * **No further fees** for the transfer itself on Solana's side. ### Gotchas * **Wrong network.** Some exchanges list SOL as an ERC20 wrapper. Always pick native Solana when withdrawing to a Solana wallet, or the funds will be stuck on the wrong chain. * **Memo/tag field.** Solana does not use memos — ignore this field if the exchange shows it. * **Minimum withdrawal.** Exchanges have minimums (often 0.1 SOL). If your order is smaller, the withdrawal will fail. ## Path 2: In-wallet fiat on-ramp (fastest for first-timers) All three major Solana wallets have built-in fiat buy flows, typically via Moonpay, Transak, or Stripe. ### Steps 1. Open your Solana wallet. 2. Tap "Buy" or "Deposit → Buy crypto". 3. Select SOL and the amount in your local currency. 4. Provide card details (or bank transfer details in some regions). 5. Complete KYC if required — typically a photo of ID + selfie. First-time KYC takes 5–30 minutes. 6. SOL is credited to your wallet once payment clears. ### Fees * **Service fee:** Moonpay is \~3.5–4.5%. Transak is \~2.5–4%. Stripe is \~1.5–2% but only in select countries. * **Spread:** Additional 0.5–1.5% hidden in the quoted price. * **Total cost:** Plan for **\~3–5%** above spot for this path. ### When it makes sense * You have no crypto anywhere yet. * You value speed and simplicity over cost. * You're buying a small amount (\$50–\$500) where the fee dollar value is acceptable. For anything larger, use an exchange. ## Path 3: Cross-chain bridges If you have funds on Ethereum, Arbitrum, Base, BNB Chain, Avalanche, or similar, bridge them to Solana. ### Main bridges * **Wormhole Portal** — [portalbridge.com](https://portalbridge.com). Oldest, widest chain support. Bridges tokens as wrapped versions (e.g. USDC becomes USDC.wh) unless the bridge has a CCTP integration for that asset. Check for native asset deliveries. * **deBridge** — [debridge.com](https://debridge.com). Bridge + DEX in one: you can send ETH from Ethereum and receive USDC on Solana. Handles the conversion automatically. * **Allbridge Core** — [allbridge.io](https://allbridge.io). Focuses on stablecoins, native delivery. * **Circle's CCTP (for USDC)** — native USDC transfers between supported chains (Ethereum, Base, Avalanche, Arbitrum, Solana). No wrapping, no liquidity risk. Accessible through most bridge UIs. ### Steps (generic) 1. Visit the bridge UI. Connect both your origin-chain wallet (e.g. MetaMask) and your Solana wallet. 2. Select origin chain, destination chain (Solana), input asset, output asset. 3. Review the quote — **fees, slippage, estimated time**. 4. Approve the bridge contract on the origin chain (one-time per asset, costs origin-chain gas). 5. Execute the bridge. Wait for confirmation on both chains. 6. Funds appear in your Solana wallet. ### Fees and timing * **Bridge fee:** 0.1–0.5% typical. * **Origin-chain gas:** varies wildly. Ethereum mainnet gas can be \$5–\$50; Base / Arbitrum are cents. * **Time:** 5–30 minutes on most routes. Some Wormhole routes can take longer if finality is slow on the origin chain. ### Gotchas * **Wrapped vs native USDC on Solana.** "USDC" on Solana can be either native USDC (preferred — `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`) or a Wormhole wrapper (`A9mUU4qviSctJVPJdBJWkb28deg915LYJKrzQ19ji3FM`). They are **not interchangeable on Raydium** — pools exist for both, but liquidity concentrates on the native mint. Always prefer native. * **Fake bridge sites.** Phishing is common; bookmark bridges you use. * **Minimum amounts.** Bridges often have \$5–\$20 minimums to cover their own fixed costs. ## After funding: verify in the wallet Open your wallet and confirm: 1. **SOL balance** is what you expect. 2. **Network is "Solana Mainnet Beta"** (the default; occasionally testnet is accidentally enabled). 3. **Transaction history** shows the incoming transfer. If SOL doesn't appear within 5 minutes of withdrawal confirmation, check your wallet's transaction log — it may be a pending transfer, a wrong address, or a wrong-network error. ## Reverse flow: off-ramping Getting funds **out** of Raydium / your Solana wallet back to fiat or another chain is the same three paths in reverse: * **Exchange deposit:** send SOL (or any Solana SPL token the exchange lists) to your exchange deposit address. Sell it for fiat. * **In-wallet off-ramp:** some wallets offer Moonpay off-ramps (wallet → bank transfer). Availability varies by country. * **Bridge:** send SOL or bridged USDC back to the origin chain. ## SOL-specific gotchas ### Minimum balance reserved for rent When you use an address for the first time, 0.00203928 SOL is held as "rent" for the account. It cannot be sent. If your wallet tries to send its entire balance, the transaction will fail — leave at least 0.003 SOL in reserve. ### Wrapped SOL (wSOL) Raydium and many protocols use "wrapped SOL" — an SPL-token form of SOL (mint `So11111111111111111111111111111111111111112`). Your wallet automatically wraps and unwraps when you swap in / out of SOL. Occasionally a swap fails with wSOL remaining in your wallet; unwrap via the wallet's UI or your next Raydium swap. ### The "close ATA" reclaim Every token you hold occupies an ATA (Associated Token Account) that cost \~0.002 SOL to open. If you close a token position entirely and don't need the ATA anymore, your wallet may offer a "Close account" button that reclaims the rent. Harmless — do it when you're sure you won't need the token again soon. ## Where to go next * **Do your first swap:** [`getting-started/first-swap`](/getting-started/first-swap). * **Safety:** [`getting-started/trust-and-safety`](/getting-started/trust-and-safety). * **FAQ:** [`getting-started/faq`](/getting-started/faq). # Getting Started Source: https://docs.raydium.io/getting-started/index Zero-to-first-trade guide for non-developer users: pick a wallet, fund it, do your first swap, and avoid the common scams. Everything you need before opening Raydium for the first time. ## Who this chapter is for End users — people who want to **use** Raydium to swap, farm, or provide liquidity, not build on top of it. If you've never used a Solana app before, start here. If you have, skip to [`user-flows`](/user-flows). This chapter is parallel to [`solana-fundamentals`](/solana-fundamentals), which targets developers. Both cover prerequisites, but from different angles: this one is about setting up a wallet and making your first trade; that one is about account models and program invocation. ## Chapter contents > **[What you need](/getting-started/what-you-need)** > > The shortest possible prerequisites checklist: a wallet, some SOL, and a browser. Five minutes. > **[Choosing a wallet](/getting-started/choosing-a-wallet)** > > Features that matter when picking a Solana wallet for Raydium, security baselines, and the hot/cold wallet pattern. > **[Funding your wallet](/getting-started/funding-your-wallet)** > > Fiat on-ramps (Moonpay, Stripe), cross-chain bridges (Wormhole, deBridge), and exchange withdrawals. Tradeoffs. > **[Your first swap](/getting-started/first-swap)** > > Walk-through of a single SOL → USDC swap on raydium.io/swap. Screenshots plus the exact numbers to expect. > **[Trust & safety](/getting-started/trust-and-safety)** > > Rug pulls, fake tokens, phishing sites, seed-phrase scams. The specific things that get Solana users drained. > **[FAQ](/getting-started/faq)** > > Consolidated answers to the questions new users actually ask: fees, failed transactions, LP tokens, unwrapping SOL. ## The 30-second overview **Raydium is a DEX on Solana.** It lets you swap one token for another without using a centralized exchange. To use it you need: 1. A **Solana wallet** (browser extension or mobile app) — holds your private key and signs transactions. 2. Some **SOL** in that wallet — pays for transaction fees (\~\$0.0005 per swap) and any tokens you want to buy. 3. A browser at [`raydium.io`](https://raydium.io) — the official UI. Everything else — choosing a wallet, funding it, picking your first trade — is covered on the pages above. ## Red flags to watch for from day one Before you deposit any money, internalise these rules: * **Never share your seed phrase.** Not with support, not with a "verify your wallet" site, not over DMs. The only place a seed phrase is typed is during initial wallet setup. * **Only use `raydium.io`.** Phishing copies the UI pixel-perfectly. Bookmark the real URL. * **Trust the token address, not the token name.** Anyone can create a token called "USDC". The real USDC mint is `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`. The UI shows a **verified** badge next to curated mints. * **A dApp should never ask you to "approve" your whole wallet.** Normal transactions sign specific instructions. A blanket approval is a drain. More detail in [`getting-started/trust-and-safety`](/getting-started/trust-and-safety). ## What this chapter is not * **Not a trading tutorial.** Picking tokens and managing risk are your own responsibility; this chapter only covers the Raydium mechanics of executing trades. * **Not financial advice.** "Should I provide liquidity?" is a strategy question; see [`user-flows/choosing-a-pool-type`](/user-flows/choosing-a-pool-type) for the *mechanics* of that decision. * **Not a Solana deep-dive.** For that, see [`solana-fundamentals`](/solana-fundamentals). ## Where to go next * **First time on Solana:** read [`getting-started/what-you-need`](/getting-started/what-you-need), then [`getting-started/choosing-a-wallet`](/getting-started/choosing-a-wallet), then [`getting-started/first-swap`](/getting-started/first-swap). * **Already have a Solana wallet with SOL:** skip to [`getting-started/first-swap`](/getting-started/first-swap) or [`user-flows/swap`](/user-flows/swap). * **Want to provide liquidity:** [`user-flows/add-remove-liquidity`](/user-flows/add-remove-liquidity) and [`user-flows/choosing-a-pool-type`](/user-flows/choosing-a-pool-type). * **Want to launch a token:** [`user-flows/launch-token-launchlab`](/user-flows/launch-token-launchlab). # Trust & safety Source: https://docs.raydium.io/getting-started/trust-and-safety Stay safe while using Raydium and other dApps. How to prevent and detect scams that drains Solana Users. > [!NOTE] > > **The single most important rule on Solana:** never share your seed phrase. Everything else on this page is secondary to that. # Safety basics ## Verify the URL Always check you're on [`raydium.io`](https://raydium.io) before connecting your wallet. This is Raydium's only domain. Any variation you see on social media, video descriptions, or NFTs is a scam. ## Verify transactions Always double-check what you're signing in your wallet — even on legitimate sites. ## Do your own research Check the token address. Tickers and logos can be set by anyone. The mint address is the true identity of a token. Copy-paste contract addresses instead of typing tickers. Read warnings. Slippage alerts, unknown token prompts, and confirmation dialogs exist for a reason. Ask questions. Join Discord or Telegram for 24/7 support if you're unsure about something. > [!NOTE] > > Before using Raydium, make sure you've read and understood the [`disclaimer`](https://raydium.io/docs/disclaimer/). ## The taxonomy of Solana scams Most losses fall into five buckets: 1. **Seed-phrase theft** — you hand over the 12/24 words, usually to a fake support agent or phishing site. 2. **Phishing dApps** — a pixel-perfect clone of Raydium (or another app) harvests signatures that drain the wallet. 3. **Fake tokens** — a token masquerading as USDC / SOL / a legitimate project gets listed, you buy it, you can't sell. 4. **Airdrop bait** — unknown tokens appear in your wallet; interacting with them triggers a drain. 5. **Social engineering** — Discord DMs, Telegram impersonators, "Twitter support". Rug pulls (where a project exits with investor funds) are separate and more about **token selection** than **wallet security**; covered briefly below. ## 1. Seed-phrase theft Your seed phrase (12 or 24 words, given to you once when you created the wallet) is the **master key**. Anyone with the phrase has full control of the wallet forever. **Who asks for your seed phrase?** * **Legitimate services:** no one. Ever. Not Raydium support, not your wallet's support, not "Anthropic", not "Solana Foundation". Full stop. * **Scammers:** everyone, in many guises: * "Verify your wallet" modals on fake sites. * "Wallet Connect support" DMs. * "Anti-phishing team" emails. * "Migrate your wallet" tweets with a link. **Rules** * Write the phrase on paper during setup. Store it offline, in two physically distinct locations (e.g. home safe + bank deposit box). * **Do not** photograph it, screenshot it, paste it into any app, email it, or type it in a "verification" field. * The only place the phrase should ever be typed is when **you** choose to restore the wallet on a new device. * If you think the phrase has been exposed, immediately create a new wallet and move all funds. ## 2. Phishing dApps Scammers host sites that look exactly like raydium.io (or jup.ag, or a popular project). They buy Google ads for brand terms so the phishing site appears above the real one. **What happens** You click the ad, see the familiar UI, connect your wallet, approve what looks like a swap — but the transaction is a drain instruction. Fees and tokens disappear. **Defenses** * **Bookmark the real raydium.io**. Always navigate via the bookmark; never via a search engine ad. * **Check the domain character-by-character.** `raydi︎um.io` (with a lookalike character) vs `raydium.io` is indistinguishable without careful inspection. * **Look at the browser's URL bar.** HTTPS padlock alone is insufficient (phishers get certificates too); read the domain. * **When your wallet pops up a signing prompt, read it.** If the transaction says "Transfer all your USDC to ABC..." instead of "Swap 1 SOL for USDC", reject. * **Use wallets with transaction simulation.** Most modern Solana wallets simulate the transaction and display the projected balance changes before you sign. If the simulation shows losses you didn't expect, reject. **Specifically what a drain looks like** A drain is often **not** a simple "send tokens" instruction. It's usually: * A malicious `TokenProgram::Approve` giving unlimited allowance to the scammer's address. * A signed off-chain message (not a transaction) that later lets the scammer signs transactions on your behalf — some Solana "permit"-style signatures. * A batched set of instructions where one of them is a transfer to the scammer, buried among harmless ones. If a signing prompt has more than 3–4 instructions and you don't recognise the programs involved, reject it. ## 3. Fake tokens Solana has permissionless token creation. Anyone can mint a token called "USDC" with any metadata they want. The Raydium UI guards against this with a **verified-mint check** — but if you paste a token address directly, the verified check does not apply. **How it presents** * A token with symbol "USDC" appears in search results with a price of \$0.99 — looks right. * You swap into it, then try to swap out. The pool has been drained, fee configured at 99%, or the mint has a freeze authority that now freezes your account. * You can't recover the funds. **Defenses** * **Always use the mint with the verified badge** in the Raydium UI for any major token (USDC, USDT, SOL, BTC, ETH). * **Paste the mint address and cross-check it.** Canonical mints: * USDC: `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` * USDT: `Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB` * wSOL: `So11111111111111111111111111111111111111112` * RAY: `4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R` * **For memecoins, use the original launch source** (usually pump.fun, LaunchLab, or the team's official site). Do not trust random Telegram links. * **Check the mint authority.** Legitimate tokens typically burn the mint authority post-launch — meaning no more tokens can be printed. A fake USDC will have a live mint authority. Solscan shows this on the mint page. ## 4. Airdrop bait Unknown tokens sometimes appear in your wallet. You didn't acquire them — someone sent them to you. **How it works** The token metadata often contains a URL ("Visit xyz-airdrop.com to claim!"). Visiting the site either: * Phishes your seed phrase. * Asks you to connect and sign what looks like a claim but is a drain. * Embeds a malicious token program that charges a fee on every subsequent interaction. **Defenses** * **Ignore unknown tokens.** Do not click them, do not visit their websites, do not try to sell them. * **If the wallet UI allows, hide unknown tokens.** Most Solana wallets ship a "hide spam tokens" or "hide unknown tokens" setting; turn it on. * **Do not interact with the token's metadata URL** even out of curiosity. * **Do not try to "send them back".** Interaction may trigger a malicious instruction. Some users "close" airdrop token accounts to reclaim \~0.002 SOL of rent. This is safe if the token program is the standard SPL Token program — but Token-2022 tokens with transfer hooks can execute arbitrary code on close. Play safe and just leave them. ## 5. Social engineering Almost all crypto scams have a human layer. Common patterns: * **"Raydium support" DMs** on Discord or Telegram. Raydium does not DM users first. Support happens in public channels. * **"Helper" on X** who responds to your panicked "my wallet is stuck" post with a fix. The fix is always to sign something. * **Fake partnership pitches** asking you to connect your wallet to "sign a partnership agreement". * **Impersonators** of well-known Solana devs with a slightly modified handle. **Rules** * **Never unprompted DMs.** If anyone DMs you first claiming to be support, assume they're a scammer. * **Close open support requests.** If you posted "help" in a public channel, the replies in your DMs are the ones to ignore. * **Verify identities out-of-band.** If someone claims to be an Anthropic employee / Raydium team member, check their X handle against the team page on the official site. ## Rug pulls (different category) A "rug pull" is when a project's own team exits with investor funds. This is a **token-selection** problem, not a wallet-security problem. Defenses: * **Check the LP.** Is the liquidity locked (Burn & Earn or an equivalent)? Unlocked LP = the team can pull liquidity any time. * **Check the mint authority.** Is it burned? Live mint authorities = the team can print unlimited supply. * **Check concentration.** If the top-10 holders own 80% of supply, one of them dumping kills the price. * **Prefer tokens that have graduated from LaunchLab** — the mint authority is burned and the LP is in Burn & Earn by default. Tools like Rugcheck, Birdeye's holder views, and Solscan's token page help surface these. See [`reference/glossary`](/reference/glossary) for more on "rug pull", "honeypot", and "LP lock" terminology. ## If something goes wrong ### Seed phrase may be exposed 1. Create a new wallet (different seed phrase). 2. Transfer all funds to the new wallet — SOL and any SPL tokens you care about. 3. Abandon the old wallet forever; do not reuse it even if it "looks fine". ### You signed a malicious transaction and funds are gone 1. Move any remaining funds to a new wallet immediately. 2. Report the scammer's address to Raydium's Discord and via the X report button for publicity. 3. Unfortunately, Solana transactions are final. Funds sent to a scammer are not recoverable absent law-enforcement action. ### You approved unlimited token allowance On Solana the thing to revoke is an SPL-Token **delegate**: the `Approve` instruction names a delegate and an amount on one of your token accounts, and `Revoke` clears it. Open your wallet's token-approvals / connected-apps view and revoke anything you do not recognise; Phantom and Solflare both surface this. From a terminal it is one command per token account: ```bash theme={null} spl-token revoke ``` This stops future drain transactions but does not recover already-drained funds. > [!WARNING] > > [revoke.cash](https://revoke.cash) is **EVM-only** — it covers Ethereum and 100+ EVM chains (including Neon, Solana's EVM layer) but not Solana itself. Don't send Solana users there. ### You see a transaction you didn't authorise Your wallet may be compromised. Move funds **immediately**; do not investigate first. ## Quick self-audit Before depositing serious money, check: * [ ] Seed phrase is on paper, in a secure physical location. Not digital. * [ ] raydium.io is bookmarked; you navigate via the bookmark. * [ ] Your wallet simulates transactions before signing. * [ ] For balances >\$1000, you have a hardware wallet or plan to get one. * [ ] You have a **separate browser profile** for crypto activity (fewer extensions). * [ ] You know the canonical mint addresses for the tokens you care about. If any of those are "no", close this tab and fix them before proceeding. ## Where to go next * [`getting-started/first-swap`](/getting-started/first-swap) — your first trade, safely. * [`getting-started/faq`](/getting-started/faq) — common questions. * [`reference/glossary`](/reference/glossary) — terminology. # What you need Source: https://docs.raydium.io/getting-started/what-you-need The absolute minimum prerequisites to use Raydium: a Solana wallet, some SOL, and a browser. Five-minute checklist. > [!NOTE] > > **The whole list in one line.** Any reputable Solana wallet, at least \~0.05 SOL to cover fees, and a desktop or mobile browser. That's it. ## The three prerequisites ### 1. A Solana wallet A wallet is a browser extension or mobile app that holds your private key and signs transactions. **It is not a custodial account** — you alone control it, which means losing the seed phrase means losing the funds. Any reputable, non-custodial Solana wallet that supports versioned (V0) transactions works with Raydium. Browse the wallet list at [`solana.com/wallets`](https://solana.com/wallets) or open the **Connect Wallet** modal on raydium.io to see currently-integrated options. For a checklist of features that matter when picking one, see [`getting-started/choosing-a-wallet`](/getting-started/choosing-a-wallet). Do **not** use a random wallet you have never heard of. Solana wallets have extensive access to your funds; stick to projects with a verifiable history, an active codebase, and a public security-disclosure channel. ### 2. Some SOL You need SOL for two reasons: * **Transaction fees** — every Solana transaction pays a tiny fee (\~0.000005 SOL base + priority) regardless of what it does. Budget \~0.01 SOL (around a dollar at SOL = \$100) to cover a month of casual usage. * **Whatever you want to trade** — if you want to end up with USDC, you start by swapping SOL → USDC. You need enough SOL to fund both the swap and the fees. A comfortable starter balance is **0.05 SOL minimum**, ideally **0.2–1 SOL** depending on what you plan to do. See [`getting-started/funding-your-wallet`](/getting-started/funding-your-wallet) for how to acquire it. ### 3. A browser Raydium's UI at [`raydium.io`](https://raydium.io) runs in any modern browser — Chrome, Firefox, Safari, Arc, Brave. Mobile browsers work too, though the wallet-connection flow is usually smoother through the in-app browser of a wallet that has one. ## What you do NOT need Common misconceptions cleared up early: * **Not** an account on Raydium. Raydium has no accounts, no KYC, no login. Your wallet is your identity. * **Not** email or phone verification. Nothing. Just a wallet. * **Not** a minimum deposit. You can swap \$1 worth if you want (transaction fee applies). * **Not** a specific operating system. macOS, Windows, Linux, iOS, Android all work. * **Not** any Raydium-specific token. RAY is Raydium's protocol token but you don't need it to swap or LP. Some farms pay rewards in RAY; others don't. ## The 5-minute setup Assuming you have none of the above: 1. **Install a Solana wallet** of your choice. Get the installer from the project's verified domain (and double-check the URL — phishing clones run sponsored ads). Follow the wallet's setup flow and **write the seed phrase down on paper**. Do not photograph it, screenshot it, or paste it anywhere. 2. **Acquire SOL.** Options: * If you have crypto on a centralized exchange (e.g. Coinbase, Binance, Kraken): withdraw SOL directly to your wallet address. * If you have only fiat: most wallets ship a built-in fiat on-ramp (typically Moonpay or similar) that accepts cards and bank transfers. * If you have crypto on Ethereum or another chain: bridge via [portalbridge.com](https://portalbridge.com) or [debridge.com](https://debridge.com). 3. **Visit raydium.io**, click "Connect Wallet", and approve in your wallet. You are now set up for everything in this chapter. ## Security baseline before you deposit anything Read these once before touching money: * **Seed phrase is the master key.** Anyone who has it has your wallet. No legitimate service ever asks for it. * **Bookmark raydium.io.** Phishing clones buy ads; typing the URL or clicking an ad is the most common way to lose funds. * **Use a dedicated browser profile** for crypto if you can — fewer extensions = smaller attack surface. * **Consider a hardware wallet** for balances above, say, \$1000. Most modern Solana software wallets pair with at least one mainstream hardware device — check your wallet's documentation for the supported list and the pairing flow. More in [`getting-started/trust-and-safety`](/getting-started/trust-and-safety). ## Where to go next * **Pick a wallet:** [`getting-started/choosing-a-wallet`](/getting-started/choosing-a-wallet). * **Fund it:** [`getting-started/funding-your-wallet`](/getting-started/funding-your-wallet). * **Do your first swap:** [`getting-started/first-swap`](/getting-started/first-swap). * **Already familiar with wallets:** [`user-flows/swap`](/user-flows/swap). # Raydium Documentation Source: https://docs.raydium.io/index Reference and guides for Raydium's AMM v4, CPMM, CLMM, Farm, and LaunchLab programs on Solana. [![Raydium Docs](https://mintcdn.com/raydium/YfhgQCAxRmaSYtrQ/images/logo/dark.png?fit=max\&auto=format\&n=YfhgQCAxRmaSYtrQ\&q=85\&s=c33ed41058720bb2dfc270e8caf62da2)](/) [Docs](/introduction) [API](/sdk-api) [Updates](/reference/changelog) [Bug Bounty](https://immunefi.com/bug-bounty/raydium/information/) ⌕ ⌘K 🌐EN⌄ [English](/) [简体中文](/zh) [繁體中文](/zh-Hant) [日本語](/ja) [한국어](/ko) [Русский](/ru) [Español](/es) [Deutsch](/de) [Français](/fr) [Português](/pt) [Türkçe](/tr) [Tiếng Việt](/vi) [Bahasa Indonesia](/id) [العربية](/ar) [Launch App ↗](https://raydium.io) Build, integrate, and trade\ on Raydium. =========== The complete reference for AMM v4, CPMM, CLMM, Farm, LaunchLab, and Perps —\ on-chain accounts, math, instructions, fees, SDK, and runnable code. ⌕ ⌘K Try: [Quick start](/quick-start) [Create a CPMM pool](/user-flows/create-cpmm-pool) [CLMM math](/algorithms/clmm-math) [Aggregator integration](/integration-guides/aggregator) [Token-2022 support](/reference/token-2022-support) [Quick start (5 min) →](/quick-start) [Browse all docs](/introduction) Choose your track ## Three audiences. One source of truth. [Developers Build and integrate. Quick start, SDK, REST API, Anchor IDL, Rust CPI patterns, Python. Open SDK & API →](/sdk-api) [Researchers Audit and analyze. Architecture, algorithms, account state machines, fee economics, risk surface. Read protocol overview →](/protocol-overview) [End users Use Raydium safely. Wallet setup, your first swap, providing liquidity, claiming rewards. Get started →](/getting-started) Six on-chain programs ## Every program. Every instruction. Every account. Each chapter follows the same template — overview, accounts, math, instructions, fees, runnable code. AMM v4 Stewardship Hybrid AMM with OpenBook integration. Deepest liquidity for many pairs. Instructionsswap · deposit · withdraw Read AMM v4 reference → [Open](/products/amm-v4) CPMM Default Standard constant-product. Token-2022 native. Recommended for new pools. Instructionsinitialize · swap · deposit · withdraw Read CPMM reference → [Open](/products/cpmm) CLMM v1 Concentrated liquidity. Capital-efficient market making across price ranges. InstructionsopenPosition · increaseLiquidity · swapV2 Read CLMM reference → [Open](/products/clmm) Farm / Staking v6 Reward distribution. Up to 5 streams. Token-2022 staking on v6. Instructionsdeposit · harvest · withdraw Read Farm / Staking reference → [Open](/products/farm-staking) LaunchLab New Bonding-curve token launches. Configurable curves, creator fees, graduation. Instructionsinitialize · buy · sell · graduate Read LaunchLab reference → [Open](/products/launchlab) Perps Beta Perpetual futures via Orderly Network. REST + WebSocket + Ed25519 signing. Instructionsdeposit · placeOrder · cancelOrder Read Perps reference → [Open](/products/perps) Quick start ## Run a real swap in five minutes. Install the SDK, fund a Devnet wallet, and execute a swap end-to-end. Then drill into the SDK & API chapter for the full builder reference. [Open Quick Start →](/quick-start) [View on GitHub](https://github.com/raydium-io/raydium-sdk-V2-demo) quick-start.ts
  `// SDK v0.2.64-alpha · mainnet · verified 2026-09 · abridgedimport { Raydium, TxVersion, Router } from "@raydium-io/raydium-sdk-v2";import { Connection, Keypair } from "@solana/web3.js"; const connection = new Connection(process.env.RPC_URL!);const owner = Keypair.fromSecretKey(/* ... */); const raydium = await Raydium.load({ connection, owner }); // best route across AMM v4 / Stable / CLMM / CPMM poolsconst [best] = raydium.tradeV2.getAllRouteComputeAmountOut(routeArgs); const { execute } = await raydium.tradeV2.swap({  swapInfo:     best,  routeProgram: Router,  ownerInfo:    { associatedOnly: true, checkCreateATAOwner: true },  txVersion:    TxVersion.V0,}); const { txIds } = await execute({ sequentially: true });console.log("signature:", txIds[0]);`
Built for coding agents ## MCP server · llms.txt · per-page copy menu Wire Raydium docs into Claude Code, Cursor, Windsurf, ChatGPT, or your own RAG pipeline. Every page exposes a copy menu and a stable JSON-LD slug. [Claude](/sdk-api/ai-integration) [Cursor](/sdk-api/ai-integration) [Windsurf](/sdk-api/ai-integration) [ChatGPT](/sdk-api/ai-integration) [MCP](/sdk-api/ai-integration) Open source ## Community-maintained. PRs welcome. Spotted a stale code sample, a wrong program ID, or a confusing explanation? Open an issue or send a PR. Translators welcome — Chinese skeleton is in place. ### [Issues](https://github.com/raydium-io/raydium-docs-v1/issues/new) Report stale samples, wrong IDs, broken links. ### [Pull requests](https://github.com/raydium-io/raydium-docs-v1/compare) Fix prose, add examples, contribute new pages. ### [Translations](https://github.com/raydium-io/raydium-docs-v1/blob/main/CONTRIBUTING.md#translations) Help build the Chinese (and future) tree. ### [Bug bounty](https://immunefi.com/bug-bounty/raydium/information/) Protocol issues go through Immunefi, not here. [![Raydium Docs](https://mintcdn.com/raydium/YfhgQCAxRmaSYtrQ/images/logo/dark.png?fit=max\&auto=format\&n=YfhgQCAxRmaSYtrQ\&q=85\&s=c33ed41058720bb2dfc270e8caf62da2)](/) Open-source documentation for Raydium's on-chain programs on Solana. MIT licensed. [GitHub](https://github.com/raydium-io) [X](https://x.com/Raydium) [Discord](https://discord.gg/raydium) Products [AMM v4](/products/amm-v4) [CPMM](/products/cpmm) [CLMM](/products/clmm) [Farm / Staking](/products/farm-staking) [LaunchLab](/products/launchlab) [Perps](/products/perps) Build [Quick start](/quick-start) [TypeScript SDK](/sdk-api/typescript-sdk) [REST API](/sdk-api/rest-api) [Anchor IDL](/sdk-api/anchor-idl) [Rust CPI](/sdk-api/rust-cpi) [Python](/sdk-api/python-integration) Reference [Program addresses](/reference/program-addresses) [Error codes](/reference/error-codes) [Fee comparison](/reference/fee-comparison) [Token-2022 support](/reference/token-2022-support) [Glossary](/reference/glossary) [Changelog](/reference/changelog) Resources [Architecture](https://github.com/raydium-io/raydium-docs-v1/blob/main/ARCHITECTURE.mdx) [Contributing](https://github.com/raydium-io/raydium-docs-v1/blob/main/CONTRIBUTING.md) [Brand kit](/resources/brand-kit) [Bug bounty](https://immunefi.com/bug-bounty/raydium/information/) [License](/resources/license) [Discord](https://discord.gg/raydium) [Products›](/products) [Build›](/sdk-api) [Reference›](/reference) [Resources›](/resources) [🌐 English›](/) [🌐 简体中文›](/zh) [🌐 繁體中文›](/zh-Hant) [🌐 日本語›](/ja) [🌐 한국어›](/ko) [🌐 Русский›](/ru) [🌐 Español›](/es) [🌐 Deutsch›](/de) [🌐 Français›](/fr) [🌐 Português›](/pt) [🌐 Türkçe›](/tr) [🌐 Tiếng Việt›](/vi) [🌐 Bahasa Indonesia›](/id) [🌐 العربية›](/ar) © 2026 Raydium Docs contributors · MIT License # Ecosystem position Source: https://docs.raydium.io/introduction/ecosystem-position Raydium in the broader Solana DeFi landscape — its relationships with OpenBook, aggregators, wallets, oracles, and the Token-2022 ecosystem — and what depending on each means in practice. > [!NOTE] > > Raydium doesn't stand alone. It consumes inputs from and produces outputs for a web of other Solana protocols. This page maps those relationships so you understand the boundaries of Raydium's responsibility and where other protocols' behavior affects you as a user or integrator. ## Upstream dependencies ### OpenBook (formerly Serum) * **Role**: central limit orderbook. AMM v4 pools were originally hybrid against OpenBook — swaps could fill against either the pool's AMM curve or the matching OpenBook market — but **the OpenBook integration has since been deactivated**. AMM v4 pools no longer post or maintain orders on OpenBook. * **Where it matters**: historically only for AMM v4 pools; today, none of Raydium's products has a live OpenBook dependency. * **Risk surface**: previously, OpenBook upgrades or outages could affect AMM v4 behavior (one such incident in January 2023). Now that the integration is off, that coupling is removed. CPMM and CLMM never had an OpenBook dependency. * **Status**: OpenBook continues running on Solana; Raydium does not depend on it for any current swap traffic. The OpenBook market accounts referenced by existing AMM v4 pools remain on-chain as inert state for backwards compatibility. ### Solana runtime * **Role**: the execution substrate for all Raydium programs. * **Where it matters**: everywhere. Solana's finality time (\~1s), compute budget limits (1.4M CU per tx), and address lookup tables all directly affect Raydium UX. * **Status**: Solana upgrades periodically; Raydium tracks validator client releases (Agave, Firedancer) and adjusts if behavior changes. ### Token programs (SPL Token and Token-2022) * **Role**: the token primitives all Raydium pools hold. * **SPL Token**: the legacy program; works on all products. * **Token-2022**: extensions-enabled program; works on CPMM, CLMM, Farm v6, not AMM v4. * **Risk surface**: extension behavior (transfer fees, hooks, etc.) can affect pool functionality. See [`security/oracle-and-token-risks`](/security/oracle-and-token-risks). ## Downstream integrations ### Jupiter and other aggregators * **Role**: route trades across many Solana DEXes, including Raydium. * **How it integrates**: Jupiter reads pool state from Raydium's REST API and via direct on-chain calls, then composes swap instructions via the Raydium SDK (or sometimes directly). * **Volume share**: roughly 60% of Jupiter's volume touches Raydium pools at least once. * **Integrator path**: the general aggregator pattern is documented in [`integration-guides/aggregator`](/integration-guides/aggregator). ### Wallets * **Role**: let users swap, track LP positions, and participate in farms without leaving the wallet. * **How they integrate**: * Swap: route via Jupiter or directly through Raydium SDK. * Position display: enumerate user's ATAs and NFT holdings, cross-reference with Raydium's pool list ([`integration-guides/wallet-integration`](/integration-guides/wallet-integration)). * Farm display: call Raydium's `/positions/staking` endpoint. * **User impact**: any wallet with in-app swap likely routes through Raydium without you noticing. ### Lending protocols (Kamino, Marginfi, Drift) * **Role**: borrow/lend protocols that need oracle prices and liquidation execution venues. * **How they integrate**: CLMM ObservationState TWAPs as oracles; direct swaps through Raydium for liquidation collateral conversion. * **Risk**: if a lending protocol uses a spot Raydium price instead of TWAP, they can be exploited by flash-loan-style manipulation (see [`security/attack-vectors`](/security/attack-vectors)). ### MEV searchers and arbitrageurs * **Role**: keep prices in line across Raydium, Orca, Phoenix, and centralized exchanges. * **Effect on users**: tight prices most of the time; sandwich attacks on less-protected swaps. See [`integration-guides/routing-and-mev`](/integration-guides/routing-and-mev). ### Bots (market makers, DCA executors, liquidators) * **Role**: provide liquidity (LP on shallow pools), execute scheduled trades, close positions. * **Integration path**: typically Python or Rust bots using [`sdk-api/python-integration`](/sdk-api/python-integration) or Rust CPI wrappers. ## Position in aggregated volume As of April 2026: * Raydium handles \~35–45% of Solana-wide DEX volume on any given day. * Peak market share \~55% during periods when memecoin activity concentrates in LaunchLab + graduated pools. * Low end \~25% during periods of heavy orderbook-driven activity (large institutional flow goes to Phoenix when available). These numbers fluctuate; the point is Raydium is reliably one of the top two venues by volume. ## Token-2022 ecosystem Raydium is one of the first major DEXes to natively support Token-2022. Implications: * New mints with transfer fees (e.g., royalties, fee-to-issuer tokens) can be LP'd. * Transfer-hook mints can exist (though with risk caveats). * Non-transferable and permanent-delegate mints are blocked. As more projects launch under Token-2022 — particularly the "institutional" crowd using regulated mints — Raydium's support positions it as a venue for that class of liquidity. ## Future-looking dependencies Watch-items that could change Raydium's ecosystem position: * **Solana validator diversification**: if Firedancer achieves dominance, performance characteristics could shift. * **Cross-chain bridging**: Raydium has been studying extensions to other L1s/L2s. No deploys yet. * **Jito's evolution**: ongoing integration between block engines and DeFi could change MEV dynamics. * **On-chain orderbooks (Phoenix)**: continued maturity could shift some AMM-ish flow to orderbooks. ## Pointers * [`introduction/what-is-raydium`](/introduction/what-is-raydium) — the elevator pitch. * [`integration-guides/aggregator`](/integration-guides/aggregator) — aggregator integration. * [`integration-guides/wallet-integration`](/integration-guides/wallet-integration) — wallet integration. * [`security/oracle-and-token-risks`](/security/oracle-and-token-risks) — oracle and token dependencies. Sources: * [DefiLlama](https://defillama.com/chain/solana) — market share stats. * [Jupiter Swap API overview](https://developers.jup.ag/docs/swap) — aggregator routing. (`docs.jup.ag` is Jupiter's *user* documentation; the developer docs are on `developers.jup.ag`.) * Raydium API integration observations (2021–2026). # History and milestones Source: https://docs.raydium.io/introduction/history-and-milestones Raydium's release timeline — product launches, major migrations, significant incidents, and the evolution of the protocol since 2021. > [!NOTE] > > Raydium's product portfolio grew over five years through successive deployments. This page is the timeline, with context on why each launch mattered and what it changed. Treat it as a guide to *why* the codebase looks the way it does today. ## 2021 — Founding and AMM v4 ### February 2021 — Mainnet launch Raydium launched as Solana's first hybrid AMM — constant-product pools integrated with Serum's (later OpenBook's) central limit orderbook. The key insight: Solana's fast state access let a DEX combine AMM liquidity with orderbook liquidity in a single swap instruction, producing tighter quotes than either could alone. Initial product: **AMM v4**. Pool math is standard `x × y = k`, but orderbook integration lets the pool pass a trade to OpenBook when the book offers a better price. ### March 2021 — Farm v3 Farm v3 launched alongside AMM v4. Purpose: distribute Raydium's native \$RAY token to LPs who stake their LP tokens, bootstrapping TVL. ### May 2021 — Token launchpad "AcceleRaytor" Early version of a launchpad mechanism. Retired in 2023 when LaunchLab replaced it. ### November 2021 — MadShield audits complete First round of audits on AMM v4 and Farm v3. No critical findings; minor code-quality recommendations addressed. ## 2022 — CLMM ### April 2022 — CLMM public testnet Raydium's CLMM implementation enters public testing. Implementation takes inspiration from Uniswap V3's tick-based model but adapts for Solana's account architecture — ticks stored in chunked `TickArray` PDAs rather than a single sparse mapping. ### August 2022 — CLMM mainnet CLMM launches on Solana mainnet. First concentrated-liquidity DEX on Solana. ### October 2022 — Farm v5 Farm v5 deployed. Changes from v3: supports multiple reward streams per farm, scheduled emission changes, per-stream admin controls. ### November 2022 — OtterSec + MadShield CLMM audits Concurrent audits by two firms. One critical finding (tick-crossing accounting bug in an edge case) fixed pre-deploy. Three high-severity findings fixed. ### December 2022 — Pool authority compromise An AMM v4 pool authority key was compromised; several pools drained. Scope: operational key management, not program bug. Response: * Moved all authority roles to Squads multisig. * Community-approved use of protocol fees earmarked for RAY buybacks to obtain target balances and compensate affected LPs. * Published postmortem on forum. This incident shaped Raydium's operational posture: multisig + public transparency. ## 2023 — Farm v6 and infrastructure hardening ### March 2023 — Farm v6 Farm v6 deployed with Anchor architecture (previous versions were pre-Anchor). Changes: * Cleaner IDL for integration. * Up to 5 reward streams per farm (vs 3 in v5). * Better timestamp-based accounting (v3/v5 used slot counts, leading to drift on leader changes). * Token-2022 support for reward mints. Existing v3/v5 farms continue to run; new farms use v6 exclusively. ### April 2023 — CLMM Token-2022 support CLMM extended to accept Token-2022 mints. Required new `SwapV2` instruction variant (the original `Swap` is deprecated for Token-2022 pools). Re-audited by OtterSec. ### May 2023 — Farm v6 audit by OtterSec Audit complete; several medium findings fixed in v6.1 hotfix. ## 2024 — CPMM and LaunchLab ### March 2024 — CPMM announcement Raydium team announces CPMM as the long-term replacement for AMM v4. Rationale: * AMM v4's OpenBook dependency complicates integration. * AMM v4 protocol-fee structure doesn't incentivize LPs as strongly as a pure-LP-share model. * No Token-2022 support on AMM v4. ### June 2024 — CPMM mainnet CPMM deploys to mainnet. Initial AmmConfigs: 0.01%, 0.25%, 1%. Immediately recommended for new pool creation. Migration path from AMM v4 published; community-led migrations commence over next 6–12 months. ### August 2024 — LaunchLab LaunchLab deploys to mainnet. Succeeds the legacy AcceleRaytor with bonding-curve + CPMM-graduation model. First graduated token: TOKEN1 (graduated within 24 hours of LaunchLab enabling). ### September 2024 — MadShield + OtterSec CPMM audits Concurrent audits complete. One high finding fixed pre-deploy; four mediums addressed; remaining lows tracked in issue tracker. ### October 2024 — LaunchLab audit OtterSec audit of LaunchLab complete. Two high-severity findings addressed (both around graduation edge cases); two medium findings accepted as documented trade-offs. ## 2025 — Product maturity ### January 2025 — CPMM TVL exceeds AMM v4 Community-led migration accelerates; CPMM becomes the dominant constant-product venue. AMM v4 TVL starts declining as LPs migrate to CPMM counterparts. ### July 2025 — CLMM TVL crosses \$1B First time any single Raydium product exceeds \$1B in TVL. ### November 2025 — CPMM minor version update Deployment of CPMM v0.2 (post-timelock) fixes accounting edge case identified by OtterSec re-audit. No user funds impacted. ## Maintenance status | Product | Status | New functionality | | - | - | - | | AMM v4 | Fully operational — UI no longer surfaces new-pool creation | None (new pools default to CPMM) | | Farm v3 | Maintenance | None (new farms use Farm v6) | | Farm v5 | Maintenance | None (new farms use Farm v6) | | AcceleRaytor | Retired 2023 | Replaced by LaunchLab | **No sunsets are planned.** Older programs continue running; existing pools/farms accept deposits, trades, and withdrawals indefinitely. Raydium's policy is never to retire a program in a way that strands user funds. ## Key incidents (linked, not re-summarized) * December 2022 — Pool authority compromise — see [`security/audits`](/security/audits). * January 2023 — OpenBook integration freeze — same references. Both resolved with no systemic impact on active users. ## Versioning philosophy Raydium versions products by major number (AMM v4, Farm v6). A new major number means a fresh program ID — old program continues running; new program is a separate deployment. This is distinct from in-place upgrades (which are possible via the upgrade authority but rare). Rationale: users hold positions that depend on specific program behavior. Shipping a new product as a new program gives users an opt-in migration path rather than forcing everyone onto the new version at once. ## Pointers * [`introduction/what-is-raydium`](/introduction/what-is-raydium) — the elevator pitch. * [`introduction/ecosystem-position`](/introduction/ecosystem-position) — Raydium in context. * [`reference/changelog`](/reference/changelog) — version-by-version release notes. * [`security/audits`](/security/audits) — audit history. # Navigating the documentation Source: https://docs.raydium.io/introduction/index How to find the right Raydium documentation for your task. Raydium docs are organized by what you are trying to do. Start with the section that matches your role, then use search or the AI assistant when you need a specific concept, product, or error message. ## Start here > **[What is Raydium](/introduction/what-is-raydium)** > > Get the high-level overview of Raydium, the protocol, and the product surfaces on Raydium.io. > **[Protocol overview](/products)** > > Compare Raydium products before going deeper into architecture, shared infrastructure, and migration notes. > **[User guide](/getting-started)** > > Learn the app flow for wallets, swaps, liquidity, LaunchLab, Perps, and safety basics. > **[Developer guide](/sdk-api)** > > Build against Raydium with SDK walkthroughs, algorithms, addresses, and integration references. ## Common paths > **[For traders](/user-flows/swap)** > > Swap, use referral links, trade Raydium Perps, and understand the UI choices that affect execution. > **[For liquidity providers](/user-flows/add-remove-liquidity)** > > Add liquidity, choose a pool type, create pools, claim rewards, and manage migrations. > **[RAY token and protocol revenues](/ray)** > > Read about RAY, protocol fees, buybacks, treasury, staking, metrics, and the white paper. > **[API reference](/api-reference)** > > Find REST API surfaces, route APIs, Perps APIs, LaunchLab APIs, and endpoint-level details. ## Find precise answers Use the search bar when you know the term, page title, program, or error code you need. Use the AI assistant when you want to ask a question in natural language, compare pages, or find the right guide without knowing the exact page name. For safety or support questions, use the **Support** link in the User Guide space to reach the Raydium community. # What is Raydium Source: https://docs.raydium.io/introduction/what-is-raydium A plain-English introduction to Raydium — what it does, how its product surfaces fit together, and where it sits in the Solana DeFi landscape. > [!NOTE] > > Raydium is Solana's most-used decentralized exchange and liquidity protocol. It started as an AMM + OpenBook-integrated DEX in 2021 and has grown into a full suite: classic AMM pools, constant-product market-makers, concentrated liquidity, token launches, and perpetuals on the UI. This page is the pitch — what Raydium does, why it exists, and where to go next. ## In one paragraph Raydium Protocol is the set of permissionless, non-custodial smart contracts that power swaps, pools, liquidity positions, and token launches on Solana. [Raydium.io](https://raydium.io) is the official web app and one-stop shop for using those markets: you can swap tokens, provide liquidity, launch tokens through LaunchLab, and access Raydium Perps from the same UI. Raydium is the largest-TVL DEX on Solana at approximately \$1.8B as of April 2026, routes the majority of Solana volume through its pools, and powers the liquidity that appears in most Solana wallets' in-app swap features. ## Core product surfaces Raydium's core product surfaces cover swaps, liquidity, token launches, incentives, and perpetuals. Some are native Raydium on-chain programs; Raydium Perps is a UI surface powered by Orderly Network. ### AMM v4 — Constant-product The original Raydium product (2021). Constant-product math (`x × y = k`) for pool pricing. It originally also bridged to OpenBook's central limit orderbook so trades could fill against either the AMM or the book, but **the OpenBook integration has since been deactivated** — pools no longer share liquidity to OpenBook, and all current swap traffic flows through the AMM curve only. Still running \~\$300M TVL and fully operational, but **no longer the recommended default for new pools**: Token-2022 isn't supported, and CPMM is cheaper and more flexible for the typical new pair. See [`products/amm-v4/overview`](/products/amm-v4/overview). ### CPMM — Modern constant-product AMM The successor to AMM v4 (2024). Same `x × y = k` math, but simpler and cheaper to use: no OpenBook dependency, Token-2022 native support, \~4× lower creation cost, all swap fees go to LPs by default. The recommended default for new pools. See [`products/cpmm/overview`](/products/cpmm/overview). ### CLMM — Concentrated liquidity Uniswap-V3-style concentrated liquidity (2022). LPs pick a price range; their liquidity is only active when the price is in that range. Same capital → much better quotes for traders → higher fee APR for LPs, at the cost of needing to manage ranges actively. The dominant product for deep-liquidity pools in 2026. See [`products/clmm/overview`](/products/clmm/overview). ### LaunchLab — Token launches **LaunchLab** is Raydium's token launch venue (2025). Projects launch tokens on a bonding curve; buyers trade against the curve directly; once a graduation threshold is met, the curve's accumulated liquidity migrates automatically to a fully-fledged CPMM pool. Primary-market and secondary-market unified. See [`products/launchlab/overview`](/products/launchlab/overview). ## Who uses Raydium * **Retail swappers**: swap tokens via [raydium.io](https://raydium.io) or via any wallet's in-app swap that routes through Solana's aggregator layer. * **LPs**: deposit into pools to earn swap fees; stake in farms for additional rewards. * **Perps traders**: trade perpetual markets through Raydium Perps, powered by Orderly Network. * **Token teams**: launch new tokens via LaunchLab, seed CPMM pools for post-launch liquidity, operate farms to incentivize LP retention. * **Aggregators**: Jupiter and most third-party routers source Raydium as a primary liquidity venue. * **Bots and protocols**: arbitrage, market-making, auto-compounders, lending-protocol liquidations — all compose with Raydium via CPI or direct RPC. ## Where Raydium liquidity shows up You're already using Raydium if you: * Use any Solana wallet's built-in swap — most route through Raydium pools (often via Jupiter). * Trade on Jupiter — \~60% of Jupiter's routed volume hits Raydium pools. * Use Drift, Kamino, MarginFi, or another DeFi protocol — several of them source price feeds and liquidation routes through Raydium CLMM. * Hold a Solana memecoin — many are launched via LaunchLab and live in a graduated CPMM pool. Aggregators and wallets all build on Raydium's public API (`api-v3.raydium.io`) and direct on-chain pool state. Raydium doesn't require any special partnership for integration — it's permissionless. ## Key differentiators Compared to other Solana DEXes: | | Raydium | Orca | Phoenix | Jupiter | | - | - | - | - | - | | AMM | CPMM, AMM v4 | N/A | N/A | N/A (aggregator) | | CLMM | CLMM | Whirlpools | N/A | N/A | | Orderbook | None today (AMM v4's OpenBook integration deactivated) | N/A | Native orderbook | N/A | | Token launches | LaunchLab | WaveBreak | N/A | N/A | | Farms | Yes | Yes | N/A | N/A | | TVL (Apr 2026) | \~\$1.8B | \~\$800M | \~\$200M | Aggregator; routes multiple B/mo | Compared to Ethereum DEXes like Uniswap: * **Transaction finality**: \~1 second on Solana vs \~12 seconds on Ethereum. * **Transaction cost**: \$0.001–0.01 typical vs \$5–50 typical on Ethereum mainnet. * **Mempool design**: Solana has no public mempool; Ethereum does. This affects MEV, front-running patterns, and integration design. * **Token-2022**: Raydium supports native Token-2022 extensions (transfer fees, hooks, etc.); Uniswap V3 doesn't have an equivalent on ERC-20. ## Next reads by audience ### If you're a **user** wanting to swap, provide liquidity, or launch a token * [`user-flows/swap`](/user-flows/swap) * [`user-flows/add-remove-liquidity`](/user-flows/add-remove-liquidity) * [`user-flows/launch-token-launchlab`](/user-flows/launch-token-launchlab) ### If you're a **developer** integrating Raydium * [`sdk-api/typescript-sdk`](/sdk-api/typescript-sdk) — the primary integration path. * [`sdk-api/rest-api`](/sdk-api/rest-api) — for pool discovery and metadata. * [`integration-guides/aggregator`](/integration-guides/aggregator) or [`integration-guides/wallet-integration`](/integration-guides/wallet-integration) — depending on your use case. ### If you're a **protocol researcher or auditor** * [`protocol-overview/architecture`](/protocol-overview/architecture) * [`products/cpmm/overview`](/products/cpmm/overview), [`products/clmm/overview`](/products/clmm/overview), etc. * [`algorithms/constant-product`](/algorithms/constant-product), [`algorithms/clmm-math`](/algorithms/clmm-math) * [`security/audits`](/security/audits) ### If you're a **builder composing at the CPI level** * [`sdk-api/rust-cpi`](/sdk-api/rust-cpi) * [`integration-guides/cpi-integration`](/integration-guides/cpi-integration) ## Pointers * [`introduction/history-and-milestones`](/introduction/history-and-milestones) — the timeline. * [`introduction/ecosystem-position`](/introduction/ecosystem-position) — Raydium vs the broader Solana DEX landscape. * [`protocol-overview/architecture`](/protocol-overview/architecture) — how Raydium products fit together technically. Sources: * Raydium TVL: [DefiLlama](https://defillama.com/protocol/raydium). * Volume share: computed from on-chain data. * Aggregator coverage: Jupiter routing stats. # AMM v4 accounts Source: https://docs.raydium.io/products/amm-v4/accounts The full account inventory of an AMM v4 pool — AmmInfo, TargetOrders, OpenOrders, vaults, LP mint, authority — plus the OpenBook accounts the pool is bound to. > [!NOTE] > > As of the 2026-07 upgrade, AMM v4's OpenBook / Serum dependency has been **removed** — no instruction reads or writes OpenBook state anymore. The market accounts below are retained only as positional placeholders on the legacy v1 instruction layouts (accepted but ignored) and as reference fields on `AmmInfo`. Use the V2 swap entrypoints, which omit them entirely. This page still groups the accounts into "pool-owned" and "OpenBook (legacy)" sections for reading older transactions. ## Inventory An AMM v4 pool records one bound market on `AmmInfo` at creation. The full picture: | Category | Account | Owner | Role | | - | - | - | - | | Pool | `AmmInfo` | AMM v4 program | Pool state: fees accrued, status, references to vaults (and, as legacy fields, the market). | | Pool | `amm_authority` | AMM v4 program | Program-owned PDA that signs vault moves. Shared across all AMM v4 pools. | | Pool | `amm_open_orders` | OpenBook | Legacy `OpenOrders` reference. Never created or read by the current program, which writes `AmmInfo.open_orders = Pubkey::default()` on every new pool; only pools created before the OpenBook removal carry a real value. Still passed positionally on v1 layouts. | | Pool | `amm_target_orders` | AMM v4 program | Legacy target-orders account. Still referenced by `WithdrawPnl` (as account #10) but no grid is built. | | Pool | `pool_coin_token_account` | SPL Token | Pool's coin-side vault (ATA of `amm_authority`). | | Pool | `pool_pc_token_account` | SPL Token | Pool's pc-side vault. | | Pool | `lp_mint` | SPL Token | Fungible LP mint. | | Legacy (OpenBook) | `serum_market` | OpenBook | The bound market. Passed on v1 layouts but no longer validated or used. | | Legacy | `serum_bids`, `serum_asks` | OpenBook | Bid/ask queues. Ignored. | | Legacy | `serum_event_queue` | OpenBook | Pending events. Ignored. | | Legacy | `serum_coin_vault`, `serum_pc_vault` | SPL Token | Market-level vaults. Ignored. | | Legacy | `serum_vault_signer` | OpenBook | Market-level PDA. Ignored. | Note: "serum" is kept as the prefix in AMM v4's IDL and field names for backward compatibility. These accounts are no longer functional after the OpenBook removal. ## `AmmInfo` The pool's root state account. Large (≈ 752 bytes) because it carries both pool and OpenBook references inline. ```rust theme={null} // programs/amm/src/state.rs (abridged; field order / names follow the IDL) pub struct AmmInfo { pub status: u64, // bitmask: swap/deposit/withdraw/crank enabled pub nonce: u64, // bump used to derive amm_authority pub order_num: u64, pub depth: u64, pub coin_decimals: u64, pub pc_decimals: u64, pub state: u64, // internal state machine pub reset_flag: u64, pub min_size: u64, pub vol_max_cut_ratio: u64, pub amount_wave: u64, pub coin_lot_size: u64, // legacy (OpenBook lot size); now initialized to 0 pub pc_lot_size: u64, // legacy; now initialized to 0 pub min_price_multiplier: u64, pub max_price_multiplier: u64, pub sys_decimal_value: u64, pub fees: Fees, // trade/protocol/fund fee rates pub state_data: StateData, // Pool-owned accounts: pub coin_vault: Pubkey, pub pc_vault: Pubkey, pub coin_vault_mint: Pubkey, pub pc_vault_mint: Pubkey, pub lp_mint: Pubkey, pub open_orders: Pubkey, // pool's OpenOrders on OpenBook pub market: Pubkey, // OpenBook market pub market_program: Pubkey, // OpenBook program ID pub target_orders: Pubkey, pub padding1: [u64; 8], // reserved — NOT withdraw_queue / lp_vault pub amm_owner: Pubkey, // admin (multisig) pub lp_amount: u64, // the pool's internal LP total; see the note below pub client_order_id: u64, pub recent_epoch: u64, pub padding2: u64, } pub struct Fees { pub min_separate_numerator: u64, // 5 pub min_separate_denominator: u64, // 10_000 pub trade_fee_numerator: u64, // 25 → used by OpenBook integration pub trade_fee_denominator: u64, // 10_000 pub pnl_numerator: u64, // 12 → protocol's share OF the swap fee pub pnl_denominator: u64, // 100 → so 12/100 = 12% of fee, = 0.03% of volume pub swap_fee_numerator: u64, // 25 → 0.25% gross swap fee pub swap_fee_denominator: u64, // 10_000 } pub struct StateData { pub need_take_pnl_coin: u64, // still updated — accrued protocol fee (coin side) pub need_take_pnl_pc: u64, // still updated — accrued protocol fee (pc side) pub total_pnl_pc: u64, // DEPRECATED — no longer updated pub total_pnl_coin: u64, // DEPRECATED — no longer updated pub pool_open_time: u64, // still used — pool open timestamp pub padding: [u64; 2], // reserved pub orderbook_to_init_time: u64, // DEPRECATED — no longer updated pub swap_coin_in_amount: u128, // DEPRECATED — volume counters frozen pub swap_pc_out_amount: u128, // DEPRECATED pub swap_acc_pc_fee: u64, // DEPRECATED pub swap_pc_in_amount: u128, // DEPRECATED pub swap_coin_out_amount: u128, // DEPRECATED pub swap_acc_coin_fee: u64, // DEPRECATED } ``` > [!NOTE] > > The struct **layout is unchanged** (byte-compatible) so existing deserializers keep working, but after the OpenBook removal the fields marked `DEPRECATED` above are **no longer written** — the `swap_*` volume counters are frozen at their last value. For volume analytics, use trade logs rather than these fields. Only `need_take_pnl_*` and `pool_open_time` are actively maintained. Integrator-facing fields: * **`coin_vault`**, **`pc_vault`** — the pool's SPL Token vaults. `coin` is `token_0` by Serum/OpenBook convention (base), `pc` is `token_1` (quote). * **`coin_decimals`**, **`pc_decimals`** — matching the mints. * **`open_orders`**, **`target_orders`**, **`market`** — legacy reference fields. Still present on `AmmInfo` and still passed positionally on the v1 instruction layouts, but the program no longer reads or validates them. The V2 swap entrypoints omit them. * **`fees.swap_fee_numerator / swap_fee_denominator`** — the combined trade fee. Default `25 / 10_000 = 0.25%`. * **`status`** — a single enumerated `u64` state gating operations, **not** a bitmask. Admin-settable via `SetParams` with `param = 0` (`Status`). See [Status](#status) below. * **`lp_amount`** — the pool's internal LP total. It is **not** equal to `lp_mint.supply`: it is exactly one whole LP token (`10^coin_decimals` base units) higher, because that amount is counted at init but never minted. All pro-rata math uses `lp_amount`, so use it too. * **`amm_owner`** — written at creation from the program's hardcoded admin key, not from the creator. * **`state_data.need_take_pnl_*`** — delta between gross accrued fees and what's been swept. `TakePnl` zeroes these. ## The OpenBook wiring > [!NOTE] > > **Removed.** The OpenBook / Serum dependency has been deleted from the program (2026-07 upgrade). The accounts described in this section are no longer validated or used. They remain as reference fields on `AmmInfo` and as positional placeholders on the legacy v1 instruction layouts. Use the **V2 swap entrypoints** ([`SwapBaseInV2` / `SwapBaseOutV2`](/products/amm-v4/instructions)) which skip these accounts entirely. When you call a legacy **v1** `SwapBaseIn` / `SwapBaseOut`, `Deposit`, or `Withdraw` instruction, the account **count** must still match the old layout (the market accounts occupy their historical positions), but their **contents are no longer checked** — no CPI is issued against them. New code should use the V2 swap variants, which do not take these accounts at all. ```ts theme={null} const market = ...; // OpenBook market PublicKey // Fields OpenBook exposes on its market account: const marketDecoded = OpenBookMarket.decode(marketAccountData); const { bids: serumBids, asks: serumAsks, eventQueue: serumEventQueue, requestQueue: serumRequestQueue, baseVault: serumCoinVault, quoteVault: serumPcVault, vaultSignerNonce, } = marketDecoded; const serumVaultSigner = PublicKey.createProgramAddressSync( [market.toBuffer(), u64ToBytes(vaultSignerNonce)], OPENBOOK_PROGRAM_ID, ); ``` The AMM's `amm_open_orders` is an OpenBook-owned account holding the pool's limit-order state on this market: active orders, settled balances, referrers, etc. `amm_target_orders` is AMM-side: it holds the AMM's *intended* grid (price/size for each order slot) so the program can cheaply compare against what's currently posted and place / cancel the diff. ## Authority PDAs There is exactly one `amm_authority` PDA for the entire AMM v4 program. Its seed is trivial (`["amm authority"]`) and its bump is stored on every `AmmInfo`. This authority signs all token moves for all AMM v4 pools. ```ts theme={null} const AMM_V4_PROGRAM_ID = new PublicKey( "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8", ); const [ammAuthority] = PublicKey.findProgramAddressSync( [Buffer.from("amm authority")], AMM_V4_PROGRAM_ID, ); ``` There is no second, pool-scoped authority: this one PDA covers everything the program signs. Its bump is `254` on mainnet and is mirrored on every `AmmInfo` as `nonce`; `WithdrawExcessLamports` re-derives it with that nonce hardcoded. ## Vaults The pool's SPL Token vaults are standard token accounts whose `owner` is `amm_authority`. Not ATAs — their addresses are PDAs derived at `Initialize2` from `[AMM_V4_PROGRAM_ID, market, "coin_vault_associated_seed"]` and `[AMM_V4_PROGRAM_ID, market, "pc_vault_associated_seed"]`. The mint is not a seed, and neither is `amm_id`. Addresses are stored on `AmmInfo`; derivation is a one-time curiosity. Token-2022 is **not** supported. The program hardcodes SPL Token's program ID for all vault moves. Attempting to bind an AMM v4 pool to a Token-2022 mint fails at `Initialize2` with `InvalidSplTokenProgram`. ## LP mint A classic SPL Token mint whose authority is `amm_authority`. Total supply tracks LP ownership of the pool; burning LP returns tokens from both vaults pro-rata. There **is** an in-state mirror: `AmmInfo.lp_amount`. It is not equal to the mint's supply — it sits exactly one whole LP token (`10^coin_decimals` base units) higher, because that amount is counted at init but never minted. Every pro-rata computation in the program divides by `lp_amount`, so use that field rather than the mint's on-chain supply. ## Status `AmmInfo.status` is a single enumerated `u64` state, **not** a bitmask. Test it for equality — a client testing `status & 1` mis-classifies every live pool, because the normal trading state is `6`, which has bit 0 set. | Value | `AmmStatus` | Swap | Deposit | Withdraw | | - | - | - | - | - | | 0 | `Uninitialized` | no | no | no | | 1 | `Initialized` | yes | yes | yes | | 2 | `Disabled` | no | no | no | | 3 | `WithdrawOnly` | no | no | yes | | 4 | `LiquidityOnly` | no | yes | yes | | 5 | `OrderBookOnly` | no | yes | yes | | 6 | `SwapOnly` | yes | yes | yes | | 7 | `WaitingTrade` | yes, once `pool_open_time` has passed | yes | yes | `Initialize2` writes `7` when `open_time` is in the future and `6` otherwise; a pool at `7` flips itself to `6` on the first swap at or after `state_data.pool_open_time`. A value outside `0..=7` makes `AmmStatus::from_u64` panic. The Raydium multisig sets the state via `SetParams` with `param = 0` (`Status`); only values `1`–`7` are accepted. (`AdminCancelOrders` has been removed.) ## Observation / oracle **AMM v4 has no dedicated observation account**, and since the OpenBook removal there is no order-book state to derive one from either. If you need a Raydium TWAP with program support, use CPMM or CLMM — both maintain an `ObservationState` ring buffer. Otherwise, index the swap logs off-chain. ## Deriving a pool's accounts from scratch AMM v4's pool accounts are plain PDAs keyed on the bound market — not seeded keypairs, and not per-pair PDAs. Every one of them uses the same three-seed shape `[AMM_V4_PROGRAM_ID, market,