doc.gno
2.36 Kb · 61 lines
1// Package gnsmath provides core mathematical operations for GnoSwap's concentrated liquidity AMM.
2//
3// ## Overview
4//
5// This package provides the fundamental calculations for concentrated liquidity,
6// including tick conversion, liquidity math calculations, sqrt price math, swap
7// calculations, and bit manipulation utilities. All operations use Q64.96,
8// Q128.128, and Q160 fixed-point arithmetic where appropriate.
9//
10// The implementation follows Uniswap V3's mathematical model.
11//
12// ## Features
13//
14// - Bit Math: MSB/LSB calculations for tick bitmap operations
15// - Tick Math: tick and Q64.96 sqrt-price conversions
16// - Liquidity Math: liquidity and token amount math for price ranges
17// - Sqrt Price Math: token amount conversions using Q64.96 format
18// - Swap Math: single-step swap calculations with fee handling
19// - Overflow Protection: explicit int256/uint256 overflow checks
20// - Rounding Control: configurable rounding for AMM safety
21//
22// ## Core Concepts
23//
24// ### Q64.96 Fixed-Point Format
25//
26// Square root prices use Q64.96 representation:
27// - sqrtPriceX96 = sqrt(token1/token0) * 2^96
28// - Enables precise integer arithmetic without floating-point
29//
30// ### Rounding Directions
31//
32// - Round UP: amounts owed TO pool (deposits, exact input)
33// - Round DOWN: amounts owed FROM pool (withdrawals, exact output)
34//
35// ## API
36//
37// ### Bit Math
38//
39// - BitMathMostSignificantBit(x *u256.Uint) uint8
40// - BitMathLeastSignificantBit(x *u256.Uint) uint8
41//
42// ### Tick Math
43//
44// - TickMathGetSqrtRatioAtTick(tick int32) *u256.Uint
45// - TickMathGetTickAtSqrtRatio(sqrtPriceX96 *u256.Uint) int32
46//
47// ### Liquidity Math
48//
49// - GetLiquidityForAmounts(sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, amount0, amount1 *u256.Uint) *u256.Uint
50// - GetAmountsForLiquidity(sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, liquidity *u256.Uint) (*u256.Uint, *u256.Uint)
51// - LiquidityMathAddDelta(x *u256.Uint, y *i256.Int) *u256.Uint
52//
53// ### Sqrt Price Math
54//
55// - GetAmount0Delta(sqrtRatioAX96, sqrtRatioBX96 *u256.Uint, liquidity *i256.Int) *i256.Int
56// - GetAmount1Delta(sqrtRatioAX96, sqrtRatioBX96 *u256.Uint, liquidity *i256.Int) *i256.Int
57//
58// ### Swap Math
59//
60// - SwapMathComputeSwapStep(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity *u256.Uint, amountRemaining *i256.Int, feePips uint64) (*u256.Uint, *u256.Uint, *u256.Uint, *u256.Uint)
61package gnsmath