Skip to main content

waterpump_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
25// Re-export commonly used types from liquidity_math for convenience
26pub use liquidity_math::{
27    decrease_liquidity_quote, decrease_liquidity_quote_a, decrease_liquidity_quote_b,
28    increase_liquidity_quote, increase_liquidity_quote_a, increase_liquidity_quote_b,
29    order_tick_indexes, DecreaseLiquidityQuote, IncreaseLiquidityQuote, TickRange, TransferFee,
30};
31// Re-export swap math primitives
32pub use swap_math::{
33    compute_swap_step, get_next_sqrt_price_from_input, get_next_sqrt_price_from_output,
34    SwapStepResult,
35};
36
37// Re-export tick array helpers from tick_math
38pub use tick_math::{
39    get_full_range_tick_indexes, get_initializable_tick_index,
40    get_next_initializable_tick_index, get_prev_initializable_tick_index,
41    get_tick_array_start_index, get_tick_index_in_array, invert_tick_index,
42    is_position_in_range, is_tick_in_bounds, is_tick_initializable, tick_count,
43    RAYDIUM_TICK_ARRAY_SIZE, WHIRLPOOL_TICK_ARRAY_SIZE,
44};
45
46// Re-export price math utilities
47pub use price_math::invert_price;
48
49// Re-export slippage and transfer fee utilities
50pub use slippage::{
51    apply_transfer_fee, max_amount_with_slippage, min_amount_with_slippage,
52    reverse_apply_transfer_fee, sqrt_price_slippage_bounds,
53};
54
55use thiserror::Error;
56
57/// Errors returned by AMM math operations.
58#[derive(Debug, Error, PartialEq, Eq)]
59pub enum AmmMathError {
60    /// A division by zero was attempted.
61    #[error("division by zero")]
62    DivisionByZero,
63    /// An intermediate or final result overflowed the target integer type.
64    #[error("result overflow")]
65    Overflow,
66    /// The tick index is outside the valid range [`MIN_TICK`, `MAX_TICK`].
67    #[error("tick out of range: {0}")]
68    TickOutOfRange(i32),
69    /// The sqrt price is outside the valid range.
70    #[error("sqrt price out of range: {0}")]
71    SqrtPriceOutOfRange(u128),
72    /// The fee rate exceeds the maximum allowed (10 000 bps = 100%).
73    #[error("invalid fee rate: {0} bps")]
74    InvalidFeeRate(u16),
75}