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

liquidity_management.gno

2.07 Kb · 67 lines
 1package position
 2
 3import (
 4	"gno.land/p/gnoswap/gnsmath/v1"
 5	u256 "gno.land/p/gnoswap/uint256/v1"
 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	sqrtPriceX96String, err := pl.GetSlot0SqrtPriceX96(params.poolKey)
24	if err != nil {
25		panic(err)
26	}
27	sqrtPriceX96 := u256.MustFromDecimal(sqrtPriceX96String)
28	sqrtRatioAX96 := gnsmath.TickMathGetSqrtRatioAtTick(params.tickLower)
29	sqrtRatioBX96 := gnsmath.TickMathGetSqrtRatioAtTick(params.tickUpper)
30
31	liquidity := gnsmath.GetLiquidityForAmounts(
32		sqrtPriceX96,
33		sqrtRatioAX96,
34		sqrtRatioBX96,
35		params.amount0Desired,
36		params.amount1Desired,
37	)
38
39	token0, token1, fee := splitOf(params.poolKey)
40	amount0Str, amount1Str := pl.Mint(
41		cross(rlm),
42		token0,
43		token1,
44		fee,
45		params.tickLower,
46		params.tickUpper,
47		liquidity.ToString(),
48		params.caller,
49	)
50
51	amount0 := u256.MustFromDecimal(amount0Str)
52	amount1 := u256.MustFromDecimal(amount1Str)
53
54	amount0Cond := amount0.Gte(params.amount0Min)
55	amount1Cond := amount1.Gte(params.amount1Min)
56
57	if !(amount0Cond && amount1Cond) {
58		panic(newErrorWithDetail(
59			errSlippage,
60			ufmt.Sprintf(
61				"Price Slippage Check(amount0(%s) >= amount0Min(%s), amount1(%s) >= amount1Min(%s))",
62				amount0Str, params.amount0Min.ToString(), amount1Str, params.amount1Min.ToString()),
63		))
64	}
65
66	return liquidity, amount0, amount1
67}