clmm_swap_math/
lib.rs

1//! Uniswap V3–style math and swap simulation in pure Rust.
2//!
3//! This crate exposes:
4//! - Low‑level math primitives (`math::*`) for ticks, prices and bitmaps.
5//! - A lightweight in‑memory `V3Pool` that can execute Uniswap V3‑style swaps.
6//! - Optional `onchain` helpers to hydrate the pool from a real on‑chain pool.
7//!
8//! # Examples
9//!
10//! ## Pure math
11//! ```no_run
12//! use clmm_swap_math::{math::tick_math, RESOLUTION, U256};
13//!
14//! let sqrt_price = tick_math::get_sqrt_ratio_at_tick(0).unwrap();
15//! assert!(sqrt_price > U256::ZERO);
16//! assert_eq!(RESOLUTION, 96);
17//! ```
18//!
19//! ## Simulating a swap in an in‑memory pool
20//! ```no_run
21//! use clmm_swap_math::{
22//!     math::tick_math::get_sqrt_ratio_at_tick,
23//!     pool::swap::{SwapParams, calculate_sqrt_price_limit},
24//!     V3Pool, FastMap, I256, U256,
25//! };
26//!
27//! // Construct a simple in‑memory pool (no on‑chain provider).
28//! # let pool_address = clmm_swap_math::Address::ZERO;
29//! # let token0 = clmm_swap_math::Address::ZERO;
30//! # let token1 = clmm_swap_math::Address::from([0u8; 20]);
31//! let mut pool: V3Pool<()> = V3Pool::new(pool_address, token0, token1, 3000);
32//! pool.slot0.sqrt_price_x96 = get_sqrt_ratio_at_tick(0).unwrap();
33//! pool.slot0.tick = 0;
34//! pool.liquidity = 1_000_000_000_000_000_000u128;
35//! pool.tick_spacing = 1;
36//! pool.bitmap = FastMap::default();
37//!
38//! let zero_for_one = true;
39//! let amount_specified = I256::from_raw(U256::from(1_000_000_000_000_000_000u128)); // 1e18
40//! let sqrt_price_limit_x96 =
41//!     calculate_sqrt_price_limit(pool.slot0.sqrt_price_x96, zero_for_one, 1.0); // 1% slippage
42//!
43//! let params = SwapParams::new(zero_for_one, amount_specified, sqrt_price_limit_x96);
44//! let result = pool.swap(params).unwrap();
45//! println!("amount0: {}, amount1: {}", result.amount0_delta, result.amount1_delta);
46//! ```
47
48pub use alloy_primitives::{Address, I256, U256};
49
50pub mod error;
51mod hash;
52pub mod math;
53
54pub use hash::FastMap;
55
56pub mod pool;
57
58pub use pool::v3_pool::V3Pool;
59
60const U256_1: U256 = U256::from_limbs([1, 0, 0, 0]);
61
62const U160_MAX: U256 = U256::from_limbs([0, 0, 4294967296, 0]);
63const U256_E4: U256 = U256::from_limbs([10000, 0, 0, 0]);
64const U256_E6: U256 = U256::from_limbs([1000000, 0, 0, 0]);
65
66pub const RESOLUTION: u8 = 96;
67pub const Q96: U256 = U256::from_limbs([0, 4294967296, 0, 0]);