Skip to content Search Apps Documentation Source Content File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

doc.gno

2.44 Kb · 62 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; accepts
46//     `[MinSqrtRatio, MaxSqrtRatio)` (the upper bound is exclusive)
47//
48// ### Liquidity Math
49//
50//   - GetLiquidityForAmounts(sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, amount0, amount1 *u256.Uint) *u256.Uint
51//   - GetAmountsForLiquidity(sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, liquidity *u256.Uint) (*u256.Uint, *u256.Uint)
52//   - LiquidityMathAddDelta(x *u256.Uint, y *i256.Int) *u256.Uint
53//
54// ### Sqrt Price Math
55//
56//   - GetAmount0Delta(sqrtRatioAX96, sqrtRatioBX96 *u256.Uint, liquidity *i256.Int) *i256.Int
57//   - GetAmount1Delta(sqrtRatioAX96, sqrtRatioBX96 *u256.Uint, liquidity *i256.Int) *i256.Int
58//
59// ### Swap Math
60//
61//   - SwapMathComputeSwapStep(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity *u256.Uint, amountRemaining *i256.Int, feePips uint64) (*u256.Uint, *u256.Uint, *u256.Uint, *u256.Uint)
62package gnsmath