From b319e465cb72790d8e5e7813fb65593230bc5fba Mon Sep 17 00:00:00 2001 From: Phu Ngo <12547020+NgoKimPhu@users.noreply.github.com> Date: Sat, 21 Dec 2024 16:50:12 +0700 Subject: [PATCH 1/7] fix: algebra integral concurrent map access --- go.mod | 2 +- go.sum | 4 +- .../algebra/integral/adaptive_fee.go | 2 +- .../algebra/integral/constant.go | 9 - .../algebra/integral/errors.go | 2 + pkg/liquidity-source/algebra/integral/math.go | 14 +- .../algebra/integral/plugin.go | 442 +++++++----------- .../algebra/integral/pool_simulator.go | 232 ++++----- .../algebra/integral/pool_simulator_test.go | 168 ++++--- .../algebra/integral/pool_tracker.go | 51 +- .../algebra/integral/ticklens.go | 9 +- pkg/liquidity-source/algebra/integral/type.go | 100 ++-- .../algebra/v1/pool_simulator_test.go | 12 +- .../balancer-v1/pool_simulator_test.go | 2 +- .../composable-stable/pool_simulator_test.go | 22 +- .../balancer-v2/stable/pool_simulator_test.go | 10 +- .../weighted/pool_simulator_test.go | 12 +- .../bancor-v3/pool_simulator_test.go | 12 +- .../plain/pool_simulator_basepool_test.go | 4 +- .../plain/pool_simulator_compare_test.go | 4 +- .../curve/plain/pool_simulator_test.go | 14 +- .../stable-meta-ng/pool_simulator_test.go | 4 +- .../curve/stable-ng/pool_simulator_test.go | 8 +- .../curve/tricrypto-ng/pool_simulator_test.go | 6 +- .../curve/twocrypto-ng/pool_simulator_test.go | 6 +- .../dai-usds/pool_simulator_test.go | 2 +- .../dodo/classical/pool_simulator_test.go | 4 +- .../dodo/dpp/pool_simulator_test.go | 2 +- .../dodo/dsp/pool_simulator_test.go | 2 +- .../dodo/dvm/pool_simulator_test.go | 2 +- .../pool_simulator_test.go | 2 +- .../integral/pool_simulator_test.go | 4 +- .../mkr-sky/pool_simulator_test.go | 2 +- .../nomiswapstable/pool_simulator_test.go | 2 +- .../ringswap/pool_simulator_test.go | 2 +- .../swaap-v2/pool_simulator_test.go | 2 +- .../syncswapv2/aqua/pool_simulator_test.go | 2 +- .../syncswapv2/classic/pool_simulator_test.go | 4 +- .../syncswapv2/stable/pool_simulator_test.go | 2 +- .../uniswap-v1/pool_simulator_test.go | 2 +- .../uniswap-v2/pool_simulator_test.go | 2 +- .../velocore-v2/cpmm/pool_simulartor_test.go | 8 +- .../wombat-stable/pool_simulator_test.go | 2 +- .../velodrome-v1/pool_simulator_test.go | 4 +- .../velodrome-v2/pool_simulator_test.go | 4 +- .../woofi-v2/pool_simulator_test.go | 10 +- .../woofi-v21/pool_simulator_test.go | 10 +- pkg/source/algebrav1/pool_simulator_test.go | 12 +- .../pool_simulator_test.go | 4 +- .../balancer/stable/pool_simulator_test.go | 2 +- .../balancer/weighted/pool_simulator_test.go | 6 +- pkg/source/camelot/pool_simulator_test.go | 4 +- pkg/source/curve/aave/pool_simulator_test.go | 6 +- pkg/source/curve/base/pool_simulator_test.go | 8 +- .../curve/compound/pool_simulator_test.go | 4 +- pkg/source/curve/meta/pool_simulator_test.go | 8 +- .../curve/plain-oracle/pool_simulator_test.go | 6 +- .../curve/tricrypto/pool_simulator_test.go | 4 +- pkg/source/curve/two/pool_simulator_test.go | 2 +- pkg/source/dmm/pool_simulator_test.go | 2 +- pkg/source/dodo/pool_simulator_test.go | 6 +- pkg/source/equalizer/pool_simulator_test.go | 2 +- pkg/source/fraxswap/pool_simulator_test.go | 2 +- pkg/source/fulcrom/pool_simulator_test.go | 2 +- pkg/source/fxdx/pool_simulator_test.go | 2 +- pkg/source/gmx-glp/pool_simulator_test.go | 2 +- pkg/source/gmx/pool_simulator_test.go | 2 +- pkg/source/iziswap/pool_simulator_test.go | 4 +- .../kokonut-crypto/pool_simulator_test.go | 2 +- pkg/source/kyber-pmm/pool_simulator_test.go | 4 +- pkg/source/lido-steth/pool_simulator_test.go | 2 +- pkg/source/lido/pool_simulator_test.go | 2 +- .../pool_simulator_calc_amount_in_test.go | 6 +- pkg/source/limitorder/pool_simulator_test.go | 2 +- .../liquiditybookv20/pool_simulator_test.go | 2 +- .../liquiditybookv21/pool_simulator_test.go | 10 +- pkg/source/madmex/pool_simulator_test.go | 4 +- pkg/source/makerpsm/pool_simulator_test.go | 14 +- pkg/source/mantisswap/pool_simulator_test.go | 2 +- pkg/source/maverickv1/pool_simulator_test.go | 14 +- pkg/source/metavault/pool_simulator_test.go | 4 +- pkg/source/nuriv2/pool_simulator_test.go | 2 +- .../pancakev3/pool_simulator_bigint_test.go | 4 +- pkg/source/pancakev3/pool_simulator_test.go | 4 +- pkg/source/platypus/pool_simulator_test.go | 6 +- pkg/source/pol-matic/pool_simulator_test.go | 2 +- pkg/source/quickperps/pool_simulator_test.go | 2 +- pkg/source/ramsesv2/pool_simulator_test.go | 2 +- pkg/source/saddle/pool_simulator_test.go | 10 +- pkg/source/smardex/pool_simulator_test.go | 6 +- pkg/source/solidly-v3/pool_simulator_test.go | 4 +- .../swapbased-perp/pool_simulator_test.go | 2 +- .../syncswapclassic/pool_simulator_test.go | 4 +- .../syncswapstable/pool_simulator_test.go | 4 +- pkg/source/synthetix/pool_simulator_test.go | 2 +- pkg/source/uniswap/pool_simulator_test.go | 2 +- .../uniswapv3/pool_simulator_bigint_test.go | 2 +- pkg/source/uniswapv3/pool_simulator_test.go | 4 +- pkg/source/usdfi/pool_simulator_test.go | 2 +- pkg/source/velocimeter/pool_simulator_test.go | 2 +- pkg/source/velodrome/pool_simulator_test.go | 2 +- pkg/source/velodromev2/pool_simulator_test.go | 2 +- pkg/source/vooi/pool_simulator_test.go | 12 +- .../wombat/wombatlsd/pool_simulator_test.go | 2 +- .../wombat/wombatmain/pool_simulator_test.go | 2 +- pkg/source/woofiv2/pool_simulator_test.go | 2 +- pkg/util/testutil/concurrent.go | 40 +- 107 files changed, 704 insertions(+), 809 deletions(-) diff --git a/go.mod b/go.mod index 0056f01d4..0abb3e8c4 100644 --- a/go.mod +++ b/go.mod @@ -13,7 +13,7 @@ require ( github.com/KyberNetwork/logger v0.2.1 github.com/KyberNetwork/msgpack/v5 v5.4.2 github.com/KyberNetwork/pancake-v3-sdk v0.2.0 - github.com/KyberNetwork/uniswapv3-sdk-uint256 v0.5.0 + github.com/KyberNetwork/uniswapv3-sdk-uint256 v0.5.3-0.20241221122441-5808be2e7503 github.com/daoleno/uniswap-sdk-core v0.1.7 github.com/daoleno/uniswapv3-sdk v0.4.0 github.com/davecgh/go-spew v1.1.1 diff --git a/go.sum b/go.sum index 1fedaa5a1..dfd32ea8d 100644 --- a/go.sum +++ b/go.sum @@ -20,8 +20,8 @@ github.com/KyberNetwork/uniswap-sdk-core v0.1.7 h1:9CfjLkFZcOxgu0US0ZB1vvdgA1sp3 github.com/KyberNetwork/uniswap-sdk-core v0.1.7/go.mod h1:DPzL8zNicstPzvX74ZeeHsiIUquZRpwviceDHQ8+UQ4= github.com/KyberNetwork/uniswapv3-sdk v0.5.5 h1:PLkDL8YWgN00yfNGbQpOGRcKRD3eoFXOFzjvuHP9Gmo= github.com/KyberNetwork/uniswapv3-sdk v0.5.5/go.mod h1:XFySgQXZ+dl0yRze6Rj8jloILcFP8FbXJjcyk/1RmSU= -github.com/KyberNetwork/uniswapv3-sdk-uint256 v0.5.0 h1:AkEmCEBmyYAUU+WHGrgw9uaXHteqNn66CD36FaXoUig= -github.com/KyberNetwork/uniswapv3-sdk-uint256 v0.5.0/go.mod h1:VQNKmTwlX6gyW1gzaSQjYG+xCBpqmgH0VQslYMtqzAg= +github.com/KyberNetwork/uniswapv3-sdk-uint256 v0.5.3-0.20241221122441-5808be2e7503 h1:FvNvHE1yHjLK8owNpOnVUdZNYNZ5xnXJ9uKvuWMC0NY= +github.com/KyberNetwork/uniswapv3-sdk-uint256 v0.5.3-0.20241221122441-5808be2e7503/go.mod h1:VQNKmTwlX6gyW1gzaSQjYG+xCBpqmgH0VQslYMtqzAg= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/VictoriaMetrics/fastcache v1.12.2 h1:N0y9ASrJ0F6h0QaC3o6uJb3NIZ9VKLjCM7NQbSmF7WI= diff --git a/pkg/liquidity-source/algebra/integral/adaptive_fee.go b/pkg/liquidity-source/algebra/integral/adaptive_fee.go index 2fe7f24bc..1d6dee43f 100644 --- a/pkg/liquidity-source/algebra/integral/adaptive_fee.go +++ b/pkg/liquidity-source/algebra/integral/adaptive_fee.go @@ -7,7 +7,7 @@ import ( // / @notice Calculates fee based on formula: // / baseFee + sigmoid1(volatility) + sigmoid2(volatility) // / maximum value capped by baseFee + alpha1 + alpha2 -func getFee(volatility *uint256.Int, config FeeConfiguration) uint16 { +func getFee(volatility *uint256.Int, config *DynamicFeeConfig) uint16 { // normalize for 15 sec interval normalizedVolatility := new(uint256.Int).Div(volatility, uFIFTEEN) diff --git a/pkg/liquidity-source/algebra/integral/constant.go b/pkg/liquidity-source/algebra/integral/constant.go index 29a49bf24..054fe132b 100644 --- a/pkg/liquidity-source/algebra/integral/constant.go +++ b/pkg/liquidity-source/algebra/integral/constant.go @@ -4,7 +4,6 @@ import ( "math/big" "time" - "github.com/KyberNetwork/int256" "github.com/holiman/uint256" ) @@ -59,14 +58,7 @@ var ( FEE_DENOMINATOR = uint256.NewInt(1e6) COMMUNITY_FEE_DENOMINATOR = uint256.NewInt(1e3) - ZERO = int256.NewInt(0) - ONE = int256.NewInt(1) - - MIN_INT256 = new(int256.Int).Neg(new(int256.Int).Lsh(ZERO, 255)) // -2^255 - MAX_UINT256 = new(uint256.Int).Sub(new(uint256.Int).Lsh(uZERO, 256), uONE) - MAX_UINT16 = new(uint256.Int).SetUint64(1<<16 - 1) - MIN_UINT16 = new(uint256.Int).SetUint64(1) uZERO = uint256.NewInt(0) uONE = uint256.NewInt(1) @@ -82,7 +74,6 @@ var ( MAX_SQRT_RATIO, _ = new(big.Int).SetString("1461446703485210103287273052203988822378723970342", 10) Q96 = new(uint256.Int).Lsh(uONE, 96) // 1 << 96 - Q128 = new(uint256.Int).Lsh(uONE, 128) // 1 << 128 BASE_FEE_MULTIPLIER = new(uint256.Int).Lsh(uONE, FEE_FACTOR_SHIFT) // 1 << 96 DOUBLE_FEE_MULTIPLIER = new(uint256.Int).Lsh(uONE, 2*FEE_FACTOR_SHIFT) // 1 << 2*96 diff --git a/pkg/liquidity-source/algebra/integral/errors.go b/pkg/liquidity-source/algebra/integral/errors.go index aa6901ba7..fb9060d0d 100644 --- a/pkg/liquidity-source/algebra/integral/errors.go +++ b/pkg/liquidity-source/algebra/integral/errors.go @@ -22,4 +22,6 @@ var ( ErrOutOfRangeOrInvalid = errors.New("value out of range or invalid") ErrLiquiditySub = errors.New("liquidity sub error") ErrLiquidityAdd = errors.New("liquidity add error") + ErrOverflow = errors.New("overflow") + ErrUnderflow = errors.New("underflow") ) diff --git a/pkg/liquidity-source/algebra/integral/math.go b/pkg/liquidity-source/algebra/integral/math.go index 415bda67f..c20a927df 100644 --- a/pkg/liquidity-source/algebra/integral/math.go +++ b/pkg/liquidity-source/algebra/integral/math.go @@ -1,26 +1,22 @@ package integral import ( - "errors" - "github.com/KyberNetwork/int256" v3Utils "github.com/KyberNetwork/uniswapv3-sdk-uint256/utils" "github.com/holiman/uint256" ) -func unsafeDivRoundingUp(x, y *uint256.Int) (*uint256.Int, error) { +func unsafeDivRoundingUp(x, y *uint256.Int) *uint256.Int { if y.Sign() == 0 { - return nil, errors.New("division by zero") + panic("division by zero") } - quotient := new(uint256.Int).Div(x, y) - - remainder := new(uint256.Int).Mod(x, y) + quotient, remainder := new(uint256.Int).DivMod(x, y, new(uint256.Int)) if remainder.Sign() > 0 { - quotient.Add(quotient, uONE) + quotient.AddUint64(quotient, 1) } - return quotient, nil + return quotient } func addDelta(x *uint256.Int, y *int256.Int) (*uint256.Int, error) { diff --git a/pkg/liquidity-source/algebra/integral/plugin.go b/pkg/liquidity-source/algebra/integral/plugin.go index 120445dcf..211c0c9c2 100644 --- a/pkg/liquidity-source/algebra/integral/plugin.go +++ b/pkg/liquidity-source/algebra/integral/plugin.go @@ -6,8 +6,7 @@ import ( "sync" "github.com/KyberNetwork/elastic-go-sdk/v2/utils" - "github.com/KyberNetwork/int256" - "github.com/KyberNetwork/logger" + "github.com/samber/lo" v3Utils "github.com/KyberNetwork/uniswapv3-sdk-uint256/utils" "github.com/holiman/uint256" @@ -33,12 +32,9 @@ func (s *TimepointStorage) Get(index uint16) Timepoint { defer s.mu.RUnlock() if v, ok := s.data[index]; ok { - logger.Debugf("access exists %v %v", index, v) return v } - logger.Debugf("access none %v", index) - return Timepoint{ Initialized: false, BlockTimestamp: 0, @@ -70,7 +66,8 @@ func (s *TimepointStorage) write(lastIndex uint16, blockTimestamp uint32, tick i oldestIndex = indexUpdated } - avgTick, windowStartIndex, err := s.getAverageTickCasted(blockTimestamp, tick, lastIndex, oldestIndex, last.BlockTimestamp, last.TickCumulative) + avgTick, windowStartIndex, err := s.getAverageTick(blockTimestamp, tick, lastIndex, oldestIndex, + last.BlockTimestamp, last.TickCumulative) if err != nil { return 0, 0, err } @@ -78,9 +75,7 @@ func (s *TimepointStorage) write(lastIndex uint16, blockTimestamp uint32, tick i if windowStartIndex == indexUpdated { windowStartIndex++ } - s.set(indexUpdated, createNewTimepoint(last, blockTimestamp, tick, avgTick, windowStartIndex)) - if oldestIndex == indexUpdated { oldestIndex++ } @@ -88,54 +83,41 @@ func (s *TimepointStorage) write(lastIndex uint16, blockTimestamp uint32, tick i return indexUpdated, oldestIndex, nil } -func (s *TimepointStorage) getAverageTickCasted( - time uint32, - tick int32, - lastIndex, oldestIndex uint16, - lastTimestamp uint32, - lastTickCumulative int64, -) (int32, uint16, error) { - avgTick, windowStartIndex, err := s.getAverageTick(time, tick, lastIndex, oldestIndex, lastTimestamp, lastTickCumulative) - if err != nil { - return 0, 0, err - } - - return int32(avgTick.Int64()), uint16(windowStartIndex.Uint64()), nil -} - -func (s *TimepointStorage) getAverageTick(currentTime uint32, tick int32, lastIndex, oldestIndex uint16, lastTimestamp uint32, lastTickCumulative int64) (*int256.Int, *uint256.Int, error) { +func (s *TimepointStorage) getAverageTick(currentTime uint32, tick int32, lastIndex, oldestIndex uint16, + lastTimestamp uint32, lastTickCumulative int64) (int32, uint16, error) { self := s.Get(oldestIndex) - oldestTimestamp, oldestTickCumulative := self.BlockTimestamp, self.TickCumulative - currentTickCumulative := lastTickCumulative + int64(tick)*int64(uint64(currentTime-lastTimestamp)) + currentTickCumulative := lastTickCumulative + int64(tick)*int64(currentTime-lastTimestamp) if !lteConsideringOverflow(oldestTimestamp, currentTime-WINDOW, currentTime) { if currentTime == oldestTimestamp { - return int256.NewInt(int64(tick)), uint256.NewInt(uint64(oldestIndex)), nil + return tick, oldestIndex, nil } - return int256.NewInt((currentTickCumulative - oldestTickCumulative) / int64(uint64(currentTime-oldestTimestamp))), uint256.NewInt(uint64(oldestIndex)), nil + avgTick := (currentTickCumulative - oldestTickCumulative) / int64(currentTime-oldestTimestamp) + return int32(avgTick), oldestIndex, nil } if lteConsideringOverflow(lastTimestamp, currentTime-WINDOW, currentTime) { - return int256.NewInt(int64(tick)), uint256.NewInt(uint64(lastIndex)), nil + return tick, lastIndex, nil } else { - tickCumulativeAtStart, windowStartIndex, err := s.getTickCumulativeAt(currentTime, WINDOW, tick, lastIndex, oldestIndex) + tickCumulativeAtStart, windowStartIndex, err := s.getTickCumulativeAt(currentTime, WINDOW, tick, + lastIndex, oldestIndex) if err != nil { - return nil, nil, err + return 0, 0, err } avgTick := (currentTickCumulative - tickCumulativeAtStart) / int64(WINDOW) - - return int256.NewInt(avgTick), windowStartIndex, nil + return int32(avgTick), windowStartIndex, nil } } -func (s *TimepointStorage) getTickCumulativeAt(time, secondsAgo uint32, tick int32, lastIndex, oldestIndex uint16) (int64, *uint256.Int, error) { +func (s *TimepointStorage) getTickCumulativeAt(time, secondsAgo uint32, tick int32, + lastIndex, oldestIndex uint16) (int64, uint16, error) { target := time - secondsAgo beforeOrAt, atOrAfter, samePoint, indexBeforeOrAt, err := s.getTimepointsAt(time, target, lastIndex, oldestIndex) if err != nil { - return 0, nil, err + return 0, 0, err } timestampBefore, tickCumulativeBefore := beforeOrAt.BlockTimestamp, beforeOrAt.TickCumulative @@ -144,34 +126,31 @@ func (s *TimepointStorage) getTickCumulativeAt(time, secondsAgo uint32, tick int } if samePoint { - return tickCumulativeBefore + int64(tick)*int64(uint64(target-timestampBefore)), indexBeforeOrAt, nil + return tickCumulativeBefore + int64(tick)*int64(target-timestampBefore), indexBeforeOrAt, nil } timestampAfter, tickCumulativeAfter := atOrAfter.BlockTimestamp, atOrAfter.TickCumulative if target == timestampAfter { - return tickCumulativeAfter, new(uint256.Int).Add(indexBeforeOrAt, uONE), nil + return tickCumulativeAfter, indexBeforeOrAt + 1, nil } timepointTimeDelta, targetDelta := timestampAfter-timestampBefore, target-timestampBefore - return tickCumulativeBefore + ((tickCumulativeAfter-tickCumulativeBefore)/int64(uint64(timepointTimeDelta)))*int64(uint64(targetDelta)), + return tickCumulativeBefore + ((tickCumulativeAfter-tickCumulativeBefore)/int64(timepointTimeDelta))*int64(targetDelta), indexBeforeOrAt, nil } -func (s *TimepointStorage) getTimepointsAt(currentTime, target uint32, lastIndex, oldestIndex uint16) ( - beforeOrAt, atOrAfter Timepoint, - samePoint bool, - indexBeforeOrAt *uint256.Int, - err error, -) { +func (s *TimepointStorage) getTimepointsAt(currentTime, target uint32, + lastIndex, oldestIndex uint16) (beforeOrAt, atOrAfter Timepoint, samePoint bool, indexBeforeOrAt uint16, + err error) { lastTimepoint := s.Get(lastIndex) lastTimepointTimestamp := lastTimepoint.BlockTimestamp windowStartIndex := lastTimepoint.WindowStartIndex if target == currentTime || lteConsideringOverflow(lastTimepointTimestamp, target, currentTime) { - return lastTimepoint, lastTimepoint, true, uint256.NewInt(uint64(lastIndex)), nil + return lastTimepoint, lastTimepoint, true, lastIndex, nil } var useHeuristic bool @@ -191,11 +170,11 @@ func (s *TimepointStorage) getTimepointsAt(currentTime, target uint32, lastIndex } if oldestTimestamp == target { - return oldestTimepoint, oldestTimepoint, true, uint256.NewInt(uint64(oldestIndex)), nil + return oldestTimepoint, oldestTimepoint, true, oldestIndex, nil } if lastIndex == oldestIndex+1 { - return oldestTimepoint, lastTimepoint, false, uint256.NewInt(uint64(oldestIndex)), nil + return oldestTimepoint, lastTimepoint, false, oldestIndex, nil } beforeOrAt, atOrAfter, indexBeforeOrAt = s.binarySearch(currentTime, target, lastIndex, oldestIndex, useHeuristic) @@ -203,11 +182,11 @@ func (s *TimepointStorage) getTimepointsAt(currentTime, target uint32, lastIndex return } -func (s *TimepointStorage) getAverageVolatility(currentTime uint32, tick int32, lastIndex, oldestIndex uint16) (*uint256.Int, error) { +// getAverageVolatility returns average volatility in the range from currentTime-WINDOW to currentTime +func (s *TimepointStorage) getAverageVolatility(currentTime uint32, tick int32, + lastIndex, oldestIndex uint16) (*uint256.Int, error) { lastTimepoint := s.Get(lastIndex) - timeAtLastTimepoint := lastTimepoint.BlockTimestamp == currentTime - lastCumulativeVolatility := lastTimepoint.VolatilityCumulative windowStartIndex := lastTimepoint.WindowStartIndex @@ -219,20 +198,22 @@ func (s *TimepointStorage) getAverageVolatility(currentTime uint32, tick int32, } } - oldestTimestamp := s.Get(oldestIndex).BlockTimestamp + oldestTimepoint := s.Get(oldestIndex) + oldestTimestamp := oldestTimepoint.BlockTimestamp if lteConsideringOverflow(oldestTimestamp, currentTime-WINDOW, currentTime) { var cumulativeVolatilityAtStart *uint256.Int if timeAtLastTimepoint { - oldestTimestamp, cumulativeVolatilityAtStart = s.Get(windowStartIndex).BlockTimestamp, s.Get(windowStartIndex).VolatilityCumulative - - timeDeltaBetweenPoints := s.Get(windowStartIndex+1).BlockTimestamp - oldestTimestamp + windowStart, windowStartPlus1 := s.Get(windowStartIndex), s.Get(windowStartIndex+1) + oldestTimestamp, cumulativeVolatilityAtStart = windowStart.BlockTimestamp, windowStart.VolatilityCumulative + timeDeltaBetweenPoints := windowStartPlus1.BlockTimestamp - oldestTimestamp - cumulativeVolatilityAtStart = cumulativeVolatilityAtStart.Add( + var tmp uint256.Int + cumulativeVolatilityAtStart = tmp.Add( cumulativeVolatilityAtStart, - new(uint256.Int).Div( - new(uint256.Int).Mul( - new(uint256.Int).Sub( - s.Get(windowStartIndex+1).VolatilityCumulative, + tmp.Div( + tmp.Mul( + tmp.Sub( + windowStartPlus1.VolatilityCumulative, cumulativeVolatilityAtStart, ), uint256.NewInt(uint64(currentTime-WINDOW-oldestTimestamp)), @@ -242,34 +223,36 @@ func (s *TimepointStorage) getAverageVolatility(currentTime uint32, tick int32, ) } else { var err error - cumulativeVolatilityAtStart, err = s.getVolatilityCumulativeAt(currentTime, WINDOW, tick, lastIndex, oldestIndex) - if err != nil { + if cumulativeVolatilityAtStart, err = s.getVolatilityCumulativeAt(currentTime, WINDOW, tick, + lastIndex, oldestIndex); err != nil { return nil, err } } - return new(uint256.Int).Div( - new(uint256.Int).Sub(lastCumulativeVolatility, cumulativeVolatilityAtStart), + return cumulativeVolatilityAtStart.Div( + cumulativeVolatilityAtStart.Sub(lastCumulativeVolatility, cumulativeVolatilityAtStart), uint256.NewInt(uint64(WINDOW)), ), nil } else if currentTime != oldestTimestamp { - oldestVolatilityCumulative := s.Get(oldestIndex).VolatilityCumulative + oldestVolatilityCumulative := oldestTimepoint.VolatilityCumulative unbiasedDenominator := currentTime - oldestTimestamp if unbiasedDenominator > 1 { unbiasedDenominator-- } - return new(uint256.Int).Div( - new(uint256.Int).Sub(lastCumulativeVolatility, oldestVolatilityCumulative), + var tmp uint256.Int + return tmp.Div( + tmp.Sub(lastCumulativeVolatility, oldestVolatilityCumulative), uint256.NewInt(uint64(unbiasedDenominator)), ), nil } - return nil, nil + return uZERO, nil } -func (s *TimepointStorage) getVolatilityCumulativeAt(time, secondsAgo uint32, tick int32, lastIndex, oldestIndex uint16) (*uint256.Int, error) { +func (s *TimepointStorage) getVolatilityCumulativeAt(time, secondsAgo uint32, tick int32, + lastIndex, oldestIndex uint16) (*uint256.Int, error) { target := time - secondsAgo beforeOrAt, atOrAfter, samePoint, _, err := s.getTimepointsAt(time, target, lastIndex, oldestIndex) @@ -283,19 +266,15 @@ func (s *TimepointStorage) getVolatilityCumulativeAt(time, secondsAgo uint32, ti } if samePoint { - avgTick, _, err := s.getAverageTickCasted(target, tick, lastIndex, oldestIndex, timestampBefore, beforeOrAt.TickCumulative) + avgTick, _, err := s.getAverageTick(target, tick, lastIndex, oldestIndex, timestampBefore, + beforeOrAt.TickCumulative) if err != nil { return nil, err } return new(uint256.Int).Add( volatilityCumulativeBefore, - volatilityOnRange(uint256.NewInt(uint64(target-timestampBefore)), - uint256.NewInt(uint64(tick)), - uint256.NewInt(uint64(tick)), - uint256.NewInt(uint64(beforeOrAt.AverageTick)), - uint256.NewInt(uint64(avgTick)), - ), + volatilityOnRange(target-timestampBefore, tick, tick, beforeOrAt.AverageTick, avgTick), ), nil } @@ -306,11 +285,12 @@ func (s *TimepointStorage) getVolatilityCumulativeAt(time, secondsAgo uint32, ti timepointTimeDelta, targetDelta := timestampAfter-timestampBefore, target-timestampBefore - return new(uint256.Int).Add( + var ret uint256.Int + return ret.Add( volatilityCumulativeBefore, - new(uint256.Int).Mul( - new(uint256.Int).Div( - new(uint256.Int).Sub( + ret.Mul( + ret.Div( + ret.Sub( volatilityCumulativeAfter, volatilityCumulativeBefore, ), @@ -330,69 +310,50 @@ func (s *TimepointStorage) getOldestIndex(lastIndex uint16) uint16 { return 0 } -func createNewTimepoint(last Timepoint, blockTimestamp uint32, tick, averageTick int32, windowStartIndex uint16) Timepoint { +func createNewTimepoint(last Timepoint, blockTimestamp uint32, tick, averageTick int32, + windowStartIndex uint16) Timepoint { delta := blockTimestamp - last.BlockTimestamp - volatility := volatilityOnRange(uint256.NewInt(uint64(delta)), uint256.NewInt(uint64(tick)), - uint256.NewInt(uint64(tick)), uint256.NewInt(uint64(last.AverageTick)), uint256.NewInt(uint64(averageTick))) - - last.Initialized = true - last.BlockTimestamp = blockTimestamp - last.TickCumulative += int64(tick) * int64(delta) - last.VolatilityCumulative = new(uint256.Int).Add(last.VolatilityCumulative, volatility) - last.Tick = tick - last.AverageTick = averageTick - last.WindowStartIndex = windowStartIndex + volatility := volatilityOnRange(delta, tick, tick, last.AverageTick, averageTick) - return last + return Timepoint{ + Initialized: true, + BlockTimestamp: blockTimestamp, + TickCumulative: last.TickCumulative + int64(tick)*int64(delta), + VolatilityCumulative: new(uint256.Int).Add(last.VolatilityCumulative, volatility), + Tick: tick, + AverageTick: averageTick, + WindowStartIndex: windowStartIndex, + } } -func volatilityOnRange(dt, tick0, tick1, avgTick0, avgTick1 *uint256.Int) *uint256.Int { - // (k = (tick1 - tick0) - (avgTick1 - avgTick0)) - k := new(uint256.Int).Sub(tick1, tick0) - k.Sub(k, new(uint256.Int).Sub(avgTick1, avgTick0)) - - // (b = (tick0 - avgTick0) * dt) - b := new(uint256.Int).Sub(tick0, avgTick0) - b.Mul(b, dt) +func volatilityOnRange(dt uint32, tick0, tick1, avgTick0, avgTick1 int32) *uint256.Int { + k := uint64((tick1 - tick0) - (avgTick1 - avgTick0)) + b := int64(tick0-avgTick0) * int64(dt) + sumOfSequence := uint64(dt) * (uint64(dt) + 1) - // sumOfSequence = dt * (dt + 1) - sumOfSequence := new(uint256.Int).Add(dt, uONE) - sumOfSequence.Mul(sumOfSequence, dt) + var tmp uint256.Int // sumOfSquares = sumOfSequence * (2 * dt + 1) - sumOfSquares := new(uint256.Int).Mul(uTWO, dt) - sumOfSquares.Add(sumOfSquares, uONE) - sumOfSquares.Mul(sumOfSquares, sumOfSequence) - - // k^2 - kSquared := new(uint256.Int).Mul(k, k) - - // b^2 - bSquared := new(uint256.Int).Mul(b, b) + sumOfSquares := uint256.NewInt(sumOfSequence) + sumOfSquares.Mul(sumOfSquares, tmp.SetUint64(2*uint64(dt)+1)) // k^2 * sumOfSquares - term1 := new(uint256.Int).Mul(kSquared, sumOfSquares) + term1 := sumOfSquares.Mul(tmp.SetUint64(k*k), sumOfSquares) // 6 * b * k * sumOfSequence - term2 := new(uint256.Int).Mul(b, k) - term2.Mul(term2, sumOfSequence) - term2.Mul(term2, uSIX) + term2 := uint256.NewInt(6 * k) + term2.Mul(term2, tmp.SetUint64(uint64(b))).Mul(term2, tmp.SetUint64(sumOfSequence)) // 6 * dt * b^2 - term3 := new(uint256.Int).Mul(bSquared, dt) - term3.Mul(term3, uSIX) - - // dt^2 - dtSquared := new(uint256.Int).Mul(dt, dt) + term3 := uint256.NewInt(uint64(6 * dt)) + term3.Mul(term3, tmp.SetUint64(uint64(b*b))) // Calculate volatility = (term1 + term2 + term3) / (6 * dt^2) - denominator := new(uint256.Int).Mul(dtSquared, uSIX) - numerator := new(uint256.Int).Add(term1, term2) - numerator.Add(numerator, term3) - - volatility := new(uint256.Int).Div(numerator, denominator) + numerator := term1.Add(term1, term2).Add(term1, term3) + denominator := term2.Mul(uSIX, term2.SetUint64(uint64(dt)*uint64(dt))) + volatility := numerator.Div(numerator, denominator) return volatility } @@ -402,102 +363,84 @@ func (s *TimepointStorage) binarySearch( upperIndex uint16, lowerIndex uint16, withHeuristic bool, -) (beforeOrAt, atOrAfter Timepoint, indexBeforeOrAt *uint256.Int) { - var right *uint256.Int - - left := uint256.NewInt(uint64(lowerIndex)) +) (beforeOrAt, atOrAfter Timepoint, indexBeforeOrAt uint16) { + left := uint32(lowerIndex) + right := uint32(upperIndex) if upperIndex < lowerIndex { - right = uint256.NewInt(uint64(upperIndex) + UINT16_MODULO) - } else { - right = uint256.NewInt(uint64(upperIndex)) + right += UINT16_MODULO } - return s.binarySearchInternal(currentTime, target, left, right, withHeuristic) + beforeOrAt, atOrAfter, left = s.binarySearchInternal(currentTime, target, left, right, withHeuristic) + return beforeOrAt, atOrAfter, uint16(left) } -func (s *TimepointStorage) binarySearchInternal( - currentTime uint32, - target uint32, - left, - right *uint256.Int, - withHeuristic bool, -) (beforeOrAt, atOrAfter Timepoint, indexBeforeOrAt *uint256.Int) { - if withHeuristic && new(uint256.Int).Sub(right, left).Cmp(uTWO) > 0 { - indexBeforeOrAt = new(uint256.Int).Add(left, uONE) +func (s *TimepointStorage) binarySearchInternal(currentTime, target, left, right uint32, + withHeuristic bool) (beforeOrAt, atOrAfter Timepoint, indexBeforeOrAt uint32) { + if withHeuristic && right-left > 2 { + indexBeforeOrAt = left + 1 } else { - indexBeforeOrAt = new(uint256.Int).Rsh( - new(uint256.Int).Add(left, right), - 1, - ) + indexBeforeOrAt = (left + right) >> 1 } - beforeOrAt = s.Get(uint16(indexBeforeOrAt.Uint64())) + beforeOrAt = s.Get(uint16(indexBeforeOrAt)) atOrAfter = beforeOrAt - var firstIteration bool = true + firstIteration := true for { initializedBefore, timestampBefore := beforeOrAt.Initialized, beforeOrAt.BlockTimestamp if initializedBefore { if lteConsideringOverflow(timestampBefore, target, currentTime) { - atOrAfter = s.Get(uint16(indexBeforeOrAt.Uint64() + 1)) + atOrAfter = s.Get(uint16(indexBeforeOrAt + 1)) initializedAfter, timestampAfter := atOrAfter.Initialized, atOrAfter.BlockTimestamp if initializedAfter { if lteConsideringOverflow(target, timestampAfter, currentTime) { return beforeOrAt, atOrAfter, indexBeforeOrAt } - left = new(uint256.Int).Add(indexBeforeOrAt, uONE) + left = indexBeforeOrAt + 1 } else { return beforeOrAt, beforeOrAt, indexBeforeOrAt } } else { - right = new(uint256.Int).Sub(indexBeforeOrAt, uONE) + right = indexBeforeOrAt - 1 } } else { - left = new(uint256.Int).Add(indexBeforeOrAt, uONE) + left = indexBeforeOrAt + 1 } - useHeuristic := firstIteration && withHeuristic && left.Cmp(new(uint256.Int).Add(indexBeforeOrAt, uONE)) == 0 - if useHeuristic && new(uint256.Int).Sub(right, left).Cmp(uSIXTEEN) > 0 { - indexBeforeOrAt = indexBeforeOrAt.Add(left, uEIGHT) + useHeuristic := firstIteration && withHeuristic && left == indexBeforeOrAt+1 + if useHeuristic && right-left > 16 { + indexBeforeOrAt = left + 8 } else { - indexBeforeOrAt = indexBeforeOrAt.Rsh( - new(uint256.Int).Add(left, right), - 1, - ) + indexBeforeOrAt = (left + right) >> 1 } - beforeOrAt = s.Get(uint16(indexBeforeOrAt.Uint64())) + beforeOrAt = s.Get(uint16(indexBeforeOrAt)) firstIteration = false } } -func calculateFeeFactors(currentTick, lastTick int32, priceChangeFactor uint16) (FeeFactors, error) { - tickDelta := new(int256.Int).Sub(int256.NewInt(int64(currentTick)), int256.NewInt(int64(lastTick))) - if tickDelta.Int64() > int64(utils.MaxTick) { - tickDelta = int256.NewInt(int64(utils.MaxTick)) - } else if tickDelta.Int64() < int64(utils.MinTick) { - tickDelta = int256.NewInt(int64(utils.MinTick)) - } +func calculateFeeFactors(currentTick, lastTick int32, priceChangeFactor uint16) (*SlidingFeeConfig, error) { + tickDelta := lo.Clamp(currentTick-lastTick, utils.MinTick, utils.MaxTick) - sqrtPriceDelta, err := v3Utils.GetSqrtRatioAtTick(int(tickDelta.Uint64())) + var sqrtPriceDelta v3Utils.Uint160 + err := v3Utils.GetSqrtRatioAtTickV2(int(tickDelta), &sqrtPriceDelta) if err != nil { - return FeeFactors{}, err + return nil, err } - sqrtPriceDelta256 := uint256.MustFromBig(sqrtPriceDelta) - - priceRatioSquared, err := v3Utils.MulDiv(sqrtPriceDelta256, sqrtPriceDelta256, DOUBLE_FEE_MULTIPLIER) + priceRatioSquared, err := v3Utils.MulDiv(&sqrtPriceDelta, &sqrtPriceDelta, DOUBLE_FEE_MULTIPLIER) if err != nil { - return FeeFactors{}, err + return nil, err } - priceChangeRatio := new(uint256.Int).Sub(priceRatioSquared, BASE_FEE_MULTIPLIER) + priceChangeRatio := priceRatioSquared.Sub(priceRatioSquared, BASE_FEE_MULTIPLIER) - factor := new(uint256.Int).SetUint64(uint64(priceChangeFactor)) - feeFactorImpact := new(uint256.Int).Div(new(uint256.Int).Mul(priceChangeRatio, factor), uint256.NewInt(FACTOR_DENOMINATOR)) + factor := uint256.NewInt(uint64(priceChangeFactor)) + feeFactorImpact := priceChangeRatio.Div(priceChangeRatio.Mul(priceChangeRatio, factor), + uint256.NewInt(FACTOR_DENOMINATOR)) - feeFactors := FeeFactors{ + feeFactors := &SlidingFeeConfig{ ZeroToOneFeeFactor: BASE_FEE_MULTIPLIER, OneToZeroFeeFactor: BASE_FEE_MULTIPLIER, } @@ -506,10 +449,10 @@ func calculateFeeFactors(currentTick, lastTick int32, priceChangeFactor uint16) twoShift := DOUBLE_FEE_MULTIPLIER - if newZeroToOneFeeFactor.Cmp(uZERO) > 0 && newZeroToOneFeeFactor.Cmp(twoShift) < 0 { + if newZeroToOneFeeFactor.Sign() > 0 && newZeroToOneFeeFactor.Cmp(twoShift) < 0 { feeFactors.ZeroToOneFeeFactor = newZeroToOneFeeFactor feeFactors.OneToZeroFeeFactor = new(uint256.Int).Add(feeFactors.OneToZeroFeeFactor, feeFactorImpact) - } else if newZeroToOneFeeFactor.Cmp(uZERO) <= 0 { + } else if newZeroToOneFeeFactor.Sign() <= 0 { feeFactors.ZeroToOneFeeFactor = uZERO feeFactors.OneToZeroFeeFactor = twoShift } else { @@ -537,10 +480,10 @@ func getOutputTokenDelta10(to, from, liquidity *uint256.Int) (*uint256.Int, erro } func getToken0Delta(priceLower, priceUpper, liquidity *uint256.Int, roundUp bool) (*uint256.Int, error) { - priceDelta := new(uint256.Int).Sub(priceUpper, priceLower) - if priceDelta.Cmp(priceUpper) >= 0 { - return nil, errors.New("price delta must be smaller than price upper") + if priceUpper.Cmp(priceLower) < 0 { + return nil, errors.New("price upper must not be less than price lower") } + priceDelta := new(uint256.Int).Sub(priceUpper, priceLower) liquidityShifted := new(uint256.Int).Lsh(liquidity, RESOLUTION) @@ -550,41 +493,31 @@ func getToken0Delta(priceLower, priceUpper, liquidity *uint256.Int, roundUp bool return nil, err } - token0Delta, err := unsafeDivRoundingUp(division, priceLower) - if err != nil { - return nil, err - } - - return token0Delta, nil - } else { - mulDivResult, err := v3Utils.MulDiv(priceDelta, liquidityShifted, priceUpper) - if err != nil { - return nil, err - } - - token0Delta := new(uint256.Int).Div(mulDivResult, priceLower) + return unsafeDivRoundingUp(division, priceLower), nil + } - return token0Delta, nil + mulDivResult, overflow := priceDelta.MulDivOverflow(priceDelta, liquidityShifted, priceUpper) + if overflow { + return nil, ErrOverflow } + return mulDivResult.Div(mulDivResult, priceLower), nil } func getToken1Delta(priceLower, priceUpper, liquidity *uint256.Int, roundUp bool) (*uint256.Int, error) { if priceUpper.Cmp(priceLower) < 0 { - return nil, errors.New("price upper must be greater or equal than price lower") + return nil, errors.New("price upper must not be less than price lower") } - priceDelta := new(uint256.Int).Sub(priceUpper, priceLower) if roundUp { return v3Utils.MulDivRoundingUp(priceDelta, liquidity, Q96) - } else { - token1Delta, err := v3Utils.MulDiv(priceDelta, liquidity, Q96) - if err != nil { - return nil, err - } + } - return token1Delta, nil + token1Delta, overflow := priceDelta.MulDivOverflow(priceDelta, liquidity, Q96) + if overflow { + return nil, ErrOverflow } + return token1Delta, nil } func getNewPriceAfterInput(price, liquidity, input *uint256.Int, zeroToOne bool) (*uint256.Int, error) { @@ -613,94 +546,71 @@ func getNewPrice( liquidityShifted := new(uint256.Int).Lsh(liquidity, RESOLUTION) if zeroToOne == fromInput { - if fromInput { - product := new(uint256.Int).Mul(amount, price) - if new(uint256.Int).Div(product, amount).Cmp(price) != 0 { - return nil, fmt.Errorf("product overflow") - } - - denominator := new(uint256.Int).Add(liquidityShifted, product) - if denominator.Cmp(liquidityShifted) < 0 { - return nil, fmt.Errorf("denominator underflow") - } - - resultPrice, err := v3Utils.MulDivRoundingUp(liquidityShifted, price, denominator) - if err != nil { - return nil, err - } + product, overflow := new(uint256.Int).MulOverflow(amount, price) + if overflow { + return nil, ErrOverflow + } - if resultPrice.BitLen() > 160 { - return nil, fmt.Errorf("resulting price exceeds 160 bits") + denominator := new(uint256.Int) + if fromInput { + if denominator, overflow = denominator.AddOverflow(liquidityShifted, product); overflow { + return nil, ErrOverflow } - - return resultPrice, nil } else { - product := new(uint256.Int).Mul(amount, price) - if new(uint256.Int).Div(product, amount).Cmp(price) != 0 { - return nil, fmt.Errorf("product overflow") + if denominator, overflow = denominator.SubOverflow(liquidityShifted, product); overflow { + return nil, ErrUnderflow } - if liquidityShifted.Cmp(product) <= 0 { - return nil, fmt.Errorf("denominator underflow") - } - - denominator := new(uint256.Int).Sub(liquidityShifted, product) - - resultPrice, err := v3Utils.MulDivRoundingUp(liquidityShifted, price, denominator) - if err != nil { - return nil, err - } - if resultPrice.BitLen() > 160 { - return nil, fmt.Errorf("resulting price exceeds 160 bits") - } - - return resultPrice, nil } + resultPrice, err := v3Utils.MulDivRoundingUp(liquidityShifted, price, denominator) + if err != nil { + return nil, err + } else if resultPrice.BitLen() > 160 { + return nil, ErrOverflow + } + + return resultPrice, nil } else { if fromInput { var ( - shiftedAmount = new(uint256.Int) - err error + shiftedAmount *uint256.Int + overflow bool ) - if amount.Cmp(new(uint256.Int).Sub(new(uint256.Int).Lsh(uONE, 160), uONE)) <= 0 { + if amount.BitLen() < 160 { shiftedAmount = new(uint256.Int).Lsh(amount, RESOLUTION) shiftedAmount.Div(shiftedAmount, liquidity) } else { - shiftedAmount, err = v3Utils.MulDiv(amount, new(uint256.Int).Lsh(uONE, RESOLUTION), liquidity) - if err != nil { - return nil, err + shiftedAmount, overflow = new(uint256.Int).MulDivOverflow(amount, + new(uint256.Int).Lsh(uONE, RESOLUTION), liquidity) + if overflow { + return nil, ErrOverflow } } - resultPrice := new(uint256.Int).Add(price, shiftedAmount) - if resultPrice.BitLen() > 160 { - return nil, fmt.Errorf("resulting price exceeds 160 bits") + resultPrice, overflow := shiftedAmount.AddOverflow(price, shiftedAmount) + if overflow || resultPrice.BitLen() > 160 { + return nil, ErrOverflow } return resultPrice, nil } else { var ( - quotient *uint256.Int - err error + shiftedAmount *uint256.Int + err error ) - if amount.Cmp(new(uint256.Int).Sub(new(uint256.Int).Lsh(uONE, 160), uONE)) <= 0 { - shiftedAmount := new(uint256.Int).Lsh(amount, RESOLUTION) - quotient, err = unsafeDivRoundingUp(shiftedAmount, liquidity) - if err != nil { - return nil, err - } + if amount.BitLen() < 160 { + shiftedAmount = new(uint256.Int).Lsh(amount, RESOLUTION) + shiftedAmount = unsafeDivRoundingUp(shiftedAmount, liquidity) } else { - quotient, err = v3Utils.MulDivRoundingUp(amount, new(uint256.Int).Lsh(uONE, RESOLUTION), liquidity) + shiftedAmount, err = v3Utils.MulDivRoundingUp(amount, new(uint256.Int).Lsh(uONE, RESOLUTION), liquidity) if err != nil { return nil, err } } - if price.Cmp(quotient) <= 0 { - return nil, fmt.Errorf("price must be greater than quotient") - } - - resultPrice := new(uint256.Int).Sub(price, quotient) - if resultPrice.BitLen() > 160 { - return nil, fmt.Errorf("resulting price exceeds 160 bits") + resultPrice, overflow := shiftedAmount.SubOverflow(price, shiftedAmount) + if overflow { + return nil, ErrUnderflow + } else if resultPrice.BitLen() > 160 { + return nil, ErrOverflow } return resultPrice, nil } diff --git a/pkg/liquidity-source/algebra/integral/pool_simulator.go b/pkg/liquidity-source/algebra/integral/pool_simulator.go index 09a67cbfa..bce47fd77 100644 --- a/pkg/liquidity-source/algebra/integral/pool_simulator.go +++ b/pkg/liquidity-source/algebra/integral/pool_simulator.go @@ -5,6 +5,7 @@ import ( "fmt" "math/big" "strings" + "sync" "time" "github.com/KyberNetwork/int256" @@ -14,6 +15,7 @@ import ( "github.com/daoleno/uniswapv3-sdk/utils" "github.com/goccy/go-json" "github.com/holiman/uint256" + "github.com/samber/lo" "github.com/KyberNetwork/kyberswap-dex-lib/pkg/entity" "github.com/KyberNetwork/kyberswap-dex-lib/pkg/source/pool" @@ -32,28 +34,15 @@ type PoolSimulator struct { tickMax int32 tickSpacing int - timepoints *TimepointStorage - volatilityOracle *VotatilityOraclePlugin - dynamicFee *DynamicFeePlugin - slidingFee *SlidingFeePlugin + timepoints *TimepointStorage + volatilityOracle *VolatilityOraclePlugin + dynamicFee *DynamicFeeConfig + slidingFee *SlidingFeeConfig + writeTimePointLock *sync.RWMutex useBasePluginV2 bool } -type VotatilityOraclePlugin struct { - TimepointIndex uint16 - LastTimepointTimestamp uint32 - IsInitialized bool -} - -type DynamicFeePlugin struct { - FeeConfig FeeConfiguration -} - -type SlidingFeePlugin struct { - FeeFactors FeeFactors -} - func NewPoolSimulator(entityPool entity.Pool, defaultGas int64) (*PoolSimulator, error) { var extra Extra if err := json.Unmarshal([]byte(entityPool.Extra), &extra); err != nil { @@ -98,24 +87,24 @@ func NewPoolSimulator(entityPool entity.Pool, defaultGas int64) (*PoolSimulator, Type: entityPool.Type, Tokens: tokens, Reserves: reserves, - Checked: false, BlockNumber: entityPool.BlockNumber, } return &PoolSimulator{ - Pool: pool.Pool{Info: info}, - globalState: extra.GlobalState, - liquidity: uint256.MustFromBig(extra.Liquidity), - ticks: ticks, - gas: defaultGas, - tickMin: int32(tickMin), - tickMax: int32(tickMax), - tickSpacing: int(extra.TickSpacing), - timepoints: timepoints, - volatilityOracle: &extra.VotatilityOracle, - dynamicFee: &extra.DynamicFee, - slidingFee: &extra.SlidingFee, - useBasePluginV2: staticExtra.UseBasePluginV2, + Pool: pool.Pool{Info: info}, + globalState: extra.GlobalState, + liquidity: uint256.MustFromBig(extra.Liquidity), + ticks: ticks, + gas: defaultGas, + tickMin: int32(tickMin), + tickMax: int32(tickMax), + tickSpacing: int(extra.TickSpacing), + timepoints: timepoints, + volatilityOracle: &extra.VolatilityOracle, + dynamicFee: &extra.DynamicFee, + slidingFee: &extra.SlidingFee, + writeTimePointLock: new(sync.RWMutex), + useBasePluginV2: staticExtra.UseBasePluginV2, }, nil } @@ -161,7 +150,10 @@ func (p *PoolSimulator) CalcAmountOut(param pool.CalcAmountOutParams) (*pool.Cal return nil, err } - amountRequired := int256.MustFromBig(tokenAmountIn.Amount) + amountRequired, err := int256.FromBig(tokenAmountIn.Amount) + if err != nil { + return nil, ErrInvalidAmountRequired + } amount0, amount1, currentPrice, currentTick, currentLiquidity, fees, err := p.calculateSwap( overrideFee, pluginFee, zeroForOne, amountRequired, priceLimit) @@ -185,7 +177,7 @@ func (p *PoolSimulator) CalcAmountOut(param pool.CalcAmountOutParams) (*pool.Cal amountOut = new(int256.Int).Neg(amount0) } - if amountOut.Cmp(ZERO) == 0 { + if amountOut.IsZero() { return nil, ErrZeroAmountOut } @@ -196,7 +188,7 @@ func (p *PoolSimulator) CalcAmountOut(param pool.CalcAmountOutParams) (*pool.Cal }, Fee: &pool.TokenAmount{ Token: param.TokenAmountIn.Token, - Amount: new(big.Int).Add(fees.communityFeeAmount.ToBig(), fees.pluginFeeAmount.ToBig()), + Amount: new(uint256.Int).Add(fees.communityFeeAmount, fees.pluginFeeAmount).ToBig(), }, Gas: p.gas, SwapInfo: StateUpdate{ @@ -206,10 +198,19 @@ func (p *PoolSimulator) CalcAmountOut(param pool.CalcAmountOutParams) (*pool.Cal }, nil } +func (p *PoolSimulator) CloneState() pool.IPoolSimulator { + cloned := *p + cloned.liquidity = p.liquidity.Clone() + cloned.globalState.Price = p.globalState.Price.Clone() + cloned.writeTimePointLock = new(sync.RWMutex) + return &cloned +} + func (p *PoolSimulator) UpdateBalance(params pool.UpdateBalanceParams) { si, ok := params.SwapInfo.(StateUpdate) if !ok { - logger.Warnf("failed to UpdateBalance for Algebra %v %v pool, wrong swapInfo type", p.Info.Address, p.Info.Exchange) + logger.Warnf("failed to UpdateBalance for Algebra %v %v pool, wrong swapInfo type", + p.Info.Address, p.Info.Exchange) return } p.liquidity = new(uint256.Int).Set(si.Liquidity) @@ -236,71 +237,77 @@ func (p *PoolSimulator) getSqrtPriceLimit(zeroForOne bool) (*uint256.Int, error) tickLimit = p.tickMax } - sqrtPriceX96LimitBig, err := v3Utils.GetSqrtRatioAtTick(int(tickLimit)) + var sqrtPriceX96Limit v3Utils.Uint160 + err := v3Utils.GetSqrtRatioAtTickV2(int(tickLimit), &sqrtPriceX96Limit) if err != nil { return nil, err } - sqrtPriceX96Limit := uint256.MustFromBig(sqrtPriceX96LimitBig) - if zeroForOne { - sqrtPriceX96Limit = new(uint256.Int).Add(sqrtPriceX96Limit, uONE) // = (sqrtPrice at minTick) + 1 + sqrtPriceX96Limit.AddUint64(&sqrtPriceX96Limit, 1) // = (sqrtPrice at minTick) + 1 } else { - sqrtPriceX96Limit = new(uint256.Int).Sub(sqrtPriceX96Limit, uONE) // = (sqrtPrice at maxTick) - 1 + sqrtPriceX96Limit.SubUint64(&sqrtPriceX96Limit, 1) // = (sqrtPrice at maxTick) - 1 } - return sqrtPriceX96Limit, nil + return &sqrtPriceX96Limit, nil } -func (p *PoolSimulator) writeTimepoint() error { - lastIndex := p.volatilityOracle.TimepointIndex - lastTimepointTimestamp := p.volatilityOracle.LastTimepointTimestamp - - if !p.volatilityOracle.IsInitialized { +// writeTimepoint locks and writes timepoint only once per second, triggers onWrite only if said write happened +func (p *PoolSimulator) writeTimepoint(onWrite func() error) error { + volatilityOracle := p.volatilityOracle + if !volatilityOracle.IsInitialized { return ErrNotInitialized } - currentTimestamp := time.Now().Unix() - if lastTimepointTimestamp == uint32(currentTimestamp) { + p.writeTimePointLock.RLock() + done := volatilityOracle.UpdatedWithinThisBlock + p.writeTimePointLock.RUnlock() + if done { return nil } + p.writeTimePointLock.Lock() + defer p.writeTimePointLock.Unlock() + if volatilityOracle.UpdatedWithinThisBlock { // check again for other concurrent writes + return nil + } + + lastIndex := volatilityOracle.TimepointIndex + currentTimestamp := uint32(time.Now().Unix()) tick := p.globalState.Tick - newLastIndex, _, err := p.timepoints.write(lastIndex, uint32(currentTimestamp), tick) + newLastIndex, _, err := p.timepoints.write(lastIndex, currentTimestamp, tick) if err != nil { return err } - p.volatilityOracle.TimepointIndex = newLastIndex - p.volatilityOracle.LastTimepointTimestamp = uint32(currentTimestamp) + volatilityOracle.TimepointIndex = newLastIndex + volatilityOracle.LastTimepointTimestamp = currentTimestamp + volatilityOracle.UpdatedWithinThisBlock = true - return nil + if onWrite == nil { + return nil + } + return onWrite() } func (p *PoolSimulator) beforeSwapV1() (uint32, uint32, error) { - if p.globalState.PluginConfig&BEFORE_SWAP_FLAG != 0 { - if err := p.writeTimepoint(); err != nil { - return 0, 0, err - } - - votatilityAverage, err := p.getAverageVotatilityLast() + if p.globalState.PluginConfig&BEFORE_SWAP_FLAG == 0 { + return 0, 0, nil + } + return 0, 0, p.writeTimepoint(func() error { + volatilityLast, err := p.getAverageVolatilityLast() if err != nil { - return 0, 0, err + return err } - var newFee uint16 - if p.dynamicFee.FeeConfig.Alpha1|p.dynamicFee.FeeConfig.Alpha2 == 0 { - newFee = p.dynamicFee.FeeConfig.BaseFee + if p.dynamicFee.Alpha1 == 0 && p.dynamicFee.Alpha2 == 0 { + newFee = p.dynamicFee.BaseFee } else { - newFee = getFee(votatilityAverage, p.dynamicFee.FeeConfig) - } - - if newFee != p.globalState.LastFee { - p.globalState.LastFee = newFee + newFee = getFee(volatilityLast, p.dynamicFee) } - } - - return 0, 0, nil + p.globalState.LastFee = newFee + return nil + }) } func (p *PoolSimulator) beforeSwapV2(zeroToOne bool) (uint32, uint32, error) { @@ -312,7 +319,7 @@ func (p *PoolSimulator) beforeSwapV2(zeroToOne bool) (uint32, uint32, error) { return 0, 0, err } - if err := p.writeTimepoint(); err != nil { + if err := p.writeTimepoint(nil); err != nil { return 0, 0, err } @@ -320,37 +327,30 @@ func (p *PoolSimulator) beforeSwapV2(zeroToOne bool) (uint32, uint32, error) { } func (p *PoolSimulator) getFeeAndUpdateFactors(zeroToOne bool, currentTick, lastTick int32) (uint16, error) { - var currentFeeFactors FeeFactors + var currentFeeFactors *SlidingFeeConfig if currentTick != lastTick { - currentFeeFactors, err := calculateFeeFactors(currentTick, lastTick, s_priceChangeFactor) + var err error + currentFeeFactors, err = calculateFeeFactors(currentTick, lastTick, s_priceChangeFactor) if err != nil { return 0, err } - p.slidingFee.FeeFactors = currentFeeFactors + p.slidingFee = currentFeeFactors } else { - currentFeeFactors = p.slidingFee.FeeFactors + currentFeeFactors = p.slidingFee } var adjustedFee *uint256.Int baseFeeBig := uint256.NewInt(s_baseFee) + adjustedFee = baseFeeBig.Rsh( + baseFeeBig.Mul(baseFeeBig, + lo.Ternary(zeroToOne, currentFeeFactors.ZeroToOneFeeFactor, currentFeeFactors.OneToZeroFeeFactor), + ), + FEE_FACTOR_SHIFT, + ) - if zeroToOne { - adjustedFee = new(uint256.Int).Rsh( - new(uint256.Int).Mul(baseFeeBig, currentFeeFactors.ZeroToOneFeeFactor), - FEE_FACTOR_SHIFT, - ) - } else { - adjustedFee = new(uint256.Int).Rsh( - new(uint256.Int).Mul(baseFeeBig, currentFeeFactors.OneToZeroFeeFactor), - FEE_FACTOR_SHIFT, - ) - } - - if adjustedFee.Cmp(MAX_UINT16) > 0 { - adjustedFee.Set(MAX_UINT16) - } else if adjustedFee.Sign() == 0 { + if adjustedFee.Cmp(MAX_UINT16) > 0 || adjustedFee.IsZero() { adjustedFee.Set(MAX_UINT16) } @@ -360,35 +360,29 @@ func (p *PoolSimulator) getFeeAndUpdateFactors(zeroToOne bool, currentTick, last func (p *PoolSimulator) getLastTick() int32 { lastTimepointIndex := p.volatilityOracle.TimepointIndex lastTimepoint := p.timepoints.Get(lastTimepointIndex) - return lastTimepoint.Tick } -func (p *PoolSimulator) getAverageVotatilityLast() (*uint256.Int, error) { - currentTimestamp := uint32(time.Now().Unix()) - +func (p *PoolSimulator) getAverageVolatilityLast() (*uint256.Int, error) { + currentTimestamp := p.volatilityOracle.LastTimepointTimestamp tick := p.globalState.Tick lastTimepointIndex := p.volatilityOracle.TimepointIndex oldestIndex := p.timepoints.getOldestIndex(lastTimepointIndex) - votatilityAverage, err := p.timepoints.getAverageVolatility(currentTimestamp, tick, lastTimepointIndex, oldestIndex) + volatilityAverage, err := p.timepoints.getAverageVolatility(currentTimestamp, tick, lastTimepointIndex, oldestIndex) if err != nil { return nil, err } - return votatilityAverage, nil + return volatilityAverage, nil } -func (p *PoolSimulator) calculateSwap(overrideFee, pluginFee uint32, zeroToOne bool, amountRequired *int256.Int, limitSqrtPrice *uint256.Int) ( - *int256.Int, *int256.Int, *uint256.Int, int32, *uint256.Int, FeesAmount, error) { - if amountRequired.Sign() == 0 { +func (p *PoolSimulator) calculateSwap(overrideFee, pluginFee uint32, zeroToOne bool, amountRequired *int256.Int, + limitSqrtPrice *uint256.Int) (*int256.Int, *int256.Int, *uint256.Int, int32, *uint256.Int, FeesAmount, error) { + if amountRequired.IsZero() { return nil, nil, nil, 0, nil, FeesAmount{}, ErrZeroAmountRequired } - if amountRequired.Cmp(MIN_INT256) == 0 { - return nil, nil, nil, 0, nil, FeesAmount{}, ErrInvalidAmountRequired - } - var cache SwapCalculationCache var fees = FeesAmount{ communityFeeAmount: new(uint256.Int), @@ -396,7 +390,7 @@ func (p *PoolSimulator) calculateSwap(overrideFee, pluginFee uint32, zeroToOne b } cache.amountRequiredInitial = amountRequired - cache.exactInput = amountRequired.Sign() > 0 + cache.exactInput = amountRequired.IsPositive() cache.pluginFee = pluginFee cache.amountCalculated = new(int256.Int) @@ -407,7 +401,7 @@ func (p *PoolSimulator) calculateSwap(overrideFee, pluginFee uint32, zeroToOne b cache.fee = uint32(p.globalState.LastFee) cache.communityFee = uint256.NewInt(uint64(p.globalState.CommunityFee)) - if currentPrice.Sign() == 0 { + if currentPrice.IsZero() { return nil, nil, nil, 0, nil, FeesAmount{}, ErrNotInitialized } @@ -435,7 +429,7 @@ func (p *PoolSimulator) calculateSwap(overrideFee, pluginFee uint32, zeroToOne b var step PriceMovementCache initializedTick := currentTick - // swap until there is remaining input or output tokens or we reach the price limit + // swap until there is remaining input or output tokens, or we reach the price limit. // limit by maxSwapLoop to make sure we won't loop infinitely because of a bug somewhere for i := 0; i < maxSwapLoop; i++ { var ( @@ -443,7 +437,8 @@ func (p *PoolSimulator) calculateSwap(overrideFee, pluginFee uint32, zeroToOne b err error ) - nextTick, step.initialized, err = p.ticks.NextInitializedTickWithinOneWord(int(initializedTick), zeroToOne, p.tickSpacing) + nextTick, step.initialized, err = p.ticks.NextInitializedTickWithinOneWord(int(initializedTick), zeroToOne, + p.tickSpacing) if err != nil { return nil, nil, nil, 0, nil, FeesAmount{}, err } @@ -471,7 +466,8 @@ func (p *PoolSimulator) calculateSwap(overrideFee, pluginFee uint32, zeroToOne b targetPrice = limitSqrtPrice } - currentPrice, step.input, step.output, step.feeAmount, err = movePriceTowardsTarget(zeroToOne, currentPrice, targetPrice, currentLiquidity, amountRequired, cache.fee) + currentPrice, step.input, step.output, step.feeAmount, err = movePriceTowardsTarget(zeroToOne, currentPrice, + targetPrice, currentLiquidity, amountRequired, cache.fee) if err != nil { return nil, nil, nil, 0, nil, FeesAmount{}, err } @@ -495,7 +491,8 @@ func (p *PoolSimulator) calculateSwap(overrideFee, pluginFee uint32, zeroToOne b } if cache.pluginFee > 0 && cache.fee > 0 { - delta, err := v3Utils.MulDiv(step.feeAmount, uint256.NewInt(uint64(cache.pluginFee)), uint256.NewInt(uint64(cache.fee))) + delta, err := v3Utils.MulDiv(step.feeAmount, uint256.NewInt(uint64(cache.pluginFee)), + uint256.NewInt(uint64(cache.fee))) if err != nil { return nil, nil, nil, 0, nil, FeesAmount{}, err } @@ -549,7 +546,7 @@ func (p *PoolSimulator) calculateSwap(overrideFee, pluginFee uint32, zeroToOne b break } - if amountRequired.Sign() == 0 || currentPrice.Cmp(limitSqrtPrice) == 0 { + if amountRequired.IsZero() || currentPrice.Cmp(limitSqrtPrice) == 0 { break } } @@ -589,10 +586,12 @@ func movePriceTowardsTarget( resultPrice, input, output, feeAmount *uint256.Int ) + feeDenoMinusFee := new(uint256.Int).SubUint64(FEE_DENOMINATOR, uint64(fee)) if amountAvailable.Sign() >= 0 { - amountAvailableAfterFee, err := v3Utils.MulDiv(amountAvailable, new(uint256.Int).Sub(FEE_DENOMINATOR, uint256.NewInt(uint64(fee))), FEE_DENOMINATOR) - if err != nil { - return nil, nil, nil, nil, err + amountAvailableAfterFee, overflow := new(uint256.Int).MulDivOverflow(amountAvailable, feeDenoMinusFee, + FEE_DENOMINATOR) + if overflow { + return nil, nil, nil, nil, ErrOverflow } input, err = getInputTokenAmount(targetPrice, currentPrice, liquidity) @@ -602,7 +601,7 @@ func movePriceTowardsTarget( if amountAvailableAfterFee.Cmp(input) >= 0 { resultPrice = targetPrice - feeAmount, err = v3Utils.MulDivRoundingUp(input, uint256.NewInt(uint64(fee)), new(uint256.Int).Sub(FEE_DENOMINATOR, uint256.NewInt(uint64(fee)))) + feeAmount, err = v3Utils.MulDivRoundingUp(input, uint256.NewInt(uint64(fee)), feeDenoMinusFee) if err != nil { return nil, nil, nil, nil, err } @@ -665,7 +664,8 @@ func movePriceTowardsTarget( return nil, nil, nil, nil, err } - feeAmount, err = v3Utils.MulDivRoundingUp(input, uint256.NewInt(uint64(fee)), new(uint256.Int).Sub(FEE_DENOMINATOR, uint256.NewInt(uint64(fee)))) + feeAmount, err = v3Utils.MulDivRoundingUp(input, uint256.NewInt(uint64(fee)), + feeDenoMinusFee) if err != nil { return nil, nil, nil, nil, err } diff --git a/pkg/liquidity-source/algebra/integral/pool_simulator_test.go b/pkg/liquidity-source/algebra/integral/pool_simulator_test.go index 313af43ae..e55dec722 100644 --- a/pkg/liquidity-source/algebra/integral/pool_simulator_test.go +++ b/pkg/liquidity-source/algebra/integral/pool_simulator_test.go @@ -3,10 +3,13 @@ package integral import ( "encoding/json" "math/big" + "sync" "testing" "github.com/KyberNetwork/kyberswap-dex-lib/pkg/entity" "github.com/KyberNetwork/kyberswap-dex-lib/pkg/source/pool" + "github.com/KyberNetwork/kyberswap-dex-lib/pkg/util/testutil" + v3Entities "github.com/daoleno/uniswapv3-sdk/entities" "github.com/holiman/uint256" "github.com/stretchr/testify/assert" @@ -105,7 +108,6 @@ var ( mockTimepointIndex uint16 = 19874 mockLastTimepointTimestamp uint32 = 1733131721 - mockIsInitialized = true mockAlpha1 uint16 = 2900 mockAlpha2 uint16 = 12000 @@ -116,9 +118,6 @@ var ( mockVolumeBeta uint32 = 0 mockVolumeGamma uint16 = 0 mockBaseFee uint16 = 100 - - // mockSlidingFeeZeroToOneFeeFactor *int - // mockSlidingFeeOneToZeroFeeFactor *int ) func TestCalcAmountOut(t *testing.T) { @@ -162,26 +161,25 @@ func TestCalcAmountOut(t *testing.T) { tickMax: mockTickmax, tickSpacing: mockTickSpacing, timepoints: mockTimepoints, - volatilityOracle: &VotatilityOraclePlugin{ + volatilityOracle: &VolatilityOraclePlugin{ TimepointIndex: mockTimepointIndex, LastTimepointTimestamp: mockLastTimepointTimestamp, - IsInitialized: mockIsInitialized, - }, - dynamicFee: &DynamicFeePlugin{ - FeeConfig: FeeConfiguration{ - Alpha1: mockAlpha1, - Alpha2: mockAlpha2, - Beta1: mockBeta1, - Beta2: mockBeta2, - Gamma1: mockGamma1, - Gamma2: mockGamma2, - VolumeBeta: mockVolumeBeta, - VolumeGamma: mockVolumeGamma, - BaseFee: mockBaseFee, - }, - }, - useBasePluginV2: false, - gas: mockGas, + IsInitialized: true, + }, + dynamicFee: &DynamicFeeConfig{ + Alpha1: mockAlpha1, + Alpha2: mockAlpha2, + Beta1: mockBeta1, + Beta2: mockBeta2, + Gamma1: mockGamma1, + Gamma2: mockGamma2, + VolumeBeta: mockVolumeBeta, + VolumeGamma: mockVolumeGamma, + BaseFee: mockBaseFee, + }, + writeTimePointLock: new(sync.RWMutex), + useBasePluginV2: false, + gas: mockGas, }, input: pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ @@ -246,26 +244,25 @@ func TestCalcAmountOut(t *testing.T) { tickMax: mockTickmax, tickSpacing: mockTickSpacing, timepoints: mockTimepoints, - volatilityOracle: &VotatilityOraclePlugin{ + volatilityOracle: &VolatilityOraclePlugin{ TimepointIndex: mockTimepointIndex, LastTimepointTimestamp: mockLastTimepointTimestamp, - IsInitialized: mockIsInitialized, - }, - dynamicFee: &DynamicFeePlugin{ - FeeConfig: FeeConfiguration{ - Alpha1: mockAlpha1, - Alpha2: mockAlpha2, - Beta1: mockBeta1, - Beta2: mockBeta2, - Gamma1: mockGamma1, - Gamma2: mockGamma2, - VolumeBeta: mockVolumeBeta, - VolumeGamma: mockVolumeGamma, - BaseFee: mockBaseFee, - }, - }, - useBasePluginV2: false, - gas: mockGas, + IsInitialized: true, + }, + dynamicFee: &DynamicFeeConfig{ + Alpha1: mockAlpha1, + Alpha2: mockAlpha2, + Beta1: mockBeta1, + Beta2: mockBeta2, + Gamma1: mockGamma1, + Gamma2: mockGamma2, + VolumeBeta: mockVolumeBeta, + VolumeGamma: mockVolumeGamma, + BaseFee: mockBaseFee, + }, + writeTimePointLock: new(sync.RWMutex), + useBasePluginV2: false, + gas: mockGas, }, input: pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ @@ -330,26 +327,25 @@ func TestCalcAmountOut(t *testing.T) { tickMax: mockTickmax, tickSpacing: mockTickSpacing, timepoints: mockTimepoints, - volatilityOracle: &VotatilityOraclePlugin{ + volatilityOracle: &VolatilityOraclePlugin{ TimepointIndex: mockTimepointIndex, LastTimepointTimestamp: mockLastTimepointTimestamp, - IsInitialized: mockIsInitialized, - }, - dynamicFee: &DynamicFeePlugin{ - FeeConfig: FeeConfiguration{ - Alpha1: mockAlpha1, - Alpha2: mockAlpha2, - Beta1: mockBeta1, - Beta2: mockBeta2, - Gamma1: mockGamma1, - Gamma2: mockGamma2, - VolumeBeta: mockVolumeBeta, - VolumeGamma: mockVolumeGamma, - BaseFee: mockBaseFee, - }, - }, - useBasePluginV2: false, - gas: mockGas, + IsInitialized: true, + }, + dynamicFee: &DynamicFeeConfig{ + Alpha1: mockAlpha1, + Alpha2: mockAlpha2, + Beta1: mockBeta1, + Beta2: mockBeta2, + Gamma1: mockGamma1, + Gamma2: mockGamma2, + VolumeBeta: mockVolumeBeta, + VolumeGamma: mockVolumeGamma, + BaseFee: mockBaseFee, + }, + writeTimePointLock: new(sync.RWMutex), + useBasePluginV2: false, + gas: mockGas, }, input: pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ @@ -414,26 +410,25 @@ func TestCalcAmountOut(t *testing.T) { tickMax: mockTickmax, tickSpacing: mockTickSpacing, timepoints: mockTimepoints, - volatilityOracle: &VotatilityOraclePlugin{ + volatilityOracle: &VolatilityOraclePlugin{ TimepointIndex: mockTimepointIndex, LastTimepointTimestamp: mockLastTimepointTimestamp, - IsInitialized: mockIsInitialized, - }, - dynamicFee: &DynamicFeePlugin{ - FeeConfig: FeeConfiguration{ - Alpha1: mockAlpha1, - Alpha2: mockAlpha2, - Beta1: mockBeta1, - Beta2: mockBeta2, - Gamma1: mockGamma1, - Gamma2: mockGamma2, - VolumeBeta: mockVolumeBeta, - VolumeGamma: mockVolumeGamma, - BaseFee: mockBaseFee, - }, - }, - useBasePluginV2: false, - gas: mockGas, + IsInitialized: true, + }, + dynamicFee: &DynamicFeeConfig{ + Alpha1: mockAlpha1, + Alpha2: mockAlpha2, + Beta1: mockBeta1, + Beta2: mockBeta2, + Gamma1: mockGamma1, + Gamma2: mockGamma2, + VolumeBeta: mockVolumeBeta, + VolumeGamma: mockVolumeGamma, + BaseFee: mockBaseFee, + }, + writeTimePointLock: new(sync.RWMutex), + useBasePluginV2: false, + gas: mockGas, }, input: pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ @@ -469,8 +464,9 @@ func TestCalcAmountOut(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - result, err := tt.simulator.CalcAmountOut(tt.input) - + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { + return tt.simulator.CalcAmountOut(tt.input) + }) if tt.expectedErr != nil { assert.Error(t, err) assert.Equal(t, err.Error(), tt.expectedErr.Error()) @@ -500,7 +496,7 @@ func TestCalcAmountOut(t *testing.T) { } } -var mockPool = []byte(`{"address":"0xbe9c1d237d002c8d9402f30c16ace1436d008f0c","exchange":"silverswap","type":"algebra-integral","timestamp":1733225338,"reserves":["9999999999999944","2620057588865"],"tokens":[{"address":"0x21be370d5312f44cb42ce377bc9b8a0cef1a4c83","name":"Wrapped Fantom","symbol":"WFTM","decimals":18,"weight":50,"swappable":true},{"address":"0xfe7eda5f2c56160d406869a8aa4b2f365d544c7b","name":"Axelar Wrapped ETH","symbol":"axlETH","decimals":18,"weight":50,"swappable":true}],"extra":"{\"liquidity\":161865919478591,\"globalState\":{\"price\":\"1282433937397070526017841373\",\"tick\":82476,\"lastFee\":100,\"pluginConfig\":193,\"communityFee\":100,\"unlocked\":true},\"ticks\":[{\"Index\":-887220,\"LiquidityGross\":161865919478591,\"LiquidityNet\":161865919478591},{\"Index\":887220,\"LiquidityGross\":161865919478591,\"LiquidityNet\":-161865919478591}],\"tickSpacing\":60,\"timepoints\":{\"0\":{\"Initialized\":true,\"BlockTimestamp\":1712116096,\"TickCumulative\":0,\"VolatilityCumulative\":\"0\",\"Tick\":-82476,\"AverageTick\":-82476,\"WindowStartIndex\":0},\"1\":{\"Initialized\":false,\"BlockTimestamp\":0,\"TickCumulative\":0,\"VolatilityCumulative\":\"0\",\"Tick\":0,\"AverageTick\":0,\"WindowStartIndex\":0},\"2\":{\"Initialized\":false,\"BlockTimestamp\":0,\"TickCumulative\":0,\"VolatilityCumulative\":\"0\",\"Tick\":0,\"AverageTick\":0,\"WindowStartIndex\":0},\"65535\":{\"Initialized\":false,\"BlockTimestamp\":0,\"TickCumulative\":0,\"VolatilityCumulative\":\"0\",\"Tick\":0,\"AverageTick\":0,\"WindowStartIndex\":0}},\"votalityOracle\":{\"TimepointIndex\":0,\"LastTimepointTimestamp\":1712116096,\"IsInitialized\":true},\"slidingFee\":{\"FeeFactors\":{\"ZeroToOneFeeFactor\":null,\"OneToZeroFeeFactor\":null}},\"dynamicFee\":{\"FeeConfig\":{\"alpha1\":2900,\"alpha2\":12000,\"beta1\":360,\"beta2\":60000,\"gamma1\":59,\"gamma2\":8500,\"volumeBeta\":0,\"volumeGamma\":0,\"baseFee\":100}}}","staticExtra":"{\"useBasePluginV2\":false}","blockNumber":99019509}`) +var mockPool = []byte(`{"address":"0xbe9c1d237d002c8d9402f30c16ace1436d008f0c","exchange":"silverswap","type":"algebra-integral","timestamp":1733225338,"reserves":["9999999999999944","2620057588865"],"tokens":[{"address":"0x21be370d5312f44cb42ce377bc9b8a0cef1a4c83","name":"Wrapped Fantom","symbol":"WFTM","decimals":18,"weight":50,"swappable":true},{"address":"0xfe7eda5f2c56160d406869a8aa4b2f365d544c7b","name":"Axelar Wrapped ETH","symbol":"axlETH","decimals":18,"weight":50,"swappable":true}],"extra":"{\"liq\":161865919478591,\"gS\":{\"price\":\"1282433937397070526017841373\",\"tick\":82476,\"lF\":100,\"pC\":193,\"cF\":100,\"un\":true},\"ticks\":[{\"Index\":-887220,\"LiquidityGross\":161865919478591,\"LiquidityNet\":161865919478591},{\"Index\":887220,\"LiquidityGross\":161865919478591,\"LiquidityNet\":-161865919478591}],\"tS\":60,\"tP\":{\"0\":{\"init\":true,\"ts\":1712116096,\"cum\":0,\"vo\":\"0\",\"tick\":-82476,\"avgT\":-82476,\"wsI\":0},\"1\":{\"init\":false,\"ts\":0,\"cum\":0,\"vo\":\"0\",\"tick\":0,\"avgT\":0,\"wsI\":0},\"2\":{\"init\":false,\"ts\":0,\"cum\":0,\"vo\":\"0\",\"tick\":0,\"avgT\":0,\"wsI\":0},\"65535\":{\"init\":false,\"ts\":0,\"cum\":0,\"vo\":\"0\",\"tick\":0,\"avgT\":0,\"wsI\":0}},\"vo\":{\"TimepointIndex\":0,\"LastTimepointTimestamp\":1712116096,\"IsInitialized\":true},\"sF\":{\"0to1fF\":null,\"1to0fF\":null},\"dF\":{\"a1\":2900,\"a2\":12000,\"b1\":360,\"b2\":60000,\"g1\":59,\"g2\":8500,\"vB\":0,\"vG\":0,\"bF\":100}}","staticExtra":"{\"2\":false}","blockNumber":99019509}`) func TestCalcAmountOut_FromPool(t *testing.T) { var p entity.Pool @@ -510,12 +506,14 @@ func TestCalcAmountOut_FromPool(t *testing.T) { ps, err := NewPoolSimulator(p, 280000) require.NoError(t, err) - res, err := ps.CalcAmountOut(pool.CalcAmountOutParams{ - TokenAmountIn: pool.TokenAmount{ - Token: "0x21be370d5312f44cb42ce377bc9b8a0cef1a4c83", - Amount: big.NewInt(100000000000000), - }, - TokenOut: "0xfe7eda5f2c56160d406869a8aa4b2f365d544c7b", + res, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { + return ps.CalcAmountOut(pool.CalcAmountOutParams{ + TokenAmountIn: pool.TokenAmount{ + Token: "0x21be370d5312f44cb42ce377bc9b8a0cef1a4c83", + Amount: big.NewInt(100000000000000), + }, + TokenOut: "0xfe7eda5f2c56160d406869a8aa4b2f365d544c7b", + }) }) require.NoError(t, err) diff --git a/pkg/liquidity-source/algebra/integral/pool_tracker.go b/pkg/liquidity-source/algebra/integral/pool_tracker.go index de6e8f00f..16de7088e 100644 --- a/pkg/liquidity-source/algebra/integral/pool_tracker.go +++ b/pkg/liquidity-source/algebra/integral/pool_tracker.go @@ -126,7 +126,7 @@ func (d *PoolTracker) GetNewPoolState( Ticks: ticks, TickSpacing: int32(rpcData.TickSpacing.Int64()), Timepoints: rpcData.Timepoints, - VotatilityOracle: rpcData.VotatilityOracle, + VolatilityOracle: rpcData.VolatilityOracle, SlidingFee: rpcData.SlidingFee, DynamicFee: rpcData.DynamicFee, }) @@ -239,7 +239,8 @@ func (d *PoolTracker) fetchRPCData(ctx context.Context, p entity.Pool, blockNumb Unlocked: rpcState.Unlocked, } - timepoints, votalityOracleData, dynamicFeeData, slidingFeeData, err := d.getPluginData(ctx, p.Address, result.BlockNumber) + timepoints, volatilityOracleData, dynamicFeeData, slidingFeeData, err := d.getPluginData(ctx, p.Address, + result.BlockNumber) if err != nil { l.WithFields(logger.Fields{ "error": err, @@ -248,7 +249,7 @@ func (d *PoolTracker) fetchRPCData(ctx context.Context, p entity.Pool, blockNumb } res.Timepoints = timepoints - res.VotatilityOracle = votalityOracleData + res.VolatilityOracle = volatilityOracleData res.SlidingFee = slidingFeeData res.DynamicFee = dynamicFeeData res.BlockNumber = result.BlockNumber @@ -257,7 +258,7 @@ func (d *PoolTracker) fetchRPCData(ctx context.Context, p entity.Pool, blockNumb } func (d *PoolTracker) getPluginData(ctx context.Context, poolAddress string, blockNumber *big.Int) ( - map[uint16]Timepoint, VotatilityOraclePlugin, DynamicFeePlugin, SlidingFeePlugin, error) { + map[uint16]Timepoint, VolatilityOraclePlugin, DynamicFeeConfig, SlidingFeeConfig, error) { l := logger.WithFields(logger.Fields{ "poolAddress": poolAddress, @@ -283,15 +284,15 @@ func (d *PoolTracker) getPluginData(ctx context.Context, poolAddress string, blo l.WithFields(logger.Fields{ "error": err, }).Error("failed to fetch Plugin address from pool") - return nil, VotatilityOraclePlugin{}, DynamicFeePlugin{}, SlidingFeePlugin{}, err + return nil, VolatilityOraclePlugin{}, DynamicFeeConfig{}, SlidingFeeConfig{}, err } - volatilityOracleData, err := d.getVotalityOracleData(ctx, plugin.Hex(), blockNumber) + volatilityOracleData, err := d.getVolatilityOracleData(ctx, plugin.Hex(), blockNumber) if err != nil { l.WithFields(logger.Fields{ "error": err, - }).Error("failed to fetch VotatilityOracle data from plugin") - return nil, VotatilityOraclePlugin{}, DynamicFeePlugin{}, SlidingFeePlugin{}, err + }).Error("failed to fetch VolatilityOracle data from plugin") + return nil, VolatilityOraclePlugin{}, DynamicFeeConfig{}, SlidingFeeConfig{}, err } timepoints, err := d.fetchTimepoints(ctx, plugin.Hex(), blockNumber, volatilityOracleData.TimepointIndex) @@ -299,7 +300,7 @@ func (d *PoolTracker) getPluginData(ctx context.Context, poolAddress string, blo l.WithFields(logger.Fields{ "error": err, }).Error("failed to fetch timepoints data from plugin") - return nil, VotatilityOraclePlugin{}, DynamicFeePlugin{}, SlidingFeePlugin{}, err + return nil, VolatilityOraclePlugin{}, DynamicFeeConfig{}, SlidingFeeConfig{}, err } dynamicFeeData, err := d.getDynamicFeeData(ctx, plugin.Hex(), blockNumber) @@ -307,26 +308,26 @@ func (d *PoolTracker) getPluginData(ctx context.Context, poolAddress string, blo l.WithFields(logger.Fields{ "error": err, }).Error("failed to fetch DynamicFee data from plugin") - return nil, VotatilityOraclePlugin{}, DynamicFeePlugin{}, SlidingFeePlugin{}, err + return nil, VolatilityOraclePlugin{}, DynamicFeeConfig{}, SlidingFeeConfig{}, err } - var slidingFeeData SlidingFeePlugin + var slidingFeeData SlidingFeeConfig if d.config.UseBasePluginV2 { slidingFeeData, err = d.getSlidingFeeData(ctx, plugin.Hex(), blockNumber) if err != nil { l.WithFields(logger.Fields{ "error": err, }).Error("failed to fetch Sliding data from plugin") - return nil, VotatilityOraclePlugin{}, DynamicFeePlugin{}, SlidingFeePlugin{}, err + return nil, VolatilityOraclePlugin{}, DynamicFeeConfig{}, SlidingFeeConfig{}, err } } return timepoints, volatilityOracleData, dynamicFeeData, slidingFeeData, nil } -func (d *PoolTracker) getVotalityOracleData(ctx context.Context, pluginAddress string, - blockNumber *big.Int) (VotatilityOraclePlugin, error) { - var result VotatilityOraclePlugin +func (d *PoolTracker) getVolatilityOracleData(ctx context.Context, pluginAddress string, + blockNumber *big.Int) (VolatilityOraclePlugin, error) { + var result VolatilityOraclePlugin req := d.ethrpcClient.NewRequest().SetContext(ctx) if blockNumber != nil && blockNumber.Sign() > 0 { @@ -354,14 +355,15 @@ func (d *PoolTracker) getVotalityOracleData(ctx context.Context, pluginAddress s _, err := req.Aggregate() if err != nil { - return VotatilityOraclePlugin{}, err + return VolatilityOraclePlugin{}, err } return result, nil } -func (d *PoolTracker) getSlidingFeeData(ctx context.Context, pluginAddress string, blockNumber *big.Int) (SlidingFeePlugin, error) { - var result SlidingFeePlugin +func (d *PoolTracker) getSlidingFeeData(ctx context.Context, pluginAddress string, + blockNumber *big.Int) (SlidingFeeConfig, error) { + var result SlidingFeeConfig req := d.ethrpcClient.NewRequest().SetContext(ctx) if blockNumber != nil && blockNumber.Sign() > 0 { @@ -373,18 +375,19 @@ func (d *PoolTracker) getSlidingFeeData(ctx context.Context, pluginAddress strin Target: pluginAddress, Method: slidingFeePluginFeeFactorsMethod, Params: nil, - }, []interface{}{&result.FeeFactors}) + }, []interface{}{&result}) _, err := req.Call() if err != nil { - return SlidingFeePlugin{}, err + return SlidingFeeConfig{}, err } return result, nil } -func (d *PoolTracker) getDynamicFeeData(ctx context.Context, pluginAddress string, blockNumber *big.Int) (DynamicFeePlugin, error) { - var result DynamicFeePlugin +func (d *PoolTracker) getDynamicFeeData(ctx context.Context, pluginAddress string, + blockNumber *big.Int) (DynamicFeeConfig, error) { + var result DynamicFeeConfig req := d.ethrpcClient.NewRequest().SetContext(ctx) if blockNumber != nil && blockNumber.Sign() > 0 { @@ -396,11 +399,11 @@ func (d *PoolTracker) getDynamicFeeData(ctx context.Context, pluginAddress strin Target: pluginAddress, Method: dynamicFeeManagerPluginFeeConfigMethod, Params: nil, - }, []interface{}{&result.FeeConfig}) + }, []interface{}{&result}) _, err := req.Call() if err != nil { - return DynamicFeePlugin{}, err + return DynamicFeeConfig{}, err } return result, nil diff --git a/pkg/liquidity-source/algebra/integral/ticklens.go b/pkg/liquidity-source/algebra/integral/ticklens.go index 8fbda5c7e..c042bc4a6 100644 --- a/pkg/liquidity-source/algebra/integral/ticklens.go +++ b/pkg/liquidity-source/algebra/integral/ticklens.go @@ -6,15 +6,16 @@ import ( "strconv" "github.com/KyberNetwork/ethrpc" - "github.com/KyberNetwork/kyberswap-dex-lib/pkg/entity" - sourcePool "github.com/KyberNetwork/kyberswap-dex-lib/pkg/source/pool" - "github.com/KyberNetwork/kyberswap-dex-lib/pkg/util" - "github.com/KyberNetwork/kyberswap-dex-lib/pkg/util/ticklens" "github.com/KyberNetwork/logger" mapset "github.com/deckarep/golang-set/v2" "github.com/ethereum/go-ethereum/common" "github.com/goccy/go-json" "github.com/samber/lo" + + "github.com/KyberNetwork/kyberswap-dex-lib/pkg/entity" + sourcePool "github.com/KyberNetwork/kyberswap-dex-lib/pkg/source/pool" + "github.com/KyberNetwork/kyberswap-dex-lib/pkg/util" + "github.com/KyberNetwork/kyberswap-dex-lib/pkg/util/ticklens" ) const ( diff --git a/pkg/liquidity-source/algebra/integral/type.go b/pkg/liquidity-source/algebra/integral/type.go index ae23e61d8..1de032d55 100644 --- a/pkg/liquidity-source/algebra/integral/type.go +++ b/pkg/liquidity-source/algebra/integral/type.go @@ -66,7 +66,7 @@ type SubgraphPoolTicks struct { Ticks []TickResp `json:"ticks"` } -// for algebra v1 with single fee for both direction +// GlobalStateFromRPC for algebra v1 with single fee for both direction type GlobalStateFromRPC struct { Price *big.Int Tick *big.Int @@ -76,26 +76,14 @@ type GlobalStateFromRPC struct { Unlocked bool } -// unified data for simulation +// GlobalState contains unified data for simulation type GlobalState struct { Price *uint256.Int `json:"price"` Tick int32 `json:"tick"` - LastFee uint16 `json:"lastFee"` - PluginConfig uint8 `json:"pluginConfig"` - CommunityFee uint16 `json:"communityFee"` - Unlocked bool `json:"unlocked"` -} - -type FeeConfiguration struct { - Alpha1 uint16 `json:"alpha1"` // max value of the first sigmoid - Alpha2 uint16 `json:"alpha2"` // max value of the second sigmoid - Beta1 uint32 `json:"beta1"` // shift along the x-axis for the first sigmoid - Beta2 uint32 `json:"beta2"` // shift along the x-axis for the second sigmoid - Gamma1 uint16 `json:"gamma1"` // horizontal stretch factor for the first sigmoid - Gamma2 uint16 `json:"gamma2"` // horizontal stretch factor for the second sigmoid - VolumeBeta uint32 `json:"volumeBeta"` // shift along the x-axis for the outer volume-sigmoid - VolumeGamma uint16 `json:"volumeGamma"` // horizontal stretch factor the outer volume-sigmoid - BaseFee uint16 `json:"baseFee"` // minimum possible fee + LastFee uint16 `json:"lF"` + PluginConfig uint8 `json:"pC"` + CommunityFee uint16 `json:"cF"` + Unlocked bool `json:"un"` } type FetchRPCResult struct { @@ -106,23 +94,23 @@ type FetchRPCResult struct { Reserve1 *big.Int `json:"reserve1"` Timepoints map[uint16]Timepoint - VotatilityOracle VotatilityOraclePlugin - SlidingFee SlidingFeePlugin - DynamicFee DynamicFeePlugin + VolatilityOracle VolatilityOraclePlugin + SlidingFee SlidingFeeConfig + DynamicFee DynamicFeeConfig BlockNumber *big.Int } type Timepoint struct { - Initialized bool // whether or not the timepoint is initialized - BlockTimestamp uint32 // the block timestamp of the timepoint - TickCumulative int64 // the tick accumulator, i.e., tick * time elapsed since the pool was first initialized - VolatilityCumulative *uint256.Int // the volatility accumulator; overflow after ~34800 years is desired :) - Tick int32 // tick at this blockTimestamp - AverageTick int32 // average tick at this blockTimestamp (for WINDOW seconds) - WindowStartIndex uint16 // closest timepoint lte WINDOW seconds ago (or oldest timepoint), should be used only from the last timepoint! + Initialized bool `json:"init,omitempty"` // whether the timepoint is initialized + BlockTimestamp uint32 `json:"ts,omitempty"` // the block timestamp of the timepoint + TickCumulative int64 `json:"cum,omitempty"` // the tick accumulator, i.e., tick * time elapsed since the pool was first initialized + VolatilityCumulative *uint256.Int `json:"vo,omitempty"` // the volatility accumulator; overflow after ~34800 years is desired :) + Tick int32 `json:"tick,omitempty"` // tick at this blockTimestamp + AverageTick int32 `json:"avgT,omitempty"` // average tick at this blockTimestamp (for WINDOW seconds) + WindowStartIndex uint16 `json:"wsI,omitempty"` // closest timepoint lte WINDOW seconds ago (or oldest timepoint), should be used only from the last timepoint! } -// same as Timepoint but with bigInt for correct deserialization +// TimepointRPC same as Timepoint but with bigInt for correct deserialization type TimepointRPC struct { Initialized bool BlockTimestamp uint32 @@ -133,22 +121,46 @@ type TimepointRPC struct { WindowStartIndex uint16 } -type StaticExtra struct { - UseBasePluginV2 bool `json:"useBasePluginV2"` -} - type Extra struct { - Liquidity *big.Int `json:"liquidity"` - GlobalState GlobalState `json:"globalState"` + Liquidity *big.Int `json:"liq"` + GlobalState GlobalState `json:"gS"` Ticks []v3Entities.Tick `json:"ticks"` - TickSpacing int32 `json:"tickSpacing"` - Timepoints map[uint16]Timepoint `json:"timepoints"` - VotatilityOracle VotatilityOraclePlugin `json:"votalityOracle"` - SlidingFee SlidingFeePlugin `json:"slidingFee"` - DynamicFee DynamicFeePlugin `json:"dynamicFee"` + TickSpacing int32 `json:"tS"` + Timepoints map[uint16]Timepoint `json:"tP"` + VolatilityOracle VolatilityOraclePlugin `json:"vo"` + SlidingFee SlidingFeeConfig `json:"sF"` + DynamicFee DynamicFeeConfig `json:"dF"` +} + +type VolatilityOraclePlugin struct { + TimepointIndex uint16 + LastTimepointTimestamp uint32 + IsInitialized bool + UpdatedWithinThisBlock bool // do plugin logic once. by right we should re-update the timepoint every new second +} + +type DynamicFeeConfig struct { + Alpha1 uint16 `json:"a1,omitempty"` // max value of the first sigmoid + Alpha2 uint16 `json:"a2,omitempty"` // max value of the second sigmoid + Beta1 uint32 `json:"b1,omitempty"` // shift along the x-axis for the first sigmoid + Beta2 uint32 `json:"b2,omitempty"` // shift along the x-axis for the second sigmoid + Gamma1 uint16 `json:"g1,omitempty"` // horizontal stretch factor for the first sigmoid + Gamma2 uint16 `json:"g2,omitempty"` // horizontal stretch factor for the second sigmoid + VolumeBeta uint32 `json:"vB,omitempty"` // shift along the x-axis for the outer volume-sigmoid + VolumeGamma uint16 `json:"vG,omitempty"` // horizontal stretch factor the outer volume-sigmoid + BaseFee uint16 `json:"bF,omitempty"` // minimum possible fee } -// we won't update the state when calculating amountOut, return this struct instead +type SlidingFeeConfig struct { + ZeroToOneFeeFactor *uint256.Int `json:"0to1fF,omitempty"` + OneToZeroFeeFactor *uint256.Int `json:"1to0fF,omitempty"` +} + +type StaticExtra struct { + UseBasePluginV2 bool `json:"2"` +} + +// StateUpdate to be returned instead of updating state when calculating amountOut type StateUpdate struct { Liquidity *uint256.Int GlobalState GlobalState @@ -161,7 +173,6 @@ type PoolMeta struct { func (tp *TimepointRPC) toTimepoint() Timepoint { volatilityCumulative := uint256.MustFromBig(tp.VolatilityCumulative) - return Timepoint{ Initialized: tp.Initialized, BlockTimestamp: tp.BlockTimestamp, @@ -197,8 +208,3 @@ type PriceMovementCache struct { nextTick int32 // The tick till the current step goes initialized bool // True if the _nextTick is initialized } - -type FeeFactors struct { - ZeroToOneFeeFactor *uint256.Int - OneToZeroFeeFactor *uint256.Int -} diff --git a/pkg/liquidity-source/algebra/v1/pool_simulator_test.go b/pkg/liquidity-source/algebra/v1/pool_simulator_test.go index 553d32114..2201423bc 100644 --- a/pkg/liquidity-source/algebra/v1/pool_simulator_test.go +++ b/pkg/liquidity-source/algebra/v1/pool_simulator_test.go @@ -43,7 +43,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { in := pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)} return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: in, @@ -101,7 +101,7 @@ func TestPoolSimulator_UpdateBalance(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { in := pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)} - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: in, TokenOut: tc.out, @@ -145,7 +145,7 @@ func TestPoolSimulator_CalcAmountOut_SPL(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - _, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + _, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { in := pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)} return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: in, @@ -183,7 +183,7 @@ func TestPoolSimulator_CalcAmountOut_CommFee(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { in := pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)} return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: in, @@ -234,7 +234,7 @@ func TestPoolSimulator_CalcAmountOut_v1_9(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { in := pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)} return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: in, @@ -274,7 +274,7 @@ func TestPoolSimulator_CalcAmountOut_DirFee(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { in := pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)} return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: in, diff --git a/pkg/liquidity-source/balancer-v1/pool_simulator_test.go b/pkg/liquidity-source/balancer-v1/pool_simulator_test.go index e24f090da..c0458799a 100644 --- a/pkg/liquidity-source/balancer-v1/pool_simulator_test.go +++ b/pkg/liquidity-source/balancer-v1/pool_simulator_test.go @@ -57,7 +57,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return tc.poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{TokenAmountIn: tc.tokenAmountIn, TokenOut: tc.tokenOut}) }) diff --git a/pkg/liquidity-source/balancer-v2/composable-stable/pool_simulator_test.go b/pkg/liquidity-source/balancer-v2/composable-stable/pool_simulator_test.go index 7ccb3ca09..b40a57e99 100644 --- a/pkg/liquidity-source/balancer-v2/composable-stable/pool_simulator_test.go +++ b/pkg/liquidity-source/balancer-v2/composable-stable/pool_simulator_test.go @@ -64,7 +64,7 @@ func TestRegularSwap(t *testing.T) { expectedAmountOut := "998507669837625986" // calculation - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -126,7 +126,7 @@ func TestRegularSwap(t *testing.T) { expectedAmountOut := "23155810259460675" // calculation - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -220,7 +220,7 @@ func TestBptSwap(t *testing.T) { expectedAmountOut := "22005850083674" // calculation - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -312,7 +312,7 @@ func TestBptSwap(t *testing.T) { expectedAmountOut := "128189688116719916203223884786015" // calculation - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -411,7 +411,7 @@ func TestBptSwap(t *testing.T) { expectedAmountOut := "72153658150470669505066070" // calculation - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -510,7 +510,7 @@ func TestBptSwap(t *testing.T) { expectedAmountOut := "4071333855617864209" // calculation - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -603,7 +603,7 @@ func TestBptSwap(t *testing.T) { expectedAmountOut := "473156052715491" // calculation - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -696,7 +696,7 @@ func TestBptSwap(t *testing.T) { expectedAmountOut := "17329834826337" // calculation - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -794,7 +794,7 @@ func TestBptSwap(t *testing.T) { expectedAmountOut := "2027780845478092" // calculation - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -893,7 +893,7 @@ func TestBptSwap(t *testing.T) { expectedAmountOut := "4023147984636196801" // calculation - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -1027,7 +1027,7 @@ func TestPoolSimulator_CalcAmountIn(t *testing.T) { simulator, err := NewPoolSimulator(pool) assert.Nil(t, err) - got, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountInResult](t, func() (any, error) { + got, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountInResult, error) { return simulator.CalcAmountIn(tt.params) }) if err != nil { diff --git a/pkg/liquidity-source/balancer-v2/stable/pool_simulator_test.go b/pkg/liquidity-source/balancer-v2/stable/pool_simulator_test.go index 922d2377e..bf5184507 100644 --- a/pkg/liquidity-source/balancer-v2/stable/pool_simulator_test.go +++ b/pkg/liquidity-source/balancer-v2/stable/pool_simulator_test.go @@ -45,7 +45,7 @@ func TestCalcAmountOut(t *testing.T) { Amount: new(big.Int).SetUint64(99999910000000), } tokenOut := "0x6b175474e89094c44da98b954eedeac495271d0f" - _, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + _, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return s.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -90,7 +90,7 @@ func TestCalcAmountOut(t *testing.T) { expected := "1000000000000000000" // actual - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return s.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -138,7 +138,7 @@ func TestCalcAmountOut(t *testing.T) { expected := "590000000000000000" // actual - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return s.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -198,7 +198,7 @@ func TestCalcAmountOut(t *testing.T) { expected := "63551050657042642" // actual - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return s.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -338,7 +338,7 @@ func TestPoolSimulator_CalcAmountIn(t *testing.T) { simulator, err := NewPoolSimulator(pool) assert.Nil(t, err) - got, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountInResult](t, func() (any, error) { + got, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountInResult, error) { return simulator.CalcAmountIn(tt.params) }) if err != nil { diff --git a/pkg/liquidity-source/balancer-v2/weighted/pool_simulator_test.go b/pkg/liquidity-source/balancer-v2/weighted/pool_simulator_test.go index 4a0d956d4..58dedad91 100644 --- a/pkg/liquidity-source/balancer-v2/weighted/pool_simulator_test.go +++ b/pkg/liquidity-source/balancer-v2/weighted/pool_simulator_test.go @@ -62,7 +62,7 @@ func Test_CalcAmountOut(t *testing.T) { amountOut := "3442" // calculation - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return s.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -121,7 +121,7 @@ func Test_CalcAmountOut(t *testing.T) { amountOut := "76143667376405160244" // calculation - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return s.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -180,7 +180,7 @@ func Test_CalcAmountOut(t *testing.T) { amountOut := "4538893010907736440" // calculation - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return s.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -238,7 +238,7 @@ func Test_CalcAmountOut(t *testing.T) { simulator, err := NewPoolSimulator(pool) assert.Nil(t, err) amountIn, _ := new(big.Int).SetString("2000000000000000000000", 10) - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return simulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: poolpkg.TokenAmount{ Token: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", @@ -353,7 +353,7 @@ func Test_CalcAmountOut(t *testing.T) { simulator, err := NewPoolSimulator(pool) assert.Nil(t, err) amountIn, _ := new(big.Int).SetString("77000000000000000000", 10) - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return simulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: poolpkg.TokenAmount{ Token: "0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270", @@ -753,7 +753,7 @@ func TestPoolSimulator_CalcAmountIn(t *testing.T) { simulator, err := NewPoolSimulator(pool) assert.Nil(t, err) - got, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountInResult](t, func() (any, error) { + got, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountInResult, error) { return simulator.CalcAmountIn(tt.params) }) if err != nil { diff --git a/pkg/liquidity-source/bancor-v3/pool_simulator_test.go b/pkg/liquidity-source/bancor-v3/pool_simulator_test.go index de3737516..52c96a36f 100644 --- a/pkg/liquidity-source/bancor-v3/pool_simulator_test.go +++ b/pkg/liquidity-source/bancor-v3/pool_simulator_test.go @@ -93,7 +93,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { simulator, err := NewPoolSimulator(pool) assert.Nil(t, err) amountIn, _ := new(big.Int).SetString("1663885565640917213", 10) - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return simulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: poolpkg.TokenAmount{ Token: "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984", @@ -187,7 +187,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { simulator, err := NewPoolSimulator(pool) assert.Nil(t, err) amountIn, _ := new(big.Int).SetString("1663885565640917213", 10) - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return simulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: poolpkg.TokenAmount{ Token: "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984", @@ -281,7 +281,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { simulator, err := NewPoolSimulator(pool) assert.Nil(t, err) amountIn, _ := new(big.Int).SetString("1090364867014427588545", 10) - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return simulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: poolpkg.TokenAmount{ Token: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", @@ -375,7 +375,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { simulator, err := NewPoolSimulator(pool) assert.Nil(t, err) amountIn, _ := new(big.Int).SetString("104234917775792427951", 10) - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return simulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: poolpkg.TokenAmount{ Token: "0x514910771af9ca656af840dff83e8264ecf986ca", @@ -469,7 +469,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { simulator, err := NewPoolSimulator(pool) assert.Nil(t, err) amountIn, _ := new(big.Int).SetString("166388556564091721308", 10) - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return simulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: poolpkg.TokenAmount{ Token: "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984", @@ -1114,7 +1114,7 @@ func TestPoolSimulator_CalcAmountIn(t *testing.T) { simulator, err := NewPoolSimulator(pool) assert.Nil(t, err) - got, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountInResult](t, func() (any, error) { + got, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountInResult, error) { return simulator.CalcAmountIn(tt.params) }) if err != nil { diff --git a/pkg/liquidity-source/curve/plain/pool_simulator_basepool_test.go b/pkg/liquidity-source/curve/plain/pool_simulator_basepool_test.go index a3b9d5552..50708eb9d 100644 --- a/pkg/liquidity-source/curve/plain/pool_simulator_basepool_test.go +++ b/pkg/liquidity-source/curve/plain/pool_simulator_basepool_test.go @@ -67,7 +67,7 @@ func TestCalcAmountOutAsBasePool(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, @@ -121,7 +121,7 @@ func TestUpdateBalanceAsBasePool(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { amountIn := pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)} - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: amountIn, TokenOut: tc.out, diff --git a/pkg/liquidity-source/curve/plain/pool_simulator_compare_test.go b/pkg/liquidity-source/curve/plain/pool_simulator_compare_test.go index 6b586f7e4..ae3772a10 100644 --- a/pkg/liquidity-source/curve/plain/pool_simulator_compare_test.go +++ b/pkg/liquidity-source/curve/plain/pool_simulator_compare_test.go @@ -527,7 +527,7 @@ func TestCalcAmountOutSnapshot(t *testing.T) { for idx, tc := range testCases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { p := sims[tc.poolIdx] - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)}, TokenOut: tc.out, @@ -944,7 +944,7 @@ func TestUpdateBalanceSnapshot(t *testing.T) { for idx, tc := range testCases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { p := sims[tc.poolIdx] - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)}, TokenOut: tc.out, diff --git a/pkg/liquidity-source/curve/plain/pool_simulator_test.go b/pkg/liquidity-source/curve/plain/pool_simulator_test.go index a3c4d1f51..f857bc655 100644 --- a/pkg/liquidity-source/curve/plain/pool_simulator_test.go +++ b/pkg/liquidity-source/curve/plain/pool_simulator_test.go @@ -95,7 +95,7 @@ func TestCalcAmountOutPlain(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { p := sims[tc.poolIdx] - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, @@ -149,7 +149,7 @@ func TestCalcAmountOutPlainError(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { p := sims[tc.poolIdx] - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return pool.CalcAmountOut(p, pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, tc.out, nil) }) if out != nil && out.TokenAmountOut != nil { @@ -222,7 +222,7 @@ func TestCalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, @@ -256,7 +256,7 @@ func TestCalcAmountOut_interpolate_from_initialA_and_futureA(t *testing.T) { }) require.Nil(t, err) - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: "A", Amount: big.NewInt(510000)}, TokenOut: "B", @@ -312,7 +312,7 @@ func TestGetDyVirtualPrice(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - dy, err := testutil.MustConcurrentSafe[*big.Int](t, func() (any, error) { + dy, err := testutil.MustConcurrentSafe(t, func() (*big.Int, error) { dy, _, err := p.GetDy(tc.i, tc.j, bignumber.NewBig10(tc.dx), nil) return dy, err }) @@ -320,7 +320,7 @@ func TestGetDyVirtualPrice(t *testing.T) { assert.Equal(t, bignumber.NewBig10(tc.expOut), dy) // test using cached D - dy, err = testutil.MustConcurrentSafe[*big.Int](t, func() (any, error) { + dy, err = testutil.MustConcurrentSafe(t, func() (*big.Int, error) { dy, _, err := p.GetDy(tc.i, tc.j, bignumber.NewBig10(tc.dx), dCached) return dy, err }) @@ -417,7 +417,7 @@ func TestPoolSimulatorPlain_CalcAmountIn(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { p := sims[tc.poolIdx] - amountIn, err := testutil.MustConcurrentSafe[*pool.CalcAmountInResult](t, func() (any, error) { + amountIn, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountInResult, error) { return p.CalcAmountIn(pool.CalcAmountInParams{ TokenAmountOut: pool.TokenAmount{Token: tc.tokenOut, Amount: big.NewInt(tc.amountOut)}, TokenIn: tc.tokenIn, diff --git a/pkg/liquidity-source/curve/stable-meta-ng/pool_simulator_test.go b/pkg/liquidity-source/curve/stable-meta-ng/pool_simulator_test.go index 3d42209e5..6c6ae9c5e 100644 --- a/pkg/liquidity-source/curve/stable-meta-ng/pool_simulator_test.go +++ b/pkg/liquidity-source/curve/stable-meta-ng/pool_simulator_test.go @@ -156,7 +156,7 @@ func TestCalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { p := sims[tc.poolIdx] - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)}, TokenOut: tc.out, @@ -296,7 +296,7 @@ func TestUpdateBalance(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { p := sims[tc.poolIdx] - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)}, TokenOut: tc.out, diff --git a/pkg/liquidity-source/curve/stable-ng/pool_simulator_test.go b/pkg/liquidity-source/curve/stable-ng/pool_simulator_test.go index abe651e23..49efce56e 100644 --- a/pkg/liquidity-source/curve/stable-ng/pool_simulator_test.go +++ b/pkg/liquidity-source/curve/stable-ng/pool_simulator_test.go @@ -59,7 +59,7 @@ func TestCalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { p := sims[tc.poolIdx] - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, @@ -194,7 +194,7 @@ func TestCalcAmountIn(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { p := sims[tc.poolIdx] - amountIn, err := testutil.MustConcurrentSafe[*pool.CalcAmountInResult](t, func() (any, error) { + amountIn, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountInResult, error) { return p.CalcAmountIn(pool.CalcAmountInParams{ TokenAmountOut: pool.TokenAmount{Token: tc.tokenOut, Amount: tc.amountOut}, TokenIn: tc.tokenIn, @@ -255,7 +255,7 @@ func TestUpdateBalance(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { p := sims[tc.poolIdx] - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, @@ -310,7 +310,7 @@ func TestCalcAmountOutError(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { p := sims[tc.poolIdx] - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, diff --git a/pkg/liquidity-source/curve/tricrypto-ng/pool_simulator_test.go b/pkg/liquidity-source/curve/tricrypto-ng/pool_simulator_test.go index f61845dd9..12ebe868c 100644 --- a/pkg/liquidity-source/curve/tricrypto-ng/pool_simulator_test.go +++ b/pkg/liquidity-source/curve/tricrypto-ng/pool_simulator_test.go @@ -64,7 +64,7 @@ func TestCalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { p := sims[tc.poolIdx] - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)}, TokenOut: tc.out, @@ -155,7 +155,7 @@ func TestCalcAmountIn(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { p := sims[tc.poolIdx] - amountIn, err := testutil.MustConcurrentSafe[*pool.CalcAmountInResult](t, func() (any, error) { + amountIn, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountInResult, error) { return p.CalcAmountIn(pool.CalcAmountInParams{ TokenAmountOut: pool.TokenAmount{ Token: tc.tokenOut, @@ -225,7 +225,7 @@ func TestUpdateBalance(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { p := sims[tc.poolIdx] - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)}, TokenOut: tc.out, diff --git a/pkg/liquidity-source/curve/twocrypto-ng/pool_simulator_test.go b/pkg/liquidity-source/curve/twocrypto-ng/pool_simulator_test.go index a669a5a7c..91ec84d07 100644 --- a/pkg/liquidity-source/curve/twocrypto-ng/pool_simulator_test.go +++ b/pkg/liquidity-source/curve/twocrypto-ng/pool_simulator_test.go @@ -61,7 +61,7 @@ func TestCalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { p := sims[tc.poolIdx] - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)}, TokenOut: tc.out, @@ -154,7 +154,7 @@ func TestCalcAmountIn(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { p := sims[tc.poolIdx] - amountIn, err := testutil.MustConcurrentSafe[*pool.CalcAmountInResult](t, func() (any, error) { + amountIn, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountInResult, error) { return p.CalcAmountIn(pool.CalcAmountInParams{ TokenAmountOut: pool.TokenAmount{ Token: tc.tokenOut, @@ -211,7 +211,7 @@ func TestUpdateBalance(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { p := sims[tc.poolIdx] - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)}, TokenOut: tc.out, diff --git a/pkg/liquidity-source/dai-usds/pool_simulator_test.go b/pkg/liquidity-source/dai-usds/pool_simulator_test.go index a81bb234e..95b1c6694 100644 --- a/pkg/liquidity-source/dai-usds/pool_simulator_test.go +++ b/pkg/liquidity-source/dai-usds/pool_simulator_test.go @@ -72,7 +72,7 @@ func TestGetAmountOut(t *testing.T) { t.Run(tc.name, func(t *testing.T) { pool, err := NewPoolSimulator(tc.entityPool) assert.Nil(t, err) - calcAmountOutResult, err := testutil.MustConcurrentSafe[*poolPkg.CalcAmountOutResult](t, func() (any, error) { + calcAmountOutResult, err := testutil.MustConcurrentSafe(t, func() (*poolPkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(poolPkg.CalcAmountOutParams{ TokenAmountIn: tc.tokenAmountIn, TokenOut: tc.tokenOut, diff --git a/pkg/liquidity-source/dodo/classical/pool_simulator_test.go b/pkg/liquidity-source/dodo/classical/pool_simulator_test.go index 54e79ee09..ce526ed72 100644 --- a/pkg/liquidity-source/dodo/classical/pool_simulator_test.go +++ b/pkg/liquidity-source/dodo/classical/pool_simulator_test.go @@ -239,7 +239,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx+1), func(t *testing.T) { p := sims[tc.poolIdx] - amountOut, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + amountOut, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: tc.tokenIn, @@ -426,7 +426,7 @@ func TestPoolSimulator_CalcAmountIn(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx+1), func(t *testing.T) { p := sims[tc.poolIdx] - amountIn, err := testutil.MustConcurrentSafe[*pool.CalcAmountInResult](t, func() (any, error) { + amountIn, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountInResult, error) { return p.CalcAmountIn(pool.CalcAmountInParams{ TokenAmountOut: pool.TokenAmount{ Token: tc.tokenOut, diff --git a/pkg/liquidity-source/dodo/dpp/pool_simulator_test.go b/pkg/liquidity-source/dodo/dpp/pool_simulator_test.go index 0fffc0ca5..94de4b02d 100644 --- a/pkg/liquidity-source/dodo/dpp/pool_simulator_test.go +++ b/pkg/liquidity-source/dodo/dpp/pool_simulator_test.go @@ -147,7 +147,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx+1), func(t *testing.T) { p := sims[tc.poolIdx] - amountOut, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + amountOut, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: tc.tokenIn, diff --git a/pkg/liquidity-source/dodo/dsp/pool_simulator_test.go b/pkg/liquidity-source/dodo/dsp/pool_simulator_test.go index 47c78295a..931473569 100644 --- a/pkg/liquidity-source/dodo/dsp/pool_simulator_test.go +++ b/pkg/liquidity-source/dodo/dsp/pool_simulator_test.go @@ -159,7 +159,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx+1), func(t *testing.T) { p := sims[tc.poolIdx] - amountOut, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + amountOut, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: tc.tokenIn, diff --git a/pkg/liquidity-source/dodo/dvm/pool_simulator_test.go b/pkg/liquidity-source/dodo/dvm/pool_simulator_test.go index 1e6da22d2..10545e0a2 100644 --- a/pkg/liquidity-source/dodo/dvm/pool_simulator_test.go +++ b/pkg/liquidity-source/dodo/dvm/pool_simulator_test.go @@ -135,7 +135,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx+1), func(t *testing.T) { p := sims[tc.poolIdx] - amountOut, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + amountOut, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: tc.tokenIn, diff --git a/pkg/liquidity-source/generic-simple-rate/pool_simulator_test.go b/pkg/liquidity-source/generic-simple-rate/pool_simulator_test.go index 408a1bf83..28e523179 100644 --- a/pkg/liquidity-source/generic-simple-rate/pool_simulator_test.go +++ b/pkg/liquidity-source/generic-simple-rate/pool_simulator_test.go @@ -73,7 +73,7 @@ func TestGetAmountOut(t *testing.T) { t.Run(tc.name, func(t *testing.T) { pool, err := NewPoolSimulator(tc.entityPool) assert.Nil(t, err) - calcAmountOutResult, err := testutil.MustConcurrentSafe[*poolPkg.CalcAmountOutResult](t, func() (any, error) { + calcAmountOutResult, err := testutil.MustConcurrentSafe(t, func() (*poolPkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(poolPkg.CalcAmountOutParams{ TokenAmountIn: tc.tokenAmountIn, TokenOut: tc.tokenOut, diff --git a/pkg/liquidity-source/integral/pool_simulator_test.go b/pkg/liquidity-source/integral/pool_simulator_test.go index d675daf17..a8d53513e 100644 --- a/pkg/liquidity-source/integral/pool_simulator_test.go +++ b/pkg/liquidity-source/integral/pool_simulator_test.go @@ -72,7 +72,7 @@ func TestCalcAmountOut(t *testing.T) { simulator, err := NewPoolSimulator(pool) require.Nil(t, err) - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return simulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: poolpkg.TokenAmount{ Token: _token0, @@ -213,7 +213,7 @@ func TestUpdateBalance(t *testing.T) { Amount: _amount0In, } - result, _ := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, _ := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: _token1, diff --git a/pkg/liquidity-source/mkr-sky/pool_simulator_test.go b/pkg/liquidity-source/mkr-sky/pool_simulator_test.go index de05e82e4..ebcfa68d8 100644 --- a/pkg/liquidity-source/mkr-sky/pool_simulator_test.go +++ b/pkg/liquidity-source/mkr-sky/pool_simulator_test.go @@ -73,7 +73,7 @@ func TestGetAmountOut(t *testing.T) { t.Run(tc.name, func(t *testing.T) { pool, err := NewPoolSimulator(tc.entityPool) assert.Nil(t, err) - calcAmountOutResult, err := testutil.MustConcurrentSafe[*poolPkg.CalcAmountOutResult](t, func() (any, error) { + calcAmountOutResult, err := testutil.MustConcurrentSafe(t, func() (*poolPkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(poolPkg.CalcAmountOutParams{ TokenAmountIn: tc.tokenAmountIn, TokenOut: tc.tokenOut, diff --git a/pkg/liquidity-source/nomiswap/nomiswapstable/pool_simulator_test.go b/pkg/liquidity-source/nomiswap/nomiswapstable/pool_simulator_test.go index fd98ad972..b122051b4 100644 --- a/pkg/liquidity-source/nomiswap/nomiswapstable/pool_simulator_test.go +++ b/pkg/liquidity-source/nomiswap/nomiswapstable/pool_simulator_test.go @@ -90,7 +90,7 @@ func TestGetAmountOut(t *testing.T) { t.Run(tc.name, func(t *testing.T) { pool, err := NewPoolSimulator(tc.entityPool) assert.Nil(t, err) - calcAmountOutResult, err := testutil.MustConcurrentSafe[*poolPkg.CalcAmountOutResult](t, func() (any, error) { + calcAmountOutResult, err := testutil.MustConcurrentSafe(t, func() (*poolPkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(poolPkg.CalcAmountOutParams{ TokenAmountIn: tc.tokenAmountIn, TokenOut: tc.tokenOut, diff --git a/pkg/liquidity-source/ringswap/pool_simulator_test.go b/pkg/liquidity-source/ringswap/pool_simulator_test.go index 56c173abf..ffb5ab749 100644 --- a/pkg/liquidity-source/ringswap/pool_simulator_test.go +++ b/pkg/liquidity-source/ringswap/pool_simulator_test.go @@ -268,7 +268,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return tc.poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tc.tokenAmountIn, TokenOut: tc.tokenOut, diff --git a/pkg/liquidity-source/swaap-v2/pool_simulator_test.go b/pkg/liquidity-source/swaap-v2/pool_simulator_test.go index 5b13c8917..c181abe3c 100644 --- a/pkg/liquidity-source/swaap-v2/pool_simulator_test.go +++ b/pkg/liquidity-source/swaap-v2/pool_simulator_test.go @@ -77,7 +77,7 @@ func TestCalcAmountOut(t *testing.T) { simulator, err := NewPoolSimulator(pool) assert.Nil(t, err) amountIn, _ := new(big.Int).SetString("334332318571851640", 10) - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return simulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: poolpkg.TokenAmount{ Token: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", diff --git a/pkg/liquidity-source/syncswapv2/aqua/pool_simulator_test.go b/pkg/liquidity-source/syncswapv2/aqua/pool_simulator_test.go index 19739c857..eab3b9d1c 100644 --- a/pkg/liquidity-source/syncswapv2/aqua/pool_simulator_test.go +++ b/pkg/liquidity-source/syncswapv2/aqua/pool_simulator_test.go @@ -38,7 +38,7 @@ func TestCalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, diff --git a/pkg/liquidity-source/syncswapv2/classic/pool_simulator_test.go b/pkg/liquidity-source/syncswapv2/classic/pool_simulator_test.go index 3ad4577f7..8868c80c3 100644 --- a/pkg/liquidity-source/syncswapv2/classic/pool_simulator_test.go +++ b/pkg/liquidity-source/syncswapv2/classic/pool_simulator_test.go @@ -94,7 +94,7 @@ func TestGetAmountOut(t *testing.T) { t.Run(tc.name, func(t *testing.T) { pool, err := NewPoolSimulator(tc.entityPool) assert.Nil(t, err) - calcAmountOutResult, err := testutil.MustConcurrentSafe[*poolPkg.CalcAmountOutResult](t, func() (any, error) { + calcAmountOutResult, err := testutil.MustConcurrentSafe(t, func() (*poolPkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(poolPkg.CalcAmountOutParams{ TokenAmountIn: tc.tokenAmountIn, TokenOut: tc.tokenOut, @@ -190,7 +190,7 @@ func TestGetAmountIn(t *testing.T) { t.Run(tc.name, func(t *testing.T) { pool, err := NewPoolSimulator(tc.entityPool) assert.Nil(t, err) - calcAmountInResult, err := testutil.MustConcurrentSafe[*poolPkg.CalcAmountInResult](t, func() (any, error) { + calcAmountInResult, err := testutil.MustConcurrentSafe(t, func() (*poolPkg.CalcAmountInResult, error) { return pool.CalcAmountIn(poolPkg.CalcAmountInParams{ TokenAmountOut: tc.tokenAmountOut, TokenIn: tc.tokenIn, diff --git a/pkg/liquidity-source/syncswapv2/stable/pool_simulator_test.go b/pkg/liquidity-source/syncswapv2/stable/pool_simulator_test.go index c0b3f3255..d92a3ae9d 100644 --- a/pkg/liquidity-source/syncswapv2/stable/pool_simulator_test.go +++ b/pkg/liquidity-source/syncswapv2/stable/pool_simulator_test.go @@ -59,7 +59,7 @@ func TestGetAmountOut(t *testing.T) { t.Run(tc.name, func(t *testing.T) { pool, err := NewPoolSimulator(tc.entityPool) assert.Nil(t, err) - calcAmountOutResult, err := testutil.MustConcurrentSafe[*poolPkg.CalcAmountOutResult](t, func() (any, error) { + calcAmountOutResult, err := testutil.MustConcurrentSafe(t, func() (*poolPkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(poolPkg.CalcAmountOutParams{ TokenAmountIn: tc.tokenAmountIn, TokenOut: tc.tokenOut, diff --git a/pkg/liquidity-source/uniswap-v1/pool_simulator_test.go b/pkg/liquidity-source/uniswap-v1/pool_simulator_test.go index b4cd6c7ce..a2b423404 100644 --- a/pkg/liquidity-source/uniswap-v1/pool_simulator_test.go +++ b/pkg/liquidity-source/uniswap-v1/pool_simulator_test.go @@ -62,7 +62,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return tc.poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tc.tokenAmountIn, TokenOut: tc.tokenOut, diff --git a/pkg/liquidity-source/uniswap-v2/pool_simulator_test.go b/pkg/liquidity-source/uniswap-v2/pool_simulator_test.go index 129810031..51c455eb8 100644 --- a/pkg/liquidity-source/uniswap-v2/pool_simulator_test.go +++ b/pkg/liquidity-source/uniswap-v2/pool_simulator_test.go @@ -69,7 +69,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return tc.poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tc.tokenAmountIn, TokenOut: tc.tokenOut, diff --git a/pkg/liquidity-source/velocore-v2/cpmm/pool_simulartor_test.go b/pkg/liquidity-source/velocore-v2/cpmm/pool_simulartor_test.go index 45d7c0161..2fc0c3d2c 100644 --- a/pkg/liquidity-source/velocore-v2/cpmm/pool_simulartor_test.go +++ b/pkg/liquidity-source/velocore-v2/cpmm/pool_simulartor_test.go @@ -36,7 +36,7 @@ func TestCalcAmountOut(t *testing.T) { simulator, err := NewPoolSimulator(entityPool) assert.Nil(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return simulator.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -72,7 +72,7 @@ func TestCalcAmountOut(t *testing.T) { simulator, err := NewPoolSimulator(entityPool) assert.Nil(t, err) - _, err = testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + _, err = testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return simulator.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -105,7 +105,7 @@ func TestCalcAmountOut(t *testing.T) { simulator, err := NewPoolSimulator(entityPool) assert.Nil(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return simulator.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -136,7 +136,7 @@ func TestCalcAmountOut(t *testing.T) { simulator, err := NewPoolSimulator(entityPool) assert.Nil(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return simulator.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, diff --git a/pkg/liquidity-source/velocore-v2/wombat-stable/pool_simulator_test.go b/pkg/liquidity-source/velocore-v2/wombat-stable/pool_simulator_test.go index 476c68a7f..0cc76a417 100644 --- a/pkg/liquidity-source/velocore-v2/wombat-stable/pool_simulator_test.go +++ b/pkg/liquidity-source/velocore-v2/wombat-stable/pool_simulator_test.go @@ -61,7 +61,7 @@ func TestCalcAmountOutConcurrentSafe(t *testing.T) { poolSim, err := NewPoolSimulator(*poolEntity) require.NoError(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return poolSim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: tc.tokenIn, diff --git a/pkg/liquidity-source/velodrome-v1/pool_simulator_test.go b/pkg/liquidity-source/velodrome-v1/pool_simulator_test.go index 1047d3dfa..9cb851df6 100644 --- a/pkg/liquidity-source/velodrome-v1/pool_simulator_test.go +++ b/pkg/liquidity-source/velodrome-v1/pool_simulator_test.go @@ -148,7 +148,7 @@ func TestPoolSimulator_getAmountOut(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return tc.poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tc.tokenAmountIn, TokenOut: tc.tokenOut, @@ -221,7 +221,7 @@ func TestPoolSimulator_getAmountIn(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountInResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountInResult, error) { return tc.poolSimulator.CalcAmountIn(poolpkg.CalcAmountInParams{ TokenAmountOut: tc.tokenAmountOut, TokenIn: tc.tokenIn, diff --git a/pkg/liquidity-source/velodrome-v2/pool_simulator_test.go b/pkg/liquidity-source/velodrome-v2/pool_simulator_test.go index 5165824bb..0e6d17062 100644 --- a/pkg/liquidity-source/velodrome-v2/pool_simulator_test.go +++ b/pkg/liquidity-source/velodrome-v2/pool_simulator_test.go @@ -154,7 +154,7 @@ func TestPoolSimulator_getAmountOut(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return tc.poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{TokenAmountIn: tc.tokenAmountIn, TokenOut: tc.tokenOut}) }) @@ -224,7 +224,7 @@ func TestPoolSimulator_getAmountIn(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountInResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountInResult, error) { return tc.poolSimulator.CalcAmountIn(poolpkg.CalcAmountInParams{ TokenAmountOut: tc.tokenAmountOut, TokenIn: tc.tokenIn, diff --git a/pkg/liquidity-source/woofi-v2/pool_simulator_test.go b/pkg/liquidity-source/woofi-v2/pool_simulator_test.go index 3d269f7e4..c10855650 100644 --- a/pkg/liquidity-source/woofi-v2/pool_simulator_test.go +++ b/pkg/liquidity-source/woofi-v2/pool_simulator_test.go @@ -58,7 +58,7 @@ func TestPoolSimulator_NewPool(t *testing.T) { pool.wooracle.StaleDuration = 300 pool.wooracle.Bound = 10000000000000000 - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(params) }) @@ -139,7 +139,7 @@ func TestPoolSimulator_CalcAmountOut_Nil_Oracle(t *testing.T) { pool.wooracle.Timestamp = time.Now().Unix() - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(params) }) @@ -215,7 +215,7 @@ func TestPoolSimulator_CalcAmountOut_Arithmetic_OverflowUnderflow(t *testing.T) pool.wooracle.StaleDuration = 300 pool.wooracle.Bound = 10000000000000000 - _, err = testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + _, err = testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(params) }) @@ -455,7 +455,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { gas: DefaultGas, } - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(tc.params) }) assert.Equal(t, tc.expectedErr, err) @@ -667,7 +667,7 @@ func TestPoolSimulator_UpdateBalance(t *testing.T) { gas: DefaultGas, } - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(tc.params) }) assert.Equal(t, tc.expectedErr, err) diff --git a/pkg/liquidity-source/woofi-v21/pool_simulator_test.go b/pkg/liquidity-source/woofi-v21/pool_simulator_test.go index 320652c53..087276cba 100644 --- a/pkg/liquidity-source/woofi-v21/pool_simulator_test.go +++ b/pkg/liquidity-source/woofi-v21/pool_simulator_test.go @@ -87,7 +87,7 @@ func TestPoolSimulator_NewPool(t *testing.T) { pool.wooracle.StaleDuration = 300 pool.wooracle.Bound = 10000000000000000 - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(params) }) @@ -163,7 +163,7 @@ func TestPoolSimulator_CalcAmountOut_Nil_Oracle(t *testing.T) { pool.wooracle.Timestamp = time.Now().Unix() - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(params) }) @@ -239,7 +239,7 @@ func TestPoolSimulator_CalcAmountOut_Nil_Oracle(t *testing.T) { // pool.wooracle.StaleDuration = 300 // pool.wooracle.Bound = 10000000000000000 -// _, err = testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { +// _, err = testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { // return pool.CalcAmountOut(params) // }) @@ -504,7 +504,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { gas: DefaultGas, } - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(tc.params) }) @@ -732,7 +732,7 @@ func TestPoolSimulator_UpdateBalance(t *testing.T) { gas: DefaultGas, } - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(tc.params) }) assert.Equal(t, tc.expectedErr, err) diff --git a/pkg/source/algebrav1/pool_simulator_test.go b/pkg/source/algebrav1/pool_simulator_test.go index 553d32114..2201423bc 100644 --- a/pkg/source/algebrav1/pool_simulator_test.go +++ b/pkg/source/algebrav1/pool_simulator_test.go @@ -43,7 +43,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { in := pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)} return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: in, @@ -101,7 +101,7 @@ func TestPoolSimulator_UpdateBalance(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { in := pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)} - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: in, TokenOut: tc.out, @@ -145,7 +145,7 @@ func TestPoolSimulator_CalcAmountOut_SPL(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - _, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + _, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { in := pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)} return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: in, @@ -183,7 +183,7 @@ func TestPoolSimulator_CalcAmountOut_CommFee(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { in := pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)} return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: in, @@ -234,7 +234,7 @@ func TestPoolSimulator_CalcAmountOut_v1_9(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { in := pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)} return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: in, @@ -274,7 +274,7 @@ func TestPoolSimulator_CalcAmountOut_DirFee(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { in := pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)} return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: in, diff --git a/pkg/source/balancer-composable-stable/pool_simulator_test.go b/pkg/source/balancer-composable-stable/pool_simulator_test.go index 0e0e20579..147886892 100644 --- a/pkg/source/balancer-composable-stable/pool_simulator_test.go +++ b/pkg/source/balancer-composable-stable/pool_simulator_test.go @@ -94,7 +94,7 @@ func TestSwap(t *testing.T) { } for i, testcase := range testCases { t.Run(fmt.Sprintf("testcase %d, tokenIn %s amountIn %s tokenOut %s", i, testcase.tokenIn, testcase.amountIn.String(), testcase.amountOut), func(t *testing.T) { - result, _ := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, _ := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut( pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ @@ -123,7 +123,7 @@ func TestCalculateInvariant(t *testing.T) { balances := []*big.Int{ b1, b2, b3, } - _, err := testutil.MustConcurrentSafe[*big.Int](t, func() (any, error) { + _, err := testutil.MustConcurrentSafe(t, func() (*big.Int, error) { return CalculateInvariant(a, balances, false) }) assert.Equal(t, err, ErrorStableGetBalanceDidntConverge) diff --git a/pkg/source/balancer/stable/pool_simulator_test.go b/pkg/source/balancer/stable/pool_simulator_test.go index c4854661b..a1b5714dc 100644 --- a/pkg/source/balancer/stable/pool_simulator_test.go +++ b/pkg/source/balancer/stable/pool_simulator_test.go @@ -56,7 +56,7 @@ func TestSwap(t *testing.T) { AmountUsd: 100000, } var tokenOut = "D" - result, _ := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, _ := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut( pool.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, diff --git a/pkg/source/balancer/weighted/pool_simulator_test.go b/pkg/source/balancer/weighted/pool_simulator_test.go index 86d2608e1..c097da9d2 100644 --- a/pkg/source/balancer/weighted/pool_simulator_test.go +++ b/pkg/source/balancer/weighted/pool_simulator_test.go @@ -27,7 +27,7 @@ func TestSwap_2token(t *testing.T) { var p, err = NewPoolSimulator(poolInfo) require.Nil(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut( pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: "BAL", Amount: big.NewInt(1000)}, @@ -59,7 +59,7 @@ func TestSwap_3token(t *testing.T) { assert.Equal(t, 0, len(p.CanSwapTo("BALxx"))) // weight(BAL)/weight(WETH) is still the same as above, so amount out should be the same - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: "BAL", Amount: big.NewInt(1000)}, TokenOut: "WETH", @@ -71,7 +71,7 @@ func TestSwap_3token(t *testing.T) { assert.Equal(t, big.NewInt(3), result.Fee.Amount) // BAL -> DAI - result, err = testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err = testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: "BAL", Amount: big.NewInt(1000)}, TokenOut: "DAI", diff --git a/pkg/source/camelot/pool_simulator_test.go b/pkg/source/camelot/pool_simulator_test.go index 9ad69a957..86d88aa70 100644 --- a/pkg/source/camelot/pool_simulator_test.go +++ b/pkg/source/camelot/pool_simulator_test.go @@ -161,7 +161,7 @@ func TestPool_getAmountOut(t *testing.T) { assert.Equal(t, []string{tc.pool.Info.Tokens[1]}, tc.pool.CanSwapTo(tc.pool.Info.Tokens[0])) assert.Equal(t, []string{tc.pool.Info.Tokens[0]}, tc.pool.CanSwapTo(tc.pool.Info.Tokens[1])) assert.Equal(t, 0, len(tc.pool.CanSwapTo("XXX"))) - amountOut, _ := testutil.MustConcurrentSafe[*big.Int](t, func() (any, error) { + amountOut, _ := testutil.MustConcurrentSafe(t, func() (*big.Int, error) { return tc.pool.getAmountOut(tc.amountIn, tc.tokenIn), nil }) @@ -175,7 +175,7 @@ func TestPool_getAmountOut(t *testing.T) { } } // When using CalcAmountOut(), some test case will fail the K invariant check. So we don't check the returned (result, err). - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return tc.pool.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: tc.tokenIn, diff --git a/pkg/source/curve/aave/pool_simulator_test.go b/pkg/source/curve/aave/pool_simulator_test.go index 6c87b4515..4515184ec 100644 --- a/pkg/source/curve/aave/pool_simulator_test.go +++ b/pkg/source/curve/aave/pool_simulator_test.go @@ -51,7 +51,7 @@ func TestCalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut( pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, @@ -136,7 +136,7 @@ func TestGetDyVirtualPrice(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - dy, err := testutil.MustConcurrentSafe[*big.Int](t, func() (any, error) { + dy, err := testutil.MustConcurrentSafe(t, func() (*big.Int, error) { dy, _, err := p.GetDy(tc.i, tc.j, utils.NewBig10(tc.dx), nil) return dy, err }) @@ -144,7 +144,7 @@ func TestGetDyVirtualPrice(t *testing.T) { assert.Equal(t, utils.NewBig10(tc.expOut), dy) // test using cached D - dy, err = testutil.MustConcurrentSafe[*big.Int](t, func() (any, error) { + dy, err = testutil.MustConcurrentSafe(t, func() (*big.Int, error) { dy, _, err := p.GetDy(tc.i, tc.j, utils.NewBig10(tc.dx), dCached) return dy, err }) diff --git a/pkg/source/curve/base/pool_simulator_test.go b/pkg/source/curve/base/pool_simulator_test.go index b56972aeb..e11dd2e58 100644 --- a/pkg/source/curve/base/pool_simulator_test.go +++ b/pkg/source/curve/base/pool_simulator_test.go @@ -53,7 +53,7 @@ func TestCalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, @@ -89,7 +89,7 @@ func TestCalcAmountOut_interpolate_from_initialA_and_futureA(t *testing.T) { }) require.Nil(t, err) - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: "A", Amount: big.NewInt(510000)}, TokenOut: "B", @@ -172,7 +172,7 @@ func TestGetDyVirtualPrice(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - dy, err := testutil.MustConcurrentSafe[*big.Int](t, func() (any, error) { + dy, err := testutil.MustConcurrentSafe(t, func() (*big.Int, error) { dy, _, err := p.GetDy(tc.i, tc.j, bignumber.NewBig10(tc.dx), nil) return dy, err }) @@ -180,7 +180,7 @@ func TestGetDyVirtualPrice(t *testing.T) { assert.Equal(t, bignumber.NewBig10(tc.expOut), dy) // test using cached D - dy, err = testutil.MustConcurrentSafe[*big.Int](t, func() (any, error) { + dy, err = testutil.MustConcurrentSafe(t, func() (*big.Int, error) { dy, _, err := p.GetDy(tc.i, tc.j, bignumber.NewBig10(tc.dx), dCached) return dy, err }) diff --git a/pkg/source/curve/compound/pool_simulator_test.go b/pkg/source/curve/compound/pool_simulator_test.go index 6ef42d9ee..6707c3a12 100644 --- a/pkg/source/curve/compound/pool_simulator_test.go +++ b/pkg/source/curve/compound/pool_simulator_test.go @@ -79,7 +79,7 @@ func TestCalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)}, TokenOut: tc.out, @@ -161,7 +161,7 @@ func TestCalcAmountIn(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { p := sims[tc.poolIdx] - amountIn, err := testutil.MustConcurrentSafe[*pool.CalcAmountInResult](t, func() (any, error) { + amountIn, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountInResult, error) { return p.CalcAmountIn(pool.CalcAmountInParams{ TokenAmountOut: pool.TokenAmount{Token: tc.tokenOut, Amount: tc.amountOut}, TokenIn: tc.tokenIn, diff --git a/pkg/source/curve/meta/pool_simulator_test.go b/pkg/source/curve/meta/pool_simulator_test.go index 182e72aa1..e3a74ed78 100644 --- a/pkg/source/curve/meta/pool_simulator_test.go +++ b/pkg/source/curve/meta/pool_simulator_test.go @@ -68,7 +68,7 @@ func TestCalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, @@ -118,7 +118,7 @@ func TestCalcAmountOut_Underflow(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - _, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + _, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, @@ -191,7 +191,7 @@ func TestSwappable(t *testing.T) { for idx, tc := range errorcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - _, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + _, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(100000000)}, TokenOut: tc.out, @@ -239,7 +239,7 @@ func TestUpdateBalance(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { amountIn := pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)} - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: amountIn, TokenOut: tc.out, diff --git a/pkg/source/curve/plain-oracle/pool_simulator_test.go b/pkg/source/curve/plain-oracle/pool_simulator_test.go index 61ea0d07f..af2af118c 100644 --- a/pkg/source/curve/plain-oracle/pool_simulator_test.go +++ b/pkg/source/curve/plain-oracle/pool_simulator_test.go @@ -49,7 +49,7 @@ func TestCalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, @@ -108,7 +108,7 @@ func TestGetDyVirtualPrice(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - dy, err := testutil.MustConcurrentSafe[*big.Int](t, func() (any, error) { + dy, err := testutil.MustConcurrentSafe(t, func() (*big.Int, error) { dy, _, err := p.GetDy(tc.i, tc.j, bignumber.NewBig10(tc.dx), nil) return dy, err }) @@ -116,7 +116,7 @@ func TestGetDyVirtualPrice(t *testing.T) { assert.Equal(t, bignumber.NewBig10(tc.expOut), dy) // test using cached D - dy, err = testutil.MustConcurrentSafe[*big.Int](t, func() (any, error) { + dy, err = testutil.MustConcurrentSafe(t, func() (*big.Int, error) { dy, _, err := p.GetDy(tc.i, tc.j, bignumber.NewBig10(tc.dx), dCached) return dy, err }) diff --git a/pkg/source/curve/tricrypto/pool_simulator_test.go b/pkg/source/curve/tricrypto/pool_simulator_test.go index 7c9d25a53..b280c09b3 100644 --- a/pkg/source/curve/tricrypto/pool_simulator_test.go +++ b/pkg/source/curve/tricrypto/pool_simulator_test.go @@ -42,7 +42,7 @@ func TestCalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, @@ -84,7 +84,7 @@ func TestUpdateBalance(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { amountIn := pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)} - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: amountIn, TokenOut: tc.out, diff --git a/pkg/source/curve/two/pool_simulator_test.go b/pkg/source/curve/two/pool_simulator_test.go index b4681251d..3acd2675f 100644 --- a/pkg/source/curve/two/pool_simulator_test.go +++ b/pkg/source/curve/two/pool_simulator_test.go @@ -39,7 +39,7 @@ func TestCalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, diff --git a/pkg/source/dmm/pool_simulator_test.go b/pkg/source/dmm/pool_simulator_test.go index 65ea8bf3c..97cbb3688 100644 --- a/pkg/source/dmm/pool_simulator_test.go +++ b/pkg/source/dmm/pool_simulator_test.go @@ -80,7 +80,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { p, err := NewPoolSimulator(tt.fields.entityPool) assert.Nil(t1, err) - got, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + got, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut( pool.CalcAmountOutParams{ TokenAmountIn: tt.args.tokenAmountIn, diff --git a/pkg/source/dodo/pool_simulator_test.go b/pkg/source/dodo/pool_simulator_test.go index f5a69e548..1911eaa5a 100644 --- a/pkg/source/dodo/pool_simulator_test.go +++ b/pkg/source/dodo/pool_simulator_test.go @@ -55,7 +55,7 @@ func TestCalcAmountOut(t *testing.T) { require.Nil(t, err) amountIn := pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)} - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: amountIn, TokenOut: tc.out, @@ -124,7 +124,7 @@ func TestCalcAmountOut_PoolDepleted(t *testing.T) { // 1st swap 500 USDT { amountIn := pool.TokenAmount{Token: "0xc2132d05d31c914a87c6611c10748aeb04b58e8f", Amount: bignumber.NewBig10("500000000")} - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return poolSim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: amountIn, TokenOut: "0x2791bca1f2de4661ed88a30c99a7a9449aa84174", @@ -144,7 +144,7 @@ func TestCalcAmountOut_PoolDepleted(t *testing.T) { // 2nd swap 1000 USDT, if there are no reserve check then this will yield negative output { amountIn := pool.TokenAmount{Token: "0xc2132d05d31c914a87c6611c10748aeb04b58e8f", Amount: bignumber.NewBig10("1000000000")} - _, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + _, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return poolSim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: amountIn, TokenOut: "0x2791bca1f2de4661ed88a30c99a7a9449aa84174", diff --git a/pkg/source/equalizer/pool_simulator_test.go b/pkg/source/equalizer/pool_simulator_test.go index 981613e74..c089be238 100644 --- a/pkg/source/equalizer/pool_simulator_test.go +++ b/pkg/source/equalizer/pool_simulator_test.go @@ -63,7 +63,7 @@ func TestCalcAmountOutConcurrentSafe(t *testing.T) { poolSim, err := NewPoolSimulator(*poolEntity) require.NoError(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return poolSim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: tc.tokenIn, diff --git a/pkg/source/fraxswap/pool_simulator_test.go b/pkg/source/fraxswap/pool_simulator_test.go index 0a5eb07de..5639f935a 100644 --- a/pkg/source/fraxswap/pool_simulator_test.go +++ b/pkg/source/fraxswap/pool_simulator_test.go @@ -79,7 +79,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { }) require.Nil(t, err) - got, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + got, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut( pool.CalcAmountOutParams{ TokenAmountIn: tt.args.tokenAmountIn, diff --git a/pkg/source/fulcrom/pool_simulator_test.go b/pkg/source/fulcrom/pool_simulator_test.go index ecce05ee6..5eb10834c 100644 --- a/pkg/source/fulcrom/pool_simulator_test.go +++ b/pkg/source/fulcrom/pool_simulator_test.go @@ -97,7 +97,7 @@ func TestCalcAmountOutConcurrentSafe(t *testing.T) { poolSim, err := NewPoolSimulator(*poolEntity) require.NoError(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return poolSim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: tc.tokenIn, diff --git a/pkg/source/fxdx/pool_simulator_test.go b/pkg/source/fxdx/pool_simulator_test.go index a1d543c26..3aa09e65d 100644 --- a/pkg/source/fxdx/pool_simulator_test.go +++ b/pkg/source/fxdx/pool_simulator_test.go @@ -72,7 +72,7 @@ func TestCalcAmountOutConcurrentSafe(t *testing.T) { poolSim, err := NewPoolSimulator(*poolEntity) require.NoError(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return poolSim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: tc.tokenIn, diff --git a/pkg/source/gmx-glp/pool_simulator_test.go b/pkg/source/gmx-glp/pool_simulator_test.go index a9251da73..e4ed7dfd2 100644 --- a/pkg/source/gmx-glp/pool_simulator_test.go +++ b/pkg/source/gmx-glp/pool_simulator_test.go @@ -80,7 +80,7 @@ func TestPoolSimulator_MintAndStakeGlp(t *testing.T) { pool, err := NewPoolSimulator(tc.entityPool) assert.Nil(t, err) - _, err = testutil.MustConcurrentSafe[*poolPkg.CalcAmountOutResult](t, func() (any, error) { + _, err = testutil.MustConcurrentSafe(t, func() (*poolPkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(poolPkg.CalcAmountOutParams{ TokenAmountIn: tc.tokenAmountIn, TokenOut: tc.tokenOut, diff --git a/pkg/source/gmx/pool_simulator_test.go b/pkg/source/gmx/pool_simulator_test.go index ea5192c41..da8ca90f0 100644 --- a/pkg/source/gmx/pool_simulator_test.go +++ b/pkg/source/gmx/pool_simulator_test.go @@ -366,7 +366,7 @@ func TestPool_CalcAmountOut(t *testing.T) { t.Run(tc.name, func(t *testing.T) { pool, _ := NewPoolSimulator(tc.entityPool) - calcAmountOutResult, err := testutil.MustConcurrentSafe[*poolPkg.CalcAmountOutResult](t, func() (any, error) { + calcAmountOutResult, err := testutil.MustConcurrentSafe(t, func() (*poolPkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(poolPkg.CalcAmountOutParams{ TokenAmountIn: tc.tokenAmountIn, TokenOut: tc.tokenOut, diff --git a/pkg/source/iziswap/pool_simulator_test.go b/pkg/source/iziswap/pool_simulator_test.go index 835f6b534..c6856578d 100644 --- a/pkg/source/iziswap/pool_simulator_test.go +++ b/pkg/source/iziswap/pool_simulator_test.go @@ -45,7 +45,7 @@ func TestCalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { amountIn := pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)} - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: amountIn, TokenOut: tc.out, @@ -264,7 +264,7 @@ func TestCalcAmountIn(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { p := sims[tc.poolIdx] - amountIn, err := testutil.MustConcurrentSafe[*pool.CalcAmountInResult](t, func() (any, error) { + amountIn, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountInResult, error) { return p.CalcAmountIn(pool.CalcAmountInParams{ TokenAmountOut: pool.TokenAmount{ Token: tc.tokenOut, diff --git a/pkg/source/kokonut-crypto/pool_simulator_test.go b/pkg/source/kokonut-crypto/pool_simulator_test.go index d3dcd4208..2c378ad2f 100644 --- a/pkg/source/kokonut-crypto/pool_simulator_test.go +++ b/pkg/source/kokonut-crypto/pool_simulator_test.go @@ -34,7 +34,7 @@ func TestCalcAmountOut(t *testing.T) { assert.Nil(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return kokonutPool.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: "0xd9aaec86b65d86f6a7b5b1b0c42ffa531710b6ca", diff --git a/pkg/source/kyber-pmm/pool_simulator_test.go b/pkg/source/kyber-pmm/pool_simulator_test.go index cf1b34c2e..ed1c735ec 100644 --- a/pkg/source/kyber-pmm/pool_simulator_test.go +++ b/pkg/source/kyber-pmm/pool_simulator_test.go @@ -89,7 +89,7 @@ func TestPoolSimulator_getAmountOut(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - amountOut, err := testutil.MustConcurrentSafe[*big.Float](t, func() (any, error) { + amountOut, err := testutil.MustConcurrentSafe(t, func() (*big.Float, error) { return getAmountOut(tt.args.amountIn, tt.args.priceLevels) }) assert.Equal(t, tt.expectedErr, err) @@ -173,7 +173,7 @@ func TestPoolSimulator_getAmountIn(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - amountIn, err := testutil.MustConcurrentSafe[*big.Float](t, func() (any, error) { + amountIn, err := testutil.MustConcurrentSafe(t, func() (*big.Float, error) { return getAmountIn(tt.args.amountOut, tt.args.priceLevels) }) assert.Equal(t, tt.expectedErr, err) diff --git a/pkg/source/lido-steth/pool_simulator_test.go b/pkg/source/lido-steth/pool_simulator_test.go index b585d6914..985b39611 100644 --- a/pkg/source/lido-steth/pool_simulator_test.go +++ b/pkg/source/lido-steth/pool_simulator_test.go @@ -43,7 +43,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { for _, amountIn := range testamount { t.Run(fmt.Sprintf("deposit %v ETH in should get %v stETH out", amountIn, amountIn), func(t *testing.T) { tokAmountIn := pool.TokenAmount{Token: tokens[0], Amount: amountIn} - got, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + got, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: tokAmountIn, TokenOut: tokens[1], diff --git a/pkg/source/lido/pool_simulator_test.go b/pkg/source/lido/pool_simulator_test.go index 6e7058d0b..7a6a96995 100644 --- a/pkg/source/lido/pool_simulator_test.go +++ b/pkg/source/lido/pool_simulator_test.go @@ -41,7 +41,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, diff --git a/pkg/source/limitorder/pool_simulator_calc_amount_in_test.go b/pkg/source/limitorder/pool_simulator_calc_amount_in_test.go index b810506d2..90183d4c1 100644 --- a/pkg/source/limitorder/pool_simulator_calc_amount_in_test.go +++ b/pkg/source/limitorder/pool_simulator_calc_amount_in_test.go @@ -252,7 +252,7 @@ func TestPool_CalcAmountIn(t *testing.T) { t.Run(tt.name, func(t *testing.T) { p, err := NewPoolSimulator(tt.poolEntity) assert.Equal(t, nil, err) - got, err := testutil.MustConcurrentSafe[*pool.CalcAmountInResult](t, func() (any, error) { + got, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountInResult, error) { limit := swaplimit.NewInventory("", p.CalculateLimit()) return p.CalcAmountIn( pool.CalcAmountInParams{ @@ -346,7 +346,7 @@ func TestPool_CalcAmountOut_CalcAmountIn(t *testing.T) { t.Run(tt.name, func(t *testing.T) { p, err := NewPoolSimulator(tt.poolEntity) assert.Equal(t, nil, err) - calcAmountOutResult, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + calcAmountOutResult, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { limit := swaplimit.NewInventory("", p.CalculateLimit()) return p.CalcAmountOut( pool.CalcAmountOutParams{ @@ -362,7 +362,7 @@ func TestPool_CalcAmountOut_CalcAmountIn(t *testing.T) { assert.Equal(t, tt.args.amountOut, calcAmountOutResult.TokenAmountOut.Amount) - calcAmountInResult, err := testutil.MustConcurrentSafe[*pool.CalcAmountInResult](t, func() (any, error) { + calcAmountInResult, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountInResult, error) { limit := swaplimit.NewInventory("", p.CalculateLimit()) return p.CalcAmountIn( pool.CalcAmountInParams{ diff --git a/pkg/source/limitorder/pool_simulator_test.go b/pkg/source/limitorder/pool_simulator_test.go index 4b8853649..2701758e5 100644 --- a/pkg/source/limitorder/pool_simulator_test.go +++ b/pkg/source/limitorder/pool_simulator_test.go @@ -849,7 +849,7 @@ func TestPool_CalcAmountOut(t *testing.T) { t.Run(tt.name, func(t *testing.T) { p, err := NewPoolSimulator(tt.poolEntity) assert.Equal(t, nil, err) - got, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + got, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { limit := swaplimit.NewInventory("", p.CalculateLimit()) return p.CalcAmountOut( pool.CalcAmountOutParams{ diff --git a/pkg/source/liquiditybookv20/pool_simulator_test.go b/pkg/source/liquiditybookv20/pool_simulator_test.go index 3d44aa0d0..b120d7fd9 100644 --- a/pkg/source/liquiditybookv20/pool_simulator_test.go +++ b/pkg/source/liquiditybookv20/pool_simulator_test.go @@ -61,7 +61,7 @@ func TestCalcAmountOutConcurrentSafe(t *testing.T) { poolSim, err := NewPoolSimulator(*poolEntity) require.NoError(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return poolSim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: tc.tokenIn, diff --git a/pkg/source/liquiditybookv21/pool_simulator_test.go b/pkg/source/liquiditybookv21/pool_simulator_test.go index c5c3f2c5d..d609859b9 100644 --- a/pkg/source/liquiditybookv21/pool_simulator_test.go +++ b/pkg/source/liquiditybookv21/pool_simulator_test.go @@ -35,7 +35,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { tokenOut = "0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e" ) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return simulator.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -59,7 +59,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { tokenOut = "0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e" ) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return simulator.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -83,7 +83,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { tokenOut = "0x6e84a6216ea6dacc71ee8e6b0a5b7322eebc0fdd" ) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return simulator.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -117,7 +117,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { tokenOut = "0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e" ) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return simulator.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: tokenOut, @@ -290,7 +290,7 @@ func TestPoolSimulator_CalcAmountIn(t *testing.T) { simulator, err := NewPoolSimulator(entityPool) assert.Nil(t, err) - got, err := testutil.MustConcurrentSafe[*pool.CalcAmountInResult](t, func() (any, error) { + got, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountInResult, error) { return simulator.CalcAmountIn(tt.params) }) if err != nil { diff --git a/pkg/source/madmex/pool_simulator_test.go b/pkg/source/madmex/pool_simulator_test.go index c328fb0e2..bc52aff75 100644 --- a/pkg/source/madmex/pool_simulator_test.go +++ b/pkg/source/madmex/pool_simulator_test.go @@ -42,7 +42,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, @@ -81,7 +81,7 @@ func TestPoolSimulator_UpdateBalance(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { amountIn := pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)} - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: amountIn, TokenOut: tc.out, diff --git a/pkg/source/makerpsm/pool_simulator_test.go b/pkg/source/makerpsm/pool_simulator_test.go index 6f6df4fd8..ed53bfb6c 100644 --- a/pkg/source/makerpsm/pool_simulator_test.go +++ b/pkg/source/makerpsm/pool_simulator_test.go @@ -33,7 +33,7 @@ func TestGetAmountOut_sellGemNoFee(t *testing.T) { // https://github.com/makerdao/dss-psm/blob/master/src/tests/psm.t.sol#L166 pool100 := newPool(t, big.NewInt(100), big.NewInt(0), big.NewInt(0)) inAmount := pool.TokenAmount{Token: "USDX", Amount: new(big.Int).Mul(big.NewInt(100), USDX_WAD)} - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return pool100.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: inAmount, TokenOut: DAIAddress, @@ -45,7 +45,7 @@ func TestGetAmountOut_sellGemNoFee(t *testing.T) { // reach dept ceiling pool100.UpdateBalance(pool.UpdateBalanceParams{TokenAmountIn: inAmount, TokenAmountOut: *out.TokenAmountOut, Fee: *out.Fee}) - _, err = testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + _, err = testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return pool100.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: inAmount, TokenOut: DAIAddress, @@ -59,7 +59,7 @@ func TestGetAmountOut_sellGemWithFee(t *testing.T) { // https://github.com/makerdao/dss-psm/blob/master/src/tests/psm.t.sol#L189 pool100 := newPool(t, big.NewInt(100), TOLL_ONE_PCT, big.NewInt(0)) inAmount := pool.TokenAmount{Token: "USDX", Amount: new(big.Int).Mul(big.NewInt(100), USDX_WAD)} - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return pool100.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: inAmount, TokenOut: DAIAddress, @@ -75,7 +75,7 @@ func TestGetAmountOut_swapBothNoFee(t *testing.T) { // sell 100 USDX pool100 := newPool(t, big.NewInt(100), big.NewInt(0), big.NewInt(0)) inAmount := pool.TokenAmount{Token: "USDX", Amount: new(big.Int).Mul(big.NewInt(100), USDX_WAD)} - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return pool100.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: inAmount, TokenOut: DAIAddress, @@ -89,7 +89,7 @@ func TestGetAmountOut_swapBothNoFee(t *testing.T) { // then buy back with 40 eth inAmount = pool.TokenAmount{Token: DAIAddress, Amount: new(big.Int).Mul(big.NewInt(40), bignumber.BONE)} - out, err = testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err = testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return pool100.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: inAmount, TokenOut: "USDX", @@ -106,7 +106,7 @@ func TestGetAmountOut_swapBothWithFee(t *testing.T) { // sell 100 USDX -> 95 eth pool100 := newPool(t, big.NewInt(100), new(big.Int).Mul(big.NewInt(5), TOLL_ONE_PCT), new(big.Int).Mul(big.NewInt(10), TOLL_ONE_PCT)) inAmount := pool.TokenAmount{Token: "USDX", Amount: new(big.Int).Mul(big.NewInt(100), USDX_WAD)} - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return pool100.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: inAmount, TokenOut: DAIAddress, @@ -120,7 +120,7 @@ func TestGetAmountOut_swapBothWithFee(t *testing.T) { // then buy back with 44 eth -> 40 usdx inAmount = pool.TokenAmount{Token: DAIAddress, Amount: new(big.Int).Mul(big.NewInt(44), bignumber.BONE)} - out, err = testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err = testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return pool100.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: inAmount, TokenOut: "USDX", diff --git a/pkg/source/mantisswap/pool_simulator_test.go b/pkg/source/mantisswap/pool_simulator_test.go index b2c59fb1b..b1630ae4a 100644 --- a/pkg/source/mantisswap/pool_simulator_test.go +++ b/pkg/source/mantisswap/pool_simulator_test.go @@ -65,7 +65,7 @@ func TestCalcAmountOutConcurrentSafe(t *testing.T) { poolSim, err := NewPoolSimulator(*poolEntity) require.NoError(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return poolSim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: tc.tokenIn, diff --git a/pkg/source/maverickv1/pool_simulator_test.go b/pkg/source/maverickv1/pool_simulator_test.go index d431f212c..0e2e13fc9 100644 --- a/pkg/source/maverickv1/pool_simulator_test.go +++ b/pkg/source/maverickv1/pool_simulator_test.go @@ -29,7 +29,7 @@ func TestPoolCalcAmountOut(t *testing.T) { assert.Equal(t, big.NewInt(-7), maverickPool.state.minBinMapIndex) assert.Equal(t, big.NewInt(-6), maverickPool.state.maxBinMapIndex) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return maverickPool.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: "0x4200000000000000000000000000000000000006", @@ -78,7 +78,7 @@ func TestPoolCalcAmountIn(t *testing.T) { assert.Equal(t, big.NewInt(-7), maverickPool.state.minBinMapIndex) assert.Equal(t, big.NewInt(-6), maverickPool.state.maxBinMapIndex) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountInResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountInResult, error) { return maverickPool.CalcAmountIn(pool.CalcAmountInParams{ TokenAmountOut: pool.TokenAmount{ Token: "0x50c5725949a6f0c72e6c4a641f24049a917db0cb", @@ -179,7 +179,7 @@ func TestUpdateBalance(t *testing.T) { Amount: bignumber.NewBig10(tc.amountIn), } cloned := sim.CloneState() - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return sim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: in, TokenOut: tc.tokenOut, @@ -187,7 +187,7 @@ func TestUpdateBalance(t *testing.T) { }) require.Nil(t, err) require.Equal(t, tc.expAmountOut, result.TokenAmountOut.Amount.String()) - resultBeforeUpdate, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + resultBeforeUpdate, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return sim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: in, TokenOut: tc.tokenOut, @@ -204,7 +204,7 @@ func TestUpdateBalance(t *testing.T) { } sim.UpdateBalance(updateBalanceParams) - resultAfterUpdate, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + resultAfterUpdate, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return sim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: in, TokenOut: tc.tokenOut, @@ -214,7 +214,7 @@ func TestUpdateBalance(t *testing.T) { require.NotEqual(t, result.TokenAmountOut.Amount.String(), resultAfterUpdate.TokenAmountOut.Amount.String()) } - resultOfCloned, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + resultOfCloned, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return cloned.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: in, TokenOut: tc.tokenOut, @@ -257,7 +257,7 @@ func TestUpdateBalanceNextTick(t *testing.T) { Token: tc.tokenIn, Amount: bignumber.NewBig10(tc.amountIn), } - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return sim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: in, TokenOut: tc.tokenOut, diff --git a/pkg/source/metavault/pool_simulator_test.go b/pkg/source/metavault/pool_simulator_test.go index db11f7c60..6fdc278e4 100644 --- a/pkg/source/metavault/pool_simulator_test.go +++ b/pkg/source/metavault/pool_simulator_test.go @@ -47,7 +47,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, @@ -99,7 +99,7 @@ func TestPoolSimulator_UpdateBalance(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { amountIn := pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)} - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: amountIn, TokenOut: tc.out, diff --git a/pkg/source/nuriv2/pool_simulator_test.go b/pkg/source/nuriv2/pool_simulator_test.go index 0f681f2a4..11b7924e3 100644 --- a/pkg/source/nuriv2/pool_simulator_test.go +++ b/pkg/source/nuriv2/pool_simulator_test.go @@ -43,7 +43,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { in := pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)} - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: in, TokenOut: tc.out, diff --git a/pkg/source/pancakev3/pool_simulator_bigint_test.go b/pkg/source/pancakev3/pool_simulator_bigint_test.go index be80bc6ac..24b72d09d 100644 --- a/pkg/source/pancakev3/pool_simulator_bigint_test.go +++ b/pkg/source/pancakev3/pool_simulator_bigint_test.go @@ -116,7 +116,7 @@ func TestPool_CalcAmountOut(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { p, _ := NewPoolSimulatorBigInt(tt.entityPool, tt.chainId) - calcAmountOutResult, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + calcAmountOutResult, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: tt.tokenAmountIn, TokenOut: tt.tokenOut, @@ -242,7 +242,7 @@ func TestPoolSimulator_CalcAmountIn(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { p, _ := NewPoolSimulatorBigInt(tt.entityPool, tt.chainId) - calcAmountOutResult, err := testutil.MustConcurrentSafe[*pool.CalcAmountInResult](t, func() (any, error) { + calcAmountOutResult, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountInResult, error) { return p.CalcAmountIn(pool.CalcAmountInParams{ TokenAmountOut: tt.tokenAmountOut, TokenIn: tt.tokenIn, diff --git a/pkg/source/pancakev3/pool_simulator_test.go b/pkg/source/pancakev3/pool_simulator_test.go index 0a71aa36a..909e09e72 100644 --- a/pkg/source/pancakev3/pool_simulator_test.go +++ b/pkg/source/pancakev3/pool_simulator_test.go @@ -74,7 +74,7 @@ func TestCalcAmountOutConcurrentSafe(t *testing.T) { poolSim, err := NewPoolSimulatorBigInt(*poolEntity, valueobject.ChainIDEthereum) require.NoError(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return poolSim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: tc.tokenIn, @@ -95,7 +95,7 @@ func TestCalcAmountOutConcurrentSafe(t *testing.T) { poolSim, err := NewPoolSimulator(*poolEntity, valueobject.ChainIDEthereum) require.NoError(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return poolSim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: tc.tokenIn, diff --git a/pkg/source/platypus/pool_simulator_test.go b/pkg/source/platypus/pool_simulator_test.go index 6db8aa170..026daca1d 100644 --- a/pkg/source/platypus/pool_simulator_test.go +++ b/pkg/source/platypus/pool_simulator_test.go @@ -40,7 +40,7 @@ func TestPoolSimulator_CalcAmountOut_Base(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, @@ -79,7 +79,7 @@ func TestPoolSimulator_CalcAmountOut_SAvax(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, @@ -103,7 +103,7 @@ func TestPoolSimulator_DiffAggAccount(t *testing.T) { }, valueobject.ChainIDAvalancheCChain) require.Nil(t, err) - _, err = testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + _, err = testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: "A", Amount: big.NewInt(1)}, TokenOut: "B", diff --git a/pkg/source/pol-matic/pool_simulator_test.go b/pkg/source/pol-matic/pool_simulator_test.go index f44882055..8e3b714e5 100644 --- a/pkg/source/pol-matic/pool_simulator_test.go +++ b/pkg/source/pol-matic/pool_simulator_test.go @@ -58,7 +58,7 @@ func TestCalcAmountOutConcurrentSafe(t *testing.T) { poolSim, err := NewPoolSimulator(*poolEntity) require.NoError(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return poolSim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: tc.tokenIn, diff --git a/pkg/source/quickperps/pool_simulator_test.go b/pkg/source/quickperps/pool_simulator_test.go index 8564b5055..dcd579fcf 100644 --- a/pkg/source/quickperps/pool_simulator_test.go +++ b/pkg/source/quickperps/pool_simulator_test.go @@ -94,7 +94,7 @@ func TestPool_CalcAmountOut(t *testing.T) { tc.entityPool.Extra = string(extraBytes) pool, _ := NewPoolSimulator(tc.entityPool) - calcAmountOutResult, err := testutil.MustConcurrentSafe[*poolPkg.CalcAmountOutResult](t, func() (any, error) { + calcAmountOutResult, err := testutil.MustConcurrentSafe(t, func() (*poolPkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(poolPkg.CalcAmountOutParams{ TokenAmountIn: tc.tokenAmountIn, TokenOut: tc.tokenOut, diff --git a/pkg/source/ramsesv2/pool_simulator_test.go b/pkg/source/ramsesv2/pool_simulator_test.go index 0cc27ed50..7cc746091 100644 --- a/pkg/source/ramsesv2/pool_simulator_test.go +++ b/pkg/source/ramsesv2/pool_simulator_test.go @@ -43,7 +43,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { in := pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)} - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: in, TokenOut: tc.out, diff --git a/pkg/source/saddle/pool_simulator_test.go b/pkg/source/saddle/pool_simulator_test.go index 0016aa798..c93bfafab 100644 --- a/pkg/source/saddle/pool_simulator_test.go +++ b/pkg/source/saddle/pool_simulator_test.go @@ -53,7 +53,7 @@ func TestCalcAmountOut_Saddle(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, @@ -96,7 +96,7 @@ func TestCalcAmountOut_Nerve(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, @@ -144,7 +144,7 @@ func TestCalcAmountOut_OneSwap(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, @@ -193,7 +193,7 @@ func TestCalcAmountOut_IronStable(t *testing.T) { for idx, tc := range testcases { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{Token: tc.in, Amount: big.NewInt(tc.inAmount)}, TokenOut: tc.out, @@ -243,7 +243,7 @@ func TestUpdateBalance_Saddle(t *testing.T) { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { cloned := p.CloneState() amountIn := pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)} - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: amountIn, TokenOut: tc.out, diff --git a/pkg/source/smardex/pool_simulator_test.go b/pkg/source/smardex/pool_simulator_test.go index f8f6599fc..5a278168c 100644 --- a/pkg/source/smardex/pool_simulator_test.go +++ b/pkg/source/smardex/pool_simulator_test.go @@ -79,7 +79,7 @@ func TestCalcAmountOut(t *testing.T) { now = func() time.Time { return time.Unix(TIMESTAMP_JAN_2020, 0) } - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return poolSimulator.CalcAmountOut( poolpkg.CalcAmountOutParams{ TokenAmountIn: poolpkg.TokenAmount{ @@ -188,7 +188,7 @@ func TestGetAmountOut(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - result, err := testutil.MustConcurrentSafe[GetAmountResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (GetAmountResult, error) { return getAmountOut(tc.amountParams) }) if err != nil { @@ -329,7 +329,7 @@ func TestUpdateBalance(t *testing.T) { now = func() time.Time { return time.Unix(TIMESTAMP_JAN_2020, 0) } - result, _ := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, _ := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: tokenAmountIn, TokenOut: "token1", diff --git a/pkg/source/solidly-v3/pool_simulator_test.go b/pkg/source/solidly-v3/pool_simulator_test.go index 3bd14a49f..2ea1e9fc7 100644 --- a/pkg/source/solidly-v3/pool_simulator_test.go +++ b/pkg/source/solidly-v3/pool_simulator_test.go @@ -69,7 +69,7 @@ func TestCalcAmountOutConcurrentSafe(t *testing.T) { poolSim, err := NewPoolSimulator(*poolEntity, valueobject.ChainIDEthereum) require.NoError(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return poolSim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: tc.tokenIn, @@ -113,7 +113,7 @@ func TestPoolSimulator_CalcAmountIn(t *testing.T) { poolSim, err := NewPoolSimulator(*poolEntity, valueobject.ChainIDEthereum) require.NoError(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountInResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountInResult, error) { return poolSim.CalcAmountIn(pool.CalcAmountInParams{ TokenAmountOut: pool.TokenAmount{ Token: tc.tokenOut, diff --git a/pkg/source/swapbased-perp/pool_simulator_test.go b/pkg/source/swapbased-perp/pool_simulator_test.go index 1ebd45ea9..45eb23cc9 100644 --- a/pkg/source/swapbased-perp/pool_simulator_test.go +++ b/pkg/source/swapbased-perp/pool_simulator_test.go @@ -366,7 +366,7 @@ func TestPool_CalcAmountOut(t *testing.T) { t.Run(tc.name, func(t *testing.T) { pool, _ := NewPoolSimulator(tc.entityPool) - calcAmountOutResult, err := testutil.MustConcurrentSafe[*poolPkg.CalcAmountOutResult](t, func() (any, error) { + calcAmountOutResult, err := testutil.MustConcurrentSafe(t, func() (*poolPkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(poolPkg.CalcAmountOutParams{ TokenAmountIn: tc.tokenAmountIn, TokenOut: tc.tokenOut, diff --git a/pkg/source/syncswap/syncswapclassic/pool_simulator_test.go b/pkg/source/syncswap/syncswapclassic/pool_simulator_test.go index ee87c2e54..96c8f4fd8 100644 --- a/pkg/source/syncswap/syncswapclassic/pool_simulator_test.go +++ b/pkg/source/syncswap/syncswapclassic/pool_simulator_test.go @@ -94,7 +94,7 @@ func TestGetAmountOut(t *testing.T) { t.Run(tc.name, func(t *testing.T) { pool, err := NewPoolSimulator(tc.entityPool) assert.Nil(t, err) - calcAmountOutResult, err := testutil.MustConcurrentSafe[*poolPkg.CalcAmountOutResult](t, func() (any, error) { + calcAmountOutResult, err := testutil.MustConcurrentSafe(t, func() (*poolPkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(poolPkg.CalcAmountOutParams{ TokenAmountIn: tc.tokenAmountIn, TokenOut: tc.tokenOut, @@ -190,7 +190,7 @@ func TestGetAmountIn(t *testing.T) { t.Run(tc.name, func(t *testing.T) { pool, err := NewPoolSimulator(tc.entityPool) assert.Nil(t, err) - calcAmountInResult, err := testutil.MustConcurrentSafe[*poolPkg.CalcAmountInResult](t, func() (any, error) { + calcAmountInResult, err := testutil.MustConcurrentSafe(t, func() (*poolPkg.CalcAmountInResult, error) { return pool.CalcAmountIn(poolPkg.CalcAmountInParams{ TokenAmountOut: tc.tokenAmountOut, TokenIn: tc.tokenIn, diff --git a/pkg/source/syncswap/syncswapstable/pool_simulator_test.go b/pkg/source/syncswap/syncswapstable/pool_simulator_test.go index f039996a3..42bea1ce4 100644 --- a/pkg/source/syncswap/syncswapstable/pool_simulator_test.go +++ b/pkg/source/syncswap/syncswapstable/pool_simulator_test.go @@ -92,7 +92,7 @@ func TestGetAmountOut(t *testing.T) { t.Run(tc.name, func(t *testing.T) { pool, err := NewPoolSimulator(tc.entityPool) assert.Nil(t, err) - calcAmountOutResult, err := testutil.MustConcurrentSafe[*poolPkg.CalcAmountOutResult](t, func() (any, error) { + calcAmountOutResult, err := testutil.MustConcurrentSafe(t, func() (*poolPkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(poolPkg.CalcAmountOutParams{ TokenAmountIn: tc.tokenAmountIn, TokenOut: tc.tokenOut, @@ -187,7 +187,7 @@ func TestGetAmountIn(t *testing.T) { t.Run(tc.name, func(t *testing.T) { pool, err := NewPoolSimulator(tc.entityPool) assert.Nil(t, err) - calcAmountInResult, err := testutil.MustConcurrentSafe[*poolPkg.CalcAmountInResult](t, func() (any, error) { + calcAmountInResult, err := testutil.MustConcurrentSafe(t, func() (*poolPkg.CalcAmountInResult, error) { return pool.CalcAmountIn(poolPkg.CalcAmountInParams{ TokenAmountOut: tc.tokenAmountOut, TokenIn: tc.tokenIn, diff --git a/pkg/source/synthetix/pool_simulator_test.go b/pkg/source/synthetix/pool_simulator_test.go index f3840e57f..436280836 100644 --- a/pkg/source/synthetix/pool_simulator_test.go +++ b/pkg/source/synthetix/pool_simulator_test.go @@ -206,7 +206,7 @@ func TestPool_CalcAmountOut(t *testing.T) { t.Run(tc.name, func(t *testing.T) { pool, _ := NewPoolSimulator(tc.entityPool, tc.chainId) fmt.Println("atomic vol", pool.poolState.AtomicMaxVolumePerBlock.String()) - result, err := testutil.MustConcurrentSafe[*poolPkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolPkg.CalcAmountOutResult, error) { return pool.CalcAmountOut(poolPkg.CalcAmountOutParams{ TokenAmountIn: tc.tokenAmountIn, TokenOut: tc.tokenOut, diff --git a/pkg/source/uniswap/pool_simulator_test.go b/pkg/source/uniswap/pool_simulator_test.go index faeeac338..68307dc25 100644 --- a/pkg/source/uniswap/pool_simulator_test.go +++ b/pkg/source/uniswap/pool_simulator_test.go @@ -59,7 +59,7 @@ func TestCalcAmountOutConcurrentSafe(t *testing.T) { poolSim, err := NewPoolSimulator(*poolEntity) require.NoError(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return poolSim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: tc.tokenIn, diff --git a/pkg/source/uniswapv3/pool_simulator_bigint_test.go b/pkg/source/uniswapv3/pool_simulator_bigint_test.go index 380f14e5e..e5b0c1c7e 100644 --- a/pkg/source/uniswapv3/pool_simulator_bigint_test.go +++ b/pkg/source/uniswapv3/pool_simulator_bigint_test.go @@ -72,7 +72,7 @@ func TestPoolSimulatorBigInt_CalcAmountIn(t *testing.T) { poolSim, err := NewPoolSimulatorBigInt(*poolEntity, valueobject.ChainIDEthereum) require.NoError(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountInResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountInResult, error) { return poolSim.CalcAmountIn(pool.CalcAmountInParams{ TokenAmountOut: pool.TokenAmount{ Token: tc.tokenOut, diff --git a/pkg/source/uniswapv3/pool_simulator_test.go b/pkg/source/uniswapv3/pool_simulator_test.go index def94cdd6..d0adb24f3 100644 --- a/pkg/source/uniswapv3/pool_simulator_test.go +++ b/pkg/source/uniswapv3/pool_simulator_test.go @@ -72,7 +72,7 @@ func TestCalcAmountOutConcurrentSafe(t *testing.T) { poolSim, err := NewPoolSimulatorBigInt(*poolEntity, valueobject.ChainIDEthereum) require.NoError(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return poolSim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: tc.tokenIn, @@ -93,7 +93,7 @@ func TestCalcAmountOutConcurrentSafe(t *testing.T) { poolSim, err := NewPoolSimulator(*poolEntity, valueobject.ChainIDEthereum) require.NoError(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return poolSim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: tc.tokenIn, diff --git a/pkg/source/usdfi/pool_simulator_test.go b/pkg/source/usdfi/pool_simulator_test.go index 2bb5de7dd..8dead48b6 100644 --- a/pkg/source/usdfi/pool_simulator_test.go +++ b/pkg/source/usdfi/pool_simulator_test.go @@ -43,7 +43,7 @@ func TestCalcAmountOut(t *testing.T) { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { amountIn := pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)} - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: amountIn, TokenOut: tc.out, diff --git a/pkg/source/velocimeter/pool_simulator_test.go b/pkg/source/velocimeter/pool_simulator_test.go index d35620c62..e91ef78f7 100644 --- a/pkg/source/velocimeter/pool_simulator_test.go +++ b/pkg/source/velocimeter/pool_simulator_test.go @@ -42,7 +42,7 @@ func TestCalcAmountOut(t *testing.T) { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { amountIn := pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)} - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: amountIn, TokenOut: tc.out, diff --git a/pkg/source/velodrome/pool_simulator_test.go b/pkg/source/velodrome/pool_simulator_test.go index 56ef6ebba..dbfe817aa 100644 --- a/pkg/source/velodrome/pool_simulator_test.go +++ b/pkg/source/velodrome/pool_simulator_test.go @@ -46,7 +46,7 @@ func TestCalcAmountOut(t *testing.T) { assert.Equal(t, []string{"B"}, p.CanSwapTo("A")) amountIn := pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)} - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: amountIn, TokenOut: tc.out, diff --git a/pkg/source/velodromev2/pool_simulator_test.go b/pkg/source/velodromev2/pool_simulator_test.go index a89832024..9a96929b6 100644 --- a/pkg/source/velodromev2/pool_simulator_test.go +++ b/pkg/source/velodromev2/pool_simulator_test.go @@ -42,7 +42,7 @@ func TestCalcAmountOut(t *testing.T) { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { amountIn := pool.TokenAmount{Token: tc.in, Amount: bignumber.NewBig10(tc.inAmount)} - out, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + out, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return p.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: amountIn, TokenOut: tc.out, diff --git a/pkg/source/vooi/pool_simulator_test.go b/pkg/source/vooi/pool_simulator_test.go index bc131b656..8e1f59e5f 100644 --- a/pkg/source/vooi/pool_simulator_test.go +++ b/pkg/source/vooi/pool_simulator_test.go @@ -90,7 +90,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { gas: defaultGas, } - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: poolpkg.TokenAmount{ Token: "0x176211869ca2b568f2a7d4ee941e073a821ee1ff", @@ -110,7 +110,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { paused: true, } - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: poolpkg.TokenAmount{ Token: "0x176211869ca2b568f2a7d4ee941e073a821ee1ff", @@ -130,7 +130,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { paused: false, } - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: poolpkg.TokenAmount{ Token: "0x176211869ca2b568f2a7d4ee941e073a821ee1ff", @@ -150,7 +150,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { paused: false, } - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: poolpkg.TokenAmount{ Token: "0x176211869ca2b568f2a7d4ee941e073a821ee1ff", @@ -209,7 +209,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { gas: defaultGas, } - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: poolpkg.TokenAmount{ Token: "0x176211869ca2b568f2a7d4ee941e073a821ee1ff", @@ -268,7 +268,7 @@ func TestPoolSimulator_CalcAmountOut(t *testing.T) { gas: defaultGas, } - result, err := testutil.MustConcurrentSafe[*poolpkg.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*poolpkg.CalcAmountOutResult, error) { return poolSimulator.CalcAmountOut(poolpkg.CalcAmountOutParams{ TokenAmountIn: poolpkg.TokenAmount{ Token: "0x176211869ca2b568f2a7d4ee941e073a821ee1ff", diff --git a/pkg/source/wombat/wombatlsd/pool_simulator_test.go b/pkg/source/wombat/wombatlsd/pool_simulator_test.go index 4f50446b7..59416b8e5 100644 --- a/pkg/source/wombat/wombatlsd/pool_simulator_test.go +++ b/pkg/source/wombat/wombatlsd/pool_simulator_test.go @@ -151,7 +151,7 @@ func TestCalcAmountOutConcurrentSafe(t *testing.T) { poolSim, err := NewPoolSimulator(*poolEntity) require.NoError(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return poolSim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: tc.tokenIn, diff --git a/pkg/source/wombat/wombatmain/pool_simulator_test.go b/pkg/source/wombat/wombatmain/pool_simulator_test.go index a79b87c52..1e0f93016 100644 --- a/pkg/source/wombat/wombatmain/pool_simulator_test.go +++ b/pkg/source/wombat/wombatmain/pool_simulator_test.go @@ -144,7 +144,7 @@ func TestCalcAmountOutConcurrentSafe(t *testing.T) { poolSim, err := NewPoolSimulator(*poolEntity) require.NoError(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return poolSim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: tc.tokenIn, diff --git a/pkg/source/woofiv2/pool_simulator_test.go b/pkg/source/woofiv2/pool_simulator_test.go index ce933da74..523e08820 100644 --- a/pkg/source/woofiv2/pool_simulator_test.go +++ b/pkg/source/woofiv2/pool_simulator_test.go @@ -89,7 +89,7 @@ func TestCalcAmountOutConcurrentSafe(t *testing.T) { poolSim, err := NewPoolSimulator(*poolEntity) require.NoError(t, err) - result, err := testutil.MustConcurrentSafe[*pool.CalcAmountOutResult](t, func() (any, error) { + result, err := testutil.MustConcurrentSafe(t, func() (*pool.CalcAmountOutResult, error) { return poolSim.CalcAmountOut(pool.CalcAmountOutParams{ TokenAmountIn: pool.TokenAmount{ Token: tc.tokenIn, diff --git a/pkg/util/testutil/concurrent.go b/pkg/util/testutil/concurrent.go index 89e45fe1f..a9e481569 100644 --- a/pkg/util/testutil/concurrent.go +++ b/pkg/util/testutil/concurrent.go @@ -6,6 +6,8 @@ import ( "sync" "testing" + "github.com/samber/lo" + "github.com/KyberNetwork/kyberswap-dex-lib/pkg/util/israce" ) @@ -13,12 +15,7 @@ var ( concurrentFactor = runtime.NumCPU() * 10 ) -type valueAndError struct { - value any - err error -} - -func mustReturnSameOutputAndConcurrentSafe[R any](t *testing.T, f func() (any, error)) (ret R, err error) { +func mustReturnSameOutputAndConcurrentSafe[R any](t *testing.T, f func() (R, error)) (ret R, err error) { if concurrentFactor <= 0 { panic("n must > 0") } @@ -29,14 +26,14 @@ func mustReturnSameOutputAndConcurrentSafe[R any](t *testing.T, f func() (any, e var ( wg sync.WaitGroup - outputs = make([]valueAndError, concurrentFactor) + outputs = make([]lo.Tuple2[R, error], concurrentFactor) ) for i := 0; i < concurrentFactor; i++ { wg.Add(1) go func(i int) { defer wg.Done() value, err := f() - outputs[i] = valueAndError{value, err} + outputs[i] = lo.T2(value, err) }(i) } wg.Wait() @@ -44,28 +41,21 @@ func mustReturnSameOutputAndConcurrentSafe[R any](t *testing.T, f func() (any, e reference := outputs[0] for i := 1; i < concurrentFactor; i++ { - if (reference.value == nil) == (outputs[i].value == nil) { - if !reflect.DeepEqual(outputs[0].value, outputs[i].value) { - t.Fatalf("outputs value are not equal, expected %v actual %v", reference.value, outputs[i].value) - return - } - } else { - t.Fatalf("outputs are not equal, expected %v actual %v", reference, outputs[i]) + if !reflect.DeepEqual(reference.A, outputs[i].A) { + t.Fatalf("outputs value are not equal, expected %v actual %v", reference.A, outputs[i].A) return } - if (reference.err == nil) == (outputs[i].err == nil) { - if reference.err != nil && reference.err.Error() != outputs[i].err.Error() { - t.Fatalf("outputs error are not equal, expected %v actual %v", reference.err, outputs[i].err) - return - } - } else { + if (reference.B == nil) != (outputs[i].B == nil) { t.Fatalf("outputs are not equal, expected %v actual %v", reference, outputs[i]) return + } else if reference.B != nil && reference.B.Error() != outputs[i].B.Error() { + t.Fatalf("outputs error are not equal, expected %v actual %v", reference.B, outputs[i].B) + return } } - return reference.value.(R), reference.err + return reference.Unpack() } // MustConcurrentSafe check concurrent calls of the same parameters @@ -73,11 +63,9 @@ func mustReturnSameOutputAndConcurrentSafe[R any](t *testing.T, f func() (any, e // * are not racy AND // // * produces the same output -func MustConcurrentSafe[R any](t *testing.T, f func() (any, error)) (R, error) { +func MustConcurrentSafe[R any](t *testing.T, f func() (R, error)) (R, error) { if israce.Enabled { return mustReturnSameOutputAndConcurrentSafe[R](t, f) } - - value, err := f() - return value.(R), err + return f() } From bbbb4bf54aa836318642cfe7641ce267f425bc67 Mon Sep 17 00:00:00 2001 From: Phu Ngo <12547020+NgoKimPhu@users.noreply.github.com> Date: Mon, 23 Dec 2024 03:27:18 +0700 Subject: [PATCH 2/7] refactor: simplify lock logic to Once logic --- .../algebra/integral/pool_simulator.go | 51 +++++++------------ .../algebra/integral/pool_simulator_test.go | 8 +-- pkg/liquidity-source/algebra/integral/type.go | 1 - 3 files changed, 21 insertions(+), 39 deletions(-) diff --git a/pkg/liquidity-source/algebra/integral/pool_simulator.go b/pkg/liquidity-source/algebra/integral/pool_simulator.go index bce47fd77..e2a6dc219 100644 --- a/pkg/liquidity-source/algebra/integral/pool_simulator.go +++ b/pkg/liquidity-source/algebra/integral/pool_simulator.go @@ -38,7 +38,7 @@ type PoolSimulator struct { volatilityOracle *VolatilityOraclePlugin dynamicFee *DynamicFeeConfig slidingFee *SlidingFeeConfig - writeTimePointLock *sync.RWMutex + writeTimePointOnce *sync.Once useBasePluginV2 bool } @@ -103,7 +103,7 @@ func NewPoolSimulator(entityPool entity.Pool, defaultGas int64) (*PoolSimulator, volatilityOracle: &extra.VolatilityOracle, dynamicFee: &extra.DynamicFee, slidingFee: &extra.SlidingFee, - writeTimePointLock: new(sync.RWMutex), + writeTimePointOnce: new(sync.Once), useBasePluginV2: staticExtra.UseBasePluginV2, }, nil } @@ -202,7 +202,7 @@ func (p *PoolSimulator) CloneState() pool.IPoolSimulator { cloned := *p cloned.liquidity = p.liquidity.Clone() cloned.globalState.Price = p.globalState.Price.Clone() - cloned.writeTimePointLock = new(sync.RWMutex) + cloned.writeTimePointOnce = new(sync.Once) return &cloned } @@ -252,42 +252,25 @@ func (p *PoolSimulator) getSqrtPriceLimit(zeroForOne bool) (*uint256.Int, error) return &sqrtPriceX96Limit, nil } -// writeTimepoint locks and writes timepoint only once per second, triggers onWrite only if said write happened -func (p *PoolSimulator) writeTimepoint(onWrite func() error) error { +// writeTimepoint locks and writes timepoint only once, triggering onWrite only if said write happened. +// By right we should re-update the timepoint every new second, but the difference should be small enough, and +// new pool should have already been created and used in replacement of this pool. +func (p *PoolSimulator) writeTimepoint(onWrite func() error) (err error) { volatilityOracle := p.volatilityOracle if !volatilityOracle.IsInitialized { return ErrNotInitialized } - p.writeTimePointLock.RLock() - done := volatilityOracle.UpdatedWithinThisBlock - p.writeTimePointLock.RUnlock() - if done { - return nil - } - - p.writeTimePointLock.Lock() - defer p.writeTimePointLock.Unlock() - if volatilityOracle.UpdatedWithinThisBlock { // check again for other concurrent writes - return nil - } - - lastIndex := volatilityOracle.TimepointIndex - currentTimestamp := uint32(time.Now().Unix()) - tick := p.globalState.Tick - newLastIndex, _, err := p.timepoints.write(lastIndex, currentTimestamp, tick) - if err != nil { - return err - } - - volatilityOracle.TimepointIndex = newLastIndex - volatilityOracle.LastTimepointTimestamp = currentTimestamp - volatilityOracle.UpdatedWithinThisBlock = true - - if onWrite == nil { - return nil - } - return onWrite() + p.writeTimePointOnce.Do(func() { + volatilityOracle.LastTimepointTimestamp = uint32(time.Now().Unix()) + volatilityOracle.TimepointIndex, _, err = p.timepoints.write( + volatilityOracle.TimepointIndex, volatilityOracle.LastTimepointTimestamp, p.globalState.Tick) + if err != nil || onWrite == nil { + return + } + err = onWrite() + }) + return err } func (p *PoolSimulator) beforeSwapV1() (uint32, uint32, error) { diff --git a/pkg/liquidity-source/algebra/integral/pool_simulator_test.go b/pkg/liquidity-source/algebra/integral/pool_simulator_test.go index e55dec722..1849fbb92 100644 --- a/pkg/liquidity-source/algebra/integral/pool_simulator_test.go +++ b/pkg/liquidity-source/algebra/integral/pool_simulator_test.go @@ -177,7 +177,7 @@ func TestCalcAmountOut(t *testing.T) { VolumeGamma: mockVolumeGamma, BaseFee: mockBaseFee, }, - writeTimePointLock: new(sync.RWMutex), + writeTimePointOnce: new(sync.Once), useBasePluginV2: false, gas: mockGas, }, @@ -260,7 +260,7 @@ func TestCalcAmountOut(t *testing.T) { VolumeGamma: mockVolumeGamma, BaseFee: mockBaseFee, }, - writeTimePointLock: new(sync.RWMutex), + writeTimePointOnce: new(sync.Once), useBasePluginV2: false, gas: mockGas, }, @@ -343,7 +343,7 @@ func TestCalcAmountOut(t *testing.T) { VolumeGamma: mockVolumeGamma, BaseFee: mockBaseFee, }, - writeTimePointLock: new(sync.RWMutex), + writeTimePointOnce: new(sync.Once), useBasePluginV2: false, gas: mockGas, }, @@ -426,7 +426,7 @@ func TestCalcAmountOut(t *testing.T) { VolumeGamma: mockVolumeGamma, BaseFee: mockBaseFee, }, - writeTimePointLock: new(sync.RWMutex), + writeTimePointOnce: new(sync.Once), useBasePluginV2: false, gas: mockGas, }, diff --git a/pkg/liquidity-source/algebra/integral/type.go b/pkg/liquidity-source/algebra/integral/type.go index 1de032d55..813d6f5b0 100644 --- a/pkg/liquidity-source/algebra/integral/type.go +++ b/pkg/liquidity-source/algebra/integral/type.go @@ -136,7 +136,6 @@ type VolatilityOraclePlugin struct { TimepointIndex uint16 LastTimepointTimestamp uint32 IsInitialized bool - UpdatedWithinThisBlock bool // do plugin logic once. by right we should re-update the timepoint every new second } type DynamicFeeConfig struct { From 54dc3f8fd112e546ccfc37e042ee83b96a264b05 Mon Sep 17 00:00:00 2001 From: sunspirit99 Date: Mon, 23 Dec 2024 09:15:42 +0700 Subject: [PATCH 3/7] remove unused const --- pkg/liquidity-source/algebra/integral/constant.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/pkg/liquidity-source/algebra/integral/constant.go b/pkg/liquidity-source/algebra/integral/constant.go index 054fe132b..c19a00ad6 100644 --- a/pkg/liquidity-source/algebra/integral/constant.go +++ b/pkg/liquidity-source/algebra/integral/constant.go @@ -65,15 +65,13 @@ var ( uTWO = uint256.NewInt(2) uFOUR = uint256.NewInt(4) uSIX = uint256.NewInt(6) - uEIGHT = uint256.NewInt(8) uFIFTEEN = uint256.NewInt(15) - uSIXTEEN = uint256.NewInt(16) uTWENTYFOUR = uint256.NewInt(24) MIN_SQRT_RATIO = big.NewInt(4295128739) MAX_SQRT_RATIO, _ = new(big.Int).SetString("1461446703485210103287273052203988822378723970342", 10) - Q96 = new(uint256.Int).Lsh(uONE, 96) // 1 << 96 + Q96 = new(uint256.Int).Lsh(uONE, 96) // 1 << 96 BASE_FEE_MULTIPLIER = new(uint256.Int).Lsh(uONE, FEE_FACTOR_SHIFT) // 1 << 96 DOUBLE_FEE_MULTIPLIER = new(uint256.Int).Lsh(uONE, 2*FEE_FACTOR_SHIFT) // 1 << 2*96 From 3c1d71c6c1d80ff6ceec8479bda6c134243b6d65 Mon Sep 17 00:00:00 2001 From: sunspirit99 Date: Mon, 23 Dec 2024 12:24:07 +0700 Subject: [PATCH 4/7] use IsZero instead --- pkg/liquidity-source/algebra/integral/math.go | 2 +- pkg/liquidity-source/algebra/integral/plugin.go | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pkg/liquidity-source/algebra/integral/math.go b/pkg/liquidity-source/algebra/integral/math.go index c20a927df..92f002576 100644 --- a/pkg/liquidity-source/algebra/integral/math.go +++ b/pkg/liquidity-source/algebra/integral/math.go @@ -7,7 +7,7 @@ import ( ) func unsafeDivRoundingUp(x, y *uint256.Int) *uint256.Int { - if y.Sign() == 0 { + if y.IsZero() { panic("division by zero") } diff --git a/pkg/liquidity-source/algebra/integral/plugin.go b/pkg/liquidity-source/algebra/integral/plugin.go index 211c0c9c2..b3932a744 100644 --- a/pkg/liquidity-source/algebra/integral/plugin.go +++ b/pkg/liquidity-source/algebra/integral/plugin.go @@ -533,13 +533,13 @@ func getNewPrice( amount *uint256.Int, zeroToOne, fromInput bool, ) (*uint256.Int, error) { - if price.Sign() == 0 { + if price.IsZero() { return nil, fmt.Errorf("price cannot be zero") } - if liquidity.Sign() == 0 { + if liquidity.IsZero() { return nil, fmt.Errorf("liquidity cannot be zero") } - if amount.Sign() == 0 { + if amount.IsZero() { return new(uint256.Int).Set(price), nil } From 5257a6b23996c0bc9ad1c06adb02b2b94ff1ff4b Mon Sep 17 00:00:00 2001 From: Phu Ngo <12547020+NgoKimPhu@users.noreply.github.com> Date: Tue, 24 Dec 2024 19:08:38 +0700 Subject: [PATCH 5/7] refactor: more optimization for algebra integral --- .../algebra/integral/adaptive_fee.go | 118 ++++++++---------- .../algebra/integral/constant.go | 25 ++-- pkg/liquidity-source/algebra/integral/math.go | 4 - .../algebra/integral/pool_simulator.go | 4 +- 4 files changed, 67 insertions(+), 84 deletions(-) diff --git a/pkg/liquidity-source/algebra/integral/adaptive_fee.go b/pkg/liquidity-source/algebra/integral/adaptive_fee.go index 1d6dee43f..1d9de060d 100644 --- a/pkg/liquidity-source/algebra/integral/adaptive_fee.go +++ b/pkg/liquidity-source/algebra/integral/adaptive_fee.go @@ -12,16 +12,16 @@ func getFee(volatility *uint256.Int, config *DynamicFeeConfig) uint16 { normalizedVolatility := new(uint256.Int).Div(volatility, uFIFTEEN) sumOfSigmoids := new(uint256.Int).Add( - sigmoid(normalizedVolatility, config.Gamma1, config.Alpha1, uint256.NewInt(uint64(config.Beta1))), - sigmoid(normalizedVolatility, config.Gamma2, config.Alpha2, uint256.NewInt(uint64(config.Beta2))), + sigmoid(normalizedVolatility, config.Gamma1, config.Alpha1, config.Beta1), + sigmoid(normalizedVolatility, config.Gamma2, config.Alpha2, config.Beta2), ) - result := new(uint256.Int).Add( - new(uint256.Int).SetUint64(uint64(config.BaseFee)), + result := normalizedVolatility.Add( + normalizedVolatility.SetUint64(uint64(config.BaseFee)), sumOfSigmoids, ) - if result.Cmp(MAX_UINT16) > 0 { // should always be true + if result.BitLen() > 15 { // should not happen panic("Fee calculation exceeded uint16 max value") } @@ -31,105 +31,93 @@ func getFee(volatility *uint256.Int, config *DynamicFeeConfig) uint16 { // / @notice calculates α / (1 + e^( (β-x) / γ)) // / that is a sigmoid with a maximum value of α, x-shifted by β, and stretched by γ // / @dev returns uint256 for fuzzy testing. Guaranteed that the result is not greater than alpha -func sigmoid(x *uint256.Int, g uint16, alpha uint16, beta *uint256.Int) *uint256.Int { - // Determine if x is greater than beta - comparison := x.Cmp(beta) - - var res *uint256.Int - if comparison > 0 { - // x > beta case - x.Sub(x, beta) - +func sigmoid(x *uint256.Int, gU16 uint16, alpha uint16, beta uint32) *uint256.Int { + x.SubUint64(x, uint64(beta)) + g := uint64(gU16) + g4 := g*g*g*g + var tmp, res uint256.Int + if x.Sign() > 0 { // If x >= 6*g, return alpha - sixTimesG := new(uint256.Int).Mul(uSIX, uint256.NewInt(uint64(g))) - if x.Cmp(sixTimesG) >= 0 { - return new(uint256.Int).SetUint64(uint64(alpha)) + if x.CmpUint64(6*g) >= 0 { + return tmp.SetUint64(uint64(alpha)) } - g4 := new(uint256.Int).Exp(uint256.NewInt(uint64(g)), uFOUR) - ex := expXg4(x, g, g4) + ex := expXg4(x, g) // (alpha * ex) / (g4 + ex) - numerator := new(uint256.Int).Mul(uint256.NewInt(uint64(alpha)), ex) - denominator := new(uint256.Int).Add(g4, ex) - res = new(uint256.Int).Div(numerator, denominator) + numerator := res.Mul(res.SetUint64(uint64(alpha)), ex) + denominator := tmp.AddUint64(ex, g4) + return res.Div(numerator, denominator) } else { - // x <= beta case - x.Sub(beta, x) + x.Abs(x) - // If x >= 6*g, return 0 - sixTimesG := new(uint256.Int).Mul(uSIX, uint256.NewInt(uint64(g))) - if x.Cmp(sixTimesG) >= 0 { + if x.CmpUint64(6*g) >= 0 { return uZERO } - g4 := new(uint256.Int).Exp(uint256.NewInt(uint64(g)), uFOUR) - ex := new(uint256.Int).Add(g4, expXg4(x, g, g4)) + ex := expXg4(x, g) + ex.AddUint64(ex, g4) // (alpha * g4) / ex - numerator := new(uint256.Int).Mul(uint256.NewInt(uint64(alpha)), g4) - res = new(uint256.Int).Div(numerator, ex) + numerator := res.Mul(res.SetUint64(uint64(alpha)), tmp.SetUint64(g4)) + return res.Div(numerator, ex) } - - return res } -func expXg4(x *uint256.Int, g uint16, gHighestDegree *uint256.Int) *uint256.Int { +func expXg4(x *uint256.Int, g uint64) *uint256.Int { var closestValue *uint256.Int + var tmp uint256.Int - gBig := uint256.NewInt(uint64(g)) + gU := uint256.NewInt(g) // Predefined e values multiplied by 10^20 - xdg := new(uint256.Int).Div(x, gBig) + xdg := tmp.Div(x, gU) switch xdg.Uint64() { case 0: - closestValue = uint256.MustFromBig(CLOSEST_VALUE_0) + closestValue = CLOSEST_VALUE_0 case 1: - closestValue = uint256.MustFromBig(CLOSEST_VALUE_1) + closestValue = CLOSEST_VALUE_1 case 2: - closestValue = uint256.MustFromBig(CLOSEST_VALUE_2) + closestValue = CLOSEST_VALUE_2 case 3: - closestValue = uint256.MustFromBig(CLOSEST_VALUE_3) + closestValue = CLOSEST_VALUE_3 case 4: - closestValue = uint256.MustFromBig(CLOSEST_VALUE_4) + closestValue = CLOSEST_VALUE_4 default: - closestValue = uint256.MustFromBig(CLOSEST_VALUE_DEFAULT) + closestValue = CLOSEST_VALUE_DEFAULT } - x.Mod(x, gBig) + x.Mod(x, gU) - gDiv2 := new(uint256.Int).Div(gBig, uTWO) - if x.Cmp(gDiv2) >= 0 { + if x.CmpUint64(g/2) >= 0 { // (x - closestValue) >= 0.5, so closestValue := closestValue * e^0.5 - x.Sub(x, gDiv2) - closestValue.Mul(closestValue, uint256.MustFromBig(E_HALF_MULTIPLIER)).Div(closestValue, uint256.MustFromBig(E_MULTIPLIER_BIG)) + x.SubUint64(x, g/2) + closestValue.Mul(closestValue, E_HALF_MULTIPLIER).Div(closestValue, E_MULTIPLIER_BIG) } // After calculating the closestValue x/g is <= 0.5, so that the series in the neighborhood of zero converges with sufficient speed - xLowestDegree := new(uint256.Int).Set(x) - res := new(uint256.Int).Set(gHighestDegree) // g**4 + var xLowestDegree uint256.Int + xLowestDegree.Set(x) + res := uint256.NewInt(g*g*g*g) // g**4 - gHighestDegree.Div(gHighestDegree, gBig) // g**3 - res.Add(res, new(uint256.Int).Mul(xLowestDegree, gHighestDegree)) // g**4 + x*g**3 + res.Add(res, tmp.Mul(&xLowestDegree, tmp.SetUint64(g*g*g))) // g**4 + x*g**3 - gHighestDegree.Div(gHighestDegree, gBig) // g**2 - xLowestDegree.Mul(xLowestDegree, x) // x**2 - res.Add(res, new(uint256.Int).Div( - new(uint256.Int).Mul(xLowestDegree, gHighestDegree), + xLowestDegree.Mul(&xLowestDegree, x) // x**2 + res.Add(res, tmp.Div( + tmp.Mul(&xLowestDegree, tmp.SetUint64(g*g)), uTWO, - )) - - gHighestDegree.Div(gHighestDegree, gBig) // g - xLowestDegree.Mul(xLowestDegree, x) // x**3 - res.Add(res, new(uint256.Int).Div( - new(uint256.Int).Add( - new(uint256.Int).Mul(xLowestDegree, new(uint256.Int).Mul(gBig, uFOUR)), - new(uint256.Int).Mul(xLowestDegree, x), + )) // g**4 + x * g**3 + (x**2 * g**2) / 2, res < 71 + + xLowestDegree.Mul(&xLowestDegree, x) // x**3 + res.Add(res, tmp.Div( + tmp.Add( + tmp.Mul(&xLowestDegree, tmp.SetUint64(g*4)), + xLowestDegree.Mul(&xLowestDegree, x), ), uTWENTYFOUR, - )) + )) // g^4 + x * g^3 + (x^2 * g^2)/2 + x^3(g*4 + x)/24, res < 73 - res.Mul(res, closestValue).Div(res, uint256.MustFromBig(E_MULTIPLIER_BIG)) + res.Mul(res, closestValue).Div(res, E_MULTIPLIER_BIG) return res } diff --git a/pkg/liquidity-source/algebra/integral/constant.go b/pkg/liquidity-source/algebra/integral/constant.go index 054fe132b..250800cba 100644 --- a/pkg/liquidity-source/algebra/integral/constant.go +++ b/pkg/liquidity-source/algebra/integral/constant.go @@ -1,7 +1,6 @@ package integral import ( - "math/big" "time" "github.com/holiman/uint256" @@ -58,7 +57,7 @@ var ( FEE_DENOMINATOR = uint256.NewInt(1e6) COMMUNITY_FEE_DENOMINATOR = uint256.NewInt(1e3) - MAX_UINT16 = new(uint256.Int).SetUint64(1<<16 - 1) + MAX_UINT16 = uint256.NewInt(1<<16 - 1) uZERO = uint256.NewInt(0) uONE = uint256.NewInt(1) @@ -70,8 +69,8 @@ var ( uSIXTEEN = uint256.NewInt(16) uTWENTYFOUR = uint256.NewInt(24) - MIN_SQRT_RATIO = big.NewInt(4295128739) - MAX_SQRT_RATIO, _ = new(big.Int).SetString("1461446703485210103287273052203988822378723970342", 10) + MIN_SQRT_RATIO = uint256.NewInt(4295128739) + MAX_SQRT_RATIO, _ = uint256.FromDecimal("1461446703485210103287273052203988822378723970342") Q96 = new(uint256.Int).Lsh(uONE, 96) // 1 << 96 @@ -79,13 +78,13 @@ var ( DOUBLE_FEE_MULTIPLIER = new(uint256.Int).Lsh(uONE, 2*FEE_FACTOR_SHIFT) // 1 << 2*96 // Predefined e values multiplied by 10^20 as constants - CLOSEST_VALUE_0, _ = new(big.Int).SetString("100000000000000000000", 10) // 1 - CLOSEST_VALUE_1, _ = new(big.Int).SetString("271828182845904523536", 10) // ~= e - CLOSEST_VALUE_2, _ = new(big.Int).SetString("738905609893065022723", 10) // ~= e^2 - CLOSEST_VALUE_3, _ = new(big.Int).SetString("2008553692318766774092", 10) // ~= e^3 - CLOSEST_VALUE_4, _ = new(big.Int).SetString("5459815003314423907811", 10) // ~= e^4 - CLOSEST_VALUE_DEFAULT, _ = new(big.Int).SetString("14841315910257660342111", 10) // ~= e^5 - - E_HALF_MULTIPLIER, _ = new(big.Int).SetString("164872127070012814684", 10) // e^0.5 - E_MULTIPLIER_BIG, _ = new(big.Int).SetString("100000000000000000000", 10) // 1e20 + CLOSEST_VALUE_0, _ = uint256.FromDecimal("100000000000000000000") // 1 + CLOSEST_VALUE_1, _ = uint256.FromDecimal("271828182845904523536") // ~= e + CLOSEST_VALUE_2, _ = uint256.FromDecimal("738905609893065022723") // ~= e^2 + CLOSEST_VALUE_3, _ = uint256.FromDecimal("2008553692318766774092") // ~= e^3 + CLOSEST_VALUE_4, _ = uint256.FromDecimal("5459815003314423907811") // ~= e^4 + CLOSEST_VALUE_DEFAULT, _ = uint256.FromDecimal("14841315910257660342111") // ~= e^5 + + E_HALF_MULTIPLIER, _ = uint256.FromDecimal("164872127070012814684") // e^0.5 + E_MULTIPLIER_BIG, _ = uint256.FromDecimal("100000000000000000000") // 1e20 ) diff --git a/pkg/liquidity-source/algebra/integral/math.go b/pkg/liquidity-source/algebra/integral/math.go index c20a927df..5a491224a 100644 --- a/pkg/liquidity-source/algebra/integral/math.go +++ b/pkg/liquidity-source/algebra/integral/math.go @@ -7,10 +7,6 @@ import ( ) func unsafeDivRoundingUp(x, y *uint256.Int) *uint256.Int { - if y.Sign() == 0 { - panic("division by zero") - } - quotient, remainder := new(uint256.Int).DivMod(x, y, new(uint256.Int)) if remainder.Sign() > 0 { quotient.AddUint64(quotient, 1) diff --git a/pkg/liquidity-source/algebra/integral/pool_simulator.go b/pkg/liquidity-source/algebra/integral/pool_simulator.go index e2a6dc219..a5e086494 100644 --- a/pkg/liquidity-source/algebra/integral/pool_simulator.go +++ b/pkg/liquidity-source/algebra/integral/pool_simulator.go @@ -401,11 +401,11 @@ func (p *PoolSimulator) calculateSwap(overrideFee, pluginFee uint32, zeroToOne b } if zeroToOne { - if limitSqrtPrice.Cmp(currentPrice) >= 0 || limitSqrtPrice.Cmp(uint256.MustFromBig(MIN_SQRT_RATIO)) <= 0 { + if limitSqrtPrice.Cmp(currentPrice) >= 0 || limitSqrtPrice.Cmp(MIN_SQRT_RATIO) <= 0 { return nil, nil, nil, 0, nil, FeesAmount{}, ErrInvalidLimitSqrtPrice } } else { - if limitSqrtPrice.Cmp(currentPrice) <= 0 || limitSqrtPrice.Cmp(uint256.MustFromBig(MAX_SQRT_RATIO)) >= 0 { + if limitSqrtPrice.Cmp(currentPrice) <= 0 || limitSqrtPrice.Cmp(MAX_SQRT_RATIO) >= 0 { return nil, nil, nil, 0, nil, FeesAmount{}, ErrInvalidLimitSqrtPrice } } From 9698ea27f13e308087ae23fe2bceafaf63543cb3 Mon Sep 17 00:00:00 2001 From: Phu Ngo <12547020+NgoKimPhu@users.noreply.github.com> Date: Tue, 24 Dec 2024 19:19:11 +0700 Subject: [PATCH 6/7] refactor: remove a bit more unused consts --- pkg/liquidity-source/algebra/integral/constant.go | 3 --- pkg/liquidity-source/algebra/integral/pool_simulator.go | 5 +++-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/pkg/liquidity-source/algebra/integral/constant.go b/pkg/liquidity-source/algebra/integral/constant.go index 52403aca2..c8ed72347 100644 --- a/pkg/liquidity-source/algebra/integral/constant.go +++ b/pkg/liquidity-source/algebra/integral/constant.go @@ -57,12 +57,9 @@ var ( FEE_DENOMINATOR = uint256.NewInt(1e6) COMMUNITY_FEE_DENOMINATOR = uint256.NewInt(1e3) - MAX_UINT16 = uint256.NewInt(1<<16 - 1) - uZERO = uint256.NewInt(0) uONE = uint256.NewInt(1) uTWO = uint256.NewInt(2) - uFOUR = uint256.NewInt(4) uSIX = uint256.NewInt(6) uFIFTEEN = uint256.NewInt(15) uTWENTYFOUR = uint256.NewInt(24) diff --git a/pkg/liquidity-source/algebra/integral/pool_simulator.go b/pkg/liquidity-source/algebra/integral/pool_simulator.go index a5e086494..6b6be4067 100644 --- a/pkg/liquidity-source/algebra/integral/pool_simulator.go +++ b/pkg/liquidity-source/algebra/integral/pool_simulator.go @@ -3,6 +3,7 @@ package integral import ( "errors" "fmt" + "math" "math/big" "strings" "sync" @@ -333,8 +334,8 @@ func (p *PoolSimulator) getFeeAndUpdateFactors(zeroToOne bool, currentTick, last FEE_FACTOR_SHIFT, ) - if adjustedFee.Cmp(MAX_UINT16) > 0 || adjustedFee.IsZero() { - adjustedFee.Set(MAX_UINT16) + if adjustedFee.BitLen() > 15 || adjustedFee.IsZero() { + adjustedFee.SetUint64(math.MaxUint16) } return uint16(adjustedFee.Uint64()), nil From 434110188bc7ced6ce1d467b9ff3bbf1768fe7dd Mon Sep 17 00:00:00 2001 From: Phu Ngo <12547020+NgoKimPhu@users.noreply.github.com> Date: Thu, 26 Dec 2024 15:42:18 +0700 Subject: [PATCH 7/7] refactor: tiny bit more optimization --- go.mod | 2 +- go.sum | 4 ++-- .../algebra/integral/constant.go | 11 ++++------- .../algebra/integral/errors.go | 10 ++++------ .../algebra/integral/pool_simulator_test.go | 2 +- pkg/liquidity-source/algebra/integral/type.go | 18 +++++++++--------- pkg/source/gmx-glp/vault_scanner.go | 2 +- 7 files changed, 22 insertions(+), 27 deletions(-) diff --git a/go.mod b/go.mod index bacbf9150..31d0a74a8 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,7 @@ require ( github.com/KyberNetwork/logger v0.2.1 github.com/KyberNetwork/msgpack/v5 v5.4.2 github.com/KyberNetwork/pancake-v3-sdk v0.2.0 - github.com/KyberNetwork/uniswapv3-sdk-uint256 v0.5.3-0.20241221122441-5808be2e7503 + github.com/KyberNetwork/uniswapv3-sdk-uint256 v0.5.3 github.com/daoleno/uniswap-sdk-core v0.1.7 github.com/daoleno/uniswapv3-sdk v0.4.0 github.com/davecgh/go-spew v1.1.1 diff --git a/go.sum b/go.sum index 29616a53e..20da50a32 100644 --- a/go.sum +++ b/go.sum @@ -22,8 +22,8 @@ github.com/KyberNetwork/uniswap-sdk-core v0.1.7 h1:9CfjLkFZcOxgu0US0ZB1vvdgA1sp3 github.com/KyberNetwork/uniswap-sdk-core v0.1.7/go.mod h1:DPzL8zNicstPzvX74ZeeHsiIUquZRpwviceDHQ8+UQ4= github.com/KyberNetwork/uniswapv3-sdk v0.5.5 h1:PLkDL8YWgN00yfNGbQpOGRcKRD3eoFXOFzjvuHP9Gmo= github.com/KyberNetwork/uniswapv3-sdk v0.5.5/go.mod h1:XFySgQXZ+dl0yRze6Rj8jloILcFP8FbXJjcyk/1RmSU= -github.com/KyberNetwork/uniswapv3-sdk-uint256 v0.5.3-0.20241221122441-5808be2e7503 h1:FvNvHE1yHjLK8owNpOnVUdZNYNZ5xnXJ9uKvuWMC0NY= -github.com/KyberNetwork/uniswapv3-sdk-uint256 v0.5.3-0.20241221122441-5808be2e7503/go.mod h1:VQNKmTwlX6gyW1gzaSQjYG+xCBpqmgH0VQslYMtqzAg= +github.com/KyberNetwork/uniswapv3-sdk-uint256 v0.5.3 h1:J0odlUz0NVgtawgnanos/lkYUCcs0o76j3JY9pvURCo= +github.com/KyberNetwork/uniswapv3-sdk-uint256 v0.5.3/go.mod h1:VQNKmTwlX6gyW1gzaSQjYG+xCBpqmgH0VQslYMtqzAg= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/VictoriaMetrics/fastcache v1.12.2 h1:N0y9ASrJ0F6h0QaC3o6uJb3NIZ9VKLjCM7NQbSmF7WI= diff --git a/pkg/liquidity-source/algebra/integral/constant.go b/pkg/liquidity-source/algebra/integral/constant.go index c8ed72347..bb51aa707 100644 --- a/pkg/liquidity-source/algebra/integral/constant.go +++ b/pkg/liquidity-source/algebra/integral/constant.go @@ -22,13 +22,10 @@ const ( WINDOW = 86400 // 1 day in seconds UINT16_MODULO = 65536 - poolTicksMethod = "ticks" - poolLiquidityMethod = "liquidity" - poolGlobalStateMethod = "globalState" - poolTickSpacingMethod = "tickSpacing" - PoolPrevTickGlobalMethod = "prevTickGlobal" - PoolNextTickGlobalMethod = "nextTickGlobal" - poolPluginMethod = "plugin" + poolLiquidityMethod = "liquidity" + poolGlobalStateMethod = "globalState" + poolTickSpacingMethod = "tickSpacing" + poolPluginMethod = "plugin" dynamicFeeManagerPluginFeeConfigMethod = "feeConfig" diff --git a/pkg/liquidity-source/algebra/integral/errors.go b/pkg/liquidity-source/algebra/integral/errors.go index fb9060d0d..cd35a3b7c 100644 --- a/pkg/liquidity-source/algebra/integral/errors.go +++ b/pkg/liquidity-source/algebra/integral/errors.go @@ -6,7 +6,6 @@ import ( var ( ErrStaleTimepoints = errors.New("getting stale timepoint data") - ErrTickNil = errors.New("tick is nil") ErrTicksEmpty = errors.New("ticks list is empty") ErrInvalidToken = errors.New("invalid token info") ErrZeroAmountOut = errors.New("amountOut is 0") @@ -19,9 +18,8 @@ var ( ErrInvalidAmountRequired = errors.New("invalid amount required") ErrZeroAmountRequired = errors.New("zero amount required") - ErrOutOfRangeOrInvalid = errors.New("value out of range or invalid") - ErrLiquiditySub = errors.New("liquidity sub error") - ErrLiquidityAdd = errors.New("liquidity add error") - ErrOverflow = errors.New("overflow") - ErrUnderflow = errors.New("underflow") + ErrLiquiditySub = errors.New("liquidity sub error") + ErrLiquidityAdd = errors.New("liquidity add error") + ErrOverflow = errors.New("overflow") + ErrUnderflow = errors.New("underflow") ) diff --git a/pkg/liquidity-source/algebra/integral/pool_simulator_test.go b/pkg/liquidity-source/algebra/integral/pool_simulator_test.go index 1849fbb92..f50acbaf5 100644 --- a/pkg/liquidity-source/algebra/integral/pool_simulator_test.go +++ b/pkg/liquidity-source/algebra/integral/pool_simulator_test.go @@ -496,7 +496,7 @@ func TestCalcAmountOut(t *testing.T) { } } -var mockPool = []byte(`{"address":"0xbe9c1d237d002c8d9402f30c16ace1436d008f0c","exchange":"silverswap","type":"algebra-integral","timestamp":1733225338,"reserves":["9999999999999944","2620057588865"],"tokens":[{"address":"0x21be370d5312f44cb42ce377bc9b8a0cef1a4c83","name":"Wrapped Fantom","symbol":"WFTM","decimals":18,"weight":50,"swappable":true},{"address":"0xfe7eda5f2c56160d406869a8aa4b2f365d544c7b","name":"Axelar Wrapped ETH","symbol":"axlETH","decimals":18,"weight":50,"swappable":true}],"extra":"{\"liq\":161865919478591,\"gS\":{\"price\":\"1282433937397070526017841373\",\"tick\":82476,\"lF\":100,\"pC\":193,\"cF\":100,\"un\":true},\"ticks\":[{\"Index\":-887220,\"LiquidityGross\":161865919478591,\"LiquidityNet\":161865919478591},{\"Index\":887220,\"LiquidityGross\":161865919478591,\"LiquidityNet\":-161865919478591}],\"tS\":60,\"tP\":{\"0\":{\"init\":true,\"ts\":1712116096,\"cum\":0,\"vo\":\"0\",\"tick\":-82476,\"avgT\":-82476,\"wsI\":0},\"1\":{\"init\":false,\"ts\":0,\"cum\":0,\"vo\":\"0\",\"tick\":0,\"avgT\":0,\"wsI\":0},\"2\":{\"init\":false,\"ts\":0,\"cum\":0,\"vo\":\"0\",\"tick\":0,\"avgT\":0,\"wsI\":0},\"65535\":{\"init\":false,\"ts\":0,\"cum\":0,\"vo\":\"0\",\"tick\":0,\"avgT\":0,\"wsI\":0}},\"vo\":{\"TimepointIndex\":0,\"LastTimepointTimestamp\":1712116096,\"IsInitialized\":true},\"sF\":{\"0to1fF\":null,\"1to0fF\":null},\"dF\":{\"a1\":2900,\"a2\":12000,\"b1\":360,\"b2\":60000,\"g1\":59,\"g2\":8500,\"vB\":0,\"vG\":0,\"bF\":100}}","staticExtra":"{\"2\":false}","blockNumber":99019509}`) +var mockPool = []byte(`{"address":"0xbe9c1d237d002c8d9402f30c16ace1436d008f0c","exchange":"silverswap","type":"algebra-integral","timestamp":1733225338,"reserves":["9999999999999944","2620057588865"],"tokens":[{"address":"0x21be370d5312f44cb42ce377bc9b8a0cef1a4c83","name":"Wrapped Fantom","symbol":"WFTM","decimals":18,"weight":50,"swappable":true},{"address":"0xfe7eda5f2c56160d406869a8aa4b2f365d544c7b","name":"Axelar Wrapped ETH","symbol":"axlETH","decimals":18,"weight":50,"swappable":true}],"extra":"{\"liq\":161865919478591,\"gS\":{\"price\":\"1282433937397070526017841373\",\"tick\":82476,\"lF\":100,\"pC\":193,\"cF\":100,\"un\":true},\"ticks\":[{\"Index\":-887220,\"LiquidityGross\":161865919478591,\"LiquidityNet\":161865919478591},{\"Index\":887220,\"LiquidityGross\":161865919478591,\"LiquidityNet\":-161865919478591}],\"tS\":60,\"tP\":{\"0\":{\"init\":true,\"ts\":1712116096,\"cum\":0,\"vo\":\"0\",\"tick\":-82476,\"avgT\":-82476,\"wsI\":0},\"1\":{\"init\":false,\"ts\":0,\"cum\":0,\"vo\":\"0\",\"tick\":0,\"avgT\":0,\"wsI\":0},\"2\":{\"init\":false,\"ts\":0,\"cum\":0,\"vo\":\"0\",\"tick\":0,\"avgT\":0,\"wsI\":0},\"65535\":{\"init\":false,\"ts\":0,\"cum\":0,\"vo\":\"0\",\"tick\":0,\"avgT\":0,\"wsI\":0}},\"vo\":{\"tpIdx\":0,\"lastTs\":1712116096,\"init\":true},\"sF\":{\"0to1fF\":null,\"1to0fF\":null},\"dF\":{\"a1\":2900,\"a2\":12000,\"b1\":360,\"b2\":60000,\"g1\":59,\"g2\":8500,\"vB\":0,\"vG\":0,\"bF\":100}}","staticExtra":"{\"pluginV2\":false}","blockNumber":99019509}`) func TestCalcAmountOut_FromPool(t *testing.T) { var p entity.Pool diff --git a/pkg/liquidity-source/algebra/integral/type.go b/pkg/liquidity-source/algebra/integral/type.go index 813d6f5b0..6cd5e0687 100644 --- a/pkg/liquidity-source/algebra/integral/type.go +++ b/pkg/liquidity-source/algebra/integral/type.go @@ -87,11 +87,11 @@ type GlobalState struct { } type FetchRPCResult struct { - Liquidity *big.Int `json:"liquidity"` - State GlobalState `json:"state"` - TickSpacing *big.Int `json:"tickSpacing"` - Reserve0 *big.Int `json:"reserve0"` - Reserve1 *big.Int `json:"reserve1"` + Liquidity *big.Int + State GlobalState + TickSpacing *big.Int + Reserve0 *big.Int + Reserve1 *big.Int Timepoints map[uint16]Timepoint VolatilityOracle VolatilityOraclePlugin @@ -133,9 +133,9 @@ type Extra struct { } type VolatilityOraclePlugin struct { - TimepointIndex uint16 - LastTimepointTimestamp uint32 - IsInitialized bool + TimepointIndex uint16 `json:"tpIdx,omitempty"` + LastTimepointTimestamp uint32 `json:"lastTs,omitempty"` + IsInitialized bool `json:"init,omitempty"` } type DynamicFeeConfig struct { @@ -156,7 +156,7 @@ type SlidingFeeConfig struct { } type StaticExtra struct { - UseBasePluginV2 bool `json:"2"` + UseBasePluginV2 bool `json:"pluginV2"` } // StateUpdate to be returned instead of updating state when calculating amountOut diff --git a/pkg/source/gmx-glp/vault_scanner.go b/pkg/source/gmx-glp/vault_scanner.go index 94aae2fa8..eaa89a44b 100644 --- a/pkg/source/gmx-glp/vault_scanner.go +++ b/pkg/source/gmx-glp/vault_scanner.go @@ -161,7 +161,7 @@ func (vs *VaultScanner) getPriceFeeds( return priceFeeds, nil } -func (vs VaultScanner) getFastPriceFeed( +func (vs *VaultScanner) getFastPriceFeed( ctx context.Context, version SecondaryPriceFeedVersion, address string,