From 23f46ac7aaab3da126a45e697063dafff56eae47 Mon Sep 17 00:00:00 2001 From: n3wbie Date: Wed, 6 Mar 2024 21:21:51 +0900 Subject: [PATCH 1/5] feat: uint256, int256 instead of bigint --- ...ST_scenario_99_router_uniswap_sdk_test.gno | 245 ------------------ ...scenario_99_router_uniswap_sdk_test.gnoXXX | 244 +++++++++++++++++ packages/big/uint512/uint512.gno | 131 ++++++++++ packages/big/uint512/uint512_test.gno | 37 +++ pool/_TEST_pool_dryswap_and_swap_test.gno | 6 +- ...est.gnoa => _TEST_pool_single_lp_test.gno} | 0 pool/pool.gno | 4 +- pool/position_modify.gno | 11 + position/liquidity_management.gno | 3 + position/position.gno | 3 + position/sqrt_price_math.gno | 18 ++ router/_RPC_api.gno | 19 +- ...ST_router_swap_route_1route_1hop_test.gno} | 10 +- 13 files changed, 468 insertions(+), 263 deletions(-) delete mode 100644 _test/_TEST_scenario_99_router_uniswap_sdk_test.gno create mode 100644 _test/_TEST_scenario_99_router_uniswap_sdk_test.gnoXXX create mode 100644 packages/big/uint512/uint512.gno create mode 100644 packages/big/uint512/uint512_test.gno rename pool/{_TEST_pool_single_lp_test.gnoa => _TEST_pool_single_lp_test.gno} (100%) rename router/{_TEST_router_swap_route_1route_1hop_test.gnoa => _TEST_router_swap_route_1route_1hop_test.gno} (95%) diff --git a/_test/_TEST_scenario_99_router_uniswap_sdk_test.gno b/_test/_TEST_scenario_99_router_uniswap_sdk_test.gno deleted file mode 100644 index f75a75f52..000000000 --- a/_test/_TEST_scenario_99_router_uniswap_sdk_test.gno +++ /dev/null @@ -1,245 +0,0 @@ -/* -UNISWAP TEST REF - - https://github.com/Uniswap/v3-core/blob/main/test/shared/fixtures.ts - - https://github.com/Uniswap/v3-core/blob/main/test/UniswapV3Router.spec.ts - - https://github.com/Uniswap/router-sdk/blob/main/src/swapRouter.test.ts -*/ -package swap_scenario - -import ( - "std" - "testing" - - "gno.land/p/demo/testutils" - - "gno.land/r/demo/consts" - - pl "gno.land/r/demo/pool" - pn "gno.land/r/demo/position" - rr "gno.land/r/demo/router" - - "gno.land/r/demo/bar" - "gno.land/r/demo/baz" - "gno.land/r/demo/foo" - - "gno.land/r/demo/gns" -) - -var ( - lp01 = testutils.TestAddress("lp01") - tr01 = testutils.TestAddress("tr01") - - // vars from Uniswap TEST - feeAmount uint32 = 3000 - // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/UniswapV3Router.spec.ts#L24 - // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/shared/utilities.ts#L23 - - tickSpacing = 60 - // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/UniswapV3Router.spec.ts#L25 - // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/shared/utilities.ts#L29 - - minTick int32 = -887272 - maxTick int32 = 887272 - // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/shared/utilities.ts#L10-L11 -) - -func TestPoolInitByAdmin(t *testing.T) { - std.TestSetOrigCaller(gsa) - pl.InitManual() - - std.TestSkipHeights(1) -} - -func TestPoolCreatePools(t *testing.T) { - std.TestSetPrevAddr(test1) - gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE*2) - - // bar-baz - pl.CreatePool(barPath, bazPath, 100, "79228162514264337593543950337") // tick 0 ≈ 1:1 - - // baz-foo - pl.CreatePool(bazPath, fooPath, 100, "79228162514264337593543950337") // tick 0 ≈ 1:1 - - std.TestSkipHeights(4) -} - -func TestFaucetLP01(t *testing.T) { - std.TestSetOrigCaller(lp01) - - shouldEQ(t, bar.BalanceOf(a2u(lp01)), 0) - shouldEQ(t, baz.BalanceOf(a2u(lp01)), 0) - shouldEQ(t, foo.BalanceOf(a2u(lp01)), 0) - - bar.Faucet(lp01) - baz.Faucet(lp01) - foo.Faucet(lp01) - - shouldEQ(t, bar.BalanceOf(a2u(lp01)), 100000000) - shouldEQ(t, baz.BalanceOf(a2u(lp01)), 100000000) - shouldEQ(t, foo.BalanceOf(a2u(lp01)), 100000000) - std.TestSkipHeights(5) -} - -// https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/UniswapV3Router.spec.ts#L83C16-L83C16 -func TestPositionMintBarBazInRange(t *testing.T) { - std.TestSetOrigCaller(lp01) - - // approve bar, baz to pool ( position.Mint() calls pool.Mint() ≈ so approve to pool ) - bar.Approve(a2u(consts.POOL_ADDR), 10000000) - baz.Approve(a2u(consts.POOL_ADDR), 10000000) - - tokenId, liquidity, amount0, amoutn1 := pn.Mint( - barPath, // token0 - bazPath, // token1 - 100, // fee - minTick, // tickLower - maxTick, // tickUpper - "10000000", // amount0Desired - "10000000", // amount1Desired - "0", // amount0Min - "0", // amount1Min - max_timeout, // deadline - ) - - shouldEQ(t, tokenId, 1) - shouldEQ(t, liquidity, "10000000") - shouldEQ(t, amount0, "10000000") - shouldEQ(t, amoutn1, "9999999") - - std.TestSkipHeights(3) -} - -// https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/UniswapV3Router.spec.ts#L84 -func TestPositionMintBazFooInRange(t *testing.T) { - std.TestSetOrigCaller(lp01) - - // approve bar, baz to pool ( position.Mint() calls pool.Mint() ≈ so approve to pool ) - baz.Approve(a2u(consts.POOL_ADDR), 10000000) - foo.Approve(a2u(consts.POOL_ADDR), 10000000) - - tokenId, liquidity, amount0, amoutn1 := pn.Mint( - bazPath, // token0 - fooPath, // token1 - 100, // fee - minTick, // tickLower - maxTick, // tickUpper - "10000000", // amount0Desired - "10000000", // amount1Desired - "0", // amount0Min - "0", // amount1Min - max_timeout, // deadline - ) - - shouldEQ(t, tokenId, 2) - shouldEQ(t, liquidity, "10000000") - shouldEQ(t, amount0, "10000000") - shouldEQ(t, amoutn1, "9999999") - - std.TestSkipHeights(3) -} - -func TestFaucetTR01(t *testing.T) { - std.TestSetOrigCaller(tr01) - - shouldEQ(t, bar.BalanceOf(a2u(tr01)), 0) - - bar.Faucet(tr01) - - shouldEQ(t, bar.BalanceOf(a2u(tr01)), 100000000) - - std.TestSkipHeights(5) -} - -func TestRouterDrySwapRouteBarFooExactIn(t *testing.T) { - std.TestSetOrigCaller(tr01) - - dryResult := rr.DrySwapRoute( - barPath, // inputToken - fooPath, // outputToken - "100000", // amountSpecified - "EXACT_IN", // swapType - "gno.land/r/demo/bar:gno.land/r/demo/baz:100*POOL*gno.land/r/demo/baz:gno.land/r/demo/foo:100", // strRouteArr - "100", // quoteArr - ) - shouldEQ(t, dryResult, "98019") - std.TestSkipHeights(2) -} - -func TestRouterSwapRouteBarFooExactIn(t *testing.T) { - std.TestSetOrigCaller(tr01) - - // approve bar to pool - bar.Approve(a2u(consts.POOL_ADDR), 100000) - foo.Approve(a2u(consts.ROUTER_ADDR), 148) // 0.15% of 98019 - - barOld := bar.BalanceOf(a2u(tr01)) - fooOld := foo.BalanceOf(a2u(tr01)) - shouldEQ(t, barOld, 100000000) - shouldEQ(t, fooOld, 0) - - swapResult := rr.SwapRoute( - barPath, // inputToken - fooPath, // outputToken - "100000", // amountSpecified - "EXACT_IN", // swapType - "gno.land/r/demo/bar:gno.land/r/demo/baz:100*POOL*gno.land/r/demo/baz:gno.land/r/demo/foo:100", // strRouteArr - "100", // quoteArr - "1", // tokenAmountLimit (minRecv) - ) - shouldEQ(t, swapResult, "97872") - - barNew := bar.BalanceOf(a2u(tr01)) - fooNew := foo.BalanceOf(a2u(tr01)) - - shouldEQ(t, barOld-barNew, 100000) - shouldEQ(t, fooNew-fooOld, 97872) - - std.TestSkipHeights(2) -} - -func TestRouterDrySwapRouteBarFooExactOutAfterSwap(t *testing.T) { - std.TestSetOrigCaller(tr01) - - dryResult := rr.DrySwapRoute( - barPath, // inputToken - fooPath, // outputToken - "100000", // amountSpecified - "EXACT_OUT", // swapType - "gno.land/r/demo/bar:gno.land/r/demo/baz:100*POOL*gno.land/r/demo/baz:gno.land/r/demo/foo:100", // strRouteArr - "100", // quoteArr - ) - shouldEQ(t, dryResult, "106228") - std.TestSkipHeights(2) -} - -func TestRouterSwapRouteBarFooExactOutAfterSwap(t *testing.T) { - std.TestSetOrigCaller(tr01) - - // approve bar to pool - bar.Approve(a2u(consts.POOL_ADDR), 106228) - foo.Approve(a2u(consts.ROUTER_ADDR), consts.UINT64_MAX) - - barOld := bar.BalanceOf(a2u(tr01)) - fooOld := foo.BalanceOf(a2u(tr01)) - shouldEQ(t, barOld, 99900000) - shouldEQ(t, fooOld, 97872) - - swapResult := rr.SwapRoute( - barPath, // inputToken - fooPath, // outputToken - "100000", // amountSpecified - "EXACT_OUT", // swapType - "gno.land/r/demo/bar:gno.land/r/demo/baz:100*POOL*gno.land/r/demo/baz:gno.land/r/demo/foo:100", // strRouteArr - "100", // quoteArr - "123456", // tokenAmountLimit (maxSpent) - ) - shouldEQ(t, swapResult, "106228") - - barNew := bar.BalanceOf(a2u(tr01)) - fooNew := foo.BalanceOf(a2u(tr01)) - - shouldEQ(t, barOld-barNew, 106228) - shouldEQ(t, fooNew-fooOld, 99850) - - std.TestSkipHeights(2) -} diff --git a/_test/_TEST_scenario_99_router_uniswap_sdk_test.gnoXXX b/_test/_TEST_scenario_99_router_uniswap_sdk_test.gnoXXX new file mode 100644 index 000000000..8d9b5718c --- /dev/null +++ b/_test/_TEST_scenario_99_router_uniswap_sdk_test.gnoXXX @@ -0,0 +1,244 @@ +/* +UNISWAP TEST REF + - https://github.com/Uniswap/v3-core/blob/main/test/shared/fixtures.ts + - https://github.com/Uniswap/v3-core/blob/main/test/UniswapV3Router.spec.ts + - https://github.com/Uniswap/router-sdk/blob/main/src/swapRouter.test.ts +*/ +package swap_scenario + +import ( + "std" + "testing" + + "gno.land/p/demo/testutils" + + "gno.land/r/demo/consts" + + pl "gno.land/r/demo/pool" + pn "gno.land/r/demo/position" + + "gno.land/r/demo/bar" + "gno.land/r/demo/baz" + "gno.land/r/demo/foo" + + "gno.land/r/demo/gns" +) + +var ( + lp01 = testutils.TestAddress("lp01") + tr01 = testutils.TestAddress("tr01") + + // vars from Uniswap TEST + feeAmount uint32 = 3000 + // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/UniswapV3Router.spec.ts#L24 + // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/shared/utilities.ts#L23 + + tickSpacing = 60 + // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/UniswapV3Router.spec.ts#L25 + // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/shared/utilities.ts#L29 + + minTick int32 = -887272 + maxTick int32 = 887272 + // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/shared/utilities.ts#L10-L11 +) + +func TestPoolInitByAdmin(t *testing.T) { + std.TestSetOrigCaller(gsa) + pl.InitManual() + + std.TestSkipHeights(1) +} + +func TestPoolCreatePools(t *testing.T) { + std.TestSetPrevAddr(test1) + gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE*2) + + // bar-baz + pl.CreatePool(barPath, bazPath, 100, "79228162514264337593543950337") // tick 0 ≈ 1:1 + + // baz-foo + // pl.CreatePool(bazPath, fooPath, 100, "79228162514264337593543950337") // tick 0 ≈ 1:1 + + std.TestSkipHeights(4) +} + +func TestFaucetLP01(t *testing.T) { + std.TestSetOrigCaller(lp01) + + shouldEQ(t, bar.BalanceOf(a2u(lp01)), 0) + shouldEQ(t, baz.BalanceOf(a2u(lp01)), 0) + shouldEQ(t, foo.BalanceOf(a2u(lp01)), 0) + + bar.Faucet(lp01) + baz.Faucet(lp01) + foo.Faucet(lp01) + + shouldEQ(t, bar.BalanceOf(a2u(lp01)), 100000000) + shouldEQ(t, baz.BalanceOf(a2u(lp01)), 100000000) + shouldEQ(t, foo.BalanceOf(a2u(lp01)), 100000000) + std.TestSkipHeights(5) +} + +// https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/UniswapV3Router.spec.ts#L83C16-L83C16 +func TestPositionMintBarBazInRange(t *testing.T) { + std.TestSetOrigCaller(lp01) + + // approve bar, baz to pool ( position.Mint() calls pool.Mint() ≈ so approve to pool ) + bar.Approve(a2u(consts.POOL_ADDR), 10000000) + baz.Approve(a2u(consts.POOL_ADDR), 10000000) + + tokenId, liquidity, amount0, amoutn1 := pn.Mint( + barPath, // token0 + bazPath, // token1 + 100, // fee + minTick, // tickLower + maxTick, // tickUpper + "10000000", // amount0Desired + "10000000", // amount1Desired + "0", // amount0Min + "0", // amount1Min + max_timeout, // deadline + ) + + shouldEQ(t, tokenId, 1) + shouldEQ(t, liquidity, "10000000") + shouldEQ(t, amount0, "9999999") + shouldEQ(t, amoutn1, "9999999") + + std.TestSkipHeights(3) +} + +// // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/UniswapV3Router.spec.ts#L84 +// func TestPositionMintBazFooInRange(t *testing.T) { +// std.TestSetOrigCaller(lp01) + +// // approve bar, baz to pool ( position.Mint() calls pool.Mint() ≈ so approve to pool ) +// baz.Approve(a2u(consts.POOL_ADDR), 10000000) +// foo.Approve(a2u(consts.POOL_ADDR), 10000000) + +// tokenId, liquidity, amount0, amoutn1 := pn.Mint( +// bazPath, // token0 +// fooPath, // token1 +// 100, // fee +// minTick, // tickLower +// maxTick, // tickUpper +// "10000000", // amount0Desired +// "10000000", // amount1Desired +// "0", // amount0Min +// "0", // amount1Min +// max_timeout, // deadline +// ) + +// shouldEQ(t, tokenId, 2) +// shouldEQ(t, liquidity, "10000000") +// shouldEQ(t, amount0, "9999999") +// shouldEQ(t, amoutn1, "9999999") + +// std.TestSkipHeights(3) +// } + +// func TestFaucetTR01(t *testing.T) { +// std.TestSetOrigCaller(tr01) + +// shouldEQ(t, bar.BalanceOf(a2u(tr01)), 0) + +// bar.Faucet(tr01) + +// shouldEQ(t, bar.BalanceOf(a2u(tr01)), 100000000) + +// std.TestSkipHeights(5) +// } + +// func TestRouterDrySwapRouteBarFooExactIn(t *testing.T) { +// std.TestSetOrigCaller(tr01) + +// dryResult := rr.DrySwapRoute( +// barPath, // inputToken +// fooPath, // outputToken +// "100000", // amountSpecified +// "EXACT_IN", // swapType +// "gno.land/r/demo/bar:gno.land/r/demo/baz:100*POOL*gno.land/r/demo/baz:gno.land/r/demo/foo:100", // strRouteArr +// "100", // quoteArr +// ) +// shouldEQ(t, dryResult, "98019") +// std.TestSkipHeights(2) +// } + +// func TestRouterSwapRouteBarFooExactIn(t *testing.T) { +// std.TestSetOrigCaller(tr01) + +// // approve bar to pool +// bar.Approve(a2u(consts.POOL_ADDR), 100000) +// foo.Approve(a2u(consts.ROUTER_ADDR), 148) // 0.15% of 98019 + +// barOld := bar.BalanceOf(a2u(tr01)) +// fooOld := foo.BalanceOf(a2u(tr01)) +// shouldEQ(t, barOld, 100000000) +// shouldEQ(t, fooOld, 0) + +// swapResult := rr.SwapRoute( +// barPath, // inputToken +// fooPath, // outputToken +// "100000", // amountSpecified +// "EXACT_IN", // swapType +// "gno.land/r/demo/bar:gno.land/r/demo/baz:100*POOL*gno.land/r/demo/baz:gno.land/r/demo/foo:100", // strRouteArr +// "100", // quoteArr +// "1", // tokenAmountLimit (minRecv) +// ) +// shouldEQ(t, swapResult, "97872") + +// barNew := bar.BalanceOf(a2u(tr01)) +// fooNew := foo.BalanceOf(a2u(tr01)) + +// shouldEQ(t, barOld-barNew, 100000) +// shouldEQ(t, fooNew-fooOld, 97872) + +// std.TestSkipHeights(2) +// } + +// func TestRouterDrySwapRouteBarFooExactOutAfterSwap(t *testing.T) { +// std.TestSetOrigCaller(tr01) + +// dryResult := rr.DrySwapRoute( +// barPath, // inputToken +// fooPath, // outputToken +// "100000", // amountSpecified +// "EXACT_OUT", // swapType +// "gno.land/r/demo/bar:gno.land/r/demo/baz:100*POOL*gno.land/r/demo/baz:gno.land/r/demo/foo:100", // strRouteArr +// "100", // quoteArr +// ) +// shouldEQ(t, dryResult, "106226") +// std.TestSkipHeights(2) +// } + +// func TestRouterSwapRouteBarFooExactOutAfterSwap(t *testing.T) { +// std.TestSetOrigCaller(tr01) + +// // approve bar to pool +// bar.Approve(a2u(consts.POOL_ADDR), 106226) +// foo.Approve(a2u(consts.ROUTER_ADDR), consts.UINT64_MAX) + +// barOld := bar.BalanceOf(a2u(tr01)) +// fooOld := foo.BalanceOf(a2u(tr01)) +// shouldEQ(t, barOld, 99900000) +// shouldEQ(t, fooOld, 97872) + +// swapResult := rr.SwapRoute( +// barPath, // inputToken +// fooPath, // outputToken +// "100000", // amountSpecified +// "EXACT_OUT", // swapType +// "gno.land/r/demo/bar:gno.land/r/demo/baz:100*POOL*gno.land/r/demo/baz:gno.land/r/demo/foo:100", // strRouteArr +// "100", // quoteArr +// "123456", // tokenAmountLimit (maxSpent) +// ) +// shouldEQ(t, swapResult, "106226") + +// barNew := bar.BalanceOf(a2u(tr01)) +// fooNew := foo.BalanceOf(a2u(tr01)) + +// shouldEQ(t, barOld-barNew, 106226) +// shouldEQ(t, fooNew-fooOld, 99849) + +// std.TestSkipHeights(2) +// } diff --git a/packages/big/uint512/uint512.gno b/packages/big/uint512/uint512.gno new file mode 100644 index 000000000..38ce69c99 --- /dev/null +++ b/packages/big/uint512/uint512.gno @@ -0,0 +1,131 @@ +// REF: https://github.com/Uniswap/solidity-lib/blob/master/contracts/libraries/FullMath.sol +package uint512 + +import ( + i256 "gno.land/p/big/int256" + u256 "gno.land/p/big/uint256" +) + +func fullMul( + x *u256.Uint, + y *u256.Uint, +) (*u256.Uint, *u256.Uint) { // l, h + mm := new(u256.Uint).MulMod(x, y, u256.UnsafeFromDecimal("115792089237316195423570985008687907853269984665640564039457584007913129639935")) + + l := new(u256.Uint).Mul(x, y) + h := new(u256.Uint).Sub(mm, l) + + if mm.Lt(l) { + h = new(u256.Uint).Sub(h, u256.One()) + } + + return l, h +} + +func fullDiv( + l *u256.Uint, + h *u256.Uint, + d *u256.Uint, +) *u256.Uint { + // uint256 pow2 = d & -d; + posD := i256.FromUint256(d) + negD := i256.Zero().Neg(posD) + + intPow2 := i256.Zero().And(posD, negD) + + d = new(u256.Uint).Div(d, intPow2.Abs()) + l = new(u256.Uint).Div(l, intPow2.Abs()) + + // l += h * ((-pow2) / pow2 + 1); + _negPow2 := new(u256.Uint).Sub(u256.UnsafeFromDecimal("115792089237316195423570985008687907853269984665640564039457584007913129639935"), intPow2.Abs()) + _negPow2 = new(u256.Uint).Add(_negPow2, u256.One()) + + value1 := new(u256.Uint).Div(_negPow2, intPow2.Abs()) // (-pow2) / pow2 + // println("value1:", value1.ToString()) + + value2 := new(u256.Uint).UnsafeAdd(value1, u256.One()) // (-pow2) / pow2 + 1) + // println("value2:", value2.ToString()) + + // _intH := i256.FromUint256(h) + value3 := new(u256.Uint).Mul(h, value2) // h * ((-pow2) / pow2 + 1); + l = new(u256.Uint).UnsafeAdd(l, value3) + + r := u256.One() + + // r *= 2 - d * r; [ x8 ] + // value11 := new(u256.Uint).UnsafeSub(u256.NewUint(2), d) // 2 - d + // value12 := new(u256.Uint).Mul(value11, r) // 2 - d * r + // r = new(u256.Uint).Mul(r, value12) // r *= 2 - d * r; + + // d * r + // 2 - ( d * r ) + + for i := 0; i < 8; i++ { + value1 := new(u256.Uint).Mul(d, r) // d * r + value2 := new(u256.Uint).UnsafeSub(u256.NewUint(2), value1) // 2 - ( d * r ) + r = new(u256.Uint).Mul(r, value2) // r *= 2 - d * r; + + } + + println("l:", l.ToString()) + println("r:", r.ToString()) + + res := new(u256.Uint).Mul(l, r) + println("res:", res.ToString()) + return res + // return new(u256.Uint).Mul(l, r) + +} + +func MulDiv( + x *u256.Uint, + y *u256.Uint, + d *u256.Uint, +) *u256.Uint { + l, h := fullMul(x, y) + mm := new(u256.Uint).MulMod(x, y, d) + + if mm.Gt(l) { + h = new(u256.Uint).Sub(h, u256.One()) + } + l = new(u256.Uint).Sub(l, mm) + + if h.IsZero() { + return new(u256.Uint).Div(l, d) + } + + if !(h.Lt(d)) { + panic("FULLDIV_OVERFLOW") + } + + return fullDiv(l, h, d) +} + +func DivRoundingUp( + x *u256.Uint, + y *u256.Uint, +) *u256.Uint { + div := new(u256.Uint).Div(x, y) + + mod := new(u256.Uint).Mod(x, y) + gt := u256.Zero() + if mod.Gt(u256.Zero()) { + gt = mod + } else { + gt = u256.Zero() + } + + return new(u256.Uint).Add(div, gt) +} + +// HELPERs +func mulmod( + x *u256.Uint, + y *u256.Uint, + z *u256.Uint, +) *u256.Uint { + mul := new(u256.Uint).Mul(x, y) + mod := new(u256.Uint).Mod(mul, z) + + return mod +} diff --git a/packages/big/uint512/uint512_test.gno b/packages/big/uint512/uint512_test.gno new file mode 100644 index 000000000..b261c0488 --- /dev/null +++ b/packages/big/uint512/uint512_test.gno @@ -0,0 +1,37 @@ +package uint512 + +import ( + i256 "gno.land/p/big/int256" + u256 "gno.land/p/big/uint256" + + "testing" +) + +func init() { + var _1 = i256.Zero() + var _2 = u256.Zero() +} + +// func TestFunc(*testing.T) { +// x := u256.UnsafeFromDecimal("792281625142643375935439503360000000") +// y := u256.UnsafeFromDecimal("1461446703485210103208044889689724484785180020005") +// d := u256.One() + +// z := MulDiv(x, y, d) +// println(z.ToString()) +// } + +func TestFunc2(t *testing.T) { + x := u256.UnsafeFromDecimal("792281625142643375935439503360000000") // num1 + y := u256.UnsafeFromDecimal("1461446703485210103208044889689724484785180020005") // num2 + // d := u256.One() + + sqrtB := u256.UnsafeFromDecimal("1461446703485210103287273052203988822378723970342") + sqrtA := u256.UnsafeFromDecimal("79228162514264337593543950337") + + z := MulDiv(x, y, sqrtB) + println("num1 * num2 / sqrtB:", z.ToString()) + + r := DivRoundingUp(z, sqrtA) + println("num1 * num2 / sqrtB / sqrtA:", r.ToString()) +} diff --git a/pool/_TEST_pool_dryswap_and_swap_test.gno b/pool/_TEST_pool_dryswap_and_swap_test.gno index f7b6af101..65988e306 100644 --- a/pool/_TEST_pool_dryswap_and_swap_test.gno +++ b/pool/_TEST_pool_dryswap_and_swap_test.gno @@ -73,9 +73,9 @@ func TestDrySwap_ZeroForOneTrue_AmountSpecified_Positive_16000(t *testing.T) { shouldEQ(t, poolOut, "-5883") } -func TestDrySwap_ZeroForOneTrue_AmountSpecified_Negative_16000(t *testing.T) { - // zeroForOne true - // amountSpecified -16000 +// func TestDrySwap_ZeroForOneTrue_AmountSpecified_Negative_16000(t *testing.T) { +// // zeroForOne true +// // amountSpecified -16000 poolIn, poolOut, _ := DrySwap( fooPath, // fooPath diff --git a/pool/_TEST_pool_single_lp_test.gnoa b/pool/_TEST_pool_single_lp_test.gno similarity index 100% rename from pool/_TEST_pool_single_lp_test.gnoa rename to pool/_TEST_pool_single_lp_test.gno diff --git a/pool/pool.gno b/pool/pool.gno index 194a1b9bc..c4ba8acaa 100644 --- a/pool/pool.gno +++ b/pool/pool.gno @@ -40,6 +40,9 @@ func Mint( i256.FromUint256(liquidityAmount), // liquidityDelta }, ) + println("amount0:", amount0.ToString()) + println("amount1:", amount1.ToString()) + panic("FIX 0 3") if amount0.Gt(i256.Zero()) { balance0Before := balanceOfByRegisterCall(pool.token0Path, GetOrigPkgAddr()) @@ -499,7 +502,6 @@ func Swap( } require(pool.balances.token0.Gte(u256.Zero()), ufmt.Sprintf("[POOL] pool.gno__Swap() || pool.balances.token0(%d) >= 0", pool.balances.token0)) } - pool.slot0.unlocked = true return amount0.ToString(), amount1.ToString() } diff --git a/pool/position_modify.gno b/pool/position_modify.gno index eebdb482f..69023ec4a 100644 --- a/pool/position_modify.gno +++ b/pool/position_modify.gno @@ -24,21 +24,32 @@ func (pool *Pool) modifyPosition(params ModifyPositionParams) (PositionInfo, *i2 params.liquidityDelta, ) } else if pool.slot0.tick < params.tickUpper { + println("HERE") liquidityBefore := pool.liquidity + println("tickUpper:", params.tickUpper) + println("common.TickMathGetSqrtRatioAtTick(params.tickUpper):", common.TickMathGetSqrtRatioAtTick(params.tickUpper).ToString()) + println() + println("tickLower:", params.tickLower) + println("common.TickMathGetSqrtRatioAtTick(params.tickLower):", common.TickMathGetSqrtRatioAtTick(params.tickLower).ToString()) + println() + amount0 = sqrtPriceMathGetAmount0Delta( pool.slot0.sqrtPriceX96, common.TickMathGetSqrtRatioAtTick(params.tickUpper), params.liquidityDelta, ) + println("amount0:", amount0.ToString()) amount1 = sqrtPriceMathGetAmount1Delta( common.TickMathGetSqrtRatioAtTick(params.tickLower), pool.slot0.sqrtPriceX96, params.liquidityDelta, ) + println("amount1:", amount1.ToString()) pool.liquidity = liquidityMathAddDelta(liquidityBefore, params.liquidityDelta) + panic("FIX 0 666") } else { amount1 = sqrtPriceMathGetAmount1Delta( diff --git a/position/liquidity_management.gno b/position/liquidity_management.gno index 4cf29d51a..9d7818c56 100644 --- a/position/liquidity_management.gno +++ b/position/liquidity_management.gno @@ -36,6 +36,9 @@ func addLiquidity(params AddLiquidityParams) (*u256.Uint, *u256.Uint, *u256.Uint params.tickUpper, // tickUpper int32 liquidity.ToString(), // _liquidityAmount string(uint128) ) + println("amount0:", amount0) + println("amount1:", amount1) + panic("FIX 0 2") amount0Uint, err := u256.FromDecimal(amount0) if err != nil { diff --git a/position/position.gno b/position/position.gno index 4e9b2c295..534605e85 100644 --- a/position/position.gno +++ b/position/position.gno @@ -85,6 +85,9 @@ func mint(params MintParams) (uint64, string, string, string) { amount1Min: params.amount1Min, }, ) + println("amount0", amount0.ToString()) + println("amount1", amount1.ToString()) + panic("FIX 0") tokenId := nextId nextId++ // nextId = nextId + 1 diff --git a/position/sqrt_price_math.gno b/position/sqrt_price_math.gno index 8ccf6415f..be72693e5 100644 --- a/position/sqrt_price_math.gno +++ b/position/sqrt_price_math.gno @@ -80,6 +80,24 @@ func sqrtPriceMathGetNextSqrtPriceFromAmount1RoundingDown( quotient = new(u256.Uint).Sub(quotient, u256.One()) return new(u256.Uint).Sub(sqrtPX96, quotient) } + + // quotient mutst be positive when amount and liquidity are positive + if add { + result := new(u256.Uint).Add(sqrtPX96, quotient) + + if !(result.Gte(sqrtPX96)) { + panic("position_sqrt price math #3") + } + + return result + } + + result := new(u256.Uint).Sub(sqrtPX96, quotient) + if !(result.Gte(u256.Zero())) { + panic("position_sqrt price math #4") + } + + return result } func sqrtPriceMathGetNextSqrtPriceFromInput( diff --git a/router/_RPC_api.gno b/router/_RPC_api.gno index 5e09bb93d..18f59875b 100644 --- a/router/_RPC_api.gno +++ b/router/_RPC_api.gno @@ -52,7 +52,7 @@ func ApiGetRatiosFromBase() string { func findRatios(maxHops int) []TokenRatio { var tokenRatio = make(map[string]*u256.Uint, 0) // WGNOT - tokenRatio[consts.WRAPPED_WUGNOT] = u256.MustFromDecimal(consts.Q96) // ~= 1 + tokenRatio[consts.WRAPPED_WUGNOT] = consts.Q96 // ~= 1 tokens := getTokenList() @@ -71,7 +71,7 @@ func findRatios(maxHops int) []TokenRatio { } else { numRoutes := uint64(len(routes)) - _tokenRatioX96 := u256.Zero() + var _tokenRatioX96 bigint for _, route := range routes { numHops := uint64(len(route.route)) @@ -125,18 +125,19 @@ func calculateTokenRatio(currentToken string, routes []PoolWithMeta, proceed int currentToken = token1Path } else { // wrong condition - panic("[ROUTER] _RPC_api.gno__calculateTokenRatio() || wrong condition") - return u256.Zero() + // panic("[ROUTER] _RPC_api.gno__calculateTokenRatio() || wrong condition") + return 0 + } proceed += 1 - for { // remove as much X96 as possible - tempPriceX96 := priceX96.Clone() - priceX96 = new(u256.Uint).Div(priceX96, u256.MustFromDecimal(consts.Q96)) + if proceed == len(routes) { // numHops + for { // remove as much X96 as possible + tempPriceX96 := priceX96 + priceX96 /= consts.Q96 - if priceX96.Lt(u256.MustFromDecimal(consts.MIN_PRICE)) { - if proceed == len(routes) { + if priceX96 < consts.MIN_PRICE { return tempPriceX96 } return calculateTokenRatio(currentToken, routes, proceed, priceX96) diff --git a/router/_TEST_router_swap_route_1route_1hop_test.gnoa b/router/_TEST_router_swap_route_1route_1hop_test.gno similarity index 95% rename from router/_TEST_router_swap_route_1route_1hop_test.gnoa rename to router/_TEST_router_swap_route_1route_1hop_test.gno index d1e541f63..70d174f9c 100644 --- a/router/_TEST_router_swap_route_1route_1hop_test.gnoa +++ b/router/_TEST_router_swap_route_1route_1hop_test.gno @@ -34,13 +34,13 @@ func TestCreatePool(t *testing.T) { func TestPositionMint(t *testing.T) { // bar_baz_500 by test1 std.TestSetPrevAddr(test1) - bar.Approve(a2u(consts.POOL_ADDR), 36790) - baz.Approve(a2u(consts.POOL_ADDR), 100000) + bar.Approve(a2u(consts.POOL_ADDR), 36789) + baz.Approve(a2u(consts.POOL_ADDR), 99999) // Mint tokenId, liquidity, amount0, amount1 := pn.Mint(barPath, bazPath, fee500, int32(9000), int32(11000), "100000", "100000", "0", "0", max_timeout) shouldEQ(t, tokenId, uint64(1)) - shouldEQ(t, amount0, "36790") + shouldEQ(t, amount0, "36789") shouldEQ(t, amount1, "99999") } @@ -89,7 +89,7 @@ func TestDrySwapRouteBarBazExactOut(t *testing.T) { "100", // quoteArr ) - shouldEQ(t, dryResult, "370") + shouldEQ(t, dryResult, "369") } func TestSwapRouteBarBazExactOut(t *testing.T) { @@ -108,7 +108,7 @@ func TestSwapRouteBarBazExactOut(t *testing.T) { "370", // tokenAmountLimit ) - shouldEQ(t, swapResult, "370") + shouldEQ(t, swapResult, "369") } func TestDrySwapRouteBazBarExactIn(t *testing.T) { From 910aeb8b9d7e6184fddc24df5c955b7d1d90b6ae Mon Sep 17 00:00:00 2001 From: n3wbie Date: Thu, 7 Mar 2024 17:08:42 +0900 Subject: [PATCH 2/5] fix all testcase --- ...ST_scenario_99_router_uniswap_sdk_test.gno | 245 ++++++++++++++++++ ...scenario_99_router_uniswap_sdk_test.gnoXXX | 244 ----------------- packages/big/uint256/uint256.gno | 2 +- packages/big/uint512/consts.gno | 5 + packages/big/uint512/uint512.gno | 86 +++--- packages/big/uint512/uint512_test.gno | 2 +- pool/_RPC_dry.gno | 16 ++ pool/_TEST_pool_dryswap_and_swap_test.gno | 8 +- ...est.gno => _TEST_pool_single_lp_test.gnoa} | 0 pool/pool.gno | 4 +- pool/position_modify.gno | 11 - pool/sqrt_price_math.gno | 2 + pool/swap_math.gno | 12 + position/liquidity_management.gno | 3 - position/position.gno | 3 - position/sqrt_price_math.gno | 37 ++- ...T_router_swap_route_1route_1hop_test.gnoa} | 10 +- 17 files changed, 357 insertions(+), 333 deletions(-) create mode 100644 _test/_TEST_scenario_99_router_uniswap_sdk_test.gno delete mode 100644 _test/_TEST_scenario_99_router_uniswap_sdk_test.gnoXXX create mode 100644 packages/big/uint512/consts.gno rename pool/{_TEST_pool_single_lp_test.gno => _TEST_pool_single_lp_test.gnoa} (100%) rename router/{_TEST_router_swap_route_1route_1hop_test.gno => _TEST_router_swap_route_1route_1hop_test.gnoa} (95%) diff --git a/_test/_TEST_scenario_99_router_uniswap_sdk_test.gno b/_test/_TEST_scenario_99_router_uniswap_sdk_test.gno new file mode 100644 index 000000000..f75a75f52 --- /dev/null +++ b/_test/_TEST_scenario_99_router_uniswap_sdk_test.gno @@ -0,0 +1,245 @@ +/* +UNISWAP TEST REF + - https://github.com/Uniswap/v3-core/blob/main/test/shared/fixtures.ts + - https://github.com/Uniswap/v3-core/blob/main/test/UniswapV3Router.spec.ts + - https://github.com/Uniswap/router-sdk/blob/main/src/swapRouter.test.ts +*/ +package swap_scenario + +import ( + "std" + "testing" + + "gno.land/p/demo/testutils" + + "gno.land/r/demo/consts" + + pl "gno.land/r/demo/pool" + pn "gno.land/r/demo/position" + rr "gno.land/r/demo/router" + + "gno.land/r/demo/bar" + "gno.land/r/demo/baz" + "gno.land/r/demo/foo" + + "gno.land/r/demo/gns" +) + +var ( + lp01 = testutils.TestAddress("lp01") + tr01 = testutils.TestAddress("tr01") + + // vars from Uniswap TEST + feeAmount uint32 = 3000 + // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/UniswapV3Router.spec.ts#L24 + // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/shared/utilities.ts#L23 + + tickSpacing = 60 + // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/UniswapV3Router.spec.ts#L25 + // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/shared/utilities.ts#L29 + + minTick int32 = -887272 + maxTick int32 = 887272 + // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/shared/utilities.ts#L10-L11 +) + +func TestPoolInitByAdmin(t *testing.T) { + std.TestSetOrigCaller(gsa) + pl.InitManual() + + std.TestSkipHeights(1) +} + +func TestPoolCreatePools(t *testing.T) { + std.TestSetPrevAddr(test1) + gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE*2) + + // bar-baz + pl.CreatePool(barPath, bazPath, 100, "79228162514264337593543950337") // tick 0 ≈ 1:1 + + // baz-foo + pl.CreatePool(bazPath, fooPath, 100, "79228162514264337593543950337") // tick 0 ≈ 1:1 + + std.TestSkipHeights(4) +} + +func TestFaucetLP01(t *testing.T) { + std.TestSetOrigCaller(lp01) + + shouldEQ(t, bar.BalanceOf(a2u(lp01)), 0) + shouldEQ(t, baz.BalanceOf(a2u(lp01)), 0) + shouldEQ(t, foo.BalanceOf(a2u(lp01)), 0) + + bar.Faucet(lp01) + baz.Faucet(lp01) + foo.Faucet(lp01) + + shouldEQ(t, bar.BalanceOf(a2u(lp01)), 100000000) + shouldEQ(t, baz.BalanceOf(a2u(lp01)), 100000000) + shouldEQ(t, foo.BalanceOf(a2u(lp01)), 100000000) + std.TestSkipHeights(5) +} + +// https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/UniswapV3Router.spec.ts#L83C16-L83C16 +func TestPositionMintBarBazInRange(t *testing.T) { + std.TestSetOrigCaller(lp01) + + // approve bar, baz to pool ( position.Mint() calls pool.Mint() ≈ so approve to pool ) + bar.Approve(a2u(consts.POOL_ADDR), 10000000) + baz.Approve(a2u(consts.POOL_ADDR), 10000000) + + tokenId, liquidity, amount0, amoutn1 := pn.Mint( + barPath, // token0 + bazPath, // token1 + 100, // fee + minTick, // tickLower + maxTick, // tickUpper + "10000000", // amount0Desired + "10000000", // amount1Desired + "0", // amount0Min + "0", // amount1Min + max_timeout, // deadline + ) + + shouldEQ(t, tokenId, 1) + shouldEQ(t, liquidity, "10000000") + shouldEQ(t, amount0, "10000000") + shouldEQ(t, amoutn1, "9999999") + + std.TestSkipHeights(3) +} + +// https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/UniswapV3Router.spec.ts#L84 +func TestPositionMintBazFooInRange(t *testing.T) { + std.TestSetOrigCaller(lp01) + + // approve bar, baz to pool ( position.Mint() calls pool.Mint() ≈ so approve to pool ) + baz.Approve(a2u(consts.POOL_ADDR), 10000000) + foo.Approve(a2u(consts.POOL_ADDR), 10000000) + + tokenId, liquidity, amount0, amoutn1 := pn.Mint( + bazPath, // token0 + fooPath, // token1 + 100, // fee + minTick, // tickLower + maxTick, // tickUpper + "10000000", // amount0Desired + "10000000", // amount1Desired + "0", // amount0Min + "0", // amount1Min + max_timeout, // deadline + ) + + shouldEQ(t, tokenId, 2) + shouldEQ(t, liquidity, "10000000") + shouldEQ(t, amount0, "10000000") + shouldEQ(t, amoutn1, "9999999") + + std.TestSkipHeights(3) +} + +func TestFaucetTR01(t *testing.T) { + std.TestSetOrigCaller(tr01) + + shouldEQ(t, bar.BalanceOf(a2u(tr01)), 0) + + bar.Faucet(tr01) + + shouldEQ(t, bar.BalanceOf(a2u(tr01)), 100000000) + + std.TestSkipHeights(5) +} + +func TestRouterDrySwapRouteBarFooExactIn(t *testing.T) { + std.TestSetOrigCaller(tr01) + + dryResult := rr.DrySwapRoute( + barPath, // inputToken + fooPath, // outputToken + "100000", // amountSpecified + "EXACT_IN", // swapType + "gno.land/r/demo/bar:gno.land/r/demo/baz:100*POOL*gno.land/r/demo/baz:gno.land/r/demo/foo:100", // strRouteArr + "100", // quoteArr + ) + shouldEQ(t, dryResult, "98019") + std.TestSkipHeights(2) +} + +func TestRouterSwapRouteBarFooExactIn(t *testing.T) { + std.TestSetOrigCaller(tr01) + + // approve bar to pool + bar.Approve(a2u(consts.POOL_ADDR), 100000) + foo.Approve(a2u(consts.ROUTER_ADDR), 148) // 0.15% of 98019 + + barOld := bar.BalanceOf(a2u(tr01)) + fooOld := foo.BalanceOf(a2u(tr01)) + shouldEQ(t, barOld, 100000000) + shouldEQ(t, fooOld, 0) + + swapResult := rr.SwapRoute( + barPath, // inputToken + fooPath, // outputToken + "100000", // amountSpecified + "EXACT_IN", // swapType + "gno.land/r/demo/bar:gno.land/r/demo/baz:100*POOL*gno.land/r/demo/baz:gno.land/r/demo/foo:100", // strRouteArr + "100", // quoteArr + "1", // tokenAmountLimit (minRecv) + ) + shouldEQ(t, swapResult, "97872") + + barNew := bar.BalanceOf(a2u(tr01)) + fooNew := foo.BalanceOf(a2u(tr01)) + + shouldEQ(t, barOld-barNew, 100000) + shouldEQ(t, fooNew-fooOld, 97872) + + std.TestSkipHeights(2) +} + +func TestRouterDrySwapRouteBarFooExactOutAfterSwap(t *testing.T) { + std.TestSetOrigCaller(tr01) + + dryResult := rr.DrySwapRoute( + barPath, // inputToken + fooPath, // outputToken + "100000", // amountSpecified + "EXACT_OUT", // swapType + "gno.land/r/demo/bar:gno.land/r/demo/baz:100*POOL*gno.land/r/demo/baz:gno.land/r/demo/foo:100", // strRouteArr + "100", // quoteArr + ) + shouldEQ(t, dryResult, "106228") + std.TestSkipHeights(2) +} + +func TestRouterSwapRouteBarFooExactOutAfterSwap(t *testing.T) { + std.TestSetOrigCaller(tr01) + + // approve bar to pool + bar.Approve(a2u(consts.POOL_ADDR), 106228) + foo.Approve(a2u(consts.ROUTER_ADDR), consts.UINT64_MAX) + + barOld := bar.BalanceOf(a2u(tr01)) + fooOld := foo.BalanceOf(a2u(tr01)) + shouldEQ(t, barOld, 99900000) + shouldEQ(t, fooOld, 97872) + + swapResult := rr.SwapRoute( + barPath, // inputToken + fooPath, // outputToken + "100000", // amountSpecified + "EXACT_OUT", // swapType + "gno.land/r/demo/bar:gno.land/r/demo/baz:100*POOL*gno.land/r/demo/baz:gno.land/r/demo/foo:100", // strRouteArr + "100", // quoteArr + "123456", // tokenAmountLimit (maxSpent) + ) + shouldEQ(t, swapResult, "106228") + + barNew := bar.BalanceOf(a2u(tr01)) + fooNew := foo.BalanceOf(a2u(tr01)) + + shouldEQ(t, barOld-barNew, 106228) + shouldEQ(t, fooNew-fooOld, 99850) + + std.TestSkipHeights(2) +} diff --git a/_test/_TEST_scenario_99_router_uniswap_sdk_test.gnoXXX b/_test/_TEST_scenario_99_router_uniswap_sdk_test.gnoXXX deleted file mode 100644 index 8d9b5718c..000000000 --- a/_test/_TEST_scenario_99_router_uniswap_sdk_test.gnoXXX +++ /dev/null @@ -1,244 +0,0 @@ -/* -UNISWAP TEST REF - - https://github.com/Uniswap/v3-core/blob/main/test/shared/fixtures.ts - - https://github.com/Uniswap/v3-core/blob/main/test/UniswapV3Router.spec.ts - - https://github.com/Uniswap/router-sdk/blob/main/src/swapRouter.test.ts -*/ -package swap_scenario - -import ( - "std" - "testing" - - "gno.land/p/demo/testutils" - - "gno.land/r/demo/consts" - - pl "gno.land/r/demo/pool" - pn "gno.land/r/demo/position" - - "gno.land/r/demo/bar" - "gno.land/r/demo/baz" - "gno.land/r/demo/foo" - - "gno.land/r/demo/gns" -) - -var ( - lp01 = testutils.TestAddress("lp01") - tr01 = testutils.TestAddress("tr01") - - // vars from Uniswap TEST - feeAmount uint32 = 3000 - // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/UniswapV3Router.spec.ts#L24 - // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/shared/utilities.ts#L23 - - tickSpacing = 60 - // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/UniswapV3Router.spec.ts#L25 - // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/shared/utilities.ts#L29 - - minTick int32 = -887272 - maxTick int32 = 887272 - // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/shared/utilities.ts#L10-L11 -) - -func TestPoolInitByAdmin(t *testing.T) { - std.TestSetOrigCaller(gsa) - pl.InitManual() - - std.TestSkipHeights(1) -} - -func TestPoolCreatePools(t *testing.T) { - std.TestSetPrevAddr(test1) - gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE*2) - - // bar-baz - pl.CreatePool(barPath, bazPath, 100, "79228162514264337593543950337") // tick 0 ≈ 1:1 - - // baz-foo - // pl.CreatePool(bazPath, fooPath, 100, "79228162514264337593543950337") // tick 0 ≈ 1:1 - - std.TestSkipHeights(4) -} - -func TestFaucetLP01(t *testing.T) { - std.TestSetOrigCaller(lp01) - - shouldEQ(t, bar.BalanceOf(a2u(lp01)), 0) - shouldEQ(t, baz.BalanceOf(a2u(lp01)), 0) - shouldEQ(t, foo.BalanceOf(a2u(lp01)), 0) - - bar.Faucet(lp01) - baz.Faucet(lp01) - foo.Faucet(lp01) - - shouldEQ(t, bar.BalanceOf(a2u(lp01)), 100000000) - shouldEQ(t, baz.BalanceOf(a2u(lp01)), 100000000) - shouldEQ(t, foo.BalanceOf(a2u(lp01)), 100000000) - std.TestSkipHeights(5) -} - -// https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/UniswapV3Router.spec.ts#L83C16-L83C16 -func TestPositionMintBarBazInRange(t *testing.T) { - std.TestSetOrigCaller(lp01) - - // approve bar, baz to pool ( position.Mint() calls pool.Mint() ≈ so approve to pool ) - bar.Approve(a2u(consts.POOL_ADDR), 10000000) - baz.Approve(a2u(consts.POOL_ADDR), 10000000) - - tokenId, liquidity, amount0, amoutn1 := pn.Mint( - barPath, // token0 - bazPath, // token1 - 100, // fee - minTick, // tickLower - maxTick, // tickUpper - "10000000", // amount0Desired - "10000000", // amount1Desired - "0", // amount0Min - "0", // amount1Min - max_timeout, // deadline - ) - - shouldEQ(t, tokenId, 1) - shouldEQ(t, liquidity, "10000000") - shouldEQ(t, amount0, "9999999") - shouldEQ(t, amoutn1, "9999999") - - std.TestSkipHeights(3) -} - -// // https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/test/UniswapV3Router.spec.ts#L84 -// func TestPositionMintBazFooInRange(t *testing.T) { -// std.TestSetOrigCaller(lp01) - -// // approve bar, baz to pool ( position.Mint() calls pool.Mint() ≈ so approve to pool ) -// baz.Approve(a2u(consts.POOL_ADDR), 10000000) -// foo.Approve(a2u(consts.POOL_ADDR), 10000000) - -// tokenId, liquidity, amount0, amoutn1 := pn.Mint( -// bazPath, // token0 -// fooPath, // token1 -// 100, // fee -// minTick, // tickLower -// maxTick, // tickUpper -// "10000000", // amount0Desired -// "10000000", // amount1Desired -// "0", // amount0Min -// "0", // amount1Min -// max_timeout, // deadline -// ) - -// shouldEQ(t, tokenId, 2) -// shouldEQ(t, liquidity, "10000000") -// shouldEQ(t, amount0, "9999999") -// shouldEQ(t, amoutn1, "9999999") - -// std.TestSkipHeights(3) -// } - -// func TestFaucetTR01(t *testing.T) { -// std.TestSetOrigCaller(tr01) - -// shouldEQ(t, bar.BalanceOf(a2u(tr01)), 0) - -// bar.Faucet(tr01) - -// shouldEQ(t, bar.BalanceOf(a2u(tr01)), 100000000) - -// std.TestSkipHeights(5) -// } - -// func TestRouterDrySwapRouteBarFooExactIn(t *testing.T) { -// std.TestSetOrigCaller(tr01) - -// dryResult := rr.DrySwapRoute( -// barPath, // inputToken -// fooPath, // outputToken -// "100000", // amountSpecified -// "EXACT_IN", // swapType -// "gno.land/r/demo/bar:gno.land/r/demo/baz:100*POOL*gno.land/r/demo/baz:gno.land/r/demo/foo:100", // strRouteArr -// "100", // quoteArr -// ) -// shouldEQ(t, dryResult, "98019") -// std.TestSkipHeights(2) -// } - -// func TestRouterSwapRouteBarFooExactIn(t *testing.T) { -// std.TestSetOrigCaller(tr01) - -// // approve bar to pool -// bar.Approve(a2u(consts.POOL_ADDR), 100000) -// foo.Approve(a2u(consts.ROUTER_ADDR), 148) // 0.15% of 98019 - -// barOld := bar.BalanceOf(a2u(tr01)) -// fooOld := foo.BalanceOf(a2u(tr01)) -// shouldEQ(t, barOld, 100000000) -// shouldEQ(t, fooOld, 0) - -// swapResult := rr.SwapRoute( -// barPath, // inputToken -// fooPath, // outputToken -// "100000", // amountSpecified -// "EXACT_IN", // swapType -// "gno.land/r/demo/bar:gno.land/r/demo/baz:100*POOL*gno.land/r/demo/baz:gno.land/r/demo/foo:100", // strRouteArr -// "100", // quoteArr -// "1", // tokenAmountLimit (minRecv) -// ) -// shouldEQ(t, swapResult, "97872") - -// barNew := bar.BalanceOf(a2u(tr01)) -// fooNew := foo.BalanceOf(a2u(tr01)) - -// shouldEQ(t, barOld-barNew, 100000) -// shouldEQ(t, fooNew-fooOld, 97872) - -// std.TestSkipHeights(2) -// } - -// func TestRouterDrySwapRouteBarFooExactOutAfterSwap(t *testing.T) { -// std.TestSetOrigCaller(tr01) - -// dryResult := rr.DrySwapRoute( -// barPath, // inputToken -// fooPath, // outputToken -// "100000", // amountSpecified -// "EXACT_OUT", // swapType -// "gno.land/r/demo/bar:gno.land/r/demo/baz:100*POOL*gno.land/r/demo/baz:gno.land/r/demo/foo:100", // strRouteArr -// "100", // quoteArr -// ) -// shouldEQ(t, dryResult, "106226") -// std.TestSkipHeights(2) -// } - -// func TestRouterSwapRouteBarFooExactOutAfterSwap(t *testing.T) { -// std.TestSetOrigCaller(tr01) - -// // approve bar to pool -// bar.Approve(a2u(consts.POOL_ADDR), 106226) -// foo.Approve(a2u(consts.ROUTER_ADDR), consts.UINT64_MAX) - -// barOld := bar.BalanceOf(a2u(tr01)) -// fooOld := foo.BalanceOf(a2u(tr01)) -// shouldEQ(t, barOld, 99900000) -// shouldEQ(t, fooOld, 97872) - -// swapResult := rr.SwapRoute( -// barPath, // inputToken -// fooPath, // outputToken -// "100000", // amountSpecified -// "EXACT_OUT", // swapType -// "gno.land/r/demo/bar:gno.land/r/demo/baz:100*POOL*gno.land/r/demo/baz:gno.land/r/demo/foo:100", // strRouteArr -// "100", // quoteArr -// "123456", // tokenAmountLimit (maxSpent) -// ) -// shouldEQ(t, swapResult, "106226") - -// barNew := bar.BalanceOf(a2u(tr01)) -// fooNew := foo.BalanceOf(a2u(tr01)) - -// shouldEQ(t, barOld-barNew, 106226) -// shouldEQ(t, fooNew-fooOld, 99849) - -// std.TestSkipHeights(2) -// } diff --git a/packages/big/uint256/uint256.gno b/packages/big/uint256/uint256.gno index d78ac6aa5..32359cf96 100644 --- a/packages/big/uint256/uint256.gno +++ b/packages/big/uint256/uint256.gno @@ -958,7 +958,7 @@ func (z *Uint) fromDecimal(bs string) error { z.SetUint64(num) } else { base := NewUint(num) - z.Add(z, base.Mul(base, mult)) + z.UnsafeAdd(z, base.Mul(base, mult)) } // Chop off another 19 characters if remaining > 19 { diff --git a/packages/big/uint512/consts.gno b/packages/big/uint512/consts.gno new file mode 100644 index 000000000..48eb1edbc --- /dev/null +++ b/packages/big/uint512/consts.gno @@ -0,0 +1,5 @@ +package uint512 + +const ( + MAX_UINT256 = "115792089237316195423570985008687907853269984665640564039457584007913129639935" +) diff --git a/packages/big/uint512/uint512.gno b/packages/big/uint512/uint512.gno index 38ce69c99..f79138206 100644 --- a/packages/big/uint512/uint512.gno +++ b/packages/big/uint512/uint512.gno @@ -10,7 +10,7 @@ func fullMul( x *u256.Uint, y *u256.Uint, ) (*u256.Uint, *u256.Uint) { // l, h - mm := new(u256.Uint).MulMod(x, y, u256.UnsafeFromDecimal("115792089237316195423570985008687907853269984665640564039457584007913129639935")) + mm := new(u256.Uint).MulMod(x, y, u256.UnsafeFromDecimal(MAX_UINT256)) l := new(u256.Uint).Mul(x, y) h := new(u256.Uint).Sub(mm, l) @@ -32,49 +32,24 @@ func fullDiv( negD := i256.Zero().Neg(posD) intPow2 := i256.Zero().And(posD, negD) - d = new(u256.Uint).Div(d, intPow2.Abs()) l = new(u256.Uint).Div(l, intPow2.Abs()) - // l += h * ((-pow2) / pow2 + 1); - _negPow2 := new(u256.Uint).Sub(u256.UnsafeFromDecimal("115792089237316195423570985008687907853269984665640564039457584007913129639935"), intPow2.Abs()) - _negPow2 = new(u256.Uint).Add(_negPow2, u256.One()) - - value1 := new(u256.Uint).Div(_negPow2, intPow2.Abs()) // (-pow2) / pow2 - // println("value1:", value1.ToString()) + _negPow2 := new(u256.Uint).Neg(intPow2.Abs()) + value1 := new(u256.Uint).Div(_negPow2, intPow2.Abs()) // (-pow2) / pow2 value2 := new(u256.Uint).UnsafeAdd(value1, u256.One()) // (-pow2) / pow2 + 1) - // println("value2:", value2.ToString()) - - // _intH := i256.FromUint256(h) - value3 := new(u256.Uint).Mul(h, value2) // h * ((-pow2) / pow2 + 1); + value3 := new(u256.Uint).Mul(h, value2) // h * ((-pow2) / pow2 + 1); l = new(u256.Uint).UnsafeAdd(l, value3) r := u256.One() - - // r *= 2 - d * r; [ x8 ] - // value11 := new(u256.Uint).UnsafeSub(u256.NewUint(2), d) // 2 - d - // value12 := new(u256.Uint).Mul(value11, r) // 2 - d * r - // r = new(u256.Uint).Mul(r, value12) // r *= 2 - d * r; - - // d * r - // 2 - ( d * r ) - for i := 0; i < 8; i++ { - value1 := new(u256.Uint).Mul(d, r) // d * r - value2 := new(u256.Uint).UnsafeSub(u256.NewUint(2), value1) // 2 - ( d * r ) - r = new(u256.Uint).Mul(r, value2) // r *= 2 - d * r; - + value1 := new(u256.Uint).Mul(d, r) // d * r + value2 := new(u256.Uint).Sub(u256.NewUint(2), value1) // 2 - ( d * r ) + r = new(u256.Uint).Mul(r, value2) // r *= 2 - d * r; } - - println("l:", l.ToString()) - println("r:", r.ToString()) - res := new(u256.Uint).Mul(l, r) - println("res:", res.ToString()) return res - // return new(u256.Uint).Mul(l, r) - } func MulDiv( @@ -101,31 +76,46 @@ func MulDiv( return fullDiv(l, h, d) } -func DivRoundingUp( +func MulDivRoundingUp( x *u256.Uint, y *u256.Uint, + d *u256.Uint, ) *u256.Uint { - div := new(u256.Uint).Div(x, y) + result := MulDiv(x, y, d) - mod := new(u256.Uint).Mod(x, y) - gt := u256.Zero() - if mod.Gt(u256.Zero()) { - gt = mod - } else { - gt = u256.Zero() - } + // _mm := new(u256.Uint).MulMod(x, y, d) + // if _mm.Gt(u256.Zero()) { + // if result.Lt(u256.UnsafeFromDecimal(MAX_UINT256)) { + // result = new(u256.Uint).Add(result, u256.One()) + // } + // } - return new(u256.Uint).Add(div, gt) + return result } -// HELPERs -func mulmod( +func DivRoundingUp( x *u256.Uint, y *u256.Uint, - z *u256.Uint, ) *u256.Uint { - mul := new(u256.Uint).Mul(x, y) - mod := new(u256.Uint).Mod(mul, z) + div := new(u256.Uint).Div(x, y) + + mod := new(u256.Uint).Mod(x, y) + return new(u256.Uint).Add(div, gt(mod, u256.Zero())) +} - return mod +// HELPERs +func lt(x, y *u256.Uint) *u256.Uint { + if x.Lt(y) { + return u256.One() + } else { + return u256.Zero() + } +} + +func gt(x, y *u256.Uint) *u256.Uint { + if x.Gt(y) { + return u256.One() + } else { + return u256.Zero() + } } diff --git a/packages/big/uint512/uint512_test.gno b/packages/big/uint512/uint512_test.gno index b261c0488..af8a0e665 100644 --- a/packages/big/uint512/uint512_test.gno +++ b/packages/big/uint512/uint512_test.gno @@ -30,7 +30,7 @@ func TestFunc2(t *testing.T) { sqrtA := u256.UnsafeFromDecimal("79228162514264337593543950337") z := MulDiv(x, y, sqrtB) - println("num1 * num2 / sqrtB:", z.ToString()) + // println("num1 * num2 / sqrtB:", z.ToString()) r := DivRoundingUp(z, sqrtA) println("num1 * num2 / sqrtB / sqrtA:", r.ToString()) diff --git a/pool/_RPC_dry.gno b/pool/_RPC_dry.gno index c393a6f60..d11c0433a 100644 --- a/pool/_RPC_dry.gno +++ b/pool/_RPC_dry.gno @@ -95,9 +95,13 @@ func DrySwap( liquidity: cache.liquidityStart, } } + // println("state.tick:", state.tick) + // println("IN state.sqrtPriceX96:", state.sqrtPriceX96.ToString()) + // println("state.sqrtPriceX96:", state.sqrtPriceX96.ToString()) // continue swapping as long as we haven't used the entire input/output and haven't reached the price limit for !(state.amountSpecifiedRemaining.IsZero()) && !(state.sqrtPriceX96.Eq(sqrtPriceLimitX96)) { + // println("state.amountSpecifiedRemaining:", state.amountSpecifiedRemaining.ToString()) var step StepComputations step.sqrtPriceStartX96 = state.sqrtPriceX96 @@ -127,6 +131,11 @@ func DrySwap( sqrtRatioTargetX96 = step.sqrtPriceNextX96 } + // println("state.sqrtPriceX96:", state.sqrtPriceX96.ToString()) + // println("sqrtRatioTargetX96:", sqrtRatioTargetX96.ToString()) + // println("state.liquidity:", state.liquidity.ToString()) + // println("state.amountSpecifiedRemaining:", state.amountSpecifiedRemaining.ToString()) + // println("pool.fee:", pool.fee) state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount = swapMathComputeSwapStep( state.sqrtPriceX96, sqrtRatioTargetX96, @@ -134,6 +143,13 @@ func DrySwap( state.amountSpecifiedRemaining, uint64(pool.fee), ) + if step.amountIn.ToString() == "271" { + // println("> state.sqrtPriceX96:", state.sqrtPriceX96.ToString()) + // println("step.amountIn:", step.amountIn.ToString()) + // println("step.amountOut:", step.amountOut.ToString()) + // println("step.feeAmount:", step.feeAmount.ToString()) + // panic("FIX") + } amountInWithFee := i256.FromUint256(new(u256.Uint).Add(step.amountIn, step.feeAmount)) if exactInput { diff --git a/pool/_TEST_pool_dryswap_and_swap_test.gno b/pool/_TEST_pool_dryswap_and_swap_test.gno index 65988e306..12d9c94f3 100644 --- a/pool/_TEST_pool_dryswap_and_swap_test.gno +++ b/pool/_TEST_pool_dryswap_and_swap_test.gno @@ -73,9 +73,9 @@ func TestDrySwap_ZeroForOneTrue_AmountSpecified_Positive_16000(t *testing.T) { shouldEQ(t, poolOut, "-5883") } -// func TestDrySwap_ZeroForOneTrue_AmountSpecified_Negative_16000(t *testing.T) { -// // zeroForOne true -// // amountSpecified -16000 +func TestDrySwap_ZeroForOneTrue_AmountSpecified_Negative_16000(t *testing.T) { + // zeroForOne true + // amountSpecified -16000 poolIn, poolOut, _ := DrySwap( fooPath, // fooPath @@ -87,7 +87,7 @@ func TestDrySwap_ZeroForOneTrue_AmountSpecified_Positive_16000(t *testing.T) { consts.MIN_PRICE, // sqrtPriceLimitX96 ) - shouldEQ(t, poolIn, "43512") + shouldEQ(t, poolIn, "43512") shouldEQ(t, poolOut, "-16000") } diff --git a/pool/_TEST_pool_single_lp_test.gno b/pool/_TEST_pool_single_lp_test.gnoa similarity index 100% rename from pool/_TEST_pool_single_lp_test.gno rename to pool/_TEST_pool_single_lp_test.gnoa diff --git a/pool/pool.gno b/pool/pool.gno index c4ba8acaa..194a1b9bc 100644 --- a/pool/pool.gno +++ b/pool/pool.gno @@ -40,9 +40,6 @@ func Mint( i256.FromUint256(liquidityAmount), // liquidityDelta }, ) - println("amount0:", amount0.ToString()) - println("amount1:", amount1.ToString()) - panic("FIX 0 3") if amount0.Gt(i256.Zero()) { balance0Before := balanceOfByRegisterCall(pool.token0Path, GetOrigPkgAddr()) @@ -502,6 +499,7 @@ func Swap( } require(pool.balances.token0.Gte(u256.Zero()), ufmt.Sprintf("[POOL] pool.gno__Swap() || pool.balances.token0(%d) >= 0", pool.balances.token0)) } + pool.slot0.unlocked = true return amount0.ToString(), amount1.ToString() } diff --git a/pool/position_modify.gno b/pool/position_modify.gno index 69023ec4a..eebdb482f 100644 --- a/pool/position_modify.gno +++ b/pool/position_modify.gno @@ -24,32 +24,21 @@ func (pool *Pool) modifyPosition(params ModifyPositionParams) (PositionInfo, *i2 params.liquidityDelta, ) } else if pool.slot0.tick < params.tickUpper { - println("HERE") liquidityBefore := pool.liquidity - println("tickUpper:", params.tickUpper) - println("common.TickMathGetSqrtRatioAtTick(params.tickUpper):", common.TickMathGetSqrtRatioAtTick(params.tickUpper).ToString()) - println() - println("tickLower:", params.tickLower) - println("common.TickMathGetSqrtRatioAtTick(params.tickLower):", common.TickMathGetSqrtRatioAtTick(params.tickLower).ToString()) - println() - amount0 = sqrtPriceMathGetAmount0Delta( pool.slot0.sqrtPriceX96, common.TickMathGetSqrtRatioAtTick(params.tickUpper), params.liquidityDelta, ) - println("amount0:", amount0.ToString()) amount1 = sqrtPriceMathGetAmount1Delta( common.TickMathGetSqrtRatioAtTick(params.tickLower), pool.slot0.sqrtPriceX96, params.liquidityDelta, ) - println("amount1:", amount1.ToString()) pool.liquidity = liquidityMathAddDelta(liquidityBefore, params.liquidityDelta) - panic("FIX 0 666") } else { amount1 = sqrtPriceMathGetAmount1Delta( diff --git a/pool/sqrt_price_math.gno b/pool/sqrt_price_math.gno index d5bf30059..ebad171be 100644 --- a/pool/sqrt_price_math.gno +++ b/pool/sqrt_price_math.gno @@ -16,6 +16,7 @@ func sqrtPriceMathGetNextSqrtPriceFromAmount0RoundingUp( if amount.IsZero() { return sqrtPX96 } + // println("|| sqrtPriceMathGetNextSqrtPriceFromAmount0RoundingUp:", add) numerator1 := new(u256.Uint).Lsh(liquidity, 96) @@ -100,6 +101,7 @@ func sqrtPriceMathGetNextSqrtPriceFromOutput( amountOut *u256.Uint, // uint256 zeroForOne bool, // bool ) *u256.Uint { // uint160 + // println("sqrtPriceMathGetNextSqrtPriceFromOutput:", zeroForOne) if zeroForOne { return sqrtPriceMathGetNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) } diff --git a/pool/swap_math.gno b/pool/swap_math.gno index 4ea025a93..4c7820d79 100644 --- a/pool/swap_math.gno +++ b/pool/swap_math.gno @@ -18,6 +18,10 @@ func swapMathComputeSwapStep( // NEGATIVE == EXACT_OUT => Estimated AmountIn exactIn := !(amountRemaining.IsNeg()) // amountRemaining >= 0 + // println() + // println("exactIn", exactIn) // f + // println("isToken1Expensive", isToken1Expensive) // t + if exactIn { amountRemainingLessFee := u256.Zero() @@ -49,8 +53,15 @@ func swapMathComputeSwapStep( } if amountRemaining.Abs().Gte(amountOut) { + // println(3) sqrtRatioNextX96 = sqrtRatioTargetX96 } else { + // println(4) + // println("sqrtRatioCurrentX96:", sqrtRatioCurrentX96.ToString()) + // println("liquidity:", liquidity.ToString()) + // println("amountRemaining.Abs():", amountRemaining.Abs().ToString()) + // println("isToken1Expensive:", isToken1Expensive) + // println("<< SQRT") sqrtRatioNextX96 = sqrtPriceMathGetNextSqrtPriceFromOutput( sqrtRatioCurrentX96, liquidity, @@ -103,5 +114,6 @@ func swapMathComputeSwapStep( if !exactIn && !(amountOut.IsZero()) { amountOut = amountOut.Add(amountOut, u256.NewUint(1)) } + // println() return sqrtRatioNextX96, amountIn, amountOut, feeAmount } diff --git a/position/liquidity_management.gno b/position/liquidity_management.gno index 9d7818c56..4cf29d51a 100644 --- a/position/liquidity_management.gno +++ b/position/liquidity_management.gno @@ -36,9 +36,6 @@ func addLiquidity(params AddLiquidityParams) (*u256.Uint, *u256.Uint, *u256.Uint params.tickUpper, // tickUpper int32 liquidity.ToString(), // _liquidityAmount string(uint128) ) - println("amount0:", amount0) - println("amount1:", amount1) - panic("FIX 0 2") amount0Uint, err := u256.FromDecimal(amount0) if err != nil { diff --git a/position/position.gno b/position/position.gno index 534605e85..4e9b2c295 100644 --- a/position/position.gno +++ b/position/position.gno @@ -85,9 +85,6 @@ func mint(params MintParams) (uint64, string, string, string) { amount1Min: params.amount1Min, }, ) - println("amount0", amount0.ToString()) - println("amount1", amount1.ToString()) - panic("FIX 0") tokenId := nextId nextId++ // nextId = nextId + 1 diff --git a/position/sqrt_price_math.gno b/position/sqrt_price_math.gno index be72693e5..ab51eb8f9 100644 --- a/position/sqrt_price_math.gno +++ b/position/sqrt_price_math.gno @@ -5,6 +5,7 @@ import ( i256 "gno.land/p/big/int256" u256 "gno.land/p/big/uint256" + u512 "gno.land/p/big/uint512" ) func sqrtPriceMathGetNextSqrtPriceFromAmount0RoundingUp( @@ -16,6 +17,7 @@ func sqrtPriceMathGetNextSqrtPriceFromAmount0RoundingUp( if amount.IsZero() { return sqrtPX96 } + // println("|| sqrtPriceMathGetNextSqrtPriceFromAmount0RoundingUp:", add) numerator1 := new(u256.Uint).Lsh(liquidity, 96) @@ -83,21 +85,35 @@ func sqrtPriceMathGetNextSqrtPriceFromAmount1RoundingDown( // quotient mutst be positive when amount and liquidity are positive if add { - result := new(u256.Uint).Add(sqrtPX96, quotient) + if amount.Lte(u256.UnsafeFromDecimal(consts.MAX_UINT160)) { + quotient = new(u256.Uint).Lsh(amount, 96) + quotient = new(u256.Uint).Div(quotient, liquidity) + } else { + quotient = u512.MulDiv(amount, u256.UnsafeFromDecimal(consts.Q96), liquidity) + } - if !(result.Gte(sqrtPX96)) { - panic("position_sqrt price math #3") + quotient = new(u256.Uint).Sub(quotient, u256.One()) + return new(u256.Uint).Add(sqrtPX96, quotient) + } else { + // println("FF") + if amount.Lte(u256.UnsafeFromDecimal(consts.MAX_UINT160)) { + value1 := new(u256.Uint).Lsh(amount, 96) + quotient = u512.DivRoundingUp(value1, liquidity) + // println("q1:", quotient.ToString()) + } else { + quotient = u512.MulDivRoundingUp(amount, u256.UnsafeFromDecimal(consts.Q96), liquidity) + // println("q2:", quotient.ToString()) } + // println("sqrtPX96:", sqrtPX96.ToString()) - return result - } + if !(sqrtPX96.Gt(quotient)) { + panic("position_sqrt price math #2") + } - result := new(u256.Uint).Sub(sqrtPX96, quotient) - if !(result.Gte(u256.Zero())) { - panic("position_sqrt price math #4") + // roundDown + quotient = new(u256.Uint).Sub(quotient, u256.One()) + return new(u256.Uint).Sub(sqrtPX96, quotient) } - - return result } func sqrtPriceMathGetNextSqrtPriceFromInput( @@ -118,6 +134,7 @@ func sqrtPriceMathGetNextSqrtPriceFromOutput( amountOut *u256.Uint, // uint256 zeroForOne bool, // bool ) *u256.Uint { // uint160 + // println("sqrtPriceMathGetNextSqrtPriceFromOutput:", zeroForOne) if zeroForOne { return sqrtPriceMathGetNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) } diff --git a/router/_TEST_router_swap_route_1route_1hop_test.gno b/router/_TEST_router_swap_route_1route_1hop_test.gnoa similarity index 95% rename from router/_TEST_router_swap_route_1route_1hop_test.gno rename to router/_TEST_router_swap_route_1route_1hop_test.gnoa index 70d174f9c..d1e541f63 100644 --- a/router/_TEST_router_swap_route_1route_1hop_test.gno +++ b/router/_TEST_router_swap_route_1route_1hop_test.gnoa @@ -34,13 +34,13 @@ func TestCreatePool(t *testing.T) { func TestPositionMint(t *testing.T) { // bar_baz_500 by test1 std.TestSetPrevAddr(test1) - bar.Approve(a2u(consts.POOL_ADDR), 36789) - baz.Approve(a2u(consts.POOL_ADDR), 99999) + bar.Approve(a2u(consts.POOL_ADDR), 36790) + baz.Approve(a2u(consts.POOL_ADDR), 100000) // Mint tokenId, liquidity, amount0, amount1 := pn.Mint(barPath, bazPath, fee500, int32(9000), int32(11000), "100000", "100000", "0", "0", max_timeout) shouldEQ(t, tokenId, uint64(1)) - shouldEQ(t, amount0, "36789") + shouldEQ(t, amount0, "36790") shouldEQ(t, amount1, "99999") } @@ -89,7 +89,7 @@ func TestDrySwapRouteBarBazExactOut(t *testing.T) { "100", // quoteArr ) - shouldEQ(t, dryResult, "369") + shouldEQ(t, dryResult, "370") } func TestSwapRouteBarBazExactOut(t *testing.T) { @@ -108,7 +108,7 @@ func TestSwapRouteBarBazExactOut(t *testing.T) { "370", // tokenAmountLimit ) - shouldEQ(t, swapResult, "369") + shouldEQ(t, swapResult, "370") } func TestDrySwapRouteBazBarExactIn(t *testing.T) { From 8d143dd1cb54ec504f3a9ee50db22cf2593f6e1e Mon Sep 17 00:00:00 2001 From: n3wbie Date: Thu, 7 Mar 2024 17:34:38 +0900 Subject: [PATCH 3/5] feat: u256*u256 in u256 package chore: remove comments --- packages/big/uint256/uint256_test.gno | 1 - packages/big/uint512/consts.gno | 5 -- packages/big/uint512/uint512.gno | 121 -------------------------- packages/big/uint512/uint512_test.gno | 37 -------- pool/_RPC_dry.gno | 16 ---- pool/sqrt_price_math.gno | 2 - pool/swap_math.gno | 12 --- position/sqrt_price_math.gno | 13 +-- 8 files changed, 3 insertions(+), 204 deletions(-) delete mode 100644 packages/big/uint512/consts.gno delete mode 100644 packages/big/uint512/uint512.gno delete mode 100644 packages/big/uint512/uint512_test.gno diff --git a/packages/big/uint256/uint256_test.gno b/packages/big/uint256/uint256_test.gno index 2bba72a94..a3aab87a2 100644 --- a/packages/big/uint256/uint256_test.gno +++ b/packages/big/uint256/uint256_test.gno @@ -9,7 +9,6 @@ func TestFuncs(t *testing.T) { y := MustFromDecimal("130406999485845074795897568971") z := new(Uint).Add(x, y) - println("z:", z.ToString()) // 130486188034278082001322316149 if z.ToString() != "130486188034278082001322316149" { t.Error("Expected 130486188034278082001322316149, got ", z.ToString()) diff --git a/packages/big/uint512/consts.gno b/packages/big/uint512/consts.gno deleted file mode 100644 index 48eb1edbc..000000000 --- a/packages/big/uint512/consts.gno +++ /dev/null @@ -1,5 +0,0 @@ -package uint512 - -const ( - MAX_UINT256 = "115792089237316195423570985008687907853269984665640564039457584007913129639935" -) diff --git a/packages/big/uint512/uint512.gno b/packages/big/uint512/uint512.gno deleted file mode 100644 index f79138206..000000000 --- a/packages/big/uint512/uint512.gno +++ /dev/null @@ -1,121 +0,0 @@ -// REF: https://github.com/Uniswap/solidity-lib/blob/master/contracts/libraries/FullMath.sol -package uint512 - -import ( - i256 "gno.land/p/big/int256" - u256 "gno.land/p/big/uint256" -) - -func fullMul( - x *u256.Uint, - y *u256.Uint, -) (*u256.Uint, *u256.Uint) { // l, h - mm := new(u256.Uint).MulMod(x, y, u256.UnsafeFromDecimal(MAX_UINT256)) - - l := new(u256.Uint).Mul(x, y) - h := new(u256.Uint).Sub(mm, l) - - if mm.Lt(l) { - h = new(u256.Uint).Sub(h, u256.One()) - } - - return l, h -} - -func fullDiv( - l *u256.Uint, - h *u256.Uint, - d *u256.Uint, -) *u256.Uint { - // uint256 pow2 = d & -d; - posD := i256.FromUint256(d) - negD := i256.Zero().Neg(posD) - - intPow2 := i256.Zero().And(posD, negD) - d = new(u256.Uint).Div(d, intPow2.Abs()) - l = new(u256.Uint).Div(l, intPow2.Abs()) - - _negPow2 := new(u256.Uint).Neg(intPow2.Abs()) - - value1 := new(u256.Uint).Div(_negPow2, intPow2.Abs()) // (-pow2) / pow2 - value2 := new(u256.Uint).UnsafeAdd(value1, u256.One()) // (-pow2) / pow2 + 1) - value3 := new(u256.Uint).Mul(h, value2) // h * ((-pow2) / pow2 + 1); - l = new(u256.Uint).UnsafeAdd(l, value3) - - r := u256.One() - for i := 0; i < 8; i++ { - value1 := new(u256.Uint).Mul(d, r) // d * r - value2 := new(u256.Uint).Sub(u256.NewUint(2), value1) // 2 - ( d * r ) - r = new(u256.Uint).Mul(r, value2) // r *= 2 - d * r; - } - res := new(u256.Uint).Mul(l, r) - return res -} - -func MulDiv( - x *u256.Uint, - y *u256.Uint, - d *u256.Uint, -) *u256.Uint { - l, h := fullMul(x, y) - mm := new(u256.Uint).MulMod(x, y, d) - - if mm.Gt(l) { - h = new(u256.Uint).Sub(h, u256.One()) - } - l = new(u256.Uint).Sub(l, mm) - - if h.IsZero() { - return new(u256.Uint).Div(l, d) - } - - if !(h.Lt(d)) { - panic("FULLDIV_OVERFLOW") - } - - return fullDiv(l, h, d) -} - -func MulDivRoundingUp( - x *u256.Uint, - y *u256.Uint, - d *u256.Uint, -) *u256.Uint { - result := MulDiv(x, y, d) - - // _mm := new(u256.Uint).MulMod(x, y, d) - // if _mm.Gt(u256.Zero()) { - // if result.Lt(u256.UnsafeFromDecimal(MAX_UINT256)) { - // result = new(u256.Uint).Add(result, u256.One()) - // } - // } - - return result -} - -func DivRoundingUp( - x *u256.Uint, - y *u256.Uint, -) *u256.Uint { - div := new(u256.Uint).Div(x, y) - - mod := new(u256.Uint).Mod(x, y) - return new(u256.Uint).Add(div, gt(mod, u256.Zero())) -} - -// HELPERs -func lt(x, y *u256.Uint) *u256.Uint { - if x.Lt(y) { - return u256.One() - } else { - return u256.Zero() - } -} - -func gt(x, y *u256.Uint) *u256.Uint { - if x.Gt(y) { - return u256.One() - } else { - return u256.Zero() - } -} diff --git a/packages/big/uint512/uint512_test.gno b/packages/big/uint512/uint512_test.gno deleted file mode 100644 index af8a0e665..000000000 --- a/packages/big/uint512/uint512_test.gno +++ /dev/null @@ -1,37 +0,0 @@ -package uint512 - -import ( - i256 "gno.land/p/big/int256" - u256 "gno.land/p/big/uint256" - - "testing" -) - -func init() { - var _1 = i256.Zero() - var _2 = u256.Zero() -} - -// func TestFunc(*testing.T) { -// x := u256.UnsafeFromDecimal("792281625142643375935439503360000000") -// y := u256.UnsafeFromDecimal("1461446703485210103208044889689724484785180020005") -// d := u256.One() - -// z := MulDiv(x, y, d) -// println(z.ToString()) -// } - -func TestFunc2(t *testing.T) { - x := u256.UnsafeFromDecimal("792281625142643375935439503360000000") // num1 - y := u256.UnsafeFromDecimal("1461446703485210103208044889689724484785180020005") // num2 - // d := u256.One() - - sqrtB := u256.UnsafeFromDecimal("1461446703485210103287273052203988822378723970342") - sqrtA := u256.UnsafeFromDecimal("79228162514264337593543950337") - - z := MulDiv(x, y, sqrtB) - // println("num1 * num2 / sqrtB:", z.ToString()) - - r := DivRoundingUp(z, sqrtA) - println("num1 * num2 / sqrtB / sqrtA:", r.ToString()) -} diff --git a/pool/_RPC_dry.gno b/pool/_RPC_dry.gno index d11c0433a..c393a6f60 100644 --- a/pool/_RPC_dry.gno +++ b/pool/_RPC_dry.gno @@ -95,13 +95,9 @@ func DrySwap( liquidity: cache.liquidityStart, } } - // println("state.tick:", state.tick) - // println("IN state.sqrtPriceX96:", state.sqrtPriceX96.ToString()) - // println("state.sqrtPriceX96:", state.sqrtPriceX96.ToString()) // continue swapping as long as we haven't used the entire input/output and haven't reached the price limit for !(state.amountSpecifiedRemaining.IsZero()) && !(state.sqrtPriceX96.Eq(sqrtPriceLimitX96)) { - // println("state.amountSpecifiedRemaining:", state.amountSpecifiedRemaining.ToString()) var step StepComputations step.sqrtPriceStartX96 = state.sqrtPriceX96 @@ -131,11 +127,6 @@ func DrySwap( sqrtRatioTargetX96 = step.sqrtPriceNextX96 } - // println("state.sqrtPriceX96:", state.sqrtPriceX96.ToString()) - // println("sqrtRatioTargetX96:", sqrtRatioTargetX96.ToString()) - // println("state.liquidity:", state.liquidity.ToString()) - // println("state.amountSpecifiedRemaining:", state.amountSpecifiedRemaining.ToString()) - // println("pool.fee:", pool.fee) state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount = swapMathComputeSwapStep( state.sqrtPriceX96, sqrtRatioTargetX96, @@ -143,13 +134,6 @@ func DrySwap( state.amountSpecifiedRemaining, uint64(pool.fee), ) - if step.amountIn.ToString() == "271" { - // println("> state.sqrtPriceX96:", state.sqrtPriceX96.ToString()) - // println("step.amountIn:", step.amountIn.ToString()) - // println("step.amountOut:", step.amountOut.ToString()) - // println("step.feeAmount:", step.feeAmount.ToString()) - // panic("FIX") - } amountInWithFee := i256.FromUint256(new(u256.Uint).Add(step.amountIn, step.feeAmount)) if exactInput { diff --git a/pool/sqrt_price_math.gno b/pool/sqrt_price_math.gno index ebad171be..d5bf30059 100644 --- a/pool/sqrt_price_math.gno +++ b/pool/sqrt_price_math.gno @@ -16,7 +16,6 @@ func sqrtPriceMathGetNextSqrtPriceFromAmount0RoundingUp( if amount.IsZero() { return sqrtPX96 } - // println("|| sqrtPriceMathGetNextSqrtPriceFromAmount0RoundingUp:", add) numerator1 := new(u256.Uint).Lsh(liquidity, 96) @@ -101,7 +100,6 @@ func sqrtPriceMathGetNextSqrtPriceFromOutput( amountOut *u256.Uint, // uint256 zeroForOne bool, // bool ) *u256.Uint { // uint160 - // println("sqrtPriceMathGetNextSqrtPriceFromOutput:", zeroForOne) if zeroForOne { return sqrtPriceMathGetNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) } diff --git a/pool/swap_math.gno b/pool/swap_math.gno index 4c7820d79..4ea025a93 100644 --- a/pool/swap_math.gno +++ b/pool/swap_math.gno @@ -18,10 +18,6 @@ func swapMathComputeSwapStep( // NEGATIVE == EXACT_OUT => Estimated AmountIn exactIn := !(amountRemaining.IsNeg()) // amountRemaining >= 0 - // println() - // println("exactIn", exactIn) // f - // println("isToken1Expensive", isToken1Expensive) // t - if exactIn { amountRemainingLessFee := u256.Zero() @@ -53,15 +49,8 @@ func swapMathComputeSwapStep( } if amountRemaining.Abs().Gte(amountOut) { - // println(3) sqrtRatioNextX96 = sqrtRatioTargetX96 } else { - // println(4) - // println("sqrtRatioCurrentX96:", sqrtRatioCurrentX96.ToString()) - // println("liquidity:", liquidity.ToString()) - // println("amountRemaining.Abs():", amountRemaining.Abs().ToString()) - // println("isToken1Expensive:", isToken1Expensive) - // println("<< SQRT") sqrtRatioNextX96 = sqrtPriceMathGetNextSqrtPriceFromOutput( sqrtRatioCurrentX96, liquidity, @@ -114,6 +103,5 @@ func swapMathComputeSwapStep( if !exactIn && !(amountOut.IsZero()) { amountOut = amountOut.Add(amountOut, u256.NewUint(1)) } - // println() return sqrtRatioNextX96, amountIn, amountOut, feeAmount } diff --git a/position/sqrt_price_math.gno b/position/sqrt_price_math.gno index ab51eb8f9..3de01094e 100644 --- a/position/sqrt_price_math.gno +++ b/position/sqrt_price_math.gno @@ -5,7 +5,6 @@ import ( i256 "gno.land/p/big/int256" u256 "gno.land/p/big/uint256" - u512 "gno.land/p/big/uint512" ) func sqrtPriceMathGetNextSqrtPriceFromAmount0RoundingUp( @@ -17,7 +16,6 @@ func sqrtPriceMathGetNextSqrtPriceFromAmount0RoundingUp( if amount.IsZero() { return sqrtPX96 } - // println("|| sqrtPriceMathGetNextSqrtPriceFromAmount0RoundingUp:", add) numerator1 := new(u256.Uint).Lsh(liquidity, 96) @@ -89,22 +87,18 @@ func sqrtPriceMathGetNextSqrtPriceFromAmount1RoundingDown( quotient = new(u256.Uint).Lsh(amount, 96) quotient = new(u256.Uint).Div(quotient, liquidity) } else { - quotient = u512.MulDiv(amount, u256.UnsafeFromDecimal(consts.Q96), liquidity) + quotient = u256.MulDiv(amount, u256.UnsafeFromDecimal(consts.Q96), liquidity) } quotient = new(u256.Uint).Sub(quotient, u256.One()) return new(u256.Uint).Add(sqrtPX96, quotient) } else { - // println("FF") if amount.Lte(u256.UnsafeFromDecimal(consts.MAX_UINT160)) { value1 := new(u256.Uint).Lsh(amount, 96) - quotient = u512.DivRoundingUp(value1, liquidity) - // println("q1:", quotient.ToString()) + quotient = u256.DivRoundingUp(value1, liquidity) } else { - quotient = u512.MulDivRoundingUp(amount, u256.UnsafeFromDecimal(consts.Q96), liquidity) - // println("q2:", quotient.ToString()) + quotient = u256.MulDiv(amount, u256.UnsafeFromDecimal(consts.Q96), liquidity) } - // println("sqrtPX96:", sqrtPX96.ToString()) if !(sqrtPX96.Gt(quotient)) { panic("position_sqrt price math #2") @@ -134,7 +128,6 @@ func sqrtPriceMathGetNextSqrtPriceFromOutput( amountOut *u256.Uint, // uint256 zeroForOne bool, // bool ) *u256.Uint { // uint160 - // println("sqrtPriceMathGetNextSqrtPriceFromOutput:", zeroForOne) if zeroForOne { return sqrtPriceMathGetNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) } From 180f2dce673f86ab44bac355130e786937bf62c8 Mon Sep 17 00:00:00 2001 From: n3wbie Date: Thu, 7 Mar 2024 19:48:56 +0900 Subject: [PATCH 4/5] fix: test cases --- ...o_test.gno => _TEST_router_ratio_test.gnoa} | 0 ...p_route_1route_3hop_native_middle_test.gno} | 0 staker/_TEST_staker_collect_reward_test.gnoa | 12 ++++++------ staker/_TEST_staker_get_test.gnoa | 12 ++++++------ ...> _TEST_staker_internal_external_test.gnoa} | 18 +++++++++--------- .../_TEST_staker_one_external_native_test.gnoa | 12 ++++++------ staker/_TEST_staker_one_external_test.gnoa | 12 ++++++------ ...TEST_staker_one_increase_external_test.gnoa | 12 ++++++------ ...test.gnoa => _TEST_staker_rpc_get_test.gno} | 12 ++++++------ 9 files changed, 45 insertions(+), 45 deletions(-) rename router/{_TEST_router_ratio_test.gno => _TEST_router_ratio_test.gnoa} (100%) rename router/{_TEST_router_swap_route_1route_3hop_native_middle_test.gnoa => _TEST_router_swap_route_1route_3hop_native_middle_test.gno} (100%) rename staker/{_TEST_staker_internal_external_test.gno => _TEST_staker_internal_external_test.gnoa} (93%) rename staker/{_TEST_staker_rpc_get_test.gnoa => _TEST_staker_rpc_get_test.gno} (95%) diff --git a/router/_TEST_router_ratio_test.gno b/router/_TEST_router_ratio_test.gnoa similarity index 100% rename from router/_TEST_router_ratio_test.gno rename to router/_TEST_router_ratio_test.gnoa diff --git a/router/_TEST_router_swap_route_1route_3hop_native_middle_test.gnoa b/router/_TEST_router_swap_route_1route_3hop_native_middle_test.gno similarity index 100% rename from router/_TEST_router_swap_route_1route_3hop_native_middle_test.gnoa rename to router/_TEST_router_swap_route_1route_3hop_native_middle_test.gno diff --git a/staker/_TEST_staker_collect_reward_test.gnoa b/staker/_TEST_staker_collect_reward_test.gnoa index f382ba159..6d789907b 100644 --- a/staker/_TEST_staker_collect_reward_test.gnoa +++ b/staker/_TEST_staker_collect_reward_test.gnoa @@ -49,8 +49,8 @@ func TestPoolInitCreatePool(t *testing.T) { func TestPositionMint01(t *testing.T) { std.TestSetPrevAddr(test1) - bar.Approve(a2u(consts.POOL_ADDR), 367) - qux.Approve(a2u(consts.POOL_ADDR), 999) + bar.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) + qux.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) std.TestSkipHeights(2) lpTokenId, liquidity, amount0, amount1 := pn.Mint( @@ -69,7 +69,7 @@ func TestPositionMint01(t *testing.T) { shouldEQ(t, lpTokenId, 1) shouldEQ(t, gnft.OwnerOf(tid(lpTokenId)), std.GetOrigCaller()) // test1 - shouldEQ(t, amount0, "367") + shouldEQ(t, amount0, "368") shouldEQ(t, amount1, "999") // approve nft to staker @@ -80,8 +80,8 @@ func TestPositionMint01(t *testing.T) { func TestPositionMint02(t *testing.T) { std.TestSetPrevAddr(test1) - bar.Approve(a2u(consts.POOL_ADDR), 3978) - qux.Approve(a2u(consts.POOL_ADDR), 4999) + bar.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) + qux.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) std.TestSkipHeights(2) lpTokenId, liquidity, amount0, amount1 := pn.Mint( @@ -100,7 +100,7 @@ func TestPositionMint02(t *testing.T) { shouldEQ(t, lpTokenId, 2) shouldEQ(t, gnft.OwnerOf(tid(lpTokenId)), std.GetOrigCaller()) // test1 - shouldEQ(t, amount0, "3978") + shouldEQ(t, amount0, "3979") shouldEQ(t, amount1, "4999") // approve nft to staker diff --git a/staker/_TEST_staker_get_test.gnoa b/staker/_TEST_staker_get_test.gnoa index ad0504c96..cef2a724f 100644 --- a/staker/_TEST_staker_get_test.gnoa +++ b/staker/_TEST_staker_get_test.gnoa @@ -34,8 +34,8 @@ func TestPoolInitCreatePool(t *testing.T) { func TestPositionMint01(t *testing.T) { std.TestSetPrevAddr(test1) - bar.Approve(a2u(consts.POOL_ADDR), 367) - qux.Approve(a2u(consts.POOL_ADDR), 999) + bar.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) + qux.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) std.TestSkipHeights(2) lpTokenId, liquidity, amount0, amount1 := pn.Mint( @@ -54,7 +54,7 @@ func TestPositionMint01(t *testing.T) { shouldEQ(t, lpTokenId, 1) shouldEQ(t, gnft.OwnerOf(tid(lpTokenId)), std.GetOrigCaller()) // test1 - shouldEQ(t, amount0, "367") + shouldEQ(t, amount0, "368") shouldEQ(t, amount1, "999") // approve nft to staker @@ -65,8 +65,8 @@ func TestPositionMint01(t *testing.T) { func TestPositionMint02(t *testing.T) { std.TestSetPrevAddr(test1) - bar.Approve(a2u(consts.POOL_ADDR), 3978) - qux.Approve(a2u(consts.POOL_ADDR), 4999) + bar.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) + qux.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) std.TestSkipHeights(2) lpTokenId, liquidity, amount0, amount1 := pn.Mint( @@ -85,7 +85,7 @@ func TestPositionMint02(t *testing.T) { shouldEQ(t, lpTokenId, 2) shouldEQ(t, gnft.OwnerOf(tid(lpTokenId)), std.GetOrigCaller()) // test1 - shouldEQ(t, amount0, "3978") + shouldEQ(t, amount0, "3979") shouldEQ(t, amount1, "4999") // approve nft to staker diff --git a/staker/_TEST_staker_internal_external_test.gno b/staker/_TEST_staker_internal_external_test.gnoa similarity index 93% rename from staker/_TEST_staker_internal_external_test.gno rename to staker/_TEST_staker_internal_external_test.gnoa index ca86f0f07..6e83ece3a 100644 --- a/staker/_TEST_staker_internal_external_test.gno +++ b/staker/_TEST_staker_internal_external_test.gnoa @@ -52,8 +52,8 @@ func TestPoolInitCreatePool(t *testing.T) { func TestMintBarQux500(t *testing.T) { std.TestSetPrevAddr(test1) - bar.Approve(a2u(consts.POOL_ADDR), 36789) - qux.Approve(a2u(consts.POOL_ADDR), 99999) + bar.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) + qux.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) std.TestSkipHeights(2) tokenId, liquidity, amount0, amount1 := pn.Mint( @@ -72,14 +72,14 @@ func TestMintBarQux500(t *testing.T) { shouldEQ(t, tokenId, 1) shouldEQ(t, gnft.OwnerOf(tid(tokenId)), std.GetOrigCaller()) // test1 - shouldEQ(t, amount0, "36789") + shouldEQ(t, amount0, "36790") shouldEQ(t, amount1, "99999") } func TestMintBarBaz100(t *testing.T) { std.TestSetPrevAddr(test1) - bar.Approve(a2u(consts.POOL_ADDR), 99999) - baz.Approve(a2u(consts.POOL_ADDR), 99999) + bar.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) + baz.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) std.TestSkipHeights(2) tokenId, liquidity, amount0, amount1 := pn.Mint( @@ -98,14 +98,14 @@ func TestMintBarBaz100(t *testing.T) { shouldEQ(t, tokenId, 2) shouldEQ(t, gnft.OwnerOf(tid(tokenId)), std.GetOrigCaller()) // test1 - shouldEQ(t, amount0, "99999") + shouldEQ(t, amount0, "100000") shouldEQ(t, amount1, "99999") } func TestMintFooQux500(t *testing.T) { std.TestSetPrevAddr(test1) - foo.Approve(a2u(consts.POOL_ADDR), 99999) - qux.Approve(a2u(consts.POOL_ADDR), 99999) + foo.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) + qux.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) std.TestSkipHeights(2) tokenId, liquidity, amount0, amount1 := pn.Mint( @@ -124,7 +124,7 @@ func TestMintFooQux500(t *testing.T) { shouldEQ(t, tokenId, 3) shouldEQ(t, gnft.OwnerOf(tid(tokenId)), std.GetOrigCaller()) // test1 - shouldEQ(t, amount0, "99999") + shouldEQ(t, amount0, "100000") shouldEQ(t, amount1, "99999") } diff --git a/staker/_TEST_staker_one_external_native_test.gnoa b/staker/_TEST_staker_one_external_native_test.gnoa index ca72e5f85..504cf1f88 100644 --- a/staker/_TEST_staker_one_external_native_test.gnoa +++ b/staker/_TEST_staker_one_external_native_test.gnoa @@ -48,8 +48,8 @@ func TestPoolInitCreatePool(t *testing.T) { func TestPositionMint01(t *testing.T) { std.TestSetPrevAddr(test1) - bar.Approve(a2u(consts.POOL_ADDR), 367) - foo.Approve(a2u(consts.POOL_ADDR), 999) + bar.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) + foo.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) std.TestSkipHeights(2) lpTokenId, liquidity, amount0, amount1 := pn.Mint( @@ -68,7 +68,7 @@ func TestPositionMint01(t *testing.T) { shouldEQ(t, lpTokenId, 1) shouldEQ(t, gnft.OwnerOf(tid(lpTokenId)), std.GetOrigCaller()) // test1 - shouldEQ(t, amount0, "367") + shouldEQ(t, amount0, "368") shouldEQ(t, amount1, "999") // approve nft to staker for staking @@ -79,8 +79,8 @@ func TestPositionMint01(t *testing.T) { func TestPositionMint02(t *testing.T) { std.TestSetPrevAddr(test1) - bar.Approve(a2u(consts.POOL_ADDR), 3978) - foo.Approve(a2u(consts.POOL_ADDR), 4999) + bar.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) + foo.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) std.TestSkipHeights(2) lpTokenId, liquidity, amount0, amount1 := pn.Mint( @@ -99,7 +99,7 @@ func TestPositionMint02(t *testing.T) { shouldEQ(t, lpTokenId, 2) shouldEQ(t, gnft.OwnerOf(tid(lpTokenId)), std.GetOrigCaller()) // test1 - shouldEQ(t, amount0, "3978") + shouldEQ(t, amount0, "3979") shouldEQ(t, amount1, "4999") // approve nft to staker diff --git a/staker/_TEST_staker_one_external_test.gnoa b/staker/_TEST_staker_one_external_test.gnoa index 99a610033..4fb930152 100644 --- a/staker/_TEST_staker_one_external_test.gnoa +++ b/staker/_TEST_staker_one_external_test.gnoa @@ -50,8 +50,8 @@ func TestPoolInitCreatePool(t *testing.T) { func TestPositionMint01(t *testing.T) { std.TestSetPrevAddr(test1) - bar.Approve(a2u(consts.POOL_ADDR), 999) - foo.Approve(a2u(consts.POOL_ADDR), 367) + bar.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) + foo.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) std.TestSkipHeights(2) lpTokenId, liquidity, amount0, amount1 := pn.Mint( @@ -70,7 +70,7 @@ func TestPositionMint01(t *testing.T) { shouldEQ(t, lpTokenId, 1) shouldEQ(t, gnft.OwnerOf(tid(lpTokenId)), std.GetOrigCaller()) // test1 - shouldEQ(t, amount0, "999") + shouldEQ(t, amount0, "1000") shouldEQ(t, amount1, "367") // approve nft to staker for staking @@ -81,8 +81,8 @@ func TestPositionMint01(t *testing.T) { func TestPositionMint02(t *testing.T) { std.TestSetPrevAddr(test1) - bar.Approve(a2u(consts.POOL_ADDR), 4999) - foo.Approve(a2u(consts.POOL_ADDR), 3978) + bar.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) + foo.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) std.TestSkipHeights(2) lpTokenId, liquidity, amount0, amount1 := pn.Mint( @@ -101,7 +101,7 @@ func TestPositionMint02(t *testing.T) { shouldEQ(t, lpTokenId, 2) shouldEQ(t, gnft.OwnerOf(tid(lpTokenId)), std.GetOrigCaller()) // test1 - shouldEQ(t, amount0, "4999") + shouldEQ(t, amount0, "5000") shouldEQ(t, amount1, "3978") // approve nft to staker diff --git a/staker/_TEST_staker_one_increase_external_test.gnoa b/staker/_TEST_staker_one_increase_external_test.gnoa index 70a853e0e..0b9059e70 100644 --- a/staker/_TEST_staker_one_increase_external_test.gnoa +++ b/staker/_TEST_staker_one_increase_external_test.gnoa @@ -50,8 +50,8 @@ func TestPoolInitCreatePool(t *testing.T) { func TestPositionMint01(t *testing.T) { std.TestSetPrevAddr(test1) - bar.Approve(a2u(consts.POOL_ADDR), 999) - foo.Approve(a2u(consts.POOL_ADDR), 367) + bar.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) + foo.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) std.TestSkipHeights(2) lpTokenId, liquidity, amount0, amount1 := pn.Mint( @@ -70,7 +70,7 @@ func TestPositionMint01(t *testing.T) { shouldEQ(t, lpTokenId, 1) shouldEQ(t, gnft.OwnerOf(tid(lpTokenId)), std.GetOrigCaller()) // test1 - shouldEQ(t, amount0, "999") + shouldEQ(t, amount0, "1000") shouldEQ(t, amount1, "367") // approve nft to staker for staking @@ -81,8 +81,8 @@ func TestPositionMint01(t *testing.T) { func TestPositionMint02(t *testing.T) { std.TestSetPrevAddr(test1) - bar.Approve(a2u(consts.POOL_ADDR), 4999) - foo.Approve(a2u(consts.POOL_ADDR), 3978) + bar.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) + foo.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) std.TestSkipHeights(2) lpTokenId, liquidity, amount0, amount1 := pn.Mint( @@ -101,7 +101,7 @@ func TestPositionMint02(t *testing.T) { shouldEQ(t, lpTokenId, 2) shouldEQ(t, gnft.OwnerOf(tid(lpTokenId)), std.GetOrigCaller()) // test1 - shouldEQ(t, amount0, "4999") + shouldEQ(t, amount0, "5000") shouldEQ(t, amount1, "3978") // approve nft to staker diff --git a/staker/_TEST_staker_rpc_get_test.gnoa b/staker/_TEST_staker_rpc_get_test.gno similarity index 95% rename from staker/_TEST_staker_rpc_get_test.gnoa rename to staker/_TEST_staker_rpc_get_test.gno index eccc5d41e..433b32b36 100644 --- a/staker/_TEST_staker_rpc_get_test.gnoa +++ b/staker/_TEST_staker_rpc_get_test.gno @@ -49,8 +49,8 @@ func TestPoolInitCreatePool(t *testing.T) { } func TestPositionMint01(t *testing.T) { std.TestSetPrevAddr(test1) - bar.Approve(a2u(consts.POOL_ADDR), 367) - qux.Approve(a2u(consts.POOL_ADDR), 999) + bar.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) + qux.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) std.TestSkipHeights(2) lpTokenId, liquidity, amount0, amount1 := pn.Mint( @@ -69,7 +69,7 @@ func TestPositionMint01(t *testing.T) { shouldEQ(t, lpTokenId, 1) shouldEQ(t, gnft.OwnerOf(tid(lpTokenId)), std.GetOrigCaller()) // test1 - shouldEQ(t, amount0, "367") + shouldEQ(t, amount0, "368") shouldEQ(t, amount1, "999") // approve nft to staker for staking @@ -80,8 +80,8 @@ func TestPositionMint01(t *testing.T) { func TestPositionMint02(t *testing.T) { std.TestSetPrevAddr(test1) - bar.Approve(a2u(consts.POOL_ADDR), 3978) - qux.Approve(a2u(consts.POOL_ADDR), 4999) + bar.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) + qux.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) std.TestSkipHeights(2) lpTokenId, liquidity, amount0, amount1 := pn.Mint( @@ -100,7 +100,7 @@ func TestPositionMint02(t *testing.T) { shouldEQ(t, lpTokenId, 2) shouldEQ(t, gnft.OwnerOf(tid(lpTokenId)), std.GetOrigCaller()) // test1 - shouldEQ(t, amount0, "3978") + shouldEQ(t, amount0, "3979") shouldEQ(t, amount1, "4999") // approve nft to staker From 978a14bf69974facc756cd720e5722bc645d7e6b Mon Sep 17 00:00:00 2001 From: n3wbie Date: Thu, 7 Mar 2024 19:49:11 +0900 Subject: [PATCH 5/5] feat: remove require, use if ~ panic --- packages/common/tick_math.gno | 6 - pool/_GET_no_receiver.gno | 168 +++++++++++++++----- pool/_GET_no_receiver_string.gno | 116 ++++++++++---- pool/_GET_receiver.gno | 64 ++++++-- pool/_RPC_dry.gno | 16 ++ pool/emergency_halt.gno | 13 +- pool/pool.gno | 255 ++++++++++++++----------------- pool/pool_manager.gno | 31 +++- pool/swap_math.gno | 15 ++ pool/swap_parameters.gno | 10 +- pool/tick_bitmap.gno | 16 +- pool/utils.gno | 45 ++---- pool/withdrawal_fee.gno | 21 ++- position/position.gno | 161 +++++++------------ position/type.gno | 4 + position/utils.gno | 12 +- router/router.gno | 29 +++- router/router_dry.gno | 17 ++- router/utils.gno | 14 +- staker/_GET_no_receiver.gno | 52 +++++-- staker/_RPC_api_stake.gno | 4 +- staker/reward_fee.gno | 16 +- staker/reward_math.gno | 8 +- staker/staker.gno | 75 +++++---- staker/utils.gno | 24 --- 25 files changed, 674 insertions(+), 518 deletions(-) diff --git a/packages/common/tick_math.gno b/packages/common/tick_math.gno index 65bb99181..651f30379 100644 --- a/packages/common/tick_math.gno +++ b/packages/common/tick_math.gno @@ -194,12 +194,6 @@ func gt(x, y *u256.Uint) *u256.Uint { return u256.Zero() } -func require(condition bool, message string) { - if !condition { - panic(message) - } -} - func abs(x int32) int32 { if x < 0 { return -x diff --git a/pool/_GET_no_receiver.gno b/pool/_GET_no_receiver.gno index b346232dc..3e8fbbeb0 100644 --- a/pool/_GET_no_receiver.gno +++ b/pool/_GET_no_receiver.gno @@ -10,21 +10,27 @@ import ( // Slot0 func PoolGetSlot0SqrtPriceX96(poolPath string) *u256.Uint { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetSlot0SqrtPriceX96() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetSlot0SqrtPriceX96() || pool(%s) does not exist", poolPath)) + } return pool.slot0.sqrtPriceX96 } func PoolGetSlot0Tick(poolPath string) int32 { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetSlot0Tick() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetSlot0Tick() || pool(%s) does not exist", poolPath)) + } return pool.slot0.tick } func PoolGetSlot0FeeProtocol(poolPath string) uint8 { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetSlot0FeeProtocol() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetSlot0FeeProtocol() || pool(%s) does not exist", poolPath)) + } return pool.slot0.feeProtocol } @@ -32,14 +38,18 @@ func PoolGetSlot0FeeProtocol(poolPath string) uint8 { // Balances func PoolGetToken0Balance(poolPath string) *u256.Uint { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetToken0Balance() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetToken0Balance() || pool(%s) does not exist", poolPath)) + } return pool.balances.token0 } func PoolGetToken1Balance(poolPath string) *u256.Uint { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetToken1Balance() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetToken1Balance() || pool(%s) does not exist", poolPath)) + } return pool.balances.token1 } @@ -47,14 +57,18 @@ func PoolGetToken1Balance(poolPath string) *u256.Uint { // ProtocolFees func PoolGetToken0ProtocolFee(poolPath string) *u256.Uint { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetToken0ProtocolFee() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetToken0ProtocolFee() || pool(%s) does not exist", poolPath)) + } return pool.protocolFees.token0 } func PoolGetToken1ProtocolFee(poolPath string) *u256.Uint { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetToken1ProtocolFee() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetToken1ProtocolFee() || pool(%s) does not exist", poolPath)) + } return pool.protocolFees.token1 } @@ -62,50 +76,70 @@ func PoolGetToken1ProtocolFee(poolPath string) *u256.Uint { // PositionInfo func PoolGetPositionLiquidity(poolPath, key string) *u256.Uint { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetPositionLiquidity() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetPositionLiquidity() || pool(%s) does not exist", poolPath)) + } position, exist := pool.positions[key] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetPositionLiquidity() || position(%s) does not exist", key)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetPositionLiquidity() || position(%s) does not exist", key)) + } return position.liquidity } func PoolGetPositionFeeGrowthInside0LastX128(poolPath, key string) *u256.Uint { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetPositionFeeGrowthInside0LastX128() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetPositionFeeGrowthInside0LastX128() || pool(%s) does not exist", poolPath)) + } position, exist := pool.positions[key] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetPositionFeeGrowthInside0LastX128) || position(%s) does not exist", key)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetPositionFeeGrowthInside0LastX128) || position(%s) does not exist", key)) + } return position.feeGrowthInside0LastX128 } func PoolGetPositionFeeGrowthInside1LastX128(poolPath, key string) *u256.Uint { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetPositionFeeGrowthInside1LastX128() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetPositionFeeGrowthInside1LastX128() || pool(%s) does not exist", poolPath)) + } position, exist := pool.positions[key] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetPositionFeeGrowthInside1LastX128() || position(%s) does not exist", key)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetPositionFeeGrowthInside1LastX128() || position(%s) does not exist", key)) + } return position.feeGrowthInside1LastX128 } func PoolGetPositionTokensOwed0(poolPath, key string) *u256.Uint { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetPositionTokensOwed0() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetPositionTokensOwed0() || pool(%s) does not exist", poolPath)) + } position, exist := pool.positions[key] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetPositionTokensOwed0() || position(%s) does not exist", key)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetPositionTokensOwed0() || position(%s) does not exist", key)) + } return position.tokensOwed0 } func PoolGetPositionTokensOwed1(poolPath, key string) *u256.Uint { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetPositionTokensOwed1() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetPositionTokensOwed1() || pool(%s) does not exist", poolPath)) + } position, exist := pool.positions[key] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetPositionTokensOwed1() || position(%s) does not exist", key)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetPositionTokensOwed1() || position(%s) does not exist", key)) + } return position.tokensOwed1 } @@ -113,80 +147,112 @@ func PoolGetPositionTokensOwed1(poolPath, key string) *u256.Uint { // TickInfo func PoolGetTickLiquidityGross(poolPath string, x int32) *u256.Uint { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickLiquidityGross() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickLiquidityGross() || pool(%s) does not exist", poolPath)) + } tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickLiquidityGross() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickLiquidityGross() || tick(%d) does not exist", x)) + } return tick.liquidityGross } func PoolGetTickLiquidityNet(poolPath string, x int32) *i256.Int { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickLiquidityNet() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickLiquidityNet() || pool(%s) does not exist", poolPath)) + } tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickLiquidityNet() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickLiquidityNet() || tick(%d) does not exist", x)) + } return tick.liquidityNet } func PoolGetTickFeeGrowthOutside0X128(poolPath string, x int32) *u256.Uint { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickFeeGrowthOutside0X128() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickFeeGrowthOutside0X128() || pool(%s) does not exist", poolPath)) + } tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickFeeGrowthOutside0X128() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickFeeGrowthOutside0X128() || tick(%d) does not exist", x)) + } return tick.feeGrowthOutside0X128 } func PoolGetTickFeeGrowthOutside1X128(poolPath string, x int32) *u256.Uint { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickFeeGrowthOutside1X128() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickFeeGrowthOutside1X128() || pool(%s) does not exist", poolPath)) + } tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickFeeGrowthOutside1X128() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickFeeGrowthOutside1X128() || tick(%d) does not exist", x)) + } return tick.feeGrowthOutside1X128 } func PoolGetTickTickCumulativeOutside(poolPath string, x int32) int64 { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickTickCumulativeOutside() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickTickCumulativeOutside() || pool(%s) does not exist", poolPath)) + } tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickTickCumulativeOutside() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickTickCumulativeOutside() || tick(%d) does not exist", x)) + } return tick.tickCumulativeOutside } func PoolGetTickSecondsPerLiquidityOutsideX128(poolPath string, x int32) *u256.Uint { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickSecondsPerLiquidityOutsideX128() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickSecondsPerLiquidityOutsideX128() || pool(%s) does not exist", poolPath)) + } tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickSecondsPerLiquidityOutsideX128() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickSecondsPerLiquidityOutsideX128() || tick(%d) does not exist", x)) + } return tick.secondsPerLiquidityOutsideX128 } func PoolGetTickSecondsOutside(poolPath string, x int32) uint32 { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickSecondsOutside() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickSecondsOutside() || pool(%s) does not exist", poolPath)) + } tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickSecondsOutside() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickSecondsOutside() || tick(%d) does not exist", x)) + } return tick.secondsOutside } func PoolGetTickInitialized(poolPath string, x int32) bool { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickInitialized() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickInitialized() || pool(%s) does not exist", poolPath)) + } tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickInitialized() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickInitialized() || tick(%d) does not exist", x)) + } return tick.initialized } @@ -194,10 +260,14 @@ func PoolGetTickInitialized(poolPath string, x int32) bool { // TickBitmaps func PoolGetTickBitmap(poolPath string, x int16) *u256.Uint { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickBitmap() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickBitmap() || pool(%s) does not exist", poolPath)) + } tickBitmap, exist := pool.tickBitmaps[x] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickBitmap() || tickBitmap(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickBitmap() || tickBitmap(%d) does not exist", x)) + } return tickBitmap } @@ -205,49 +275,63 @@ func PoolGetTickBitmap(poolPath string, x int16) *u256.Uint { // Pool func PoolGetToken0Path(poolPath string) string { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetToken0Path() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetToken0Path() || pool(%s) does not exist", poolPath)) + } return pool.token0Path } func PoolGetToken1Path(poolPath string) string { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetToken1Path() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetToken1Path() || pool(%s) does not exist", poolPath)) + } return pool.token1Path } func PoolGetFee(poolPath string) uint32 { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetFee() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetFee() || pool(%s) does not exist", poolPath)) + } return pool.fee } func PoolGetTickSpacing(poolPath string) int32 { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickSpacing() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetTickSpacing() || pool(%s) does not exist", poolPath)) + } return pool.tickSpacing } func PoolGetFeeGrowthGlobal0X128(poolPath string) *u256.Uint { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetFeeGrowthGlobal0X128() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetFeeGrowthGlobal0X128() || pool(%s) does not exist", poolPath)) + } return pool.feeGrowthGlobal0X128 } func PoolGetFeeGrowthGlobal1X128(poolPath string) *u256.Uint { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetFeeGrowthGlobal1X128() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetFeeGrowthGlobal1X128() || pool(%s) does not exist", poolPath)) + } return pool.feeGrowthGlobal1X128 } func PoolGetLiquidity(poolPath string) *u256.Uint { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetLiquidity() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_no_receiver.gno__PoolGetLiquidity() || pool(%s) does not exist", poolPath)) + } return pool.liquidity } diff --git a/pool/_GET_no_receiver_string.gno b/pool/_GET_no_receiver_string.gno index 544393093..5cdd79ba2 100644 --- a/pool/_GET_no_receiver_string.gno +++ b/pool/_GET_no_receiver_string.gno @@ -7,14 +7,18 @@ import ( // Balances func PoolGetToken0BalanceStr(poolPath string) string { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetToken0BalanceStr() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetToken0BalanceStr() || pool(%s) does not exist", poolPath)) + } return pool.balances.token0.ToString() } func PoolGetToken1BalanceStr(poolPath string) string { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetToken1BalanceStr() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetToken1BalanceStr() || pool(%s) does not exist", poolPath)) + } return pool.balances.token1.ToString() } @@ -22,14 +26,18 @@ func PoolGetToken1BalanceStr(poolPath string) string { // ProtocolFees func PoolGetToken0ProtocolFeeStr(poolPath string) string { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetToken0ProtocolFeeStr() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetToken0ProtocolFeeStr() || pool(%s) does not exist", poolPath)) + } return pool.protocolFees.token0.ToString() } func PoolGetToken1ProtocolFeeStr(poolPath string) string { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetToken1ProtocolFeeStr() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetToken1ProtocolFeeStr() || pool(%s) does not exist", poolPath)) + } return pool.protocolFees.token1.ToString() } @@ -37,50 +45,70 @@ func PoolGetToken1ProtocolFeeStr(poolPath string) string { // PositionInfo func PoolGetPositionLiquidityStr(poolPath, key string) string { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetPositionLiquidityStr() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetPositionLiquidityStr() || pool(%s) does not exist", poolPath)) + } position, exist := pool.positions[key] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetPositionLiquidityStr() || position(%s) does not exist", key)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetPositionLiquidityStr() || position(%s) does not exist", key)) + } return position.liquidity.ToString() } func PoolGetPositionFeeGrowthInside0LastX128Str(poolPath, key string) string { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetPositionFeeGrowthInside0LastX128Str() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetPositionFeeGrowthInside0LastX128Str() || pool(%s) does not exist", poolPath)) + } position, exist := pool.positions[key] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetPositionFeeGrowthInside0LastX128Str) || position(%s) does not exist", key)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetPositionFeeGrowthInside0LastX128Str) || position(%s) does not exist", key)) + } return position.feeGrowthInside0LastX128.ToString() } func PoolGetPositionFeeGrowthInside1LastX128Str(poolPath, key string) string { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetPositionFeeGrowthInside1LastX128Str() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetPositionFeeGrowthInside1LastX128Str() || pool(%s) does not exist", poolPath)) + } position, exist := pool.positions[key] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetPositionFeeGrowthInside1LastX128Str() || position(%s) does not exist", key)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetPositionFeeGrowthInside1LastX128Str() || position(%s) does not exist", key)) + } return position.feeGrowthInside1LastX128.ToString() } func PoolGetPositionTokensOwed0Str(poolPath, key string) string { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetPositionTokensOwed0Str() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetPositionTokensOwed0Str() || pool(%s) does not exist", poolPath)) + } position, exist := pool.positions[key] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetPositionTokensOwed0Str() || position(%s) does not exist", key)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetPositionTokensOwed0Str() || position(%s) does not exist", key)) + } return position.tokensOwed0.ToString() } func PoolGetPositionTokensOwed1Str(poolPath, key string) string { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetPositionTokensOwed1Str() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetPositionTokensOwed1Str() || pool(%s) does not exist", poolPath)) + } position, exist := pool.positions[key] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetPositionTokensOwed1Str() || position(%s) does not exist", key)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetPositionTokensOwed1Str() || position(%s) does not exist", key)) + } return position.tokensOwed1.ToString() } @@ -88,50 +116,70 @@ func PoolGetPositionTokensOwed1Str(poolPath, key string) string { // TickInfo func PoolGetTickLiquidityGrossStr(poolPath string, x int32) string { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickLiquidityGrossStr() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickLiquidityGrossStr() || pool(%s) does not exist", poolPath)) + } tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickLiquidityGrossStr() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickLiquidityGrossStr() || tick(%d) does not exist", x)) + } return tick.liquidityGross.ToString() } func PoolGetTickLiquidityNetStr(poolPath string, x int32) string { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickLiquidityNetStr() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickLiquidityNetStr() || pool(%s) does not exist", poolPath)) + } tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickLiquidityNetStr() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickLiquidityNetStr() || tick(%d) does not exist", x)) + } return tick.liquidityNet.ToString() } func PoolGetTickFeeGrowthOutside0X128Str(poolPath string, x int32) string { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickFeeGrowthOutside0X128Str() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickFeeGrowthOutside0X128Str() || pool(%s) does not exist", poolPath)) + } tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickFeeGrowthOutside0X128Str() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickFeeGrowthOutside0X128Str() || tick(%d) does not exist", x)) + } return tick.feeGrowthOutside0X128.ToString() } func PoolGetTickFeeGrowthOutside1X128Str(poolPath string, x int32) string { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickFeeGrowthOutside1X128Str() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickFeeGrowthOutside1X128Str() || pool(%s) does not exist", poolPath)) + } tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickFeeGrowthOutside1X128Str() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickFeeGrowthOutside1X128Str() || tick(%d) does not exist", x)) + } return tick.feeGrowthOutside1X128.ToString() } func PoolGetTickSecondsPerLiquidityOutsideX128Str(poolPath string, x int32) string { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickSecondsPerLiquidityOutsideX128Str() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickSecondsPerLiquidityOutsideX128Str() || pool(%s) does not exist", poolPath)) + } tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickSecondsPerLiquidityOutsideX128Str() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickSecondsPerLiquidityOutsideX128Str() || tick(%d) does not exist", x)) + } return tick.secondsPerLiquidityOutsideX128.ToString() } @@ -139,10 +187,14 @@ func PoolGetTickSecondsPerLiquidityOutsideX128Str(poolPath string, x int32) stri // TickBitmaps func PoolGetTickBitmapStr(poolPath string, x int16) string { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickBitmapStr() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickBitmapStr() || pool(%s) does not exist", poolPath)) + } tickBitmap, exist := pool.tickBitmaps[x] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickBitmapStr() || tickBitmap(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetTickBitmapStr() || tickBitmap(%d) does not exist", x)) + } return tickBitmap.ToString() } @@ -150,21 +202,27 @@ func PoolGetTickBitmapStr(poolPath string, x int16) string { // Pool func PoolGetFeeGrowthGlobal0X128Str(poolPath string) string { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetFeeGrowthGlobal0X128Str() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetFeeGrowthGlobal0X128Str() || pool(%s) does not exist", poolPath)) + } return pool.feeGrowthGlobal0X128.ToString() } func PoolGetFeeGrowthGlobal1X128Str(poolPath string) string { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetFeeGrowthGlobal1X128Str() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetFeeGrowthGlobal1X128Str() || pool(%s) does not exist", poolPath)) + } return pool.feeGrowthGlobal1X128.ToString() } func PoolGetLiquidityStr(poolPath string) string { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetLiquidityStr() || pool(%s) does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL]_GET_no_receiver_string.gno__PoolGetLiquidityStr() || pool(%s) does not exist", poolPath)) + } return pool.liquidity.ToString() } diff --git a/pool/_GET_receiver.gno b/pool/_GET_receiver.gno index d0ae78203..61eb7e05b 100644 --- a/pool/_GET_receiver.gno +++ b/pool/_GET_receiver.gno @@ -58,42 +58,54 @@ func (pool *Pool) PoolGetPositions() Positions { func (pool *Pool) PoolGetPosition(key string) PositionInfo { position, exist := pool.positions[key] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetPosition() || position(%s) does not exist", key)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetPosition() || position(%s) does not exist", key)) + } return position } func (pool *Pool) PoolGetPositionLiquidity(key string) *u256.Uint { position, exist := pool.positions[key] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetPositionLiquidity() || position(%s) does not exist", key)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetPositionLiquidity() || position(%s) does not exist", key)) + } return position.liquidity } func (pool *Pool) PoolGetPositionFeeGrowthInside0LastX128(key string) *u256.Uint { position, exist := pool.positions[key] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetPositionFeeGrowthInside0LastX128) || position(%s) does not exist", key)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetPositionFeeGrowthInside0LastX128) || position(%s) does not exist", key)) + } return position.feeGrowthInside0LastX128 } func (pool *Pool) PoolGetPositionFeeGrowthInside1LastX128(key string) *u256.Uint { position, exist := pool.positions[key] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetPositionFeeGrowthInside1LastX128() || position(%s) does not exist", key)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetPositionFeeGrowthInside1LastX128() || position(%s) does not exist", key)) + } return position.feeGrowthInside1LastX128 } func (pool *Pool) PoolGetPositionTokensOwed0(key string) *u256.Uint { position, exist := pool.positions[key] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetPositionTokensOwed0() || position(%s) does not exist", key)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetPositionTokensOwed0() || position(%s) does not exist", key)) + } return position.tokensOwed0 } func (pool *Pool) PoolGetPositionTokensOwed1(key string) *u256.Uint { position, exist := pool.positions[key] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetPositionTokensOwed1() || position(%s) does not exist", key)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetPositionTokensOwed1() || position(%s) does not exist", key)) + } return position.tokensOwed1 } @@ -101,63 +113,81 @@ func (pool *Pool) PoolGetPositionTokensOwed1(key string) *u256.Uint { // TickInfo func (pool *Pool) PoolGetTick(x int32) TickInfo { tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetTick() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetTick() || tick(%d) does not exist", x)) + } return tick } func (pool *Pool) PoolGetTickLiquidityGross(x int32) *u256.Uint { tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetTickLiquidityGross() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetTickLiquidityGross() || tick(%d) does not exist", x)) + } return tick.liquidityGross } func (pool *Pool) PoolGetTickLiquidityNet(x int32) *i256.Int { tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetTickLiquidityNet() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetTickLiquidityNet() || tick(%d) does not exist", x)) + } return tick.liquidityNet } func (pool *Pool) PoolGetTickFeeGrowthOutside0X128(x int32) *u256.Uint { tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetTickFeeGrowthOutside0X128() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetTickFeeGrowthOutside0X128() || tick(%d) does not exist", x)) + } return tick.feeGrowthOutside0X128 } func (pool *Pool) PoolGetTickFeeGrowthOutside1X128(x int32) *u256.Uint { tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetTickFeeGrowthOutside1X128() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetTickFeeGrowthOutside1X128() || tick(%d) does not exist", x)) + } return tick.feeGrowthOutside1X128 } func (pool *Pool) PoolGetTickTickCumulativeOutside(x int32) int64 { tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetTickTickCumulativeOutside() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetTickTickCumulativeOutside() || tick(%d) does not exist", x)) + } return tick.tickCumulativeOutside } func (pool *Pool) PoolGetTickSecondsPerLiquidityOutsideX128(x int32) *u256.Uint { tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetTickSecondsPerLiquidityOutsideX128() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetTickSecondsPerLiquidityOutsideX128() || tick(%d) does not exist", x)) + } return tick.secondsPerLiquidityOutsideX128 } func (pool *Pool) PoolGetTickSecondsOutside(x int32) uint32 { tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetTickSecondsOutside() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetTickSecondsOutside() || tick(%d) does not exist", x)) + } return tick.secondsOutside } func (pool *Pool) PoolGetTickInitialized(x int32) bool { tick, exist := pool.ticks[x] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetTickInitialized() || tick(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetTickInitialized() || tick(%d) does not exist", x)) + } return tick.initialized } @@ -165,7 +195,9 @@ func (pool *Pool) PoolGetTickInitialized(x int32) bool { // TickBitmaps func (pool *Pool) PoolGetTickBitmap(x int16) *u256.Uint { tickBitmap, exist := pool.tickBitmaps[x] - requireExist(exist, ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetTickBitmap() || tickBitmap(%d) does not exist", x)) + if !exist { + panic(ufmt.Sprintf("[POOL] _GET_receiver.gno__PoolGetTickBitmap() || tickBitmap(%d) does not exist", x)) + } return tickBitmap } diff --git a/pool/_RPC_dry.gno b/pool/_RPC_dry.gno index c393a6f60..d11c0433a 100644 --- a/pool/_RPC_dry.gno +++ b/pool/_RPC_dry.gno @@ -95,9 +95,13 @@ func DrySwap( liquidity: cache.liquidityStart, } } + // println("state.tick:", state.tick) + // println("IN state.sqrtPriceX96:", state.sqrtPriceX96.ToString()) + // println("state.sqrtPriceX96:", state.sqrtPriceX96.ToString()) // continue swapping as long as we haven't used the entire input/output and haven't reached the price limit for !(state.amountSpecifiedRemaining.IsZero()) && !(state.sqrtPriceX96.Eq(sqrtPriceLimitX96)) { + // println("state.amountSpecifiedRemaining:", state.amountSpecifiedRemaining.ToString()) var step StepComputations step.sqrtPriceStartX96 = state.sqrtPriceX96 @@ -127,6 +131,11 @@ func DrySwap( sqrtRatioTargetX96 = step.sqrtPriceNextX96 } + // println("state.sqrtPriceX96:", state.sqrtPriceX96.ToString()) + // println("sqrtRatioTargetX96:", sqrtRatioTargetX96.ToString()) + // println("state.liquidity:", state.liquidity.ToString()) + // println("state.amountSpecifiedRemaining:", state.amountSpecifiedRemaining.ToString()) + // println("pool.fee:", pool.fee) state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount = swapMathComputeSwapStep( state.sqrtPriceX96, sqrtRatioTargetX96, @@ -134,6 +143,13 @@ func DrySwap( state.amountSpecifiedRemaining, uint64(pool.fee), ) + if step.amountIn.ToString() == "271" { + // println("> state.sqrtPriceX96:", state.sqrtPriceX96.ToString()) + // println("step.amountIn:", step.amountIn.ToString()) + // println("step.amountOut:", step.amountOut.ToString()) + // println("step.feeAmount:", step.feeAmount.ToString()) + // panic("FIX") + } amountInWithFee := i256.FromUint256(new(u256.Uint).Add(step.amountIn, step.feeAmount)) if exactInput { diff --git a/pool/emergency_halt.gno b/pool/emergency_halt.gno index ce76dd10a..bc102e846 100644 --- a/pool/emergency_halt.gno +++ b/pool/emergency_halt.gno @@ -8,26 +8,19 @@ import ( ) var ( - govRealm string - // flagHalt is set to true when the emergency halt proposal is passed // when this flag is set to true, all public functions in this package will panic flagHalt bool ) func init() { - govRealm = consts.GOV_PATH flagHalt = false } func assertCalledByGovRealm() { - requirePrevRealmPath( - consts.GOV_PATH, - ufmt.Sprintf( - "[POOL] emergency_halt.gno__assertCalledByGovRealm() || only gov(%s) can call, but called from(%s)", - consts.GOV_PATH, std.PrevRealm().PkgPath(), - ), - ) + if std.PrevRealm().PkgPath() != consts.GOV_PATH { + panic(ufmt.Sprintf("[POOL] emergency_halt.gno__assertCalledByGovRealm() || only gov(%s) can call, but called from(%s)", consts.GOV_PATH, std.PrevRealm().PkgPath())) + } } func halt() { diff --git a/pool/pool.gno b/pool/pool.gno index 194a1b9bc..1b81fd97d 100644 --- a/pool/pool.gno +++ b/pool/pool.gno @@ -14,7 +14,6 @@ import ( u256 "gno.land/p/big/uint256" ) -// only position contract can call this function func Mint( token0Path string, token1Path string, @@ -24,13 +23,13 @@ func Mint( tickUpper int32, _liquidityAmount string, // uint128 ) (string, string) { // uint256 x2 - requirePrevRealmPath(consts.POSITION_PATH, ufmt.Sprintf("[POOL] pool.gno__Mint() || expected std.PrevRealm().PkgPath()(%s), got %s", consts.POSITION_PATH, std.PrevRealm().PkgPath())) - - liquidityAmount, err := u256.FromDecimal(_liquidityAmount) - if err != nil { - panic(ufmt.Sprintf("[POOL] pool.gno__Mint() || u256.FromDecimal(_liquidityAmount[%s]) failed", _liquidityAmount)) + // only position contract can call this function + if std.PrevRealm().PkgPath() != consts.POSITION_PATH { + panic(ufmt.Sprintf("[POOL] pool.gno__Mint() || expected std.PrevRealm().PkgPath()(%s), got %s", consts.POSITION_PATH, std.PrevRealm().PkgPath())) } + liquidityAmount := u256.MustFromDecimal(_liquidityAmount) + pool := GetPool(token0Path, token1Path, fee) _, amount0, amount1 := pool.modifyPosition( // int256 x2 ModifyPositionParams{ @@ -48,21 +47,14 @@ func Mint( to := GetOrigPkgAddr() ok := transferFromByRegisterCall(pool.token0Path, from, to, amount0.Uint64()) - require( - ok, - ufmt.Sprintf( - "[POOL] pool.gno__Mint() || transferFromByRegisterCall(pool.token0Path(%s), from(%s), to(%s), amount0.Uint64())(%d) failed", - pool.token0Path, from.String(), to.String(), amount0.Uint64(), - ), - ) + if !ok { + panic(ufmt.Sprintf("[POOL] pool.gno__Mint() || transferFromByRegisterCall(pool.token0Path(%s), from(%s), to(%s), amount0.Uint64())(%d) failed", pool.token0Path, from.String(), to.String(), amount0.Uint64())) + } - require( - balance0Before+amount0.Uint64() <= balanceOfByRegisterCall(pool.token0Path, GetOrigPkgAddr()), - ufmt.Sprintf( - "[POOL] pool.gno__Mint() || balance0Before(%d) + amount0(%d) <= balanceOfByRegisterCall(pool.token0Path(%s), GetOrigPkgAddr()(%s))(%d)", - balance0Before, amount0, pool.token0Path, GetOrigPkgAddr().String(), balanceOfByRegisterCall(pool.token0Path, GetOrigPkgAddr()), - ), - ) + // pool token0 balance should be increased exactly as much amount0 + if !(balance0Before+amount0.Uint64() <= balanceOfByRegisterCall(pool.token0Path, GetOrigPkgAddr())) { + panic(ufmt.Sprintf("[POOL] pool.gno__Mint() || balance0Before(%d) + amount0(%d) <= balanceOfByRegisterCall(pool.token0Path(%s), GetOrigPkgAddr()(%s))(%d)", balance0Before, amount0, pool.token0Path, GetOrigPkgAddr().String(), balanceOfByRegisterCall(pool.token0Path, GetOrigPkgAddr()))) + } } if amount1.Gt(i256.Zero()) { @@ -72,21 +64,14 @@ func Mint( to := GetOrigPkgAddr() ok := transferFromByRegisterCall(pool.token1Path, from, to, amount1.Uint64()) - require( - ok, - ufmt.Sprintf( - "[POOL] pool.gno__Mint() || transferFromByRegisterCall(pool.token1Path(%s), from(%s), to(%s), amount1.Uint64())(%d) failed", - pool.token1Path, from.String(), to.String(), amount1.Uint64(), - ), - ) + if !ok { + panic(ufmt.Sprintf("[POOL] pool.gno__Mint() || transferFromByRegisterCall(pool.token1Path(%s), from(%s), to(%s), amount1.Uint64())(%d) failed", pool.token1Path, from.String(), to.String(), amount1.Uint64())) + } - require( - balance1Before+amount1.Uint64() <= balanceOfByRegisterCall(pool.token1Path, GetOrigPkgAddr()), - ufmt.Sprintf( - "[POOL] pool.gno__Mint() || balance1Before(%d) + amount1(%d) <= balanceOfByRegisterCall(pool.token1Path(%s), GetOrigPkgAddr()(%s))(%d)", - balance1Before, amount1, pool.token1Path, GetOrigPkgAddr().String(), balanceOfByRegisterCall(pool.token1Path, GetOrigPkgAddr()), - ), - ) + // pool token1 balance should be increased exactly as much amount1 + if !(balance1Before+amount1.Uint64() <= balanceOfByRegisterCall(pool.token1Path, GetOrigPkgAddr())) { + panic(ufmt.Sprintf("[POOL] pool.gno__Mint() || balance1Before(%d) + amount1(%d) <= balanceOfByRegisterCall(pool.token1Path(%s), GetOrigPkgAddr()(%s))(%d)", balance1Before, amount1, pool.token1Path, GetOrigPkgAddr().String(), balanceOfByRegisterCall(pool.token1Path, GetOrigPkgAddr()))) + } } pool.balances.token0 = new(u256.Uint).Add(pool.balances.token0, amount0.Abs()) @@ -95,7 +80,6 @@ func Mint( return amount0.ToString(), amount1.ToString() } -// only position contract can call this function func Burn( token0Path string, token1Path string, @@ -104,13 +88,13 @@ func Burn( tickUpper int32, _liquidityAmount string, // uint128 ) (string, string) { // uint256 x2 - requirePrevRealmPath(consts.POSITION_PATH, ufmt.Sprintf("[POOL] pool.gno__Burn() || expected PrevRealmPath(%s), got %s", consts.POSITION_PATH, std.PrevRealm().PkgPath())) - - liquidityAmount, err := u256.FromDecimal(_liquidityAmount) - if err != nil { - panic(ufmt.Sprintf("[POOL] pool.gno__Burn() || u256.FromDecimal(_liquidityAmount[%s]) failed", _liquidityAmount)) + // only position contract can call this function + if std.PrevRealm().PkgPath() != consts.POSITION_PATH { + panic(ufmt.Sprintf("[POOL] pool.gno__Burn() || expected std.PrevRealm().PkgPath()(%s), got %s", consts.POSITION_PATH, std.PrevRealm().PkgPath())) } + liquidityAmount := u256.MustFromDecimal(_liquidityAmount) + pool := GetPool(token0Path, token1Path, fee) position, amount0Int, amount1Int := pool.modifyPosition( // in256 x2 ModifyPositionParams{ @@ -135,7 +119,6 @@ func Burn( return amount0.ToString(), amount1.ToString() } -// only position contract can call this function func Collect( token0Path string, token1Path string, @@ -146,22 +129,20 @@ func Collect( _amount0Requested string, // uint128 _amount1Requested string, // uint128 ) (string, string) { // uint128 x2 - - requirePrevRealmPath(consts.POSITION_PATH, ufmt.Sprintf("[POOL] pool.gno__Collect() || expected PrevRealmPath(%s), got %s", consts.POSITION_PATH, std.PrevRealm().PkgPath())) - - amount0Requested, err := u256.FromDecimal(_amount0Requested) - if err != nil { - panic(ufmt.Sprintf("[POOL] pool.gno__Collect() || u256.FromDecimal(_amount0Requested[%s]) failed", _amount0Requested)) - } - amount1Requested, err := u256.FromDecimal(_amount1Requested) - if err != nil { - panic(ufmt.Sprintf("[POOL] pool.gno__Collect() || u256.FromDecimal(_amount1Requested[%s]) failed", _amount1Requested)) + // only position contract can call this function + if std.PrevRealm().PkgPath() != consts.POSITION_PATH { + panic(ufmt.Sprintf("[POOL] pool.gno__Collect() || expected std.PrevRealm().PkgPath()(%s), got %s", consts.POSITION_PATH, std.PrevRealm().PkgPath())) } + + amount0Requested := u256.MustFromDecimal(_amount0Requested) + amount1Requested := u256.MustFromDecimal(_amount1Requested) pool := GetPool(token0Path, token1Path, fee) positionKey := positionGetKey(std.PrevRealm().Addr(), tickLower, tickUpper) position, exist := pool.positions[positionKey] - requireExist(exist, ufmt.Sprintf("[POOL] pool.gno__Collect() || position(%s) does not exist", positionKey)) + if !exist { + panic(ufmt.Sprintf("[POOL] pool.gno__Collect() || positionKey(%s) does not exist", positionKey)) + } // Smallest of three: amount0Requested, position.tokensOwed0, pool.balances.token0 amount0 := u256Min(amount0Requested, position.tokensOwed0) @@ -196,24 +177,24 @@ func Swap( _sqrtPriceLimitX96 string, // uint160 payer std.Address, // router ) (string, string) { // int256 x2 - requirePrevRealmPath(consts.ROUTER_PATH, ufmt.Sprintf("[POOL] pool.gno__Swap() || expected PrevRealmPath(%s), got %s", consts.ROUTER_PATH, std.PrevRealm().PkgPath())) + // only router contract can call this function + if std.PrevRealm().PkgPath() != consts.ROUTER_PATH { + panic(ufmt.Sprintf("[POOL] pool.gno__Swap() || expected std.PrevRealm().PkgPath()(%s), got %s", consts.ROUTER_PATH, std.PrevRealm().PkgPath())) + } if _amountSpecified == "0" { panic("[POOL] pool.gno__Swap() || _amountSpecified == 0") } - amountSpecified, err := i256.FromDecimal(_amountSpecified) - if err != nil { - panic(ufmt.Sprintf("[POOL] pool.gno__Swap() || u256.FromDecimal(_amountSpecified[%s]) failed", _amountSpecified)) - } - sqrtPriceLimitX96, err := u256.FromDecimal(_sqrtPriceLimitX96) - if err != nil { - panic(ufmt.Sprintf("[POOL] pool.gno__Swap() || u256.FromDecimal(_sqrtPriceLimitX96[%s]) failed", _sqrtPriceLimitX96)) - } + amountSpecified := i256.MustFromDecimal(_amountSpecified) + sqrtPriceLimitX96 := u256.MustFromDecimal(_sqrtPriceLimitX96) pool := GetPool(token0Path, token1Path, fee) slot0Start := pool.slot0 - require(slot0Start.unlocked, ufmt.Sprintf("[POOL] pool.gno__Swap() || slot0 must be unlocked")) + + if !(slot0Start.unlocked) { + panic("[POOL] pool.gno__Swap() || slot0Start.unlocked must be unlocked(true)") + } var feeProtocol uint8 var feeGrowthGlobalX128 *u256.Uint @@ -222,7 +203,9 @@ func Swap( min_sqrt_ratio := u256.MustFromDecimal(consts.MIN_SQRT_RATIO) cond1 := sqrtPriceLimitX96.Lt(slot0Start.sqrtPriceX96) cond2 := sqrtPriceLimitX96.Gt(min_sqrt_ratio) - require(cond1 && cond2, ufmt.Sprintf("[POOL] pool.gno__Swap() || sqrtPriceLimitX96(%s) < slot0Start.sqrtPriceX96(%s) && sqrtPriceLimitX96(%s) > consts.MIN_SQRT_RATIO(%s)", sqrtPriceLimitX96.ToString(), slot0Start.sqrtPriceX96.ToString(), sqrtPriceLimitX96.ToString(), consts.MIN_SQRT_RATIO)) + if !(cond1 && cond2) { + panic(ufmt.Sprintf("[POOL] pool.gno__Swap() || sqrtPriceLimitX96(%s) < slot0Start.sqrtPriceX96(%s) && sqrtPriceLimitX96(%s) > consts.MIN_SQRT_RATIO(%s)", sqrtPriceLimitX96.ToString(), slot0Start.sqrtPriceX96.ToString(), sqrtPriceLimitX96.ToString(), consts.MIN_SQRT_RATIO)) + } feeProtocol = slot0Start.feeProtocol % 16 feeGrowthGlobalX128 = pool.feeGrowthGlobal0X128.Clone() @@ -230,7 +213,10 @@ func Swap( max_sqrt_ratio := u256.MustFromDecimal(consts.MAX_SQRT_RATIO) cond1 := sqrtPriceLimitX96.Gt(slot0Start.sqrtPriceX96) cond2 := sqrtPriceLimitX96.Lt(max_sqrt_ratio) - require(cond1 && cond2, ufmt.Sprintf("[POOL] pool.gno__Swap() || sqrtPriceLimitX96(%s) > slot0Start.sqrtPriceX96(%s) && sqrtPriceLimitX96(%s) < consts.MAX_SQRT_RATIO(%s)", sqrtPriceLimitX96.ToString(), slot0Start.sqrtPriceX96.ToString(), sqrtPriceLimitX96.ToString(), consts.MAX_SQRT_RATIO)) + + if !(cond1 && cond2) { + panic(ufmt.Sprintf("[POOL] pool.gno__Swap() || sqrtPriceLimitX96(%s) > slot0Start.sqrtPriceX96(%s) && sqrtPriceLimitX96(%s) < consts.MAX_SQRT_RATIO(%s)", sqrtPriceLimitX96.ToString(), slot0Start.sqrtPriceX96.ToString(), sqrtPriceLimitX96.ToString(), consts.MAX_SQRT_RATIO)) + } feeProtocol = slot0Start.feeProtocol / 16 feeGrowthGlobalX128 = pool.feeGrowthGlobal1X128.Clone() @@ -419,43 +405,39 @@ func Swap( balance0Before := balanceOfByRegisterCall(pool.token0Path, GetOrigPkgAddr()) ok := transferFromByRegisterCall(pool.token0Path, payer, consts.POOL_ADDR, uAmount0) - // payer -> pool OK - require( - ok, - ufmt.Sprintf( - "[POOL] pool.gno__Swap() || transferFromByRegisterCall(pool.token0Path(%s), payer(%s), consts.POOL_ADDR(%s), uAmount0(%d)) failed", - pool.token0Path, payer.String(), consts.POOL_ADDR.String(), uAmount0, - ), - ) + // transfer failed + if !ok { + panic(ufmt.Sprintf("[POOL] pool.gno__Swap() || transferFromByRegisterCall(pool.token0Path(%s), payer(%s), consts.POOL_ADDR(%s), uAmount0(%d)) failed", pool.token0Path, payer.String(), consts.POOL_ADDR.String(), uAmount0)) + } // pool token0 balance updated - require( - (balance0Before+uAmount0) <= balanceOfByRegisterCall(pool.token0Path, GetOrigPkgAddr()), - ufmt.Sprintf( - "[POOL] pool.gno__Swap() || (balance0Before(%d) + uAmount0(%d)) <= balanceOfByRegisterCall(pool.token0Path(%s), GetOrigPkgAddr()(%s))(%d)", - balance0Before, uAmount0, pool.token0Path, GetOrigPkgAddr().String(), balanceOfByRegisterCall(pool.token0Path, GetOrigPkgAddr()), - ), - ) + if !((balance0Before + uAmount0) <= balanceOfByRegisterCall(pool.token0Path, GetOrigPkgAddr())) { + panic(ufmt.Sprintf( + "[POOL] pool.gno__Swap() || (balance0Before(%d) + uAmount0(%d)) <= balanceOfByRegisterCall(pool.token0Path(%s), GetOrigPkgAddr()(%s))(%d)", balance0Before, uAmount0, pool.token0Path, GetOrigPkgAddr().String(), balanceOfByRegisterCall(pool.token0Path, GetOrigPkgAddr()))) + } pool.balances.token0 = new(u256.Uint).Add(pool.balances.token0, amount0.Abs()) - require(pool.balances.token0.Gte(u256.Zero()), ufmt.Sprintf("[POOL] pool.gno__Swap() || pool.balances.token0(%d) >= 0", pool.balances.token0)) + if pool.balances.token0.Lt(u256.Zero()) { + panic(ufmt.Sprintf("[POOL] pool.gno__Swap() || pool.balances.token0(%d) >= 0", pool.balances.token0)) + } // FROM pool TO recipient if amount1.IsNeg() { - require(pool.balances.token1.Gte(amount1.Abs()), ufmt.Sprintf("[POOL] pool.gno__Swap() || pool.balances.token1(%d) >= amount1.Abs(%d)", pool.balances.token1, amount1.Abs())) + if pool.balances.token1.Lt(amount1.Abs()) { + panic(ufmt.Sprintf("[POOL] pool.gno__Swap() || pool.balances.token1(%d) >= amount1.Abs(%d)", pool.balances.token1, amount1.Abs())) + } uAmount1 := amount1.Abs().Uint64() ok := transferByRegisterCall(pool.token1Path, recipient, uAmount1) - require( - ok, - ufmt.Sprintf( - "[POOL] pool.gno__Swap() || transferByRegisterCall(pool.token1Path(%s), recipient(%s), uAmount1(%d)) failed", - pool.token1Path, recipient.String(), uAmount1, - ), - ) + if !ok { + panic(ufmt.Sprintf("[POOL] pool.gno__Swap() || transferByRegisterCall(pool.token1Path(%s), recipient(%s), uAmount1(%d)) failed", pool.token1Path, recipient.String(), uAmount1)) + } pool.balances.token1 = new(u256.Uint).Sub(pool.balances.token1, amount1.Abs()) } - require(pool.balances.token1.Gte(u256.Zero()), ufmt.Sprintf("[POOL] pool.gno__Swap() || pool.balances.token1(%d) >= 0", pool.balances.token1)) + + if pool.balances.token1.Lt(u256.Zero()) { + panic(ufmt.Sprintf("[POOL] pool.gno__Swap() || pool.balances.token1(%d) >= 0", pool.balances.token1)) + } } else { uAmount1 := amount1.Abs().Uint64() @@ -463,41 +445,37 @@ func Swap( // FROM payer TO pool balance1Before := balanceOfByRegisterCall(pool.token1Path, GetOrigPkgAddr()) ok := transferFromByRegisterCall(pool.token1Path, payer, consts.POOL_ADDR, uAmount1) - require( - ok, - ufmt.Sprintf( - "[POOL] pool.gno__Swap() || transferFromByRegisterCall(pool.token1Path(%s), payer(%s), consts.POOL_ADDR(%s), uAmount1(%d)) failed", - pool.token1Path, payer.String(), consts.POOL_ADDR.String(), uAmount1, - ), - ) + if !ok { + panic(ufmt.Sprintf("[POOL] pool.gno__Swap() || transferFromByRegisterCall(pool.token1Path(%s), payer(%s), consts.POOL_ADDR(%s), uAmount1(%d)) failed", pool.token1Path, payer.String(), consts.POOL_ADDR.String(), uAmount1)) + } - require( - (balance1Before+uAmount1) <= balanceOfByRegisterCall(pool.token1Path, GetOrigPkgAddr()), - ufmt.Sprintf( - "[POOL] pool.gno__Swap() || (balance1Before(%d) + uAmount1(%d)) <= balanceOfByRegisterCall(pool.token1Path(%s), GetOrigPkgAddr()(%s))(%d)", - balance1Before, uAmount1, pool.token1Path, GetOrigPkgAddr().String(), balanceOfByRegisterCall(pool.token1Path, GetOrigPkgAddr()), - ), - ) + if !(balance1Before+uAmount1 <= balanceOfByRegisterCall(pool.token1Path, GetOrigPkgAddr())) { + panic(ufmt.Sprintf("[POOL] pool.gno__Swap() || (balance1Before(%d) + uAmount1(%d)) <= balanceOfByRegisterCall(pool.token1Path(%s), GetOrigPkgAddr()(%s))(%d)", balance1Before, uAmount1, pool.token1Path, GetOrigPkgAddr().String(), balanceOfByRegisterCall(pool.token1Path, GetOrigPkgAddr()))) + } pool.balances.token1 = new(u256.Uint).Add(pool.balances.token1, amount1.Abs()) - require(pool.balances.token1.Gte(u256.Zero()), ufmt.Sprintf("[POOL] pool.gno__Swap() || pool.balances.token1(%d) >= 0", pool.balances.token1)) + if pool.balances.token1.Lt(u256.Zero()) { + panic(ufmt.Sprintf("[POOL] pool.gno__Swap() || pool.balances.token1(%d) >= 0", pool.balances.token1)) + } // FROM pool TO recipient if amount0.IsNeg() { - require(pool.balances.token0.Gte(amount0.Abs()), ufmt.Sprintf("[POOL] pool.gno__Swap() || pool.balances.token0(%d) >= amount0.Abs(%d)", pool.balances.token0, amount0.Abs())) + if pool.balances.token0.Lt(amount0.Abs()) { + panic(ufmt.Sprintf("[POOL] pool.gno__Swap() || pool.balances.token0(%d) >= amount0.Abs(%d)", pool.balances.token0, amount0.Abs())) + } uAmount0 := amount0.Abs().Uint64() ok := transferByRegisterCall(pool.token0Path, recipient, uAmount0) - require( - ok, - ufmt.Sprintf( - "[POOL] pool.gno__Swap() || transferByRegisterCall(pool.token0Path(%s), recipient(%s), uAmount0(%d)) failed", - pool.token0Path, recipient.String(), uAmount0, - ), - ) + if !ok { + panic(ufmt.Sprintf("[POOL] pool.gno__Swap() || transferByRegisterCall(pool.token0Path(%s), recipient(%s), uAmount0(%d)) failed", pool.token0Path, recipient.String(), uAmount0)) + } + pool.balances.token0 = new(u256.Uint).Sub(pool.balances.token0, amount0.Abs()) } - require(pool.balances.token0.Gte(u256.Zero()), ufmt.Sprintf("[POOL] pool.gno__Swap() || pool.balances.token0(%d) >= 0", pool.balances.token0)) + + if pool.balances.token0.Lt(u256.Zero()) { + panic(ufmt.Sprintf("[POOL] pool.gno__Swap() || pool.balances.token0(%d) >= 0", pool.balances.token0)) + } } pool.slot0.unlocked = true @@ -509,15 +487,16 @@ func SetFeeProtocol( feeProtocol0 uint8, feeProtocol1 uint8, ) { - require(isAdmin(std.PrevRealm().Addr()), ufmt.Sprintf("[POOL] pool.gno__SetFeeProtocol() || caller(%s) must be admin", std.PrevRealm().Addr())) - - require( - (feeProtocol0 == 0 || (feeProtocol0 >= 4 && feeProtocol0 <= 10)) && (feeProtocol1 == 0 || (feeProtocol1 >= 4 && feeProtocol1 <= 10)), - ufmt.Sprintf( - "[POOL] pool.gno__SetFeeProtocol() || expected (feeProtocol0(%d) == 0 || (feeProtocol0(%d) >= 4 && feeProtocol0(%d) <= 10)) && (feeProtocol1(%d) == 0 || (feeProtocol1(%d) >= 4 && feeProtocol1(%d) <= 10))", - feeProtocol0, feeProtocol0, feeProtocol0, feeProtocol1, feeProtocol1, feeProtocol1, - ), - ) + + if !(isAdmin(std.PrevRealm().Addr())) { + panic(ufmt.Sprintf("[POOL] pool.gno__SetFeeProtocol() || caller(%s) must be admin", std.PrevRealm().Addr())) + } + + fee0Cond := (feeProtocol0 == 0 || (feeProtocol0 >= 4 && feeProtocol0 <= 10)) + fee1Cond := (feeProtocol1 == 0 || (feeProtocol1 >= 4 && feeProtocol1 <= 10)) + if !(fee0Cond && fee1Cond) { + panic(ufmt.Sprintf("[POOL] pool.gno__SetFeeProtocol() || expected (feeProtocol0(%d) == 0 || (feeProtocol0(%d) >= 4 && feeProtocol0(%d) <= 10)) && (feeProtocol1(%d) == 0 || (feeProtocol1(%d) >= 4 && feeProtocol1(%d) <= 10))", feeProtocol0, feeProtocol0, feeProtocol0, feeProtocol1, feeProtocol1, feeProtocol1)) + } // iterate all pool for _, pool := range pools { @@ -537,16 +516,12 @@ func CollectProtocol( _amount0Requested string, // uint128 _amount1Requested string, // uint128 ) (string, string) { // uint128 x2 - require(isAdmin(std.PrevRealm().Addr()), ufmt.Sprintf("[POOL] pool.gno__CollectProtocol() || caller(%s) must be admin", std.PrevRealm().Addr())) - amount0Requested, err := u256.FromDecimal(_amount0Requested) - if err != nil { - panic(ufmt.Sprintf("[POOL] pool.gno__CollectProtocol() || u256.FromDecimal(_amount0Requested[%s]) failed", _amount0Requested)) - } - amount1Requested, err := u256.FromDecimal(_amount1Requested) - if err != nil { - panic(ufmt.Sprintf("[POOL] pool.gno__CollectProtocol() || u256.FromDecimal(_amount1Requested[%s]) failed", _amount1Requested)) + if !(isAdmin(std.PrevRealm().Addr())) { + panic(ufmt.Sprintf("[POOL] pool.gno__CollectProtocol() || caller(%s) must be admin", std.PrevRealm().Addr())) } + amount0Requested := u256.MustFromDecimal(_amount0Requested) + amount1Requested := u256.MustFromDecimal(_amount1Requested) pool := GetPool(token0Path, token1Path, fee) @@ -558,22 +533,14 @@ func CollectProtocol( uAmount1 := amount1.Uint64() ok := transferByRegisterCall(pool.token0Path, recipient, uAmount0) - require( - ok, - ufmt.Sprintf( - "[POOL] pool.gno__CollectProtocol() || transferByRegisterCall(pool.token0Path(%s), recipient(%s), uAmount0)(%d) failed", - pool.token0Path, recipient.String(), uAmount0, - ), - ) + if !ok { + panic(ufmt.Sprintf("[POOL] pool.gno__CollectProtocol() || transferByRegisterCall(pool.token0Path(%s), recipient(%s), uAmount0)(%d) failed", pool.token0Path, recipient.String(), uAmount0)) + } ok = transferByRegisterCall(pool.token1Path, recipient, uAmount1) - require( - ok, - ufmt.Sprintf( - "[POOL] pool.gno__CollectProtocol() || transferByRegisterCall(pool.token1Path(%s), recipient(%s), uAmount1)(%d) failed", - pool.token1Path, recipient.String(), uAmount1, - ), - ) + if !ok { + panic(ufmt.Sprintf("[POOL] pool.gno__CollectProtocol() || transferByRegisterCall(pool.token1Path(%s), recipient(%s), uAmount1)(%d) failed", pool.token1Path, recipient.String(), uAmount1)) + } return amount0.ToString(), amount1.ToString() } diff --git a/pool/pool_manager.gno b/pool/pool_manager.gno index ba05eb0e0..a334b32f5 100644 --- a/pool/pool_manager.gno +++ b/pool/pool_manager.gno @@ -25,8 +25,14 @@ var ( func InitManual() { // MUST BE ORIGIN CALLER std.AssertOriginCall() - require(!initialized, ufmt.Sprintf("[POOl] pool_manager.gno__InitManual() || expected initialized(%t) == false", initialized)) - require(std.GetOrigCaller() == consts.GNOSWAP_ADMIN, ufmt.Sprintf("[POOl] pool_manager.gno__InitManual() || expected std.GetOrigCaller(%s) == consts.GNOSWAP_ADMIN(%s)", std.GetOrigCaller().String(), consts.GNOSWAP_ADMIN.String())) + if initialized { + panic(ufmt.Sprintf("[POOl] pool_manager.gno__InitManual() || expected initialized(%t) == false", initialized)) + } + + if !(std.GetOrigCaller() == consts.GNOSWAP_ADMIN) { + panic(ufmt.Sprintf("[POOl] pool_manager.gno__InitManual() || expected std.GetOrigCaller(%s) == consts.GNOSWAP_ADMIN(%s)", std.GetOrigCaller().String(), consts.GNOSWAP_ADMIN.String())) + } + feeAmountTickSpacing[100] = 2 // 0.01% feeAmountTickSpacing[500] = 10 // 0.05% feeAmountTickSpacing[3000] = 60 // 0.3% @@ -41,8 +47,13 @@ func CreatePool( fee uint32, _sqrtPriceX96 string, // uint ) *Pool { - require(initialized, ufmt.Sprintf("[POOl] pool_manager.gno__gno__CreatePool() || expected initialized(%t) == true", initialized)) - require(token0Path != token1Path, ufmt.Sprintf("[POOl] pool_manager.gno__CreatePool() || expected token0Path(%s) != token1Path(%s)", token0Path, token1Path)) + if !(initialized) { + panic(ufmt.Sprintf("[POOl] pool_manager.gno__gno__CreatePool() || expected initialized(%t) == true", initialized)) + } + + if token0Path == token1Path { + panic(ufmt.Sprintf("[POOl] pool_manager.gno__CreatePool() || expected token0Path(%s) != token1Path(%s)", token0Path, token1Path)) + } sqrtPriceX96, err := u256.FromDecimal(_sqrtPriceX96) if err != nil { @@ -64,7 +75,9 @@ func CreatePool( // check whether the pool already exist pool, exist := pools[poolPath] - requireExist(!exist, ufmt.Sprintf("[POOl] pool_manager.gno__CreatePool() || expected poolPath(%s) not to exist", poolPath)) + if exist { + panic(ufmt.Sprintf("[POOl] pool_manager.gno__CreatePool() || expected poolPath(%s) not to exist", poolPath)) + } if !exist { gns.TransferFrom(a2u(std.GetOrigCaller()), a2u(consts.GNOSWAP_ADMIN), consts.POOL_CREATION_FEE) @@ -79,14 +92,18 @@ func CreatePool( func GetPool(token0Path, token1Path string, fee uint32) *Pool { poolPath := GetPoolPath(token0Path, token1Path, fee) pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] pool_manager.gno__GetPool() || expected poolPath(%s) to exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] pool_manager.gno__GetPool() || expected poolPath(%s) to exist", poolPath)) + } return pool } func GetPoolFromPoolPath(poolPath string) *Pool { pool, exist := pools[poolPath] - requireExist(exist, ufmt.Sprintf("[POOL] pool_manager.gno__GetPoolFromPoolPath() || expected poolPath(%s) to exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[POOL] pool_manager.gno__GetPoolFromPoolPath() || expected poolPath(%s) to exist", poolPath)) + } return pool } diff --git a/pool/swap_math.gno b/pool/swap_math.gno index 4ea025a93..d3120fad4 100644 --- a/pool/swap_math.gno +++ b/pool/swap_math.gno @@ -18,6 +18,10 @@ func swapMathComputeSwapStep( // NEGATIVE == EXACT_OUT => Estimated AmountIn exactIn := !(amountRemaining.IsNeg()) // amountRemaining >= 0 + // println() + // println("exactIn", exactIn) // f + // println("isToken1Expensive", isToken1Expensive) // t + if exactIn { amountRemainingLessFee := u256.Zero() @@ -43,20 +47,30 @@ func swapMathComputeSwapStep( } } else { if isToken1Expensive { + // println(1) amountOut = sqrtPriceMathGetAmount1DeltaHelper(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false) } else { + // println(2) amountOut = sqrtPriceMathGetAmount0DeltaHelper(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false) } if amountRemaining.Abs().Gte(amountOut) { + // println(3) sqrtRatioNextX96 = sqrtRatioTargetX96 } else { + // println(4) + // println("sqrtRatioCurrentX96:", sqrtRatioCurrentX96.ToString()) + // println("liquidity:", liquidity.ToString()) + // println("amountRemaining.Abs():", amountRemaining.Abs().ToString()) + // println("isToken1Expensive:", isToken1Expensive) + // println("<< SQRT") sqrtRatioNextX96 = sqrtPriceMathGetNextSqrtPriceFromOutput( sqrtRatioCurrentX96, liquidity, amountRemaining.Abs(), isToken1Expensive, ) + // println("sqrtRatioNextX96:", sqrtRatioNextX96.ToString()) // panic("F") } } @@ -103,5 +117,6 @@ func swapMathComputeSwapStep( if !exactIn && !(amountOut.IsZero()) { amountOut = amountOut.Add(amountOut, u256.NewUint(1)) } + // println() return sqrtRatioNextX96, amountIn, amountOut, feeAmount } diff --git a/pool/swap_parameters.gno b/pool/swap_parameters.gno index 2974e99ab..3564a0ba5 100644 --- a/pool/swap_parameters.gno +++ b/pool/swap_parameters.gno @@ -15,13 +15,9 @@ func SubmitProposalParameterProtocolFees( newFee0 bigint, newFee1 bigint, ) uint64 { - require( - (newFee0 == 0 || (newFee0 >= 4 && newFee0 <= 10)) && (newFee1 == 0 || (newFee1 >= 4 && newFee1 <= 10)), - ufmt.Sprintf( - "[POOL] pool.gno__SubmitProposalParameterProtocolFees() || expected (newFee0(%d) == 0 || (newFee0(%d) >= 4 && newFee0(%d) <= 10)) && (newFee1(%d) == 0 || (newFee1(%d) >= 4 && newFee1(%d) <= 10))", - newFee0, newFee0, newFee0, newFee1, newFee1, newFee1, - ), - ) + if !((newFee0 == 0 || (newFee0 >= 4 && newFee0 <= 10)) && (newFee1 == 0 || (newFee1 >= 4 && newFee1 <= 10))) { + panic(ufmt.Sprintf("[POOL] pool.gno__SubmitProposalParameterProtocolFees() || expected (newFee0(%d) == 0 || (newFee0(%d) >= 4 && newFee0(%d) <= 10)) && (newFee1(%d) == 0 || (newFee1(%d) >= 4 && newFee1(%d) <= 10))", newFee0, newFee0, newFee0, newFee1, newFee1, newFee1)) + } changes := []gov.ParameterChange{ { diff --git a/pool/tick_bitmap.gno b/pool/tick_bitmap.gno index 40606c386..ec533c104 100644 --- a/pool/tick_bitmap.gno +++ b/pool/tick_bitmap.gno @@ -18,20 +18,15 @@ func (pool *Pool) tickBitmapFlipTick( tick int32, tickSpacing int32, ) { - require( - tick%tickSpacing == 0, - ufmt.Sprintf( - "[POOL] tick_bitmap.gno__tickBitmapFlipTick() || tick(%d) %% tickSpacing(%d) == 0(%d)", - tick, tickSpacing, tick%tickSpacing, - ), - ) + if tick%tickSpacing != 0 { + panic(ufmt.Sprintf("[POOL] tick_bitmap.gno__tickBitmapFlipTick() || tick(%d) %% tickSpacing(%d) == 0(%d)", tick, tickSpacing, tick%tickSpacing)) + } wordPos, bitPos := tickBitmapPosition(tick / tickSpacing) - // mask := bigint(1) << uint64(bitPos) // 2 ** bitPos + // 1 << bitPos mask := new(u256.Uint).Lsh(u256.NewUint(1), uint(bitPos)) - // pool.tickBitmaps[wordPos] ^= mask pool.tickBitmaps[wordPos] = pool.tickBitmaps[wordPos].NilToZero() pool.tickBitmaps[wordPos] = new(u256.Uint).Xor(pool.tickBitmaps[wordPos], mask) } @@ -49,14 +44,13 @@ func (pool *Pool) tickBitmapNextInitializedTickWithInOneWord( if lte { wordPos, bitPos := tickBitmapPosition(compress) - // mask := (bigint(1) << uint64(bitPos)) - bigint(1) + (bigint(1) << uint64(bitPos)) + // mask := (1 << bitPos) - 1 + (1 << bitPos) shift1LeftByBitPos := new(u256.Uint).Lsh(u256.NewUint(1), uint(bitPos)) mask := shift1LeftByBitPos.Clone() mask = new(u256.Uint).Sub(mask, u256.NewUint(1)) mask = new(u256.Uint).Add(mask, shift1LeftByBitPos.Clone()) - // masked := pool.tickBitmaps[wordPos] & mask pool.tickBitmaps[wordPos] = pool.tickBitmaps[wordPos].NilToZero() masked := new(u256.Uint).And(pool.tickBitmaps[wordPos], mask) diff --git a/pool/utils.gno b/pool/utils.gno index b0c6b1b6c..6de8453b6 100644 --- a/pool/utils.gno +++ b/pool/utils.gno @@ -12,9 +12,17 @@ import ( ) func checkTicks(tickLower, tickUpper int32) { - require(tickLower < tickUpper, ufmt.Sprintf("[POOL] utils.gno__checkTicks() || tickLower(%d) < tickUpper(%d)", tickLower, tickUpper)) - require(tickLower >= consts.MIN_TICK, ufmt.Sprintf("[POOL] utils.gno__checkTicks() || tickLower(%d) >= consts.MIN_TICK(%d)", tickLower, consts.MIN_TICK)) - require(tickUpper <= consts.MAX_TICK, ufmt.Sprintf("[POOL] utils.gno__checkTicks() || tickUpper(%d) <= consts.MAX_TICK(%d)", tickUpper, consts.MAX_TICK)) + if tickLower >= tickUpper { + panic(ufmt.Sprintf("[POOL] utils.gno__checkTicks() || tickLower(%d) >= consts.MIN_TICK(%d)", tickLower, consts.MIN_TICK)) + } + + if tickLower < consts.MIN_TICK { + panic(ufmt.Sprintf("[POOL] utils.gno__checkTicks() || tickLower(%d) >= consts.MIN_TICK(%d)", tickLower, consts.MIN_TICK)) + } + + if tickUpper > consts.MAX_TICK { + panic(ufmt.Sprintf("[POOL] utils.gno__checkTicks() || tickUpper(%d) <= consts.MAX_TICK(%d)", tickUpper, consts.MAX_TICK)) + } } func a2u(addr std.Address) users.AddressOrName { @@ -50,34 +58,3 @@ func remove(s []string, r string) []string { } return s } - -// REQUIREs -func require(cond bool, msg string) { - if !(cond) { - panic(msg) - } -} - -func requireUnsigned(x bigint, msg string) { - if !(x >= 0) { - panic(msg) - } -} - -func requirePositive(x bigint, msg string) { - if !(x > 0) { - panic(msg) - } -} - -func requireExist(exist bool, msg string) { - if !exist { - panic(msg) - } -} - -func requirePrevRealmPath(prevRealmPath, msg string) { - if std.PrevRealm().PkgPath() != prevRealmPath { - panic(msg) - } -} diff --git a/pool/withdrawal_fee.gno b/pool/withdrawal_fee.gno index b9964a6eb..7e9f9b5de 100644 --- a/pool/withdrawal_fee.gno +++ b/pool/withdrawal_fee.gno @@ -21,7 +21,10 @@ func HandleWithdrawalFee( token1Path string, _amount1 string, // uint256 ) (string, string) { // uint256 x2 - requirePrevRealmPath(consts.POSITION_PATH, ufmt.Sprintf("[POOL] withdrawal_fee.gno__HandleWithdrawFee() || expected std.PrevRealm().PkgPath()(%s), got %s", consts.POSITION_PATH, std.PrevRealm().PkgPath())) + // only position contract can call this function + if std.PrevRealm().PkgPath() != consts.POSITION_PATH { + panic(ufmt.Sprintf("[POOL] withdrawal_fee.gno__HandleWithdrawFee() || expected std.PrevRealm().PkgPath()(%s), got %s", consts.POSITION_PATH, std.PrevRealm().PkgPath())) + } amount0, err := u256.FromDecimal(_amount0) if err != nil { @@ -43,10 +46,14 @@ func HandleWithdrawalFee( feeAmount1 = new(u256.Uint).Div(feeAmount1, u256.NewUint(100)) ok := transferFromByRegisterCall(token0Path, std.GetOrigCaller(), consts.FEE_COLLECTOR, feeAmount0.Uint64()) - require(ok, ufmt.Sprintf("[POOL] withdrawal_fee.gno__HandleWithdrawFee() || expected transferFromByRegisterCall(%s, %s, %s, %s) == true", token0Path, std.GetOrigCaller(), consts.FEE_COLLECTOR, feeAmount0)) + if !ok { + panic(ufmt.Sprintf("[POOL] withdrawal_fee.gno__HandleWithdrawFee() || expected transferFromByRegisterCall(%s, %s, %s, %s) == true", token0Path, std.GetOrigCaller(), consts.FEE_COLLECTOR, feeAmount0)) + } ok = transferFromByRegisterCall(token1Path, std.GetOrigCaller(), consts.FEE_COLLECTOR, feeAmount1.Uint64()) - require(ok, ufmt.Sprintf("[POOL] withdrawal_fee.gno__HandleWithdrawFee() || expected transferFromByRegisterCall(%s, %s, %s, %s) == true", token1Path, std.GetOrigCaller(), consts.FEE_COLLECTOR, feeAmount1)) + if !ok { + panic(ufmt.Sprintf("[POOL] withdrawal_fee.gno__HandleWithdrawFee() || expected transferFromByRegisterCall(%s, %s, %s, %s) == true", token1Path, std.GetOrigCaller(), consts.FEE_COLLECTOR, feeAmount1)) + } afterAmount0 := new(u256.Uint).Sub(amount0, feeAmount0) afterAmount1 := new(u256.Uint).Sub(amount1, feeAmount1) @@ -59,9 +66,13 @@ func SetWithdrawalFee(fee uint64) { std.AssertOriginCall() // MUST BE ADMIN - require(isAdmin(std.GetOrigCaller()), ufmt.Sprintf("[POOL] withdrawal_fee.gno__SetFeeProtocol() || caller(%s) must be admin", std.GetOrigCaller())) + if !(isAdmin(std.GetOrigCaller())) { + panic(ufmt.Sprintf("[POOL] withdrawal_fee.gno__SetFeeProtocol() || caller(%s) must be admin", std.GetOrigCaller())) + } - require(fee >= 0, ufmt.Sprintf("[POOL] withdrawal_fee.gno__SetFeeProtocol() || fee(%d) must be >= 0", fee)) + if fee < 0 { + panic(ufmt.Sprintf("[POOL] withdrawal_fee.gno__SetFeeProtocol() || fee(%d) must be >= 0", fee)) + } withdrawalFee = fee } diff --git a/position/position.gno b/position/position.gno index 4e9b2c295..5ed8e3155 100644 --- a/position/position.gno +++ b/position/position.gno @@ -37,22 +37,10 @@ func Mint( tickLower, tickUpper = -tickUpper, -tickLower } - amount0Desired, err := u256.FromDecimal(_amount0Desired) - if err != nil { - panic(ufmt.Sprintf("[POSITION] position.gno__Mint() || u256.FromDecimal(_amount0Desired: %s) failed", _amount0Desired)) - } - amount1Desired, err := u256.FromDecimal(_amount1Desired) - if err != nil { - panic(ufmt.Sprintf("[POSITION] position.gno__Mint() || u256.FromDecimal(_amount1Desired: %s) failed", _amount1Desired)) - } - amount0Min, err := u256.FromDecimal(_amount0Min) - if err != nil { - panic(ufmt.Sprintf("[POSITION] position.gno__Mint() || u256.FromDecimal(_amount0Min: %s) failed", _amount0Min)) - } - amount1Min, err := u256.FromDecimal(_amount1Min) - if err != nil { - panic(ufmt.Sprintf("[POSITION] position.gno__Mint() || u256.FromDecimal(_amount1Min: %s) failed", _amount1Min)) - } + amount0Desired := u256.MustFromDecimal(_amount0Desired) + amount1Desired := u256.MustFromDecimal(_amount1Desired) + amount0Min := u256.MustFromDecimal(_amount0Min) + amount1Min := u256.MustFromDecimal(_amount1Min) mintParams := MintParams{ token0: token0, @@ -87,7 +75,7 @@ func mint(params MintParams) (uint64, string, string, string) { ) tokenId := nextId - nextId++ // nextId = nextId + 1 + nextId++ gnft.Mint(a2u(std.GetOrigCaller()), tid(tokenId)) // owner, tokenId @@ -120,22 +108,10 @@ func IncreaseLiquidity( deadline int64, ) (uint64, string, string, string) { // tokenId, liquidity, amount0, amount1 - amount0Desired, err := u256.FromDecimal(_amount0Desired) - if err != nil { - panic(ufmt.Sprintf("[POSITION] position.gno__IncreaseLiquidity() || u256.FromDecimal(_amount0Desired: %s) failed", _amount0Desired)) - } - amount1Desired, err := u256.FromDecimal(_amount1Desired) - if err != nil { - panic(ufmt.Sprintf("[POSITION] position.gno__IncreaseLiquidity() || u256.FromDecimal(_amount1Desired: %s) failed", _amount1Desired)) - } - amount0Min, err := u256.FromDecimal(_amount0Min) - if err != nil { - panic(ufmt.Sprintf("[POSITION] position.gno__IncreaseLiquidity() || u256.FromDecimal(_amount0Min: %s) failed", _amount0Min)) - } - amount1Min, err := u256.FromDecimal(_amount1Min) - if err != nil { - panic(ufmt.Sprintf("[POSITION] position.gno__IncreaseLiquidity() || u256.FromDecimal(_amount1Min: %s) failed", _amount1Min)) - } + amount0Desired := u256.MustFromDecimal(_amount0Desired) + amount1Desired := u256.MustFromDecimal(_amount1Desired) + amount0Min := u256.MustFromDecimal(_amount0Min) + amount1Min := u256.MustFromDecimal(_amount1Min) increaseLiquidityParams := IncreaseLiquidityParams{ tokenId: tokenId, @@ -151,12 +127,16 @@ func IncreaseLiquidity( func increaseLiquidity(params IncreaseLiquidityParams) (uint64, string, string, string) { // verify tokenId exists - require(exists(params.tokenId), ufmt.Sprintf("[POSITION] position.gno__increaseLiquidity() || tokenId(%d) doesn't exist", params.tokenId)) + if !exists(params.tokenId) { + panic(ufmt.Sprintf("[POSITION] position.gno__increaseLiquidity() || tokenId(%d) doesn't exist", params.tokenId)) + } // MUST BE OWNER TO INCREASE LIQUIDITY // can not be approved address > staked position can be modified owner := gnft.OwnerOf(tid(params.tokenId)) - require(owner == std.GetOrigCaller(), ufmt.Sprintf("[POSITION] position.gno__increaseLiquidity() || only owner can increase liquidity__owner(%s) == std.GetOrigCaller(%s)", owner, std.GetOrigCaller())) + if owner != std.GetOrigCaller() { + panic(ufmt.Sprintf("[POSITION] position.gno__increaseLiquidity() || only owner can increase liquidity__owner(%s) == std.GetOrigCaller(%s)", owner, std.GetOrigCaller())) + } checkDeadline(params.deadline) @@ -178,7 +158,6 @@ func increaseLiquidity(params IncreaseLiquidityParams) (uint64, string, string, feeGrowthInside0LastX128, feeGrowthInside1LastX128 := pool.PoolGetPositionFeeGrowthInside0LastX128(positionKey), pool.PoolGetPositionFeeGrowthInside1LastX128(positionKey) { - // position.tokensOwed0 += (feeGrowthInside0LastX128 - position.feeGrowthInside0LastX128) * position.liquidity / consts.Q128 value1 := new(u256.Uint).Sub(feeGrowthInside0LastX128.Clone(), position.feeGrowthInside0LastX128.Clone()) value2 := new(u256.Uint).Mul(value1, position.liquidity) value3 := new(u256.Uint).Div(value2, u256.MustFromDecimal(consts.Q128)) @@ -186,7 +165,6 @@ func increaseLiquidity(params IncreaseLiquidityParams) (uint64, string, string, } { - // position.tokensOwed1 += (feeGrowthInside1LastX128 - position.feeGrowthInside1LastX128) * position.liquidity / consts.Q128 value1 := new(u256.Uint).Sub(feeGrowthInside1LastX128.Clone(), position.feeGrowthInside1LastX128.Clone()) value2 := new(u256.Uint).Mul(value1, position.liquidity) value3 := new(u256.Uint).Div(value2, u256.MustFromDecimal(consts.Q128)) @@ -212,18 +190,9 @@ func DecreaseLiquidity( _amount1Min string, // uint256 deadline int64, ) (uint64, string, string, string, string) { // tokenId, liquidity, amount0, amount1, poolPath - liquidity, err := u256.FromDecimal(_liquidity) - if err != nil { - panic(ufmt.Sprintf("[POSITION] position.gno__DecreaseLiquidity() || u256.FromDecimal(_liquidity: %s) failed", _liquidity)) - } - amount0Min, err := u256.FromDecimal(_amount0Min) - if err != nil { - panic(ufmt.Sprintf("[POSITION] position.gno__DecreaseLiquidity() || u256.FromDecimal(_amount0Min: %s) failed", _amount0Min)) - } - amount1Min, err := u256.FromDecimal(_amount1Min) - if err != nil { - panic(ufmt.Sprintf("[POSITION] position.gno__DecreaseLiquidity() || u256.FromDecimal(_amount1Min: %s) failed", _amount1Min)) - } + liquidity := u256.MustFromDecimal(_liquidity) + amount0Min := u256.MustFromDecimal(_amount0Min) + amount1Min := u256.MustFromDecimal(_amount1Min) decreaseLiquidityParams := DecreaseLiquidityParams{ tokenId: tokenId, @@ -238,15 +207,21 @@ func DecreaseLiquidity( func decreaseLiquidity(params DecreaseLiquidityParams) (uint64, string, string, string, string) { // verify tokenId - require(exists(params.tokenId), ufmt.Sprintf("[POSITION] position.gno__decreaseLiquidity() || tokenId(%d) doesn't exist", params.tokenId)) + if !exists(params.tokenId) { + panic(ufmt.Sprintf("[POSITION] position.gno__decreaseLiquidity() || tokenId(%d) doesn't exist", params.tokenId)) + } // MUST BE OWNER TO DECREASE LIQUIDITY ( can not be approved address ) owner := gnft.OwnerOf(tid(params.tokenId)) - require(owner == std.GetOrigCaller(), ufmt.Sprintf("[POSITION] position.gno__decreaseLiquidity() || only owner can decrease liquidity__owner(%s) == std.GetOrigCaller(%s)", owner, std.GetOrigCaller())) + if owner != std.GetOrigCaller() { + panic(ufmt.Sprintf("[POSITION] position.gno__decreaseLiquidity() || only owner can decrease liquidity__owner(%s) == std.GetOrigCaller(%s)", owner, std.GetOrigCaller())) + } checkDeadline(params.deadline) - require(params.liquidity.Gte(u256.Zero()), ufmt.Sprintf("[POSITION] position.gno__decreaseLiquidity() || liquidity(%d) >= 0", params.liquidity)) + if params.liquidity.Lt(u256.Zero()) { + panic(ufmt.Sprintf("[POSITION] position.gno__decreaseLiquidity() || liquidity(%d) >= 0", params.liquidity)) + } // BEFORE DECREASE LIQUIDITY, COLLECT FEE FIRST CollectFee(params.tokenId) @@ -265,20 +240,17 @@ func decreaseLiquidity(params DecreaseLiquidityParams) (uint64, string, string, // BURN HERE _burnedAmount0, _burnedAmount1 := pl.Burn(pToken0, pToken1, pFee, position.tickLower, position.tickUpper, params.liquidity.Clone().ToString()) - burnedAmount0, err := u256.FromDecimal(_burnedAmount0) - if err != nil { - panic(ufmt.Sprintf("[POSITION] position.gno__decreaseLiquidity() || u256.FromDecimal(_burnedAmount0: %s) failed", _burnedAmount0)) - } - burnedAmount1, err := u256.FromDecimal(_burnedAmount1) - if err != nil { - panic(ufmt.Sprintf("[POSITION] position.gno__decreaseLiquidity() || u256.FromDecimal(_burnedAmount1: %s) failed", _burnedAmount1)) - } + burnedAmount0 := u256.MustFromDecimal(_burnedAmount0) + burnedAmount1 := u256.MustFromDecimal(_burnedAmount1) - require(burnedAmount0.Gte(params.amount0Min) && burnedAmount1.Gte(params.amount1Min), ufmt.Sprintf("[POSITION] position.gno__decreaseLiquidity() || burnedAmount0(%s) >= amount0Min(%s) && burnedAmount1(%s) >= amount1Min(%s)", burnedAmount0.ToString(), params.amount0Min.ToString(), burnedAmount1.ToString(), params.amount1Min.ToString())) + cond0 := burnedAmount0.Gte(params.amount0Min) + cond1 := burnedAmount1.Gte(params.amount1Min) + if !(cond0 && cond1) { + panic(ufmt.Sprintf("[POSITION] position.gno__decreaseLiquidity() || burnedAmount0(%s) >= amount0Min(%s) && burnedAmount1(%s) >= amount1Min(%s)", burnedAmount0.ToString(), params.amount0Min.ToString(), burnedAmount1.ToString(), params.amount1Min.ToString())) + } positionKey := positionKeyCompute(GetOrigPkgAddr(), position.tickLower, position.tickUpper) feeGrowthInside0LastX128, feeGrowthInside1LastX128 := pool.PoolGetPositionFeeGrowthInside0LastX128(positionKey), pool.PoolGetPositionFeeGrowthInside1LastX128(positionKey) - { value1 := new(u256.Uint).Sub(feeGrowthInside0LastX128, position.feeGrowthInside0LastX128) value2 := new(u256.Uint).Mul(value1, position.liquidity) @@ -302,15 +274,15 @@ func decreaseLiquidity(params DecreaseLiquidityParams) (uint64, string, string, if feeGrowthInside0LastX128.IsZero() { position.feeGrowthInside0LastX128 = u256.Zero() } else { - _cloneFromDecimal := u256.MustFromDecimal(feeGrowthInside0LastX128.ToString()) - position.feeGrowthInside0LastX128 = _cloneFromDecimal + _cloneMustFromDecimal := u256.MustFromDecimal(feeGrowthInside0LastX128.ToString()) + position.feeGrowthInside0LastX128 = _cloneMustFromDecimal } if feeGrowthInside1LastX128.IsZero() { position.feeGrowthInside1LastX128 = u256.Zero() } else { - _cloneFromDecimal := u256.MustFromDecimal(feeGrowthInside1LastX128.ToString()) - position.feeGrowthInside1LastX128 = _cloneFromDecimal + _cloneMustFromDecimal := u256.MustFromDecimal(feeGrowthInside1LastX128.ToString()) + position.feeGrowthInside1LastX128 = _cloneMustFromDecimal } position.liquidity = new(u256.Uint).Sub(positionLiquidity, params.liquidity) @@ -327,14 +299,8 @@ func decreaseLiquidity(params DecreaseLiquidityParams) (uint64, string, string, _burnedAmount0, _burnedAmount1, ) - amount0, err := u256.FromDecimal(_amount0) - if err != nil { - panic(ufmt.Sprintf("[POSITION] position.gno__decreaseLiquidity() || u256.FromDecimal(_amount0: %s) failed", _amount0)) - } - amount1, err := u256.FromDecimal(_amount1) - if err != nil { - panic(ufmt.Sprintf("[POSITION] position.gno__decreaseLiquidity() || u256.FromDecimal(_amount1: %s) failed", _amount1)) - } + amount0 := u256.MustFromDecimal(_amount0) + amount1 := u256.MustFromDecimal(_amount1) position.tokensOwed0 = new(u256.Uint).Sub(position.tokensOwed0, amount0) position.tokensOwed1 = new(u256.Uint).Sub(position.tokensOwed1, amount1) @@ -350,8 +316,10 @@ func decreaseLiquidity(params DecreaseLiquidityParams) (uint64, string, string, } func CollectFee(tokenId uint64) (uint64, string, string, string) { // tokenId, tokensOwed0, tokensOwed1, poolPath - // verify tokenId exists - require(exists(tokenId), ufmt.Sprintf("[POSITION] position.gno__CollectFee() || tokenId(%d) doesn't exist", tokenId)) + // verify tokenId + if !exists(tokenId) { + panic(ufmt.Sprintf("[POSITION] position.gno__CollectFee() || tokenId(%d) doesn't exist", tokenId)) + } // verify owner or approved isAuthorizedForToken(tokenId) @@ -402,14 +370,8 @@ func CollectFee(tokenId uint64) (uint64, string, string, string) { // tokenId, t consts.MAX_UINT64, // string, r3v4_xxx: current grc20 handles amount by `uint64` ) - amount0Uint, err := u256.FromDecimal(amount0) - if err != nil { - panic(ufmt.Sprintf("[POSITION] position.gno__CollectFee() || u256.FromDecimal(amount0: %s) failed (err: %s)", amount0, err.Error())) - } - amount1Uint, err := u256.FromDecimal(amount1) - if err != nil { - panic(ufmt.Sprintf("[POSITION] position.gno__CollectFee() || u256.FromDecimal(amount1: %s) failed (err: %s)", amount1, err.Error())) - } + amount0Uint := u256.MustFromDecimal(amount0) + amount1Uint := u256.MustFromDecimal(amount1) position.tokensOwed0 = new(u256.Uint).Sub(tokensOwed0, amount0Uint) position.tokensOwed1 = new(u256.Uint).Sub(tokensOwed1, amount1Uint) @@ -426,39 +388,26 @@ func burnNFT(tokenId uint64) { position := positions[tokenId] - require(position.isClear(), ufmt.Sprintf("[POSITION] position.gno__burnNFT() || position(tokenId:%d) isn't clear(liquidity:%d, tokensOwed0:%d, tokensOwed1:%d)", tokenId, position.liquidity, position.tokensOwed0, position.tokensOwed1)) - - positions = deleteFromPositions(positions, tokenId) + if !(position.isClear()) { + panic(ufmt.Sprintf("[POSITION] position.gno__burnNFT() || position(tokenId:%d) isn't clear(liquidity:%d, tokensOwed0:%d, tokensOwed1:%d)", tokenId, position.liquidity, position.tokensOwed0, position.tokensOwed1)) + } + delete(positions, tokenId) gnft.Burn(tid(tokenId)) } func burnPosition(tokenId uint64) { position := positions[tokenId] - require(position.isClear(), ufmt.Sprintf("[POSITION] position.gno__burnPosition() || position(tokenId:%d) isn't clear(liquidity:%d, tokensOwed0:%d, tokensOwed1:%d)", tokenId, position.liquidity, position.tokensOwed0, position.tokensOwed1)) + if !(position.isClear()) { + panic(ufmt.Sprintf("[POSITION] position.gno__burnPosition() || position(tokenId:%d) isn't clear(liquidity:%d, tokensOwed0:%d, tokensOwed1:%d)", tokenId, position.liquidity, position.tokensOwed0, position.tokensOwed1)) + } position.burned = true positions[tokenId] = position } func isAuthorizedForToken(tokenId uint64) { - require(isApprovedOrOwner(std.PrevRealm().Addr(), tokenId), ufmt.Sprintf("[POSITION] position.gno__isAuthorizedForToken() || caller(%s) is not approved or owner of tokenId(%d)", std.PrevRealm().Addr(), tokenId)) -} - -func deleteFromPositions(m map[uint64]Position, key uint64) map[uint64]Position { - if _, ok := m[key]; ok { - newMap := make(map[uint64]Position) - for k, v := range m { - if k != key { - newMap[k] = v - } - } - - return newMap + if !(isApprovedOrOwner(std.PrevRealm().Addr(), tokenId)) { + panic(ufmt.Sprintf("[POSITION] position.gno__isAuthorizedForToken() || caller(%s) is not approved or owner of tokenId(%d)", std.PrevRealm().Addr(), tokenId)) } - return m -} - -func (p Position) isClear() bool { - return p.liquidity.IsZero() && p.tokensOwed0.IsZero() && p.tokensOwed1.IsZero() } diff --git a/position/type.gno b/position/type.gno index eccd76120..146e74adb 100644 --- a/position/type.gno +++ b/position/type.gno @@ -27,6 +27,10 @@ type Position struct { burned bool } +func (p Position) isClear() bool { + return p.liquidity.IsZero() && p.tokensOwed0.IsZero() && p.tokensOwed1.IsZero() +} + type MintParams struct { token0 string token1 string diff --git a/position/utils.gno b/position/utils.gno index d94931790..3c0ccc815 100644 --- a/position/utils.gno +++ b/position/utils.gno @@ -11,14 +11,10 @@ import ( "gno.land/r/demo/users" ) -func require(condition bool, message string) { - if !condition { - panic(message) - } -} - func checkDeadline(deadline int64) { - require(time.Now().Unix() <= deadline, ufmt.Sprintf("[POSITION] utils.gno__checkDeadline() || transaction too old__time.Now().Unix()(%d) <= deadline(%d)", time.Now().Unix(), deadline)) + if time.Now().Unix() > deadline { + panic(ufmt.Sprintf("[POSITION] utils.gno__checkDeadline() || transaction too old__time.Now().Unix()(%d) <= deadline(%d)", time.Now().Unix(), deadline)) + } } func a2u(addr std.Address) users.AddressOrName { @@ -28,7 +24,7 @@ func a2u(addr std.Address) users.AddressOrName { func poolKeyDivide(poolKey string) (string, string, uint32) { res := strings.Split(poolKey, ":") if len(res) != 3 { - panic(ufmt.Sprintf("[POSITION] util.gno__poolKeyDivide() || invalid poolKey(%s)", poolKey)) + panic(ufmt.Sprintf("[POSITION] utils.gno__poolKeyDivide() || invalid poolKey(%s)", poolKey)) } pToken0, pToken1, pFeeStr := res[0], res[1], res[2] diff --git a/router/router.gno b/router/router.gno index 4a22b4578..fc936fda6 100644 --- a/router/router.gno +++ b/router/router.gno @@ -46,11 +46,15 @@ func SwapRoute( // check route length ( should be 1 ~ 7 ) routes := strings.Split(strRouteArr, ",") - require(1 <= len(routes) && len(routes) <= 7, ufmt.Sprintf("[ROUTER] router.gno__SwapRoute() || len(routes) should be 1 ~ 7 (len(routes):%d)", len(routes))) + if !(1 <= len(routes) && len(routes) <= 7) { + panic(ufmt.Sprintf("[ROUTER] router.gno__SwapRoute() || len(routes) should be 1 ~ 7 (len(routes)[%d])", len(routes))) + } // check if routes length and quotes length are same quotes := strings.Split(quoteArr, ",") - require(len(routes) == len(quotes), "[ROUTER] router.gno__SwapRoute() || len(routes) != len(quotes)") + if len(routes) != len(quotes) { + panic(ufmt.Sprintf("[ROUTER] router.gno__SwapRoute() || len(routes[%d]) != len(quotes[%d])", len(routes), len(quotes))) + } // check if quotes are up to 100% quotesSum := int64(0) @@ -58,7 +62,9 @@ func SwapRoute( intQuote, _ := strconv.Atoi(quote) quotesSum += int64(intQuote) } - require(quotesSum == 100, "[ROUTER] router.gno__SwapRoute() || quotesSum != 100") + if quotesSum != 100 { + panic(ufmt.Sprintf("[ROUTER] router.gno__SwapRoute() || quotesSum != 100 (quotesSum)[%d]", quotesSum)) + } resultAmountIn := u256.Zero() resultAmountOut := u256.Zero() @@ -67,8 +73,9 @@ func SwapRoute( numHops := strings.Count(route, "*POOL*") + 1 quote, _ := strconv.Atoi(quotes[i]) - // check if route hop is up to 3 - require(numHops <= 3, "[ROUTER] router.gno__SwapRoute() || numHops > 3") + if numHops < 1 || numHops > 3 { + panic(ufmt.Sprintf("[ROUTER] router.gno__SwapRoute() || numHops should be 1 ~ 3 (numHops)[%d]", numHops)) + } toSwap := i256.Zero().Mul(amountSpecified, i256.NewInt(int64(quote))) toSwap = toSwap.Div(toSwap, i256.NewInt(100)) @@ -90,10 +97,14 @@ func SwapRoute( resultAmountOut = handleProtocolFee(outputToken, resultAmountOut, false) if swapType == ExactIn { - require(tokenAmountLimit.Lte(resultAmountOut), ufmt.Sprintf("[ROUTER] router.gno__SwapRoute() || too few received (expected minimum output:%s, actual output:%s)", _tokenAmountLimit, resultAmountOut.ToString())) + if !(tokenAmountLimit.Lte(resultAmountOut)) { + panic(ufmt.Sprintf("[ROUTER] router.gno__SwapRoute() || too few received for user (expected minimum received:%s, actual received:%s)", _tokenAmountLimit, resultAmountOut.ToString())) + } return resultAmountOut.ToString() } else { // EXACT_OUT - require(resultAmountIn.Lte(tokenAmountLimit), ufmt.Sprintf("[ROUTER] router.gno__SwapRoute() || too much spend (expected maximum input:%s, actual input:%s)", _tokenAmountLimit, resultAmountIn.ToString())) + if !(resultAmountIn.Lte(tokenAmountLimit)) { + panic(ufmt.Sprintf("[ROUTER] router.gno__SwapRoute() || too much spend for user (expected maximum spend:%s, actual spend:%s)", _tokenAmountLimit, resultAmountIn.ToString())) + } return resultAmountIn.ToString() } } @@ -160,7 +171,9 @@ func handleProtocolFee(outputToken string, amount *u256.Uint, isDry bool) *u256. if !isDry { ok := transferFromByRegisterCall(outputToken, std.GetOrigCaller(), consts.FEE_COLLECTOR, feeAmount.Uint64()) - require(ok, "[ROUTER] router.gno__handleProtocolFee() || transferFromByRegisterCall failed") + if !ok { + panic(ufmt.Sprintf("[ROUTER] router.gno__handleProtocolFee() || expected transferFromByRegisterCall(%s, %s, %s, %s) == true", outputToken, std.GetOrigCaller(), consts.FEE_COLLECTOR, feeAmount.ToString())) + } } return new(u256.Uint).Sub(amount, feeAmount) diff --git a/router/router_dry.gno b/router/router_dry.gno index e4135f679..a0d73afa9 100644 --- a/router/router_dry.gno +++ b/router/router_dry.gno @@ -37,11 +37,15 @@ func DrySwapRoute( // check route length ( should be 1 ~ 7 ) routes := strings.Split(strRouteArr, ",") - require(1 <= len(routes) && len(routes) <= 7, ufmt.Sprintf("[ROUTER] router_dry.gno__DrySwapRoute() || len(routes) should be 1 ~ 7 (len(routes)[%d])", len(routes))) + if !(1 <= len(routes) && len(routes) <= 7) { + panic(ufmt.Sprintf("[ROUTER] router_dry.gno__DrySwapRoute() || len(routes) should be 1 ~ 7 (len(routes)[%d])", len(routes))) + } // check if routes length and quotes length are same quotes := strings.Split(quoteArr, ",") - require(len(routes) == len(quotes), ufmt.Sprintf("[ROUTER] router_dry.gno__DrySwapRoute() || len(routes[%d]) != len(quotes[%d])", len(routes), len(quotes))) + if len(routes) != len(quotes) { + panic(ufmt.Sprintf("[ROUTER] router_dry.gno__DrySwapRoute() || len(routes[%d]) != len(quotes[%d])", len(routes), len(quotes))) + } // check if quotes are up to 100% quotesSum := int64(0) @@ -49,7 +53,9 @@ func DrySwapRoute( intQuote, _ := strconv.Atoi(quote) quotesSum += int64(intQuote) } - require(quotesSum == 100, "[ROUTER] router_dry.gno__DrySwapRoute() || quotesSum != 100") + if quotesSum != 100 { + panic(ufmt.Sprintf("[ROUTER] router_dry.gno__DrySwapRoute() || quotesSum != 100 (quotesSum)[%d]", quotesSum)) + } resultAmountIn := u256.Zero() resultAmountOut := u256.Zero() @@ -58,8 +64,9 @@ func DrySwapRoute( numHops := strings.Count(route, "*POOL*") + 1 quote, _ := strconv.Atoi(quotes[i]) - // check if route hop is up to 3 - require(numHops <= 3, "[ROUTER] router_dry.gno__DrySwapRoute() || numHops > 3") + if numHops < 1 || numHops > 3 { + panic(ufmt.Sprintf("[ROUTER] router_dry.gno__DrySwapRoute() || numHops should be 1 ~ 3 (numHops)[%d]", numHops)) + } toSwap := i256.Zero().Mul(amountSpecified, i256.NewInt(int64(quote))) toSwap = toSwap.Div(toSwap, i256.NewInt(100)) diff --git a/router/utils.gno b/router/utils.gno index 46178073e..2343e25dc 100644 --- a/router/utils.gno +++ b/router/utils.gno @@ -12,7 +12,9 @@ import ( func poolPathWithFeeDivide(poolPath string) (string, string, int) { poolPathSplit := strings.Split(poolPath, ":") - require(len(poolPathSplit) == 3, ufmt.Sprintf("[ROUTER] _RPC_api.gno__poolPathWithFeeDivide() || len(poolPathSplit) != 3, poolPath: %s", poolPath)) + if len(poolPathSplit) != 3 { + panic(ufmt.Sprintf("[ROUTER] _RPC_api.gno__poolPathWithFeeDivide() || len(poolPathSplit) != 3, poolPath: %s", poolPath)) + } feeInt, err := strconv.Atoi(poolPathSplit[2]) if err != nil { @@ -24,7 +26,9 @@ func poolPathWithFeeDivide(poolPath string) (string, string, int) { func getDataForSinglePath(poolPath string) (string, string, uint32) { datas := strings.Split(poolPath, ":") - require(len(datas) == 3, ufmt.Sprintf("[ROUTER] _util.gno__getDataForSinglePath() || len(datas) != 3 (poolPath:%s)", poolPath)) + if len(datas) != 3 { + panic(ufmt.Sprintf("[ROUTER] _util.gno__getDataForSinglePath() || len(datas) != 3 (poolPath:%s)", poolPath)) + } token0 := datas[0] token1 := datas[1] @@ -75,12 +79,6 @@ func a2u(addr std.Address) users.AddressOrName { return users.AddressOrName(addr) } -func require(cond bool, msg string) { - if !cond { - panic(msg) - } -} - func min(a, b int) int { if a < b { return a diff --git a/staker/_GET_no_receiver.gno b/staker/_GET_no_receiver.gno index 6401da522..f83c7da0c 100644 --- a/staker/_GET_no_receiver.gno +++ b/staker/_GET_no_receiver.gno @@ -11,21 +11,27 @@ import ( // Incentive func StakerPoolIncentives(poolPath string) []string { incentives, exist := poolIncentives[poolPath] - requireExist(exist, ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerPoolIncentives() || poolPath(%s) incentives does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerPoolIncentives() || poolPath(%s) incentives does not exist", poolPath)) + } return incentives } func StakerIncentiveTargetPoolPath(incentiveId string) string { incentive, exist := incentives[incentiveId] - requireExist(exist, ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerIncentiveTargetPoolPath() || incentiveId(%s) incentive does not exist", incentiveId)) + if !exist { + panic(ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerIncentiveTargetPoolPath() || incentiveId(%s) incentive does not exist", incentiveId)) + } return incentive.targetPoolPath } func StakerIncentiveRewardToken(incentiveId string) string { incentive, exist := incentives[incentiveId] - requireExist(exist, ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerIncentiveRewardToken() || incentiveId(%s) incentive does not exist", incentiveId)) + if !exist { + panic(ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerIncentiveRewardToken() || incentiveId(%s) incentive does not exist", incentiveId)) + } return incentive.rewardToken } @@ -33,7 +39,9 @@ func StakerIncentiveRewardToken(incentiveId string) string { // UINT func StakerIncentiveRewardAmount(incentiveId string) *u256.Uint { incentive, exist := incentives[incentiveId] - requireExist(exist, ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerIncentiveRewardAmount() || incentiveId(%s) incentive does not exist", incentiveId)) + if !exist { + panic(ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerIncentiveRewardAmount() || incentiveId(%s) incentive does not exist", incentiveId)) + } return incentive.rewardAmount } @@ -41,28 +49,36 @@ func StakerIncentiveRewardAmount(incentiveId string) *u256.Uint { // STR func StakerIncentiveRewardAmountStr(incentiveId string) string { incentive, exist := incentives[incentiveId] - requireExist(exist, ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerIncentiveRewardAmount() || incentiveId(%s) incentive does not exist", incentiveId)) + if !exist { + panic(ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerIncentiveRewardAmount() || incentiveId(%s) incentive does not exist", incentiveId)) + } return incentive.rewardAmount.ToString() } func StakerIncentiveStartTimestamp(incentiveId string) int64 { incentive, exist := incentives[incentiveId] - requireExist(exist, ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerIncentiveStartTimestamp() || incentiveId(%s) incentive does not exist", incentiveId)) + if !exist { + panic(ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerIncentiveStartTimestamp() || incentiveId(%s) incentive does not exist", incentiveId)) + } return incentive.startTimestamp } func StakerIncentiveEndTimestamp(incentiveId string) int64 { incentive, exist := incentives[incentiveId] - requireExist(exist, ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerIncentiveEndTimestamp() || incentiveId(%s) incentive does not exist", incentiveId)) + if !exist { + panic(ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerIncentiveEndTimestamp() || incentiveId(%s) incentive does not exist", incentiveId)) + } return incentive.endTimestamp } func StakerIncentiveRefundee(incentiveId string) std.Address { incentive, exist := incentives[incentiveId] - requireExist(exist, ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerIncentiveRefundee() || incentiveId(%s) incentive does not exist", incentiveId)) + if !exist { + panic(ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerIncentiveRefundee() || incentiveId(%s) incentive does not exist", incentiveId)) + } return incentive.refundee } @@ -70,28 +86,36 @@ func StakerIncentiveRefundee(incentiveId string) std.Address { // Deposit func StakerDepositOwner(lpTokenId uint64) std.Address { deposit, exist := deposits[lpTokenId] - requireExist(exist, ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerDepositOwner() || tokenId(%d) deposit does not exist", lpTokenId)) + if !exist { + panic(ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerDepositOwner() || tokenId(%d) deposit does not exist", lpTokenId)) + } return deposit.owner } func StakerDepositNumberOfStakes(lpTokenId uint64) uint64 { deposit, exist := deposits[lpTokenId] - requireExist(exist, ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerDepositNumberOfStakes() || tokenId(%d) deposit does not exist", lpTokenId)) + if !exist { + panic(ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerDepositNumberOfStakes() || tokenId(%d) deposit does not exist", lpTokenId)) + } return deposit.numberOfStakes } func StakerDepositStakeTimestamp(lpTokenId uint64) int64 { deposit, exist := deposits[lpTokenId] - requireExist(exist, ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerDepositStakeTimestamp() || tokenId(%d) deposit does not exist", lpTokenId)) + if !exist { + panic(ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerDepositStakeTimestamp() || tokenId(%d) deposit does not exist", lpTokenId)) + } return deposit.stakeTimestamp } func StakerDepositTargetPoolPath(lpTokenId uint64) string { deposit, exist := deposits[lpTokenId] - requireExist(exist, ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerDepositTargetPoolPath() || tokenId(%d) deposit does not exist", lpTokenId)) + if !exist { + panic(ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerDepositTargetPoolPath() || tokenId(%d) deposit does not exist", lpTokenId)) + } return deposit.targetPoolPath } @@ -99,7 +123,9 @@ func StakerDepositTargetPoolPath(lpTokenId uint64) string { // PoolTier func StakerPoolTier(poolPath string) uint64 { tier, exist := poolTiers[poolPath] - requireExist(exist, ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerPoolTier() || poolPath(%s) poolTier does not exist", poolPath)) + if !exist { + panic(ufmt.Sprintf("[STAKER] _GET_no_receiver__StakerPoolTier() || poolPath(%s) poolTier does not exist", poolPath)) + } return tier } diff --git a/staker/_RPC_api_stake.gno b/staker/_RPC_api_stake.gno index 4e8ce4b96..b00cc2c84 100644 --- a/staker/_RPC_api_stake.gno +++ b/staker/_RPC_api_stake.gno @@ -106,7 +106,9 @@ func ApiGetRewards() string { func ApiGetRewardByLpTokenId(lpTokenId uint64) string { deposit, exist := deposits[lpTokenId] - require(exist, ufmt.Sprintf("[STAKER] _RPC_api_stake.gno__ApiGetRewardByLpTokenId() || lpTokenId(%d) deposit does not exist", lpTokenId)) + if !exist { + panic(ufmt.Sprintf("[STAKER] _RPC_api_stake.gno__ApiGetRewardByLpTokenId() || lpTokenId(%d) deposit does not exist", lpTokenId)) + } rewards := []Reward{} diff --git a/staker/reward_fee.gno b/staker/reward_fee.gno index e9bb9f915..a752fa26a 100644 --- a/staker/reward_fee.gno +++ b/staker/reward_fee.gno @@ -28,10 +28,14 @@ func handleRewardFee( if internal { // if internal, reward is in IRA ok := transferFromByRegisterCall(tokenPath, consts.INTERNAL_REWARD_ACCOUNT, consts.FEE_COLLECTOR, feeAmount.Uint64()) - require(ok, ufmt.Sprintf("[STAKER] reward_fee.gno__HandleRewardFee() || expected transferFromByRegisterCall(%s, %s, %s, %s) == true", tokenPath, consts.INTERNAL_REWARD_ACCOUNT, consts.FEE_COLLECTOR, feeAmount)) + if !ok { + panic(ufmt.Sprintf("[STAKER] reward_fee.gno__HandleRewardFee() || expected transferFromByRegisterCall(%s, %s, %s, %s) == true", tokenPath, consts.INTERNAL_REWARD_ACCOUNT, consts.FEE_COLLECTOR, feeAmount.ToString())) + } } else { // if external, reward is in staker contract ok := transferByRegisterCall(tokenPath, consts.FEE_COLLECTOR, feeAmount.Uint64()) - require(ok, ufmt.Sprintf("[STAKER] reward_fee.gno__HandleRewardFee() || expected transferByRegisterCall(%s, %s, %s) == true", tokenPath, consts.FEE_COLLECTOR, feeAmount)) + if !ok { + panic(ufmt.Sprintf("[STAKER] reward_fee.gno__HandleRewardFee() || expected transferByRegisterCall(%s, %s, %s) == true", tokenPath, consts.FEE_COLLECTOR, feeAmount.ToString())) + } } return new(u256.Uint).Sub(amount, feeAmount) @@ -42,9 +46,13 @@ func SetRewardFee(fee uint64) { std.AssertOriginCall() // MUST BE ADMIN - require(consts.GNOSWAP_ADMIN == std.GetOrigCaller(), ufmt.Sprintf("[STAKER] reward_fee.gno__SetFeeProtocol() || caller(%s) must be admin", std.GetOrigCaller())) + if consts.GNOSWAP_ADMIN != std.GetOrigCaller() { + panic(ufmt.Sprintf("[STAKER] reward_fee.gno__SetFeeProtocol() || caller(%s) must be admin", std.GetOrigCaller())) + } - require(fee >= 0, ufmt.Sprintf("[STAKER] reward_fee.gno__SetFeeProtocol() || fee(%s) must be >= 0", fee)) + if fee < 0 { + panic(ufmt.Sprintf("[STAKER] reward_fee.gno__SetFeeProtocol() || fee(%d) must be >= 0", fee)) + } rewardFee = fee } diff --git a/staker/reward_math.gno b/staker/reward_math.gno index a1013b633..21b404987 100644 --- a/staker/reward_math.gno +++ b/staker/reward_math.gno @@ -271,7 +271,9 @@ func getRewardRatio(timestamp int64) uint64 { } func getTierRatio(tier uint64) uint64 { - require(tier >= 1 && tier <= 3, ufmt.Sprintf("[STAKER] reward_math.gno__getTierRatio() || tier(%d) >= 1 && tier(%d) <= 3", tier, tier)) + if tier < 1 || tier > 3 { + panic(ufmt.Sprintf("[STAKER] reward_math.gno__getTierRatio() || tier(%d) must be 1 ~ 3", tier)) + } ratio1, ratio2, ratio3 := listTierRatio() switch tier { @@ -298,7 +300,9 @@ func listTierRatio() (uint64, uint64, uint64) { // we'll divide by 100 later numTier1, numTier2, numTier3 := getNumPoolTiers() - require(numTier1 > 0, ufmt.Sprintf("[STAKER] reward_math.gno__listTierRatio() || numTier1(%d) > 0 (numTier2:(%d), numTier3:(%d))", numTier1, numTier2, numTier3)) + if numTier1 <= 0 { + panic(ufmt.Sprintf("[STAKER] reward_math.gno__listTierRatio() || at least 1 numTier1 need(%d), [numTier2:(%d), numTier3:(%d)]", numTier1, numTier2, numTier3)) + } if numTier2 == 0 && numTier3 == 0 { // only tier 1 exists return 100, 0, 0 diff --git a/staker/staker.gno b/staker/staker.gno index 4d011023b..66c675c1b 100644 --- a/staker/staker.gno +++ b/staker/staker.gno @@ -45,12 +45,11 @@ func CreateExternalIncentive( startTimestamp int64, endTimestamp int64, ) { - rewardAmount, err := u256.FromDecimal(_rewardAmount) - if err != nil { - panic(ufmt.Sprintf("[STAKER] staker.gno__CreateExternalIncentive() || u256.FromDecimal(_rewardAmount: %s) failed", _rewardAmount)) - } + rewardAmount := u256.MustFromDecimal(_rewardAmount) - require(time.Now().Unix() <= startTimestamp, ufmt.Sprintf("[STAKER] staker.gno__CreateExternalIncentive() || startTimestamp must be in the future__time.Now().Unix(%d) <= startTimestamp(%d)", time.Now().Unix(), startTimestamp)) + if startTimestamp < time.Now().Unix() { + panic(ufmt.Sprintf("[STAKER] staker.gno__CreateExternalIncentive() || startTimestamp(%d) must be in the future [now:%d]", startTimestamp, time.Now().Unix())) + } externalDuration := uint64(endTimestamp - startTimestamp) if !(externalDuration == TIMESTAMP_90DAYS || externalDuration == TIMESTAMP_180DAYS || externalDuration == TIMESTAMP_360DAYS) { @@ -58,7 +57,10 @@ func CreateExternalIncentive( } fromBalanceBefore := balanceOfByRegisterCall(rewardToken, std.GetOrigCaller()) - require(fromBalanceBefore >= rewardAmount.Uint64(), ufmt.Sprintf("[STAKER] staker.gno__CreateExternalIncentive() || not enough rewardAmount(%d) to create incentive(%d)", fromBalanceBefore, rewardAmount.Uint64())) + + if fromBalanceBefore < rewardAmount.Uint64() { + panic(ufmt.Sprintf("[STAKER] staker.gno__CreateExternalIncentive() || user(%s) doesn't have enough amount balance(%d) to create incentive(%d)", std.GetOrigCaller(), fromBalanceBefore, rewardAmount.Uint64())) + } poolRewardBalanceBefore := balanceOfByRegisterCall(rewardToken, GetOrigPkgAddr()) @@ -76,10 +78,9 @@ func CreateExternalIncentive( transferFromByRegisterCall(rewardToken, std.GetOrigCaller(), GetOrigPkgAddr(), rewardAmount.Uint64()) poolRewardBalanceAfter := balanceOfByRegisterCall(rewardToken, GetOrigPkgAddr()) - require( - poolRewardBalanceAfter-poolRewardBalanceBefore == rewardAmount.Uint64(), - ufmt.Sprintf("[STAKER] staker.gno__CreateExternalIncentive() || pool reward balance not updated correctly(before:%d, added:%d, final:%d)", - poolRewardBalanceBefore, rewardAmount.Uint64(), poolRewardBalanceAfter)) + if !(poolRewardBalanceAfter-poolRewardBalanceBefore == rewardAmount.Uint64()) { + panic(ufmt.Sprintf("[STAKER] staker.gno__CreateExternalIncentive() || pool reward balance not updated correctly(before:%d, added:%d, final:%d)", poolRewardBalanceBefore, rewardAmount.Uint64(), poolRewardBalanceAfter)) + } incentives[incentiveId] = Incentive{ targetPoolPath: targetPoolPath, @@ -96,20 +97,20 @@ func CreateExternalIncentive( func StakeToken(tokenId uint64) (string, string, string) { // poolPath, token0Amount, token1Amount // check whether tokenId already staked or not _, exist := deposits[tokenId] - require(!exist, ufmt.Sprintf("[STAKER] staker.gno__StakeToken() || tokenId(%d) already staked", tokenId)) + if exist { + panic(ufmt.Sprintf("[STAKER] staker.gno__StakeToken() || tokenId(%d) already staked", tokenId)) + } // check tokenId owner - require( - gnft.OwnerOf(tid(tokenId)) == std.GetOrigCaller(), - ufmt.Sprintf( - "[STAKER] staker.gno__StakeToken() || only owner can stake their token tokenId(%d), owner(%s) == std.GetOrigCaller(%s)", - tokenId, gnft.OwnerOf(tid(tokenId)), std.GetOrigCaller(), - ), - ) + if gnft.OwnerOf(tid(tokenId)) != std.GetOrigCaller() { + panic(ufmt.Sprintf("[STAKER] staker.gno__StakeToken() || only owner can stake their token tokenId(%d), owner(%s) == std.GetOrigCaller(%s)", tokenId, gnft.OwnerOf(tid(tokenId)), std.GetOrigCaller())) + } // check tokenId has liquidity or not liquidity := pn.PositionGetPositionLiquidity(tokenId) // *u256.Uint - require(liquidity.Gt(u256.Zero()), ufmt.Sprintf("[STAKER] staker.gno__StakeToken() || tokenId(%d) has no liquidity", tokenId)) + if liquidity.Lte(u256.Zero()) { + panic(ufmt.Sprintf("[STAKER] staker.gno__StakeToken() || tokenId(%d) has no liquidity", tokenId)) + } // check pool path from tokenid poolKey := pn.PositionGetPositionPoolKey(tokenId) @@ -130,9 +131,13 @@ func StakeToken(tokenId uint64) (string, string, string) { // poolPath, token0Am func CollectReward(tokenId uint64) { deposit, exist := deposits[tokenId] - require(exist, ufmt.Sprintf("[STAKER] staker.gno__CollectReward() || tokenId(%d) not staked", tokenId)) + if !exist { + panic(ufmt.Sprintf("[STAKER] staker.gno__CollectReward() || tokenId(%d) not staked", tokenId)) + } - require(std.PrevRealm().Addr() == deposit.owner, ufmt.Sprintf("[STAKER] staker.gno__CollectReward() || only owner(%s) can collect reward from tokenId(%d), std.PrevRealm().Addr()(%s)", deposit.owner, tokenId, std.PrevRealm().Addr())) + if std.PrevRealm().Addr() != deposit.owner { + panic(ufmt.Sprintf("[STAKER] staker.gno__CollectReward() || only owner(%s) can collect reward from tokenId(%d), std.PrevRealm().Addr()(%s)", deposit.owner, tokenId, std.PrevRealm().Addr())) + } // poolPath to collect reward poolPath := pn.PositionGetPositionPoolKey(tokenId) @@ -174,7 +179,9 @@ func UnstakeToken(tokenId uint64) (string, string, string) { // unstaked status deposit, exist := deposits[tokenId] - require(exist, ufmt.Sprintf("[STAKER] staker.gno__UnstakeToken() || tokenId(%d) not staked", tokenId)) + if !exist { + panic(ufmt.Sprintf("[STAKER] staker.gno__UnstakeToken() || tokenId(%d) not staked", tokenId)) + } delete(deposits, tokenId) // transfer NFT ownership to origin owner @@ -187,11 +194,17 @@ func UnstakeToken(tokenId uint64) (string, string, string) { func EndExternalIncentive(refundee std.Address, targetPoolPath, rewardToken string) { incentiveId := incentiveIdCompute(refundee, targetPoolPath, rewardToken) + incentive, exist := incentives[incentiveId] - require(exist, ufmt.Sprintf("[STAKER] staker.gno__EndExternalIncentive() || cannot end non existent incentive(%s)", incentiveId)) - require(time.Now().Unix() >= incentive.endTimestamp, ufmt.Sprintf("[STAKER] staker.gno__EndExternalIncentive() || cannot end incentive before endTimestamp(%d), current(%d)", incentive.endTimestamp, time.Now().Unix())) + if !exist { + panic(ufmt.Sprintf("[STAKER] staker.gno__EndExternalIncentive() || cannot end non existent incentive(%s)", incentiveId)) + } + + if time.Now().Unix() < incentive.endTimestamp { + panic(ufmt.Sprintf("[STAKER] staker.gno__EndExternalIncentive() || cannot end incentive before endTimestamp(%d), current(%d)", incentive.endTimestamp, time.Now().Unix())) + } - // when incentive is ended + // when incentive end time is over // 1. admin can end incentive without refund // 2. refundee can end incentive with refund switch std.GetOrigCaller() { @@ -208,7 +221,11 @@ func EndExternalIncentive(refundee std.Address, targetPoolPath, rewardToken stri refund := incentive.rewardAmount poolLeftExternalRewardAmount := balanceOfByRegisterCall(incentive.rewardToken, GetOrigPkgAddr()) - require(poolLeftExternalRewardAmount >= refund.Uint64(), ufmt.Sprintf("[STAKER] staker.gno__EndExternalIncentive() || not enough poolLeftExternalRewardAmount(%s_%d) to refund(%d)", incentive.rewardToken, poolLeftExternalRewardAmount, refund)) + + if poolLeftExternalRewardAmount < refund.Uint64() { + panic(ufmt.Sprintf("[STAKER] staker.gno__EndExternalIncentive() || pool doesn't have enough token(%s) amount(%d) to refund(%d)", incentive.rewardToken, poolLeftExternalRewardAmount, refund)) + } + transferByRegisterCall(incentive.rewardToken, incentive.refundee, refund.Uint64()) delete(incentives, incentiveId) @@ -218,13 +235,15 @@ func EndExternalIncentive(refundee std.Address, targetPoolPath, rewardToken stri } } default: - require(false, ufmt.Sprintf("[STAKER] staker.gno__EndExternalIncentive() || only refundee or admin can end incentive")) + panic("[STAKER] staker.gno__EndExternalIncentive() || only refundee or admin can end incentive") } } func transferDeposit(tokenId uint64, to std.Address) { owner := gnft.OwnerOf(tid(tokenId)) - require(owner == std.GetOrigCaller(), ufmt.Sprintf("[STAKER] staker.gno__transferDeposit() || only owner(%s) can transfer tokenId(%d), std.GetOrigCaller()(%s)", owner, tokenId, std.GetOrigCaller())) + if std.GetOrigCaller() == to { + panic(ufmt.Sprintf("[STAKER] staker.gno__transferDeposit() || only owner(%s) can transfer tokenId(%d), std.GetOrigCaller()(%s)", owner, tokenId, std.GetOrigCaller())) + } deposits[tokenId].owner = owner diff --git a/staker/utils.gno b/staker/utils.gno index fb1169e36..ac322788e 100644 --- a/staker/utils.gno +++ b/staker/utils.gno @@ -65,27 +65,3 @@ func min(x, y int64) int64 { } return y } - -func requireUnsigned(x bigint, msg string) { - if x < 0 { - panic(msg) - } -} - -func require(condition bool, message string) { - if !condition { - panic(message) - } -} - -func requireExist(exist bool, msg string) { - if !exist { - panic(msg) - } -} - -func requirePrevRealmPath(prevRealmPath, msg string) { - if std.PrevRealm().PkgPath() != prevRealmPath { - panic(msg) - } -}