Skip to main content

DLMM Rust SDK Types Reference

Complete Rust type definitions for high-performance concentrated liquidity development
This reference provides authoritative type definitions for all structs, enums, and traits in the DLMM Rust SDK based on the actual source code. All types use zero-cost abstractions and memory-safe patterns for optimal performance.
SDK Version: v0.1.0 | Rust Edition: 2024 | Interface: Jupiter AMM Interface | Memory Layout: Zero-Copy

Core DLMM Types

SarosDlmm - Main SDK Struct

The primary struct implementing the Jupiter AMM interface for concentrated liquidity.
#[derive(Clone)]
pub struct SarosDlmm {
    /// DLMM program ID
    pub program_id: Pubkey,
    /// Pool address
    pub key: Pubkey,
    /// AMM identifier
    pub label: String,
    /// Pool configuration and state
    pub pair: Pair,
    /// Token transfer fee information
    pub token_transfer_fee: TokenTransferFee,
    /// Lower bin array data
    pub bin_array_lower: BinArray,
    /// Upper bin array data
    pub bin_array_upper: BinArray,
    /// Bin array addresses [lower, upper]
    pub bin_array_key: [Pubkey; 2],
    /// Hook bin array addresses [lower, upper]
    pub hook_bin_array_key: [Pubkey; 2],
    /// Token vault addresses [x, y]
    pub token_vault: [Pubkey; 2],
    /// Token program IDs [x, y]
    pub token_program: [Pubkey; 2],
    /// Event authority address
    pub event_authority: Pubkey,
    /// Current epoch (thread-safe)
    pub epoch: Arc<AtomicU64>,
    /// Current timestamp (thread-safe)
    pub timestamp: Arc<AtomicI64>,
}
Key Features:
  • Thread-Safe: Uses atomic types for shared state
  • Zero-Copy: Efficient account data deserialization
  • Jupiter Compatible: Implements standardized AMM interface

Pair - Pool Configuration and State

Core pool state with account data serialization.
pub struct Pair {
    _discriminator: [u8; 8],
    pub bump: [u8; 1],
    
    /// Liquidity book configuration
    pub liquidity_book_config: Pubkey,
    
    /// Bin step size
    pub bin_step: u8,
    pub bin_step_seed: [u8; 1],
    
    /// Token mint addresses
    pub token_mint_x: Pubkey,
    pub token_mint_y: Pubkey,
    
    /// Static fee parameters
    pub static_fee_parameters: StaticFeeParameters,
    
    /// Current active bin ID
    pub active_id: u32,
    
    /// Dynamic fee parameters
    pub dynamic_fee_parameters: DynamicFeeParameters,
    
    /// Accumulated protocol fees
    pub protocol_fees_x: u64,
    pub protocol_fees_y: u64,
    
    /// Optional hook program
    pub hook: Option<Pubkey>,
}
Memory Layout:
  • Size: 204 bytes (fixed)
  • Alignment: Account data compatible
  • Serialization: Zero-copy Pack trait implementation

StaticFeeParameters - Base Fee Configuration

Static fee parameters that don’t change during trading.
#[derive(PartialEq)]
pub struct StaticFeeParameters {
    /// Base factor for fee calculation
    pub base_factor: u16,
    /// Filter period for volatility
    pub filter_period: u16,
    /// Decay period for volatility
    pub decay_period: u16,
    /// Reduction factor for volatility
    pub reduction_factor: u16,
    /// Variable fee control parameter
    pub variable_fee_control: u32,
    /// Maximum volatility accumulator
    pub max_volatility_accumulator: u32,
    /// Protocol share (basis points)
    pub protocol_share: u16,
    _space: [u8; 2],
}
Memory Layout:
  • Size: 20 bytes (LEN constant)
  • Serialization: Little-endian byte order
  • Alignment: Optimized for Solana account storage

DynamicFeeParameters - Variable Fee State

Dynamic fee parameters that update with market volatility.
#[derive(PartialEq)]
pub struct DynamicFeeParameters {
    /// Last update timestamp
    pub time_last_updated: u64,
    /// Current volatility accumulator
    pub volatility_accumulator: u32,
    /// Volatility reference value
    pub volatility_reference: u32,
    /// Reference bin ID
    pub id_reference: u32,
    _space: [u8; 4],
}
Memory Layout:
  • Size: 24 bytes (LEN constant)
  • Updates: Modified on each significant trade
  • Thread Safety: Atomic updates via program calls

Bin - Individual Liquidity Bin

Individual concentrated liquidity bin with zero-copy optimization.
#[derive(Default, Clone, Copy)]
pub struct Bin {
    /// Total supply of liquidity tokens
    pub total_supply: u128,
    
    /// Reserve of token X in this bin
    pub reserve_x: u64,
    
    /// Reserve of token Y in this bin
    pub reserve_y: u64,
}
Memory Layout:
  • Size: 32 bytes (16 + 8 + 8)
  • Pack Implementation: Zero-copy serialization
  • Methods: swap_exact_in, swap_exact_out for trading operations
Core Methods:
impl Bin {
    /// Execute exact input swap through this bin
    pub fn swap_exact_in(
        &mut self,
        bin_step: u8,
        bin_id: u32,
        amount_in_left: u64,
        fee: u64,
        protocol_share: u64,
        swap_for_y: bool,
    ) -> Result<(u64, u64, u64, u64)> {
        // Returns: (amount_in_with_fees, amount_out, fee_amount, protocol_fee_amount)
    }
    
    /// Execute exact output swap through this bin
    pub fn swap_exact_out(
        &mut self,
        bin_step: u8,
        bin_id: u32,
        amount_out_left: u64,
        fee: u64,
        protocol_share: u64,
        swap_for_y: bool,
    ) -> Result<(u64, u64, u64, u64)> {
        // Returns: (amount_in, amount_out, fee_amount, protocol_fee_amount)
    }
}

Jupiter AMM Interface Types

Quote - Jupiter Standard Quote

Quote response following Jupiter AMM interface specification.
pub struct Quote {
    /// Required input amount
    pub in_amount: u64,
    /// Expected output amount  
    pub out_amount: u64,
    /// Fee amount in input token
    pub fee_amount: u64,
    /// Fee token mint
    pub fee_mint: Pubkey,
    /// Additional quote data (default)
    ..Default::default()
}

QuoteParams - Jupiter Quote Parameters

Parameters for requesting quotes via Jupiter interface.
pub struct QuoteParams {
    /// Amount to swap
    pub amount: u64,
    /// Swap mode (ExactIn or ExactOut)
    pub swap_mode: SwapMode,
    /// Input token mint
    pub input_mint: Pubkey,
    /// Output token mint (inferred from pool)
    pub output_mint: Pubkey,
}

#[derive(Debug, Clone, Copy)]
pub enum SwapMode {
    ExactIn,
    ExactOut,
}

SwapParams - Jupiter Swap Parameters

Parameters for swap execution via Jupiter interface.
pub struct SwapParams {
    /// Authority for token transfers
    pub token_transfer_authority: Pubkey,
    /// Source token account
    pub source_token_account: Pubkey,
    /// Destination token account  
    pub destination_token_account: Pubkey,
    /// Source token mint
    pub source_mint: Pubkey,
    /// Destination token mint
    pub destination_mint: Pubkey,
    /// Swap amount
    pub amount: u64,
}

SwapAndAccountMetas - Jupiter Transaction Data

Transaction metadata for swap execution.
pub struct SwapAndAccountMetas {
    /// Swap instruction type
    pub swap: Swap,
    /// Required account metas
    pub account_metas: Vec<AccountMeta>,
}

// Note: Currently returns unimplemented!() in SarosDlmm
// Planned for future implementation

Error Handling Types

ErrorCode - Comprehensive Error Enumeration

All possible error conditions in the DLMM SDK.
#[derive(Error, Debug)]
pub enum ErrorCode {
    #[error("Unable to divide by zero")]
    DivideByZero,
    
    #[error("Unable to cast number into BigInt")]
    NumberCastError,
    
    #[error("Bin array index mismatch")]
    BinArrayIndexMismatch,
    
    #[error("Bin not found within bin array")]
    BinNotFound,
    
    #[error("Invalid Mint")]
    InvalidMint,
    
    #[error("Transfer fee calculation error")]
    TransferFeeCalculationError,
    
    #[error("Amount Over Flow")]
    AmountOverflow,
    
    #[error("Amount Under Flow")]
    AmountUnderflow,
    
    #[error("Active id underflow")]
    ActiveIdUnderflow,
    
    #[error("Active id overflow")]
    ActiveIdOverflow,
    
    #[error("Invalid amount in")]
    InvalidAmountIn,
    
    #[error("Invalid amount out")]
    InvalidAmountOut,
    
    #[error("MulShr Math Error")]
    MulShrMathError,
    
    #[error("ShlDiv Math Error")]
    ShlDivMathError,
    
    #[error("U64 conversion overflow")]
    U64ConversionOverflow,
    
    #[error("Swap crosses too many bins – quote aborted")]
    SwapCrossesTooManyBins,
}
Error Conversion:
impl From<TryFromIntError> for ErrorCode {
    fn from(_: TryFromIntError) -> Self {
        ErrorCode::NumberCastError
    }
}

SwapQuote

Quote response containing swap pricing and execution details.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SwapQuote {
    /// Exact input amount (in token's smallest unit)
    pub amount_in: u64,
    
    /// Expected output amount (in token's smallest unit)
    pub amount_out: u64,
    
    /// Minimum output amount with slippage protection
    pub min_amount_out: u64,
    
    /// Price impact as percentage (2.5 = 2.5% impact)
    pub price_impact: f64,
    
    /// Total fees in input token's smallest unit
    pub fees: u64,
    
    /// Fee breakdown by type
    pub fee_breakdown: FeeBreakdown,
    
    /// Liquidity bins that will be used for this swap
    pub bin_arrays: Vec<BinData>,
    
    /// Other amount offset for exact calculations
    pub other_amount_offset: Option<u64>,
    
    /// Quote generation timestamp
    pub timestamp: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeeBreakdown {
    /// Protocol fee amount
    pub protocol: u64,
    /// LP provider fee amount
    pub lp_providers: u64,
}

SwapParams

Parameters for executing a swap transaction.
#[derive(Debug, Clone)]
pub struct SwapParams {
    /// Input amount in token's smallest unit
    pub amount_in: u64,
    
    /// Source token mint address
    pub token_mint_in: Pubkey,
    
    /// Destination token mint address
    pub token_mint_out: Pubkey,
    
    /// Price offset for execution precision
    pub other_amount_offset: Option<u64>,
    
    /// Whether input amount is exact
    pub exact_input: bool,
    
    /// Swap direction (true = X→Y, false = Y→X)
    pub swap_for_y: bool,
    
    /// Target pool address
    pub pool_address: Pubkey,
    
    /// User wallet public key
    pub user: Pubkey,
    
    /// Optional: Priority fee in lamports
    pub priority_fee: Option<u64>,
    
    /// Optional: Compute unit limit
    pub compute_units: Option<u32>,
    
    /// Optional: Referral account for fee sharing
    pub referral: Option<Pubkey>,
}

SwapResult

Result of an executed swap transaction.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SwapResult {
    /// Transaction signature on Solana blockchain
    pub signature: Signature,
    
    /// Actual input amount processed
    pub amount_in: u64,
    
    /// Actual output amount received
    pub amount_out: u64,
    
    /// Total fees paid
    pub fees: u64,
    
    /// Execution time in milliseconds
    pub execution_time_ms: u64,
    
    /// Effective price (output/input)
    pub effective_price: f64,
    
    /// Actual price impact experienced
    pub actual_price_impact: f64,
    
    /// Block slot when executed
    pub slot: u64,
    
    /// Transaction confirmation status
    pub confirmation_status: ConfirmationStatus,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ConfirmationStatus {
    Processed,
    Confirmed,
    Finalized,
}

Pool Information Types

PoolInfo

Comprehensive information about a DLMM pool with zero-copy optimizations.
#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct PoolInfo {
    /// Pool address
    pub address: Pubkey,
    
    /// First token information
    pub token_x: TokenInfo,
    
    /// Second token information
    pub token_y: TokenInfo,
    
    /// Current active bin ID
    pub current_bin: i32,
    
    /// Current trading price (Q64.64 fixed point)
    pub current_price: u128,
    
    /// Total value locked as raw amounts
    pub total_liquidity: PoolLiquidity,
    
    /// 24-hour trading volume statistics
    pub volume_24h: VolumeStats,
    
    /// 24-hour fees collected
    pub fees_24h: FeeStats,
    
    /// Price step between adjacent bins (basis points)
    pub bin_step: u16,
    
    /// Pool creation slot
    pub created_at: u64,
    
    /// Pool operational status
    pub status: PoolStatus,
    
    /// Bin distribution data
    pub bin_distribution: BinDistribution,
    
    /// Pool parameters and configuration
    pub parameters: PoolParameters,
}

#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct PoolLiquidity {
    /// Total X token amount
    pub total_x: u64,
    /// Total Y token amount  
    pub total_y: u64,
    /// USD equivalent value (with 6 decimals)
    pub total_usd: u64,
}

#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct VolumeStats {
    /// Volume in token X
    pub volume_x: u64,
    /// Volume in token Y
    pub volume_y: u64,
    /// USD volume (with 6 decimals)
    pub volume_usd: u64,
}

#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct FeeStats {
    /// Total fees in token X
    pub fees_x: u64,
    /// Total fees in token Y
    pub fees_y: u64,
    /// USD fees (with 6 decimals)
    pub fees_usd: u64,
}

#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct PoolParameters {
    /// Base fee rate (basis points)
    pub base_fee_rate: u16,
    /// Variable fee control
    pub variable_fee_control: u32,
    /// Protocol fee share (basis points)
    pub protocol_fee_share: u16,
    /// Max volatility accumulator
    pub max_volatility_accumulator: u32,
}

TokenInfo

Token metadata and configuration with efficient memory layout.
#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct TokenInfo {
    /// Token mint address
    pub mint: Pubkey,
    
    /// Token symbol (up to 10 chars)
    pub symbol: [u8; 10],
    
    /// Token name (up to 32 chars)
    pub name: [u8; 32],
    
    /// Number of decimal places
    pub decimals: u8,
    
    /// Logo URI hash (IPFS hash)
    pub logo_uri: Option<[u8; 32]>,
    
    /// CoinGecko ID hash for price data
    pub coingecko_id: Option<[u8; 32]>,
    
    /// Current price in USD (Q64.64 fixed point)
    pub price_usd: Option<u128>,
    
    /// 24-hour price change (basis points, can be negative)
    pub price_change_24h: Option<i32>,
    
    /// Token supply information
    pub supply: Option<TokenSupply>,
    
    /// Token program (SPL Token vs Token-2022)
    pub token_program: TokenProgram,
}

#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct TokenSupply {
    /// Total supply
    pub total: u64,
    /// Circulating supply
    pub circulating: u64,
}

#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub enum TokenProgram {
    Token,
    Token2022,
}

PoolSummary

Lightweight pool information for discovery and listing.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PoolSummary {
    /// Pool address
    pub address: Pubkey,
    
    /// First token summary
    pub token_x: TokenSummary,
    
    /// Second token summary
    pub token_y: TokenSummary,
    
    /// Total value locked in USD (6 decimals)
    pub tvl: u64,
    
    /// 24-hour trading volume in USD (6 decimals)
    pub volume_24h: u64,
    
    /// Estimated APY for liquidity providers (basis points)
    pub apy: u32,
    
    /// Current trading price (Q64.64 fixed point)
    pub price: u128,
    
    /// 24-hour price change (basis points, can be negative)
    pub price_change_24h: i32,
    
    /// Number of active liquidity providers
    pub lp_count: u32,
    
    /// Pool age in days
    pub age_in_days: u32,
    
    /// Pool risk level assessment
    pub risk_level: RiskLevel,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenSummary {
    /// Token mint
    pub mint: Pubkey,
    /// Symbol (null-terminated)
    pub symbol: [u8; 10],
    /// Decimals
    pub decimals: u8,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RiskLevel {
    Low,
    Medium,
    High,
    Critical,
}

Liquidity Management Types

AddLiquidityParams

Parameters for adding concentrated liquidity with Rust memory safety.
#[derive(Debug, Clone)]
pub struct AddLiquidityParams {
    /// Target pool address
    pub pool_address: Pubkey,
    
    /// First token mint address
    pub token_x: Pubkey,
    
    /// Second token mint address  
    pub token_y: Pubkey,
    
    /// Amount of tokenX to add (raw amount)
    pub amount_x: u64,
    
    /// Amount of tokenY to add (raw amount)
    pub amount_y: u64,
    
    /// Price range as [lower_bin, upper_bin]
    pub bin_range: BinRange,
    
    /// User wallet public key
    pub user: Pubkey,
    
    /// Liquidity distribution strategy
    pub distribution: LiquidityDistribution,
    
    /// Optional: Maximum slippage tolerance (basis points)
    pub max_slippage: Option<u16>,
    
    /// Optional: Position configuration
    pub position_config: Option<PositionConfig>,
    
    /// Optional: Priority fee in lamports
    pub priority_fee: Option<u64>,
    
    /// Optional: Compute unit limit
    pub compute_units: Option<u32>,
}

#[derive(Debug, Clone, Copy)]
pub struct BinRange {
    /// Lower bin ID (inclusive)
    pub lower: i32,
    /// Upper bin ID (inclusive)
    pub upper: i32,
}

#[derive(Debug, Clone)]
pub enum LiquidityDistribution {
    /// Uniform distribution across all bins
    Uniform,
    /// Concentrated around current price
    Concentrated { 
        /// Concentration factor (0-100)
        factor: u8 
    },
    /// Custom distribution weights
    Custom { 
        /// Per-bin weight distribution
        weights: Vec<(i32, u32)> 
    },
    /// Spot distribution (single bin)
    Spot { 
        /// Target bin ID
        bin_id: i32 
    },
}

#[derive(Debug, Clone)]
pub struct PositionConfig {
    /// Automatic rebalancing enabled
    pub auto_rebalance: bool,
    /// Fee harvesting strategy
    pub fee_harvest: FeeHarvestStrategy,
    /// Stop loss configuration
    pub stop_loss: Option<StopLossConfig>,
}

#[derive(Debug, Clone)]
pub enum FeeHarvestStrategy {
    /// Manual harvesting only
    Manual,
    /// Auto-harvest above threshold
    AutoThreshold { 
        /// Threshold in USD (6 decimals)
        threshold_usd: u64 
    },
    /// Auto-compound fees back into position
    AutoCompound,
}

#[derive(Debug, Clone)]
pub struct StopLossConfig {
    /// Maximum acceptable loss percentage (basis points)
    pub max_loss_bps: u16,
    /// Whether to execute automatically
    pub auto_execute: bool,
}

LiquidityResult

Result of adding liquidity with detailed outcome information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LiquidityResult {
    /// Transaction signature
    pub signature: Signature,
    
    /// Created position unique identifier
    pub position_id: Pubkey,
    
    /// Actual amount of tokenX added
    pub actual_amount_x: u64,
    
    /// Actual amount of tokenY added
    pub actual_amount_y: u64,
    
    /// LP token amounts received per bin
    pub lp_tokens: Vec<BinLpTokens>,
    
    /// Initial position value (USD with 6 decimals)
    pub initial_value_usd: u64,
    
    /// Active bin range where liquidity was placed
    pub active_bin_range: BinRange,
    
    /// Expected fee APR based on current volume (basis points)
    pub expected_apr: u32,
    
    /// Gas cost of transaction
    pub gas_used: u64,
    
    /// Position creation timestamp
    pub created_at: i64,
    
    /// Bin-by-bin breakdown of added liquidity
    pub bin_breakdown: Vec<BinLiquidityInfo>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BinLpTokens {
    /// Bin ID
    pub bin_id: i32,
    /// LP tokens for tokenX  
    pub lp_x: u64,
    /// LP tokens for tokenY
    pub lp_y: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BinLiquidityInfo {
    /// Bin ID
    pub bin_id: i32,
    /// Price for this bin (Q64.64)
    pub price: u128,
    /// Liquidity added in tokenX
    pub liquidity_x: u64,
    /// Liquidity added in tokenY
    pub liquidity_y: u64,
    /// Share of total bin liquidity (basis points)
    pub ownership_share: u16,
}

Position

User’s liquidity position with optimized data layout.
#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct Position {
    /// Position account address  
    pub address: Pubkey,
    
    /// Associated pool address
    pub pool_address: Pubkey,
    
    /// Position owner wallet address
    pub owner: Pubkey,
    
    /// Active bin range
    pub bin_range: BinRange,
    
    /// Current liquidity amounts per bin
    pub bin_liquidity: Vec<BinLiquidity>,
    
    /// Unclaimed fees in tokenX
    pub unclaimed_fees_x: u64,
    
    /// Unclaimed fees in tokenY
    pub unclaimed_fees_y: u64,
    
    /// Current position value (USD with 6 decimals)
    pub current_value: u64,
    
    /// Initial position value (USD with 6 decimals)
    pub initial_value: u64,
    
    /// Return on investment (basis points, can be negative)
    pub roi: i32,
    
    /// Position creation slot
    pub created_at: u64,
    
    /// Last update slot
    pub updated_at: u64,
    
    /// Position operational status
    pub status: PositionStatus,
    
    /// Position configuration
    pub config: PositionConfig,
    
    /// Lifetime statistics
    pub lifetime_stats: LifetimeStats,
}

#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct BinLiquidity {
    /// Bin ID
    pub bin_id: i32,
    /// Liquidity amount in tokenX
    pub liquidity_x: u64,
    /// Liquidity amount in tokenY  
    pub liquidity_y: u64,
    /// Share of total bin liquidity (Q32.32 fixed point)
    pub share: u64,
}

#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct LifetimeStats {
    /// Total fees earned in X
    pub total_fees_x: u64,
    /// Total fees earned in Y
    pub total_fees_y: u64,
    /// Peak position value reached
    pub peak_value: u64,
    /// Total trading volume that went through position
    pub volume_facilitated: u64,
    /// Number of swaps facilitated
    pub swaps_facilitated: u32,
}

RemoveLiquidityParams

Parameters for removing liquidity with precise control.
#[derive(Debug, Clone)]
pub struct RemoveLiquidityParams {
    /// Position address to withdraw from
    pub position_address: Pubkey,
    
    /// Withdrawal strategy
    pub withdrawal_strategy: WithdrawalStrategy,
    
    /// Minimum tokenX amount to receive
    pub min_amount_x: u64,
    
    /// Minimum tokenY amount to receive  
    pub min_amount_y: u64,
    
    /// User wallet public key
    pub user: Pubkey,
    
    /// Whether to claim accumulated fees
    pub claim_fees: bool,
    
    /// Whether to close position if fully withdrawn
    pub close_position: bool,
    
    /// Optional: Priority fee in lamports
    pub priority_fee: Option<u64>,
    
    /// Optional: Compute unit limit
    pub compute_units: Option<u32>,
}

#[derive(Debug, Clone)]
pub enum WithdrawalStrategy {
    /// Withdraw percentage from all bins
    Proportional { 
        /// Percentage to withdraw (0-10000 basis points)
        percentage: u16 
    },
    /// Withdraw from specific bins only
    Selective { 
        /// Bin IDs and amounts to withdraw
        bins: Vec<(i32, u64, u64)> 
    },
    /// Withdraw everything from out-of-range bins
    OutOfRange,
    /// Emergency withdrawal (bypass some checks)
    Emergency,
}

WithdrawResult

Result of removing liquidity with comprehensive information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WithdrawResult {
    /// Transaction signature
    pub signature: Signature,
    
    /// TokenX amount withdrawn
    pub withdrawn_x: u64,
    
    /// TokenY amount withdrawn
    pub withdrawn_y: u64,
    
    /// Fee rewards claimed in tokenX
    pub fees_x: u64,
    
    /// Fee rewards claimed in tokenY
    pub fees_y: u64,
    
    /// Total value withdrawn (USD with 6 decimals)
    pub total_value_usd: u64,
    
    /// Remaining position (if partial withdrawal)
    pub remaining_position: Option<Position>,
    
    /// Whether position was fully closed
    pub position_closed: bool,
    
    /// Gas cost of withdrawal
    pub gas_used: u64,
    
    /// Per-bin withdrawal breakdown
    pub bin_withdrawals: Vec<BinWithdrawal>,
    
    /// Realized profit/loss (USD with 6 decimals, can be negative)
    pub realized_pnl: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BinWithdrawal {
    /// Bin ID
    pub bin_id: i32,
    /// TokenX withdrawn from this bin
    pub withdrawn_x: u64,
    /// TokenY withdrawn from this bin
    pub withdrawn_y: u64,
    /// Fees claimed from this bin (X)
    pub fees_x: u64,
    /// Fees claimed from this bin (Y)
    pub fees_y: u64,
}

Analytics Types

PoolAnalytics

Comprehensive analytics with efficient data structures.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PoolAnalytics {
    /// Pool address being analyzed
    pub pool_address: Pubkey,
    
    /// Analysis timeframe
    pub timeframe: Timeframe,
    
    /// Trading volume analytics
    pub volume: VolumeAnalytics,
    
    /// Liquidity distribution analytics
    pub liquidity: LiquidityAnalytics,
    
    /// Fee collection and distribution
    pub fees: FeeAnalytics,
    
    /// Historical price data (compressed)
    pub price_history: CompressedPriceHistory,
    
    /// User engagement metrics
    pub user_metrics: UserEngagementMetrics,
    
    /// Performance benchmarks
    pub benchmarks: PerformanceBenchmarks,
    
    /// Risk assessment data
    pub risk_assessment: RiskAssessment,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Timeframe {
    OneHour,
    TwentyFourHours, 
    SevenDays,
    ThirtyDays,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VolumeAnalytics {
    /// Total volume in USD (6 decimals)
    pub total_usd: u64,
    
    /// Volume by direction
    pub by_direction: VolumeDirection,
    
    /// Volume distribution over time
    pub time_distribution: TimeDistribution,
    
    /// Large trade analysis
    pub large_trades: LargeTradingAnalysis,
    
    /// Volume concentration metrics
    pub concentration: VolumeConcentration,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VolumeDirection {
    /// TokenX to TokenY volume (USD)
    pub x_to_y: u64,
    /// TokenY to TokenX volume (USD)
    pub y_to_x: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TimeDistribution {
    /// Hourly volume points (compressed)
    pub hourly_data: Vec<u32>,
    /// Peak trading hour (0-23)
    pub peak_hour: u8,
    /// Trading concentration percentage (basis points)
    pub concentration: u16,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LargeTradingAnalysis {
    /// Trades above $10k USD count
    pub count: u32,
    /// Total volume from large trades (USD)
    pub total_volume: u64,
    /// Average size of large trades (USD)
    pub average_size: u64,
    /// Largest single trade (USD)
    pub largest_trade: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VolumeConcentration {
    /// Gini coefficient for volume distribution (0-10000)
    pub gini_coefficient: u16,
    /// Top 10% of trades volume share (basis points)
    pub top_10_percent_share: u16,
}

LiquidityAnalytics

Liquidity distribution and utilization with memory-efficient storage.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LiquidityAnalytics {
    /// Total liquidity (USD with 6 decimals)
    pub total_usd: u64,
    
    /// Number of active bins with liquidity
    pub active_bins: u32,
    
    /// Current price bin ID
    pub current_bin: i32,
    
    /// Liquidity distribution around current price
    pub distribution: LiquidityDistributionAnalysis,
    
    /// Utilization metrics
    pub utilization: UtilizationMetrics,
    
    /// Historical liquidity changes
    pub history: LiquidityHistory,
    
    /// Provider concentration
    pub provider_analysis: ProviderAnalysis,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LiquidityDistributionAnalysis {
    /// Bins within ±5 of current price
    pub near_price_bins: Vec<CompactBinData>,
    /// Total liquidity in near-price range (USD)
    pub near_price_total: u64,
    /// Percentage of liquidity near current price (basis points)
    pub near_price_percentage: u16,
    /// Liquidity depth at various distances
    pub depth_analysis: DepthAnalysis,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompactBinData {
    /// Bin ID relative to current bin
    pub relative_bin_id: i8,
    /// Liquidity amount (USD, compressed)
    pub liquidity_usd: u32,
    /// Utilization rate (basis points)
    pub utilization_rate: u16,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DepthAnalysis {
    /// Liquidity within 1% price range
    pub depth_1_percent: u64,
    /// Liquidity within 5% price range
    pub depth_5_percent: u64,
    /// Liquidity within 10% price range
    pub depth_10_percent: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]  
pub struct UtilizationMetrics {
    /// Percentage of liquidity actively used (basis points)
    pub active_percentage: u16,
    /// Average utilization over timeframe (basis points)
    pub average_utilization: u16,
    /// Peak utilization period
    pub peak_utilization: PeakUtilization,
    /// Efficiency score (0-10000)
    pub efficiency_score: u16,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PeakUtilization {
    /// Peak percentage (basis points)
    pub percentage: u16,
    /// Unix timestamp
    pub timestamp: i64,
    /// Duration in seconds
    pub duration: u32,
}

PositionAnalytics

Individual position performance analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PositionAnalytics {
    /// Position address
    pub position_address: Pubkey,
    
    /// Return on investment (basis points, can be negative)
    pub roi: i32,
    
    /// Total fees earned to date (USD with 6 decimals)
    pub fees_earned_usd: u64,
    
    /// Current impermanent loss (basis points, can be negative)
    pub impermanent_loss: i32,
    
    /// Active price range information
    pub price_range: PriceRangeAnalysis,
    
    /// Trading utilization metrics
    pub utilization: PositionUtilization,
    
    /// Performance comparison metrics
    pub performance: PerformanceComparison,
    
    /// Risk metrics
    pub risk_metrics: PositionRiskMetrics,
    
    /// Optimal rebalancing suggestions
    pub rebalancing_suggestions: Vec<RebalancingSuggestion>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PriceRangeAnalysis {
    /// Lower bound price (Q64.64)
    pub lower_price: u128,
    /// Upper bound price (Q64.64)
    pub upper_price: u128,
    /// Current price position (0-10000, where 5000 = middle)
    pub current_relative: u16,
    /// Percentage of time price was in range (basis points)
    pub in_range_percentage: u16,
    /// Width of range relative to current price (basis points)
    pub range_width: u16,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PositionUtilization {
    /// Percentage of time position was actively trading (basis points)
    pub active_rate: u16,
    /// Hours actively trading
    pub active_hours: u32,
    /// Total hours since creation
    pub total_hours: u32,
    /// Average daily volume facilitated (USD)
    pub avg_daily_volume: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceComparison {
    /// Performance vs holding tokens (basis points difference)
    pub vs_holding: i32,
    /// Performance vs pool average (basis points difference)
    pub vs_pool_average: i32,
    /// Annualized return percentage (basis points)
    pub annualized_return: i32,
    /// Sharpe ratio (scaled by 1000)
    pub sharpe_ratio: i32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PositionRiskMetrics {
    /// Value at Risk (95% confidence, USD)
    pub value_at_risk: u64,
    /// Maximum drawdown experienced (basis points)
    pub max_drawdown: u16,
    /// Volatility score (0-10000)
    pub volatility_score: u16,
    /// Concentration risk score (0-10000)
    pub concentration_risk: u16,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RebalancingSuggestion {
    /// Type of rebalancing suggested
    pub suggestion_type: RebalancingType,
    /// Expected improvement in returns (basis points)
    pub expected_improvement: u16,
    /// Cost of rebalancing (USD)
    pub estimated_cost: u64,
    /// Confidence level (basis points)
    pub confidence: u16,
    /// Detailed explanation
    pub explanation: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RebalancingType {
    NarrowRange,
    WidenRange,
    ShiftUp,
    ShiftDown,
    AddLiquidity,
    RemoveLiquidity,
    NoAction,
}

Pool Discovery Types

PoolSearchParams

Parameters for finding optimal pools with Rust-specific optimizations.
#[derive(Debug, Clone)]
pub struct PoolSearchParams {
    /// First token mint address
    pub token_a: Pubkey,
    
    /// Second token mint address
    pub token_b: Pubkey,
    
    /// Intended usage strategy
    pub strategy: TradingStrategy,
    
    /// Expected trading amount range [min, max] in USD
    pub amount_range_usd: AmountRange,
    
    /// Search filters
    pub filters: PoolSearchFilters,
    
    /// Result ordering preference
    pub ordering: SearchOrdering,
    
    /// Maximum results to return
    pub max_results: u16,
}

#[derive(Debug, Clone)]
pub struct AmountRange {
    /// Minimum amount (USD with 6 decimals)
    pub min: u64,
    /// Maximum amount (USD with 6 decimals)
    pub max: u64,
}

#[derive(Debug, Clone)]
pub enum TradingStrategy {
    /// Optimized for frequent trading
    Trading,
    /// Optimized for liquidity provision
    Liquidity,
    /// Optimized for yield generation
    Yield,
    /// Arbitrage opportunities
    Arbitrage,
    /// Market making
    MarketMaking,
}

#[derive(Debug, Clone)]
pub struct PoolSearchFilters {
    /// Minimum TVL required (USD with 6 decimals)
    pub min_tvl: Option<u64>,
    /// Minimum 24h volume (USD with 6 decimals)
    pub min_volume_24h: Option<u64>,
    /// Maximum acceptable spread (basis points)
    pub max_spread: Option<u16>,
    /// Preferred bin step sizes
    pub preferred_bin_steps: Option<Vec<u16>>,
    /// Minimum liquidity providers count
    pub min_lp_count: Option<u32>,
    /// Maximum pool age in days
    pub max_age_days: Option<u32>,
    /// Risk level filter
    pub max_risk_level: Option<RiskLevel>,
}

#[derive(Debug, Clone)]
pub enum SearchOrdering {
    /// Order by highest TVL
    HighestTvl,
    /// Order by highest volume
    HighestVolume,
    /// Order by best APY
    BestApy,
    /// Order by lowest fees
    LowestFees,
    /// Order by best fit for strategy
    BestFit,
}

PoolRecommendation

Recommendation result with comprehensive analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PoolRecommendation {
    /// Primary recommended pool
    pub recommended_pool: PoolSummary,
    
    /// Alternative pools ranked by suitability
    pub alternative_pools: Vec<RankedPool>,
    
    /// Detailed reasoning for recommendation
    pub reasoning: RecommendationReasoning,
    
    /// Expected performance metrics
    pub expected_performance: ExpectedPerformance,
    
    /// Risk assessment
    pub risk_assessment: PoolRiskAssessment,
    
    /// Recommended configuration
    pub recommended_config: RecommendedConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RankedPool {
    /// Pool information
    pub pool: PoolSummary,
    /// Suitability score (0-10000)
    pub score: u16,
    /// Ranking position
    pub rank: u16,
    /// Specific advantages
    pub advantages: Vec<String>,
    /// Potential disadvantages  
    pub disadvantages: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecommendationReasoning {
    /// Primary factors in decision
    pub primary_factors: Vec<ReasoningFactor>,
    /// Secondary considerations
    pub secondary_factors: Vec<ReasoningFactor>,
    /// Trade-offs made
    pub tradeoffs: Vec<String>,
    /// Confidence level (basis points)
    pub confidence_level: u16,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReasoningFactor {
    /// Factor name
    pub factor: String,
    /// Weight in decision (basis points)
    pub weight: u16,
    /// Value or score
    pub value: f64,
    /// Explanation
    pub explanation: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExpectedPerformance {
    /// Estimated trading fees (USD with 6 decimals)
    pub estimated_fees: u64,
    /// Expected slippage range [min, max] (basis points)
    pub slippage_range: [u16; 2],
    /// Liquidity utilization prediction (basis points)
    pub utilization_prediction: u16,
    /// Expected APY range [min, max] (basis points)
    pub apy_range: [u16; 2],
    /// Break-even analysis
    pub break_even: BreakEvenAnalysis,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BreakEvenAnalysis {
    /// Minimum volume needed to break even (USD)
    pub min_volume_usd: u64,
    /// Time to break even (days)
    pub time_to_break_even_days: u32,
    /// Probability of breaking even (basis points)
    pub break_even_probability: u16,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PoolRiskAssessment {
    /// Overall risk level
    pub level: RiskLevel,
    /// Individual risk factors
    pub factors: Vec<RiskFactor>,
    /// Mitigation suggestions
    pub mitigations: Vec<String>,
    /// Maximum recommended position size (USD)
    pub max_position_size: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RiskFactor {
    /// Risk category
    pub category: RiskCategory,
    /// Risk level for this factor
    pub level: RiskLevel,
    /// Impact score (0-10000)
    pub impact_score: u16,
    /// Description
    pub description: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RiskCategory {
    Liquidity,
    Volatility,
    SmartContract,
    Centralization,
    Market,
    Operational,
}

Configuration Types

DlmmConfig

SDK configuration with Rust-specific optimizations.
#[derive(Debug, Clone)]
pub struct DlmmConfig {
    /// Solana RPC client configuration
    pub rpc_config: RpcConfig,
    
    /// DLMM program configuration  
    pub program_config: ProgramConfig,
    
    /// Performance optimization settings
    pub performance: PerformanceConfig,
    
    /// Error handling configuration
    pub error_handling: ErrorHandlingConfig,
    
    /// Caching configuration
    pub caching: CachingConfig,
    
    /// Development/debugging options
    pub dev_options: Option<DevOptions>,
}

#[derive(Debug, Clone)]
pub struct RpcConfig {
    /// Primary RPC endpoint URL
    pub url: String,
    
    /// Transaction commitment level
    pub commitment: CommitmentConfig,
    
    /// Request timeout duration
    pub timeout: Duration,
    
    /// Number of retry attempts
    pub retry_attempts: u8,
    
    /// Retry delay strategy
    pub retry_strategy: RetryStrategy,
    
    /// Fallback RPC endpoints
    pub fallback_urls: Vec<String>,
    
    /// Rate limiting configuration
    pub rate_limit: RateLimitConfig,
}

#[derive(Debug, Clone)]
pub struct ProgramConfig {
    /// DLMM program ID
    pub program_id: Pubkey,
    
    /// Network type
    pub network: NetworkType,
    
    /// Program version compatibility
    pub version_compatibility: VersionCompatibility,
}

#[derive(Debug, Clone)]
pub struct PerformanceConfig {
    /// Enable connection pooling
    pub connection_pooling: bool,
    
    /// Maximum concurrent requests
    pub max_concurrent_requests: u16,
    
    /// Request batching configuration
    pub batching: BatchingConfig,
    
    /// Memory optimization settings
    pub memory_optimization: MemoryConfig,
    
    /// Compute budget optimization
    pub compute_optimization: ComputeConfig,
}

#[derive(Debug, Clone)]
pub struct BatchingConfig {
    /// Enable request batching
    pub enabled: bool,
    /// Maximum batch size
    pub max_batch_size: u16,
    /// Batch timeout
    pub timeout: Duration,
}

#[derive(Debug, Clone)]
pub struct MemoryConfig {
    /// Pool for reusing allocations
    pub object_pooling: bool,
    /// Maximum cache size in bytes
    pub max_cache_size: usize,
    /// Aggressive memory cleanup
    pub aggressive_cleanup: bool,
}

#[derive(Debug, Clone)]
pub struct ComputeConfig {
    /// Default compute unit limit
    pub default_compute_units: u32,
    /// Maximum compute units per transaction
    pub max_compute_units: u32,
    /// Priority fee strategy
    pub priority_fee_strategy: PriorityFeeStrategy,
}

#[derive(Debug, Clone)]
pub enum PriorityFeeStrategy {
    None,
    Fixed(u64),
    Dynamic { 
        percentile: u8, 
        max_fee: u64 
    },
    Adaptive,
}

#[derive(Debug, Clone)]
pub enum CommitmentConfig {
    Processed,
    Confirmed,
    Finalized,
}

#[derive(Debug, Clone)]
pub enum NetworkType {
    Devnet,
    MainnetBeta,
    Testnet,
}

#[derive(Debug, Clone)]
pub enum RetryStrategy {
    Linear { delay_ms: u64 },
    Exponential { 
        initial_delay_ms: u64, 
        max_delay_ms: u64 
    },
    Custom(Box<dyn Fn(u8) -> Duration + Send + Sync>),
}

Bin and Price Types

BinData

Individual liquidity bin with memory-optimized layout.
#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct BinData {
    /// Bin unique identifier
    pub bin_id: i32,
    
    /// Price for this bin (Q64.64 fixed point)
    pub price: u128,
    
    /// Liquidity amount in tokenX
    pub liquidity_x: u64,
    
    /// Liquidity amount in tokenY
    pub liquidity_y: u64,
    
    /// Total liquidity in USD (with 6 decimals)
    pub total_liquidity_usd: u64,
    
    /// Fee information for tokenX
    pub fee_info_x: FeeInfo,
    
    /// Fee information for tokenY
    pub fee_info_y: FeeInfo,
    
    /// Bin utilization rate (basis points)
    pub utilization_rate: u16,
    
    /// Last update slot
    pub last_updated: u64,
    
    /// Bin status flags
    pub status: BinStatus,
}

#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct FeeInfo {
    /// Accumulated fee amount
    pub fee_amount: u64,
    
    /// Fee rate for this bin (basis points)
    pub fee_rate: u16,
    
    /// Protocol fee portion
    pub protocol_fee: u64,
    
    /// LP provider fee portion
    pub lp_fee: u64,
    
    /// Total fees collected lifetime
    pub total_fees_collected: u64,
    
    /// Fee per share (Q64.64 fixed point)
    pub fee_per_share: u128,
}

#[derive(Debug, Clone, AnchorSerialize, AnchorDeserialize)]
pub struct BinStatus {
    /// Whether bin has active liquidity
    pub has_liquidity: bool,
    /// Whether bin is locked for updates
    pub locked: bool,
    /// Whether bin is deprecated
    pub deprecated: bool,
}

BinDistribution

Distribution of liquidity across price bins.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BinDistribution {
    /// All bins with liquidity (sorted by bin_id)
    pub active_bins: Vec<BinData>,
    
    /// Price range coverage
    pub price_range: PriceRangeCoverage,
    
    /// Liquidity concentration metrics
    pub concentration: ConcentrationMetrics,
    
    /// Distribution statistics
    pub statistics: DistributionStatistics,
    
    /// Optimal range suggestions
    pub optimal_ranges: Vec<OptimalRange>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PriceRangeCoverage {
    /// Lowest price with liquidity (Q64.64)
    pub min_price: u128,
    /// Highest price with liquidity (Q64.64)
    pub max_price: u128,
    /// Price range span as percentage of current price (basis points)
    pub span_percentage: u16,
    /// Number of gaps in liquidity
    pub gaps: u16,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConcentrationMetrics {
    /// Percentage within ±2% of current price (basis points)
    pub tight_range: u16,
    /// Percentage within ±5% of current price (basis points)  
    pub moderate_range: u16,
    /// Percentage within ±10% of current price (basis points)
    pub wide_range: u16,
    /// Gini coefficient for distribution (0-10000)
    pub gini_coefficient: u16,
    /// Herfindahl index for concentration (0-10000)
    pub herfindahl_index: u16,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DistributionStatistics {
    /// Standard deviation of liquidity amounts
    pub std_deviation: f64,
    /// Skewness of distribution
    pub skewness: f64,
    /// Kurtosis of distribution
    pub kurtosis: f64,
    /// Mode (most common liquidity amount)
    pub mode: u64,
    /// Median liquidity amount
    pub median: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OptimalRange {
    /// Lower bin ID for range
    pub lower_bin: i32,
    /// Upper bin ID for range
    pub upper_bin: i32,
    /// Expected APY for this range (basis points)
    pub expected_apy: u16,
    /// Risk score for this range (0-10000)
    pub risk_score: u16,
    /// Reasoning for recommendation
    pub reasoning: String,
}

Event Types

Event Callback Types

/// Callback function type for swap events
pub type SwapEventCallback = Arc<dyn Fn(SwapEvent) + Send + Sync>;

/// Callback function type for liquidity events
pub type LiquidityEventCallback = Arc<dyn Fn(LiquidityEvent) + Send + Sync>;

/// Callback function type for price events
pub type PriceEventCallback = Arc<dyn Fn(PriceEvent) + Send + Sync>;

SwapEvent

Swap event information with efficient serialization.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SwapEvent {
    /// Event type
    pub event_type: EventType,
    
    /// Pool where swap occurred
    pub pool_address: Pubkey,
    
    /// User who executed swap
    pub user: Pubkey,
    
    /// Input token amount
    pub amount_in: u64,
    
    /// Output token amount
    pub amount_out: u64,
    
    /// Input token mint
    pub token_in: Pubkey,
    
    /// Output token mint
    pub token_out: Pubkey,
    
    /// Fees paid
    pub fees: u64,
    
    /// Price impact (basis points)
    pub price_impact: u16,
    
    /// Event slot
    pub slot: u64,
    
    /// Unix timestamp
    pub timestamp: i64,
    
    /// Transaction signature
    pub signature: Signature,
    
    /// Swap direction
    pub swap_direction: SwapDirection,
    
    /// Active price after swap (Q64.64)
    pub active_price: u128,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EventType {
    Swap,
    AddLiquidity,
    RemoveLiquidity,
    ClaimFees,
    PriceUpdate,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SwapDirection {
    XToY,
    YToX,
}

LiquidityEvent

Liquidity change event information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LiquidityEvent {
    /// Event type
    pub event_type: LiquidityEventType,
    
    /// Pool address
    pub pool_address: Pubkey,
    
    /// User who made the change
    pub user: Pubkey,
    
    /// Position affected
    pub position_address: Pubkey,
    
    /// Amount changed (USD with 6 decimals)
    pub amount_usd: u64,
    
    /// Affected token types
    pub affected_tokens: AffectedTokens,
    
    /// Amounts by token
    pub token_amounts: TokenAmounts,
    
    /// New total pool liquidity (USD)
    pub new_total_liquidity: u64,
    
    /// Active bins after change
    pub active_bins: Vec<i32>,
    
    /// Event slot
    pub slot: u64,
    
    /// Unix timestamp
    pub timestamp: i64,
    
    /// Transaction signature
    pub signature: Signature,
    
    /// Bin range affected
    pub bin_range: Option<BinRange>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum LiquidityEventType {
    Add,
    Remove,
    Claim,
    Rebalance,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AffectedTokens {
    TokenX,
    TokenY,
    Both,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenAmounts {
    /// Amount in token X
    pub amount_x: u64,
    /// Amount in token Y
    pub amount_y: u64,
}

Subscription

Event subscription with lifecycle management.
#[derive(Debug)]
pub struct Subscription {
    /// Unique subscription identifier
    pub id: Uuid,
    
    /// Subscription type
    pub subscription_type: SubscriptionType,
    
    /// Target (pool address or global)
    pub target: SubscriptionTarget,
    
    /// Whether subscription is active
    pub active: AtomicBool,
    
    /// Subscription statistics
    pub stats: Arc<Mutex<SubscriptionStats>>,
    
    /// Cancellation token
    pub cancellation_token: CancellationToken,
}

#[derive(Debug, Clone)]
pub enum SubscriptionType {
    Swap,
    Liquidity, 
    Price,
    All,
}

#[derive(Debug, Clone)]
pub enum SubscriptionTarget {
    Global,
    Pool(Pubkey),
    Position(Pubkey),
    User(Pubkey),
}

#[derive(Debug, Clone)]
pub struct SubscriptionStats {
    /// Events received count
    pub events_received: u64,
    /// Subscription creation time
    pub created_at: Instant,
    /// Last event timestamp
    pub last_event_at: Option<Instant>,
    /// Total bytes processed
    pub bytes_processed: u64,
    /// Error count
    pub errors: u32,
}

impl Subscription {
    /// Unsubscribe from events
    pub fn unsubscribe(&self) {
        self.active.store(false, Ordering::Relaxed);
        self.cancellation_token.cancel();
    }
    
    /// Get subscription statistics
    pub fn get_stats(&self) -> SubscriptionStats {
        self.stats.lock().unwrap().clone()
    }
    
    /// Check if subscription is active
    pub fn is_active(&self) -> bool {
        self.active.load(Ordering::Relaxed)
    }
}

Error Types

DlmmError

Comprehensive error type with Rust error handling patterns.
#[derive(Debug, Error, Clone, Serialize, Deserialize)]
pub enum DlmmError {
    /// Network-related errors
    #[error("Network error: {message}")]
    Network { 
        message: String, 
        code: NetworkErrorCode,
        retryable: bool,
        retry_after: Option<Duration>,
    },
    
    /// Insufficient balance errors
    #[error("Insufficient balance: {message}")]
    InsufficientBalance { 
        message: String,
        required_amount: u64,
        available_amount: u64,
        token_mint: Pubkey,
    },
    
    /// Slippage-related errors
    #[error("Slippage exceeded: expected {expected}, got {actual}")]
    SlippageExceeded {
        expected: f64,
        actual: f64,
        threshold: f64,
    },
    
    /// Pool validation errors
    #[error("Invalid pool: {message}")]
    InvalidPool {
        message: String,
        pool_address: Pubkey,
        error_code: PoolErrorCode,
    },
    
    /// Position-related errors
    #[error("Position error: {message}")]
    PositionError {
        message: String,
        position_address: Option<Pubkey>,
        error_code: PositionErrorCode,
    },
    
    /// Parameter validation errors
    #[error("Invalid parameters: {message}")]
    InvalidParameters {
        message: String,
        field: Option<String>,
        validation_errors: Vec<ValidationError>,
    },
    
    /// Wallet/signing errors
    #[error("Wallet error: {message}")]
    WalletError {
        message: String,
        error_code: WalletErrorCode,
    },
    
    /// RPC-specific errors
    #[error("RPC error: {message}")]
    RpcError {
        message: String,
        error_code: i64,
        data: Option<Value>,
    },
    
    /// Transaction execution errors
    #[error("Transaction failed: {message}")]
    TransactionFailed {
        message: String,
        signature: Option<Signature>,
        error_code: TransactionErrorCode,
        logs: Vec<String>,
    },
    
    /// Rate limiting errors
    #[error("Rate limited: {message}")]
    RateLimited {
        message: String,
        retry_after: Duration,
        current_requests: u32,
        max_requests: u32,
    },
    
    /// Pool maintenance errors
    #[error("Pool in maintenance mode")]
    MaintenanceMode {
        pool_address: Pubkey,
        estimated_end_time: Option<SystemTime>,
    },
    
    /// Unsupported operation errors
    #[error("Unsupported operation: {message}")]
    UnsupportedOperation {
        message: String,
        operation: String,
        reason: String,
    },
    
    /// Internal SDK errors
    #[error("Internal error: {message}")]
    Internal {
        message: String,
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum NetworkErrorCode {
    ConnectionTimeout,
    ConnectionRefused,
    DnsResolution,
    SslError,
    RateLimited,
    ServiceUnavailable,
    Unknown,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PoolErrorCode {
    NotFound,
    Paused,
    Deprecated,
    InsufficientLiquidity,
    InvalidConfiguration,
    Unknown,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PositionErrorCode {
    NotFound,
    NotOwned,
    Closed,
    OutOfRange,
    InsufficientBalance,
    Unknown,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum WalletErrorCode {
    NotConnected,
    UserRejected,
    InsufficientSol,
    SigningFailed,
    Unknown,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TransactionErrorCode {
    InsufficientFunds,
    BlockhashNotFound,
    SimulationFailed,
    SendFailed,
    ConfirmationTimeout,
    Unknown,
}

ValidationError

Individual validation error with detailed information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationError {
    /// Error severity level
    pub level: ValidationLevel,
    
    /// Error category
    pub category: ValidationCategory,
    
    /// Error message
    pub message: String,
    
    /// Field that caused the error
    pub field: Option<String>,
    
    /// Current value (if applicable)
    pub current_value: Option<String>,
    
    /// Expected value or format
    pub expected: Option<String>,
    
    /// Suggested fix
    pub suggestion: Option<String>,
    
    /// Whether this blocks execution
    pub blocking: bool,
    
    /// Error code for programmatic handling
    pub code: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ValidationLevel {
    Error,
    Warning,
    Info,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ValidationCategory {
    Parameters,
    Balance,
    Slippage,
    Pool,
    Network,
    Authorization,
    Configuration,
}

Utility Types and Enums

Timeframe

Time period enumeration for analytics.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Hash, Eq, PartialEq)]
pub enum Timeframe {
    OneMinute,
    FiveMinutes,
    FifteenMinutes,
    OneHour,
    FourHours,
    TwentyFourHours,
    SevenDays,
    ThirtyDays,
}

impl Timeframe {
    /// Get duration in seconds
    pub fn to_seconds(&self) -> u64 {
        match self {
            Timeframe::OneMinute => 60,
            Timeframe::FiveMinutes => 300,
            Timeframe::FifteenMinutes => 900,
            Timeframe::OneHour => 3600,
            Timeframe::FourHours => 14400,
            Timeframe::TwentyFourHours => 86400,
            Timeframe::SevenDays => 604800,
            Timeframe::ThirtyDays => 2592000,
        }
    }
}

PositionStatus

Position lifecycle status with detailed states.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum PositionStatus {
    /// Position is being created
    Pending,
    /// Position is active and earning fees
    Active,
    /// Position is outside current trading range
    OutOfRange,
    /// Position is being rebalanced
    Rebalancing,
    /// Position is being withdrawn
    Withdrawing,
    /// Position has been closed by user
    Closed,
    /// Position creation failed
    Failed,
    /// Position is frozen due to error
    Frozen,
}

impl PositionStatus {
    /// Check if position can be modified
    pub fn is_modifiable(&self) -> bool {
        matches!(self, PositionStatus::Active | PositionStatus::OutOfRange)
    }
    
    /// Check if position is earning fees
    pub fn is_earning(&self) -> bool {
        matches!(self, PositionStatus::Active)
    }
    
    /// Check if position is in a final state
    pub fn is_final(&self) -> bool {
        matches!(self, PositionStatus::Closed | PositionStatus::Failed)
    }
}

PoolStatus

Pool operational status with detailed information.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum PoolStatus {
    /// Pool is being initialized
    Initializing,
    /// Pool is active and accepting trades
    Active,
    /// Pool is temporarily paused
    Paused,
    /// Pool is under maintenance
    Maintenance,
    /// Pool is deprecated and should not be used
    Deprecated,
    /// Pool has been permanently closed
    Closed,
    /// Pool is in emergency mode
    Emergency,
}

impl PoolStatus {
    /// Check if pool accepts new trades
    pub fn accepts_trades(&self) -> bool {
        matches!(self, PoolStatus::Active)
    }
    
    /// Check if pool accepts new liquidity
    pub fn accepts_liquidity(&self) -> bool {
        matches!(self, PoolStatus::Active | PoolStatus::Paused)
    }
    
    /// Check if pool allows withdrawals
    pub fn allows_withdrawals(&self) -> bool {
        !matches!(self, PoolStatus::Closed | PoolStatus::Emergency)
    }
}

Type Aliases and Constants

Type Aliases

/// Unix timestamp in seconds
pub type Timestamp = i64;

/// USD amount with 6 decimal places
pub type UsdAmount = u64;

/// Token amount in smallest unit
pub type TokenAmount = u64;

/// Basis points (1/10000)
pub type BasisPoints = u16;

/// Fixed point number Q64.64
pub type Q64x64 = u128;

/// Result type for SDK operations
pub type DlmmResult<T> = Result<T, DlmmError>;

/// Async result type for SDK operations
pub type DlmmAsyncResult<T> = Pin<Box<dyn Future<Output = DlmmResult<T>> + Send>>;

Constants

/// Maximum number of bins in a single pool
pub const MAX_BINS_PER_POOL: u32 = 100_000;

/// Maximum position range in bins
pub const MAX_POSITION_RANGE: u32 = 1_000;

/// Minimum bin step (1 basis point)
pub const MIN_BIN_STEP: u16 = 1;

/// Maximum bin step (100%)
pub const MAX_BIN_STEP: u16 = 10_000;

/// Default slippage tolerance (50 basis points = 0.5%)
pub const DEFAULT_SLIPPAGE_BPS: u16 = 50;

/// Maximum slippage tolerance (1000 basis points = 10%)
pub const MAX_SLIPPAGE_BPS: u16 = 1_000;

/// USD decimals (6 decimal places)
pub const USD_DECIMALS: u8 = 6;

/// Basis points scale (10,000 = 100%)
pub const BASIS_POINTS_SCALE: u16 = 10_000;

/// Q64.64 scale factor
pub const Q64X64_SCALE: u128 = 1u128 << 64;

/// Maximum priority fee in lamports
pub const MAX_PRIORITY_FEE: u64 = 1_000_000;

/// Default compute units
pub const DEFAULT_COMPUTE_UNITS: u32 = 200_000;

/// Maximum compute units
pub const MAX_COMPUTE_UNITS: u32 = 1_400_000;

Trait Definitions

Core Traits

/// Trait for types that can be converted to/from raw bytes
pub trait Serializable: Sized {
    fn to_bytes(&self) -> DlmmResult<Vec<u8>>;
    fn from_bytes(bytes: &[u8]) -> DlmmResult<Self>;
}

/// Trait for price calculations
pub trait PriceCalculation {
    fn calculate_price(&self, bin_id: i32) -> DlmmResult<Q64x64>;
    fn price_to_bin_id(&self, price: Q64x64) -> DlmmResult<i32>;
}

/// Trait for fee calculations
pub trait FeeCalculation {
    fn calculate_fees(&self, amount: TokenAmount) -> DlmmResult<TokenAmount>;
    fn calculate_protocol_fee(&self, total_fee: TokenAmount) -> TokenAmount;
}

/// Trait for liquidity calculations
pub trait LiquidityCalculation {
    fn calculate_liquidity_amounts(
        &self,
        bin_range: BinRange,
        amount_x: TokenAmount,
        amount_y: TokenAmount,
    ) -> DlmmResult<Vec<(i32, TokenAmount, TokenAmount)>>;
}

Import Examples

Complete SDK Import

use saros_dlmm_sdk::{
    // Core types
    DlmmClient,
    DlmmConfig,
    DlmmResult,
    
    // Trading types
    SwapQuoteParams,
    SwapQuote,
    SwapParams,
    SwapResult,
    
    // Pool types
    PoolInfo,
    PoolSummary,
    PoolSearchParams,
    PoolRecommendation,
    
    // Position types
    Position,
    PositionAnalytics,
    AddLiquidityParams,
    LiquidityResult,
    RemoveLiquidityParams,
    WithdrawResult,
    
    // Analytics types
    PoolAnalytics,
    VolumeAnalytics,
    LiquidityAnalytics,
    
    // Error types
    DlmmError,
    ValidationError,
    
    // Event types
    SwapEvent,
    LiquidityEvent,
    Subscription,
    
    // Utility types
    Timeframe,
    PositionStatus,
    PoolStatus,
    RiskLevel,
    
    // Constants
    DEFAULT_SLIPPAGE_BPS,
    MAX_POSITION_RANGE,
    USD_DECIMALS,
};

Selective Import

// Import only what you need for better compile times
use saros_dlmm_sdk::{
    DlmmClient,
    SwapQuoteParams,
    SwapParams,
    DlmmResult,
    DlmmError,
};

Version Compatibility

Typev2.1.0v2.0.0v1.8.0Breaking Changes
SwapQuoteParams✅ Current✅ Compatible❌ Missing fieldsv2.0: Added Rust-specific optimizations
PoolInfo✅ Current⚠️ Layout changed❌ Different serializationv2.0: Zero-copy optimizations
Position✅ Current✅ Compatible❌ Missing analyticsv1.8: Added performance tracking
DlmmConfig✅ Current⚠️ Missing perf options✅ Compatiblev2.0: Added Rust-specific config
Minimum Rust Version: 1.70.0 Dependencies: anchor-lang, solana-sdk, tokio, serde

Reference Documentation

Getting Started (Tutorials)

Solve Problems (How-To Guides)

Understanding Concepts (Explanation)