Keyboard shortcuts

Press or to navigate between chapters

Press ? to show this help

Press Esc to hide this help

pool

AMM Pool Math

Constant product (x×y=k) AMM formulas and related calculations.

Core Functions

  • constant_product_out - Calculate swap output amount
  • constant_product_in - Calculate swap input amount
  • price_from_reserves - Get spot price from reserves
  • price_impact - Calculate trade price impact
  • slippage - Calculate execution slippage

Liquidity Functions

  • initial_lp_tokens - LP tokens for initial deposit (sqrt(x×y))
  • mint_lp_tokens - LP tokens for subsequent deposits
  • liquidity_share - User’s share of reserves
  • remove_liquidity - Amounts returned on withdrawal

Example

use cairo_fp::f128::math::pool::{constant_product_out, price_from_reserves};

// Pool with 1000 ETH and 2M USDC
let eth = FixedTrait::new_unscaled(1000, false);
let usdc = FixedTrait::new_unscaled(2000000, false);

// Get spot price
let price = price_from_reserves(eth, usdc).unwrap(); // 2000 USDC/ETH

// Swap 10 ETH
let eth_in = FixedTrait::new_unscaled(10, false);
let usdc_out = constant_product_out(eth, usdc, eth_in).unwrap();

Fully qualified path: cairo_fp::f128::math::pool

Free functions

constant_product_outCalculates output amount for a constant product swap. Given reserves x, y and input dx, returns dy such that (x+dx)(y-dy) = xy…
constant_product_in
price_from_reserves
price_impact
slippage
liquidity_share
calculate_k
initial_lp_tokens
mint_lp_tokens
add_liquidity
remove_liquidity