Raydium AMM How it works

·

17 min read

Raydium AMM How it works

Overview

The Raydium AMM is an on-chain smart contract based on the “constant product” in a permissionless and decentralized manner built on the Solana blockchain, And it also shares its liquidity according to the Fibonacci sequence in the form of limit orders on OpenBook, the primary central limit order book (CLOB) of Solana.

This article provides a comprehensive technical deep dive into Raydium's core functionalities:

  • Pool Creation (initialize2)

  • Trading Mechanisms (swap_base_in, swap_base_out)

  • Liquidity Management (deposit, withdraw)

  • Reward Distribution (withdrawPnL)

For each function, we explore:

  • Processing Logic and Flow

  • Account Validation

  • State Management

  • Key Interactions

  • Sequence Diagrams

The article focuses on three key files:

Through detailed flow diagrams and technical explanations, readers will gain insight into how Raydium maintains pool stability, handles trades, manages liquidity, and distributes rewards in a secure and efficient manner.

Contant product

The formular: $$x∗y=k$$

How it works

if you start with:

  • 100 tokens of x

  • 100 tokens of y

  • k = 10,000 (100 * 100)

When someone wants to trade token x for token y: $$(x+Δx)(y+Δy)=xy=k$$

  • If they add 10 tokens of x (now 110)

  • To maintain k = 10,000

  • The new amount of y must be: 10,000/110 = ~90.9 tokens

  • So ~9.1 tokens of y are given to the trader

This mechanism ensures:

  1. Larger trades have higher price impact

  2. The pool never runs out of liquidity

  3. Prices automatically adjust based on supply and demand

The beauty is in its simplicity - just one multiplication that keeps everything balanced and working smoothly.

Terms

In Raydium AMM, 'pc' stands for "Price Currency" and 'coin' refers to the base token being traded.

For example:

  • In a SOL/USDC pool:

    • USDC would be the 'pc' (price currency)

    • SOL would be the 'coin' (base token)

This naming convention is used throughout the codebase for clarity when handling token pairs in the AMM pools. You can see this in the swap functions where calculations are done between pc and coin balances.

The terms are particularly visible in the vault naming:

  • amm_pc_vault - holds the price currency tokens

  • amm_coin_vault - holds the base tokens

This standardized terminology helps maintain consistency when dealing with different trading pairs in the AMM system.

Files in scope

The files that will be used through out this artcle are:

  1. instruction.rs

  2. processor.rs

  3. invoker.rs

instruction.rs defines the interface that users interact with - it's like a menu of available actions. It contains:

  • The instruction enum (AmmInstruction)

  • Structs for each instruction's parameters

  • Helper functions to create instructions

processor.rs is the program's internal logic that executes these instructions. When a user sends an instruction:

  1. The program receives encoded instruction data

  2. The processor unpacks it using AmmInstruction::unpack()

  3. Matches the instruction type to the appropriate processing function

Invokers.rs serves as a utility module that handles Cross-Program Invocation (CPI) calls to other Solana programs.

  1. The processor calls an Invokers function with required accounts and parameters

  2. Invokers constructs the appropriate CPI instruction with proper account metadata and signatures

  3. Invokers executes the CPI using solana_program::program::invoke_signed() with:

    • The constructed instruction

    • Required account infos

    • Any necessary PDA seeds for signing

  4. The external program executes and returns the result back through the invocation chain

This separation exists because:

  1. Clear interface for users/developers

  2. Security - users can only interact through defined instructions

  3. Clean organization - interface vs implementation

  4. Modularity - can update processing logic without changing the interface

  5. This invoker abstraction ensures all external program interactions are:

    1. Type-safe

    2. Properly signed

    3. Consistently structured

    4. Easily maintainable

The instruction/processor pattern is a common design in Solana programs for these reasons.

Entry points for major users

There are 5 major functions used the most when interacting with Raydium

  1. initialize2 - Create new liquidity pools with initial token amounts and opening time

  2. swap_base_in - Trade with exact input amount (e.g. "I want to swap exactly 10 SOL")

  3. swap_base_out - Trade with exact output amount (e.g. "I want to receive exactly 100 USDC")

  4. deposit - Add liquidity to pools and receive LP tokens

  5. withdraw - Remove liquidity from pools by burning LP tokens

Let's look at the way it works.

initialize2

Let's analyze initialize2 in detail!

The initialize2 function is a critical setup process for the Raydium AMM that consists of several key phases:

  1. Account Creation Phase
  • This requires 20 accounts to be able to complete the instrauction

  • Creates Target Orders Account to manage order tracking

  • Sets up LP Mint Account for liquidity provider tokens

  • Establishes Coin and PC (Price Currency) Vault Accounts

  • Creates the main AMM Account

  • Sets up Open Orders Account for DEX integration

  1. Initial Liquidity Phase
  • Handles the initial token transfers:

    • Transfers init_coin_amount to coin vault

    • Transfers init_pc_amount to PC vault

  • These transfers establish the initial pool liquidity

  1. LP Token Phase
  • Calculates initial LP token amount based on provided liquidity

  • Mints LP tokens to the user's account as proof of liquidity provision

  1. Configuration Phase
  • Sets critical pool parameters:

    • Decimals and lot sizes for price precision

    • Pool open_time for activation timing

    • Initializes target orders structure

    • Sets initial pool status

The program call diagram

The flow involves interaction between multiple components:

  • instruction.rs: Handles the initial command and parameter validation

  • processor.rs: Contains core business logic and state management

  • invokers.rs: Manages external interactions and token operations

Key State Management:

  • The AMM maintains various state variables including:

    • Fee parameters (trade_fee, swap_fee, etc.)

    • Pool metrics (target_x, target_y, etc.)

    • Order tracking (plan_orders_cur, place_orders_cur)

This initialization process creates a fully configured AMM pool ready for trading operations.

swap_base_in

Entry Point via instruction.rs The swap begins when a user calls swap_base_in with their desired input amount and minimum output amount. The instruction module validates the data format and routes it to the processor for execution.

Processing Logic in processor.rs Account validation forms the foundation - checking 17 required accounts spanning token program, AMM accounts, market accounts, and user accounts. This includes verifying ownership, signer status, and ensuring the pool is in a valid state for swaps.

Amount Calculation Logic: The processor then determines available trading amounts through two possible paths:

  1. With Orderbook Enabled:
  • Validates AMM open orders, market program, and market accounts

  • Loads Serum market orders and checks bids/asks

  • Calculates total amounts considering both vault balances and open orders

  1. With Orderbook Disabled:
  • Calculates total amounts directly from vault balances

This calculation ensures debt prevention by accurately tracking all available funds before proceeding with trades.

The processor then moves to state management, calculating total amounts without PnL and determining the swap direction (Coin2PC or PC2Coin). If orderbook integration is enabled, it handles the necessary market interactions.

Fee processing comes next, using the AMM's configured swap fee parameters to calculate and deduct fees from the input amount before performing the swap calculations.

External Interactions via invokers.rs For OpenBook DEX integration, the system handles order cancellations and fund settlements between AMM and DEX accounts as needed. Token operations manage the actual transfers between user and pool accounts, including authority-based transfers for pool outputs.

Swap Flow Variations

Coin2PC Direction When users swap coins for PC, the system first cancels any relevant buy orders if the orderbook is enabled. After settling funds if necessary, it executes the token transfers - coins from user to AMM and PC from AMM to user.

PC2Coin Direction For PC to coin swaps, the process mirrors the above but with sell orders. The system manages the PC transfer from user to AMM and coin transfer from AMM to user.

State Updates Throughout the process, the system maintains accurate state tracking - recording swap amounts, accumulating fees, and updating the epoch. This ensures the pool maintains proper accounting and fee collection while providing atomic execution of swaps.

Key Interactions:

  1. instruction.rs initiates the swap

  2. processor.rs handles core logic and calls invokers.rs for:

    • DEX order cancellations

    • Fund settlements

    • Token transfers (both input and output)

  3. All external calls are routed through invokers.rs

swap_base_out

The swap execution begins after amount calculations and follows two distinct paths based on swap direction.

Processing Logic in processor.rs: The core execution logic handles token transfers and state updates through systematic steps.

Coin2PC Direction Path: First validates total PC availability in the pool. When orderbook is enabled, it proceeds to cancel any existing buy orders. The system then settles funds if needed to ensure available balance. Token transfers execute from user to AMM coin vault, followed by authority-based transfer from AMM PC vault to user. Finally, state data updates with swap amounts and fees.

PC2Coin Direction Path: Begins with validation of total coin availability. With orderbook enabled, it cancels existing sell orders. Fund settlement follows when needed for balance availability. Token transfers move from user to AMM PC vault, then authority-based transfers from AMM coin vault to user occur. State data updates complete the process with swap amounts and fees.

External Interactions via invokers.rs: The system manages all external interactions through dedicated functions. Direct transfers from user accounts use token_transfer, while AMM vault transfers employ token_transfer_with_authority. Cancel order functions clear existing orders when needed, and settlement functions ensure proper balance availability.

State Management: Throughout execution, the system maintains accurate state tracking. This includes recording swap amounts for both input and output, accumulating fees in respective token types, updating recent epoch data, and ensuring atomic execution of all operations.

Key Interactions: The processor.rs manages the core swap logic flow. The invokers.rs handles all external interactions including token transfers between user and AMM, order cancellations when needed, and fund settlements for balance availability. State updates maintain accurate pool accounting.

This systematic approach ensures reliable execution of swaps while maintaining proper pool state and security throughout the process.

Key State Management:

  • The AMM tracks essential state variables during swap_base_out:

    • Swap amounts (swap_coin_in_amount, swap_pc_out_amount)

    • Accumulated fees (swap_acc_coin_fee, swap_acc_pc_fee)

    • Pool balances (total_pc_without_take_pnl, total_coin_without_take_pnl)

    • Order tracking (bids, asks when orderbook enabled)

    • Recent epoch updates

This state management ensures accurate accounting and fee collection during output-specified swaps.

deposit

The deposit process begins when a liquidity provider initiates a deposit instruction with their desired input amounts and slippage tolerance.

Processing Logic in processor.rs: Account validation forms the foundation by checking permissions, ownership, and ensuring the pool accepts deposits. The system verifies token vaults, mints, and user accounts before proceeding.

Amount Calculation Path: With orderbook enabled, the system loads market orders and calculates total amounts considering both vault balances and open orders. Without orderbook, calculations use direct vault balances. Both paths normalize token decimals and handle PnL calculations to ensure accurate pricing.

Base Coin Direction: Starting with the coin amount, the system calculates required PC based on current pool ratios. Slippage checks ensure the PC amount stays within user limits. LP token calculation uses the proportional share of the deposit relative to total pool size.

Base PC Direction: Beginning with PC amount, required coin amount calculation follows pool ratios. Slippage validation ensures coin amount meets user parameters. LP token minting amount derives from the proportional contribution to the pool.

Token Movement: The system executes token transfers from user accounts to AMM vaults for both assets. Upon successful transfers, LP token minting occurs to the user's destination account, representing their pool share.

State Management: Throughout execution, the system maintains accurate state tracking. This includes updating LP token supply, recording deposit amounts, adjusting target orders calculation data, and updating the recent epoch.

Key Interactions: The processor manages core deposit logic flow while invokers handle external interactions including token transfers and LP minting. State updates maintain accurate pool accounting and ensure proper ratio maintenance.

This systematic approach provides reliable deposit execution while maintaining pool stability and security throughout the process.

Key State Management:

  • The AMM maintains critical state variables including:

    • LP token supply (amm.lp_amount)

    • PnL calculations (calc_pnl_x, calc_pnl_y)

    • Pool metrics (total_pc_without_take_pnl, total_coin_without_take_pnl)

    • Recent epoch tracking

    • Pool status and deposit permissions

This state tracking ensures accurate pool accounting throughout deposit operations.

withdraw

The withdraw instruction in instruction.rs structures the required accounts:

  • SPL Token Program

  • AMM accounts (pool, authority, open orders, target orders, LP mint, coin/pc vaults)

  • Market accounts (program, market, event queue, vaults, signer)

  • User accounts (source LP, destination coin/pc, owner)

The processor.rs implements the core withdraw logic with these key steps:

Processing Flow: First validates account permissions and pool status for withdrawals. Calculates total amounts available considering orderbook if enabled. For orderbook pools, cancels all orders and settles funds to ensure maximum liquidity availability.

Token Movement Path: Based on LP tokens being burned, calculates proportional coin and pc amounts. Executes transfers from AMM vaults to user destinations using authority signatures. Burns the LP tokens from user's source account.

State Management: Updates LP token supply, adjusts target orders calculation data, and maintains recent epoch tracking. This ensures accurate pool accounting through the withdrawal process.

Key Interactions: The processor manages withdrawal logic while invokers handle token transfers, burns, and DEX interactions when needed.

Key State Management:

  • The AMM maintains critical state variables during withdrawals:

    • LP token supply (amm.lp_amount)

    • PnL calculations (target_orders.calc_pnl_x, target_orders.calc_pnl_y)

    • Pool balances (total_pc_without_take_pnl, total_coin_without_take_pnl)

    • Order tracking (when orderbook enabled)

    • Recent epoch updates

This state tracking ensures proportional withdrawals and accurate pool accounting throughout the process.

withdrawpnl

The withdrawPnL function enables liquidity providers to claim their accumulated trading fees and profits from the AMM pool.

Processing Logic in processor.rs: Account validation starts by checking 17 required accounts spanning token program, AMM accounts, market accounts, and user accounts. This includes verifying ownership, signer status, and ensuring the pool is in a valid state for PnL withdrawals.

Token Movement Path: Based on accumulated fees and profits in both coin and PC tokens, the system calculates claimable amounts. Executes authority-based transfers from AMM vaults to user destination accounts. The transfers maintain pool stability while distributing earned rewards.

This mechanism incentivizes liquidity provision by allowing LPs to regularly claim their earned rewards from pool operations without the need to remove their liquidity.

State Management: Throughout execution, the system maintains accurate tracking of:

  • Accumulated fees (swap_acc_coin_fee, swap_acc_pc_fee)

  • PnL calculations (calc_pnl_x, calc_pnl_y)

  • Pool balances after withdrawals

  • Recent epoch updates

Closing Thoughts

Raydium's AMM implementation showcases robust architecture through its systematic approach to pool management, trading, and liquidity provision. The separation of concerns between instruction handling, core processing logic, and external interactions creates a secure and maintainable system. The constant product formula combined with orderbook integration provides efficient price discovery and deep liquidity, while careful state management ensures atomic operations and prevents exploits. Through features like withdrawPnL, the protocol effectively incentivizes liquidity providers and maintains a healthy ecosystem.

The codebase demonstrates exemplary input validation and error handling practices that developers should emulate. Throughout the code, we see consistent patterns of thorough account validation, robust amount checks, and state consistency maintenance:

  • Every instruction validates exact account count requirements and ownership

  • Zero amount prevention and overflow protection using checked math

  • Pool status validation and atomic state updates

  • Specific error types with clear messages for different failure cases

  • Comprehensive validation of all user inputs and state changes

These practices create a resilient system that safely handles billions in trading volume while maintaining security and reliability. The extensive use of custom errors, checked math, and comprehensive validation shows how production-grade DeFi protocols should handle user inputs and maintain system integrity. This technical foundation enables Raydium to serve as a cornerstone of Solana's DeFi infrastructure.