Skip to main content

wp_solana_amm_math/
lib.rs

1//! Solana AMM math primitives.
2//!
3//! Pure math library for concentrated liquidity AMMs (Uniswap V3-style).
4//! Covers tick/price conversions, swap step computation, liquidity math,
5//! fee calculations, slippage utilities, and Meteora DLMM bin-price math.
6//!
7//! All functions are deterministic and RPC-free.
8
9pub mod bin_price;
10pub mod fee_math;
11pub mod fixed_point;
12pub mod full_math;
13pub mod liquidity_math;
14pub mod price_math;
15pub mod slippage;
16pub mod swap_math;
17pub mod tick_math;
18
19// Re-export commonly used fixed-point primitives
20pub use fixed_point::{
21    mul_div, mul_shr, pow, safe_mul_div_cast, safe_mul_shr_cast, safe_shl_div_cast, shl_div,
22    Rounding, MAX_EXPONENTIAL, ONE, PRECISION, SCALE_OFFSET,
23};
24// Re-export commonly used types from liquidity_math for convenience
25pub use liquidity_math::{
26    decrease_liquidity_quote, decrease_liquidity_quote_a, decrease_liquidity_quote_b,
27    increase_liquidity_quote, increase_liquidity_quote_a, increase_liquidity_quote_b,
28    order_tick_indexes, DecreaseLiquidityQuote, IncreaseLiquidityQuote, TickRange, TransferFee,
29};
30// Re-export price math utilities
31pub use price_math::invert_price;
32// Re-export slippage and transfer fee utilities
33pub use slippage::{
34    apply_transfer_fee, max_amount_with_slippage, min_amount_with_slippage,
35    reverse_apply_transfer_fee, sqrt_price_slippage_bounds,
36};
37// Re-export swap math primitives
38pub use swap_math::{
39    compute_swap_step, get_next_sqrt_price_from_input, get_next_sqrt_price_from_output,
40    SwapStepResult,
41};
42use thiserror::Error;
43// Re-export tick array helpers from tick_math
44pub use tick_math::{
45    get_full_range_tick_indexes, get_initializable_tick_index, get_next_initializable_tick_index,
46    get_prev_initializable_tick_index, get_tick_array_start_index, get_tick_index_in_array,
47    invert_tick_index, is_position_in_range, is_tick_in_bounds, is_tick_initializable, tick_count,
48    RAYDIUM_TICK_ARRAY_SIZE, WHIRLPOOL_TICK_ARRAY_SIZE,
49};
50
51/// Errors returned by AMM math operations.
52#[derive(Debug, Error, PartialEq, Eq)]
53pub enum AmmMathError {
54    /// A division by zero was attempted.
55    #[error("division by zero")]
56    DivisionByZero,
57    /// An intermediate or final result overflowed the target integer type.
58    #[error("result overflow")]
59    Overflow,
60    /// The tick index is outside the valid range [`MIN_TICK`, `MAX_TICK`].
61    #[error("tick out of range: {0}")]
62    TickOutOfRange(i32),
63    /// The sqrt price is outside the valid range.
64    #[error("sqrt price out of range: {0}")]
65    SqrtPriceOutOfRange(u128),
66    /// The fee rate exceeds the maximum allowed (10 000 bps = 100%).
67    #[error("invalid fee rate: {0} bps")]
68    InvalidFeeRate(u16),
69}