liquidity_management.gno
1.98 Kb · 63 lines
1package v1
2
3import (
4 "gno.land/p/gnoswap/gnsmath"
5 u256 "gno.land/p/gnoswap/uint256"
6 ufmt "gno.land/p/nt/ufmt/v0"
7 pl "gno.land/r/gnoswap/pool"
8)
9
10type AddLiquidityParams struct {
11 poolKey string // poolPath of the pool which has the position
12 tickLower int32 // lower end of the tick range for the position
13 tickUpper int32 // upper end of the tick range for the position
14 amount0Desired *u256.Uint // desired amount of token0 to be minted
15 amount1Desired *u256.Uint // desired amount of token1 to be minted
16 amount0Min *u256.Uint // minimum amount of token0 to be minted
17 amount1Min *u256.Uint // minimum amount of token1 to be minted
18 caller address // address to call the function
19}
20
21// addLiquidity calculates liquidity amounts and mints position tokens to a pool.
22func (p *positionV1) addLiquidity(_ int, rlm realm, params AddLiquidityParams) (*u256.Uint, *u256.Uint, *u256.Uint) {
23 sqrtPriceX96 := u256.MustFromDecimal(pl.GetSlot0SqrtPriceX96(params.poolKey))
24 sqrtRatioAX96 := gnsmath.TickMathGetSqrtRatioAtTick(params.tickLower)
25 sqrtRatioBX96 := gnsmath.TickMathGetSqrtRatioAtTick(params.tickUpper)
26
27 liquidity := gnsmath.GetLiquidityForAmounts(
28 sqrtPriceX96,
29 sqrtRatioAX96,
30 sqrtRatioBX96,
31 params.amount0Desired,
32 params.amount1Desired,
33 )
34
35 token0, token1, fee := splitOf(params.poolKey)
36 amount0Str, amount1Str := pl.Mint(
37 cross(rlm),
38 token0,
39 token1,
40 fee,
41 params.tickLower,
42 params.tickUpper,
43 liquidity.ToString(),
44 params.caller,
45 )
46
47 amount0 := u256.MustFromDecimal(amount0Str)
48 amount1 := u256.MustFromDecimal(amount1Str)
49
50 amount0Cond := amount0.Gte(params.amount0Min)
51 amount1Cond := amount1.Gte(params.amount1Min)
52
53 if !(amount0Cond && amount1Cond) {
54 panic(newErrorWithDetail(
55 errSlippage,
56 ufmt.Sprintf(
57 "Price Slippage Check(amount0(%s) >= amount0Min(%s), amount1(%s) >= amount1Min(%s))",
58 amount0Str, params.amount0Min.ToString(), amount1Str, params.amount1Min.ToString()),
59 ))
60 }
61
62 return liquidity, amount0, amount1
63}