Skip to content

Commit 7bd815e

Browse files
mergify[bot]p0mvn
andauthored
refactor(CL): convert priceLimit API in swaps to BigDec (backport #6368) (#6408)
* refactor(CL): convert priceLimit API in swaps to BigDec (backport #6368) * lint --------- Co-authored-by: roman <roman@osmosis.team>
1 parent f1a1ca8 commit 7bd815e

File tree

14 files changed

+123
-100
lines changed

14 files changed

+123
-100
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
5858
* Note: with the update, the Dec and Int do not get initialized to zero values
5959
by default in proto marhaling/unmarshaling. Instead, they get set to nil values.
6060
* maxDecBitLen has changed by one bit so overflow panic can be triggerred sooner.
61+
* [#6368](https://github.com/osmosis-labs/osmosis/pull/6368) Convert priceLimit API in CL swaps to BigDec
62+
6163

6264
## v19.0.0
6365

x/concentrated-liquidity/export_test.go

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ func (k Keeper) SwapOutAmtGivenIn(
6060
tokenIn sdk.Coin,
6161
tokenOutDenom string,
6262
spreadFactor osmomath.Dec,
63-
priceLimit osmomath.Dec) (calcTokenIn, calcTokenOut sdk.Coin, poolUpdates PoolUpdates, err error) {
63+
priceLimit osmomath.BigDec) (calcTokenIn, calcTokenOut sdk.Coin, poolUpdates PoolUpdates, err error) {
6464
return k.swapOutAmtGivenIn(ctx, sender, pool, tokenIn, tokenOutDenom, spreadFactor, priceLimit)
6565
}
6666

@@ -70,8 +70,7 @@ func (k Keeper) ComputeOutAmtGivenIn(
7070
tokenInMin sdk.Coin,
7171
tokenOutDenom string,
7272
spreadFactor osmomath.Dec,
73-
priceLimit osmomath.Dec,
74-
73+
priceLimit osmomath.BigDec,
7574
) (swapResult SwapResult, poolUpdates PoolUpdates, err error) {
7675
return k.computeOutAmtGivenIn(ctx, poolId, tokenInMin, tokenOutDenom, spreadFactor, priceLimit)
7776
}
@@ -83,7 +82,7 @@ func (k Keeper) SwapInAmtGivenOut(
8382
desiredTokenOut sdk.Coin,
8483
tokenInDenom string,
8584
spreadFactor osmomath.Dec,
86-
priceLimit osmomath.Dec) (calcTokenIn, calcTokenOut sdk.Coin, poolUpdates PoolUpdates, err error) {
85+
priceLimit osmomath.BigDec) (calcTokenIn, calcTokenOut sdk.Coin, poolUpdates PoolUpdates, err error) {
8786
return k.swapInAmtGivenOut(ctx, sender, pool, desiredTokenOut, tokenInDenom, spreadFactor, priceLimit)
8887
}
8988

@@ -92,7 +91,7 @@ func (k Keeper) ComputeInAmtGivenOut(
9291
desiredTokenOut sdk.Coin,
9392
tokenInDenom string,
9493
spreadFactor osmomath.Dec,
95-
priceLimit osmomath.Dec,
94+
priceLimit osmomath.BigDec,
9695
poolId uint64,
9796

9897
) (swapResult SwapResult, poolUpdates PoolUpdates, err error) {
@@ -329,7 +328,7 @@ func (k Keeper) GetLargestSupportedUptimeDuration(ctx sdk.Context) time.Duration
329328

330329
func (k Keeper) SetupSwapStrategy(ctx sdk.Context, p types.ConcentratedPoolExtension,
331330
spreadFactor osmomath.Dec, tokenInDenom string,
332-
priceLimit osmomath.Dec) (strategy swapstrategy.SwapStrategy, sqrtPriceLimit osmomath.BigDec, err error) {
331+
priceLimit osmomath.BigDec) (strategy swapstrategy.SwapStrategy, sqrtPriceLimit osmomath.BigDec, err error) {
333332
return k.setupSwapStrategy(p, spreadFactor, tokenInDenom, priceLimit)
334333
}
335334

x/concentrated-liquidity/fuzz_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,7 @@ func (s *KeeperTestSuite) swap(pool types.ConcentratedPoolExtension, swapInFunde
288288
// // Execute swap
289289
fmt.Printf("swap in: %s\n", swapInFunded)
290290
cacheCtx, writeOutGivenIn := s.Ctx.CacheContext()
291-
_, tokenOut, _, err := s.clk.SwapOutAmtGivenIn(cacheCtx, s.TestAccs[0], pool, swapInFunded, swapOutDenom, pool.GetSpreadFactor(s.Ctx), osmomath.ZeroDec())
291+
_, tokenOut, _, err := s.clk.SwapOutAmtGivenIn(cacheCtx, s.TestAccs[0], pool, swapInFunded, swapOutDenom, pool.GetSpreadFactor(s.Ctx), osmomath.ZeroBigDec())
292292
if errors.As(err, &types.InvalidAmountCalculatedError{}) {
293293
// If the swap we're about to execute will not generate enough output, we skip the swap.
294294
// it would error for a real user though. This is good though, since that user would just be burning funds.
@@ -307,7 +307,7 @@ func (s *KeeperTestSuite) swap(pool types.ConcentratedPoolExtension, swapInFunde
307307
// We expect the returned amountIn to be roughly equal to the original swapInFunded.
308308
cacheCtx, _ = s.Ctx.CacheContext()
309309
fmt.Printf("swap out: %s\n", tokenOut)
310-
amountInSwapResult, _, _, err := s.clk.SwapInAmtGivenOut(cacheCtx, s.TestAccs[0], pool, tokenOut, swapInFunded.Denom, pool.GetSpreadFactor(s.Ctx), osmomath.ZeroDec())
310+
amountInSwapResult, _, _, err := s.clk.SwapInAmtGivenOut(cacheCtx, s.TestAccs[0], pool, tokenOut, swapInFunded.Denom, pool.GetSpreadFactor(s.Ctx), osmomath.ZeroBigDec())
311311
if errors.As(err, &types.InvalidAmountCalculatedError{}) {
312312
// If the swap we're about to execute will not generate enough output, we skip the swap.
313313
// it would error for a real user though. This is good though, since that user would just be burning funds.

x/concentrated-liquidity/math/precompute.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import (
77

88
var (
99
sdkOneDec = osmomath.OneDec()
10-
sdkNineDec = osmomath.NewDec(9)
1110
sdkTenDec = osmomath.NewDec(10)
1211
powersOfTen []osmomath.Dec
1312
negPowersOfTen []osmomath.Dec

x/concentrated-liquidity/position_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1796,7 +1796,7 @@ func (s *KeeperTestSuite) TestTickRoundingEdgeCase() {
17961796
swapAddr := testAccs[2]
17971797
desiredTokenOut := sdk.NewCoin(USDC, osmomath.NewInt(10000))
17981798
s.FundAcc(swapAddr, sdk.NewCoins(sdk.NewCoin(ETH, osmomath.NewInt(1000000000000000000))))
1799-
_, _, _, err := s.clk.SwapInAmtGivenOut(s.Ctx, swapAddr, pool, desiredTokenOut, ETH, osmomath.ZeroDec(), osmomath.ZeroDec())
1799+
_, _, _, err := s.clk.SwapInAmtGivenOut(s.Ctx, swapAddr, pool, desiredTokenOut, ETH, osmomath.ZeroDec(), osmomath.ZeroBigDec())
18001800
s.Require().NoError(err)
18011801

18021802
// Both positions should be able to withdraw successfully

x/concentrated-liquidity/query.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -270,12 +270,12 @@ func (k Keeper) GetNumNextInitializedTicks(ctx sdk.Context, poolId, numberOfNext
270270
ctx.Logger().Debug(fmt.Sprintf("min_tick %d\n", types.MinInitializedTick))
271271
ctx.Logger().Debug(fmt.Sprintf("max_tick %d\n", types.MaxTick))
272272

273-
var boundTick sdk.Int
273+
var boundTick osmomath.Int
274274
if boundTick.IsNil() {
275275
if zeroForOne {
276-
boundTick = sdk.NewInt(types.MinInitializedTick)
276+
boundTick = osmomath.NewInt(types.MinInitializedTick)
277277
} else {
278-
boundTick = sdk.NewInt(types.MaxTick)
278+
boundTick = osmomath.NewInt(types.MaxTick)
279279
}
280280
}
281281

x/concentrated-liquidity/range_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -357,7 +357,7 @@ func (s *KeeperTestSuite) executeRandomizedSwap(pool types.ConcentratedPoolExten
357357
}
358358

359359
// Note that we set the price limit to zero to ensure that the swap can execute in either direction (gets automatically set to correct limit)
360-
swappedIn, swappedOut, _, err := s.clk.SwapInAmtGivenOut(s.Ctx, swapAddress, pool, swapOutCoin, swapInDenom, pool.GetSpreadFactor(s.Ctx), osmomath.ZeroDec())
360+
swappedIn, swappedOut, _, err := s.clk.SwapInAmtGivenOut(s.Ctx, swapAddress, pool, swapOutCoin, swapInDenom, pool.GetSpreadFactor(s.Ctx), osmomath.ZeroBigDec())
361361
s.Require().NoError(err)
362362

363363
return swappedIn, swappedOut
@@ -439,7 +439,7 @@ func (s *KeeperTestSuite) getInitialPositionAssets(pool types.ConcentratedPoolEx
439439

440440
// Calculate asset amounts that would be required to get the required spot price (rounding up on asset1 to ensure we stay in the intended tick)
441441
asset0Amount := osmomath.NewInt(100000000000000)
442-
asset1Amount := osmomath.NewDecFromInt(asset0Amount).Mul(requiredPrice.Dec()).Ceil().TruncateInt()
442+
asset1Amount := osmomath.BigDecFromDec(osmomath.NewDecFromInt(asset0Amount)).Mul(requiredPrice).Ceil().Dec().TruncateInt()
443443

444444
assetCoins := sdk.NewCoins(
445445
sdk.NewCoin(pool.GetToken0(), asset0Amount),

x/concentrated-liquidity/spread_rewards_test.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1370,16 +1370,16 @@ func (s *KeeperTestSuite) TestFunctional_SpreadRewards_Swaps() {
13701370
}
13711371

13721372
// Swap multiple times USDC for ETH, therefore increasing the spot price
1373-
ticksActivatedAfterEachSwap, totalSpreadRewardsExpected, _, _ := s.swapAndTrackXTimesInARow(clPool.GetId(), DefaultCoin1, ETH, types.MaxSpotPrice, positions.numSwaps)
1373+
ticksActivatedAfterEachSwap, totalSpreadRewardsExpected, _, _ := s.swapAndTrackXTimesInARow(clPool.GetId(), DefaultCoin1, ETH, types.MaxSpotPriceBigDec, positions.numSwaps)
13741374
s.CollectAndAssertSpreadRewards(s.Ctx, clPool.GetId(), totalSpreadRewardsExpected, positionIds, [][]int64{ticksActivatedAfterEachSwap}, onlyUSDC, positions)
13751375

13761376
// Swap multiple times ETH for USDC, therefore decreasing the spot price
1377-
ticksActivatedAfterEachSwap, totalSpreadRewardsExpected, _, _ = s.swapAndTrackXTimesInARow(clPool.GetId(), DefaultCoin0, USDC, types.MinSpotPrice, positions.numSwaps)
1377+
ticksActivatedAfterEachSwap, totalSpreadRewardsExpected, _, _ = s.swapAndTrackXTimesInARow(clPool.GetId(), DefaultCoin0, USDC, types.MinSpotPriceBigDec, positions.numSwaps)
13781378
s.CollectAndAssertSpreadRewards(s.Ctx, clPool.GetId(), totalSpreadRewardsExpected, positionIds, [][]int64{ticksActivatedAfterEachSwap}, onlyETH, positions)
13791379

13801380
// Do the same swaps as before, however this time we collect spread rewards after both swap directions are complete.
1381-
ticksActivatedAfterEachSwapUp, totalSpreadRewardsExpectedUp, _, _ := s.swapAndTrackXTimesInARow(clPool.GetId(), DefaultCoin1, ETH, types.MaxSpotPrice, positions.numSwaps)
1382-
ticksActivatedAfterEachSwapDown, totalSpreadRewardsExpectedDown, _, _ := s.swapAndTrackXTimesInARow(clPool.GetId(), DefaultCoin0, USDC, types.MinSpotPrice, positions.numSwaps)
1381+
ticksActivatedAfterEachSwapUp, totalSpreadRewardsExpectedUp, _, _ := s.swapAndTrackXTimesInARow(clPool.GetId(), DefaultCoin1, ETH, types.MaxSpotPriceBigDec, positions.numSwaps)
1382+
ticksActivatedAfterEachSwapDown, totalSpreadRewardsExpectedDown, _, _ := s.swapAndTrackXTimesInARow(clPool.GetId(), DefaultCoin0, USDC, types.MinSpotPriceBigDec, positions.numSwaps)
13831383
totalSpreadRewardsExpected = totalSpreadRewardsExpectedUp.Add(totalSpreadRewardsExpectedDown...)
13841384

13851385
// We expect all positions to have both denoms in their spread reward accumulators except USDC for the overlapping range position since
@@ -1413,15 +1413,15 @@ func (s *KeeperTestSuite) TestFunctional_SpreadRewards_LP() {
14131413
s.FundAcc(owner, fundCoins)
14141414

14151415
// Errors since no position.
1416-
_, _, _, err := s.App.ConcentratedLiquidityKeeper.SwapOutAmtGivenIn(s.Ctx, owner, pool, sdk.NewCoin(ETH, osmomath.OneInt()), USDC, pool.GetSpreadFactor(s.Ctx), types.MaxSpotPrice)
1416+
_, _, _, err := s.App.ConcentratedLiquidityKeeper.SwapOutAmtGivenIn(s.Ctx, owner, pool, sdk.NewCoin(ETH, osmomath.OneInt()), USDC, pool.GetSpreadFactor(s.Ctx), types.MaxSpotPriceBigDec)
14171417
s.Require().Error(err)
14181418

14191419
// Create position in the default range 1.
14201420
positionDataOne, err := concentratedLiquidityKeeper.CreatePosition(ctx, pool.GetId(), owner, DefaultCoins, osmomath.ZeroInt(), osmomath.ZeroInt(), DefaultLowerTick, DefaultUpperTick)
14211421
s.Require().NoError(err)
14221422

14231423
// Swap once.
1424-
ticksActivatedAfterEachSwap, totalSpreadRewardsExpected, _, _ := s.swapAndTrackXTimesInARow(pool.GetId(), DefaultCoin1, ETH, types.MaxSpotPrice, 1)
1424+
ticksActivatedAfterEachSwap, totalSpreadRewardsExpected, _, _ := s.swapAndTrackXTimesInARow(pool.GetId(), DefaultCoin1, ETH, types.MaxSpotPriceBigDec, 1)
14251425

14261426
// Withdraw half.
14271427
halfLiquidity := positionDataOne.Liquidity.Mul(osmomath.NewDecWithPrec(5, 1))
@@ -1446,7 +1446,7 @@ func (s *KeeperTestSuite) TestFunctional_SpreadRewards_LP() {
14461446
fullLiquidity := positionDataTwo.Liquidity
14471447

14481448
// Swap once in the other direction.
1449-
ticksActivatedAfterEachSwap, totalSpreadRewardsExpected, _, _ = s.swapAndTrackXTimesInARow(pool.GetId(), DefaultCoin0, USDC, types.MinSpotPrice, 1)
1449+
ticksActivatedAfterEachSwap, totalSpreadRewardsExpected, _, _ = s.swapAndTrackXTimesInARow(pool.GetId(), DefaultCoin0, USDC, types.MinSpotPriceBigDec, 1)
14501450

14511451
// This should claim under the hood for position 2 since full liquidity is removed.
14521452
balanceBeforeWithdraw := s.App.BankKeeper.GetBalance(ctx, owner, ETH)
@@ -1542,7 +1542,7 @@ func (s *KeeperTestSuite) tickStatusInvariance(ticksActivatedAfterEachSwap [][]i
15421542

15431543
// swapAndTrackXTimesInARow performs `numSwaps` swaps and tracks the tick activated after each swap.
15441544
// It also returns the total spread rewards collected, the total token in, and the total token out.
1545-
func (s *KeeperTestSuite) swapAndTrackXTimesInARow(poolId uint64, coinIn sdk.Coin, coinOutDenom string, priceLimit osmomath.Dec, numSwaps int) (ticksActivatedAfterEachSwap []int64, totalSpreadRewards sdk.Coins, totalTokenIn sdk.Coin, totalTokenOut sdk.Coin) {
1545+
func (s *KeeperTestSuite) swapAndTrackXTimesInARow(poolId uint64, coinIn sdk.Coin, coinOutDenom string, priceLimit osmomath.BigDec, numSwaps int) (ticksActivatedAfterEachSwap []int64, totalSpreadRewards sdk.Coins, totalTokenIn sdk.Coin, totalTokenOut sdk.Coin) {
15461546
// Retrieve pool
15471547
clPool, err := s.App.ConcentratedLiquidityKeeper.GetPoolById(s.Ctx, poolId)
15481548
s.Require().NoError(err)

x/concentrated-liquidity/swaps.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,7 @@ func (k Keeper) swapOutAmtGivenIn(
216216
tokenIn sdk.Coin,
217217
tokenOutDenom string,
218218
spreadFactor osmomath.Dec,
219-
priceLimit osmomath.Dec,
219+
priceLimit osmomath.BigDec,
220220
) (calcTokenIn, calcTokenOut sdk.Coin, poolUpdates PoolUpdates, err error) {
221221
swapResult, poolUpdates, err := k.computeOutAmtGivenIn(ctx, pool.GetId(), tokenIn, tokenOutDenom, spreadFactor, priceLimit)
222222
if err != nil {
@@ -247,7 +247,7 @@ func (k *Keeper) swapInAmtGivenOut(
247247
desiredTokenOut sdk.Coin,
248248
tokenInDenom string,
249249
spreadFactor osmomath.Dec,
250-
priceLimit osmomath.Dec,
250+
priceLimit osmomath.BigDec,
251251
) (calcTokenIn, calcTokenOut sdk.Coin, poolUpdates PoolUpdates, err error) {
252252
swapResult, poolUpdates, err := k.computeInAmtGivenOut(ctx, desiredTokenOut, tokenInDenom, spreadFactor, priceLimit, pool.GetId())
253253
if err != nil {
@@ -278,7 +278,7 @@ func (k Keeper) CalcOutAmtGivenIn(
278278
spreadFactor osmomath.Dec,
279279
) (tokenOut sdk.Coin, err error) {
280280
cacheCtx, _ := ctx.CacheContext()
281-
swapResult, _, err := k.computeOutAmtGivenIn(cacheCtx, poolI.GetId(), tokenIn, tokenOutDenom, spreadFactor, osmomath.ZeroDec())
281+
swapResult, _, err := k.computeOutAmtGivenIn(cacheCtx, poolI.GetId(), tokenIn, tokenOutDenom, spreadFactor, osmomath.ZeroBigDec())
282282
if err != nil {
283283
return sdk.Coin{}, err
284284
}
@@ -293,7 +293,7 @@ func (k Keeper) CalcInAmtGivenOut(
293293
spreadFactor osmomath.Dec,
294294
) (sdk.Coin, error) {
295295
cacheCtx, _ := ctx.CacheContext()
296-
swapResult, _, err := k.computeInAmtGivenOut(cacheCtx, tokenOut, tokenInDenom, spreadFactor, osmomath.ZeroDec(), poolI.GetId())
296+
swapResult, _, err := k.computeInAmtGivenOut(cacheCtx, tokenOut, tokenInDenom, spreadFactor, osmomath.ZeroBigDec(), poolI.GetId())
297297
if err != nil {
298298
return sdk.Coin{}, err
299299
}
@@ -354,7 +354,7 @@ func (k Keeper) computeOutAmtGivenIn(
354354
tokenInMin sdk.Coin,
355355
tokenOutDenom string,
356356
spreadFactor osmomath.Dec,
357-
priceLimit osmomath.Dec,
357+
priceLimit osmomath.BigDec,
358358
) (swapResult SwapResult, poolUpdates PoolUpdates, err error) {
359359
p, spreadRewardAccumulator, uptimeAccums, err := k.swapSetup(ctx, poolId, tokenInMin.Denom, tokenOutDenom)
360360
if err != nil {
@@ -481,7 +481,7 @@ func (k Keeper) computeInAmtGivenOut(
481481
desiredTokenOut sdk.Coin,
482482
tokenInDenom string,
483483
spreadFactor osmomath.Dec,
484-
priceLimit osmomath.Dec,
484+
priceLimit osmomath.BigDec,
485485
poolId uint64,
486486
) (swapResult SwapResult, poolUpdates PoolUpdates, err error) {
487487
p, spreadRewardAccumulator, uptimeAccums, err := k.swapSetup(ctx, poolId, tokenInDenom, desiredTokenOut.Denom)
@@ -734,7 +734,7 @@ func checkDenomValidity(inDenom, outDenom, asset0, asset1 string) error {
734734
return nil
735735
}
736736

737-
func (k Keeper) setupSwapStrategy(p types.ConcentratedPoolExtension, spreadFactor osmomath.Dec, tokenInDenom string, priceLimit osmomath.Dec) (strategy swapstrategy.SwapStrategy, sqrtPriceLimit osmomath.BigDec, err error) {
737+
func (k Keeper) setupSwapStrategy(p types.ConcentratedPoolExtension, spreadFactor osmomath.Dec, tokenInDenom string, priceLimit osmomath.BigDec) (strategy swapstrategy.SwapStrategy, sqrtPriceLimit osmomath.BigDec, err error) {
738738
zeroForOne := getZeroForOne(tokenInDenom, p.GetToken0())
739739

740740
// take provided price limit and turn this into a sqrt price limit since formulas use sqrtPrice
@@ -838,7 +838,7 @@ func (k Keeper) ComputeMaxInAmtGivenMaxTicksCrossed(
838838
}
839839

840840
// Setup the swap strategy
841-
swapStrategy, _, err := k.setupSwapStrategy(p, p.GetSpreadFactor(cacheCtx), tokenInDenom, osmomath.ZeroDec())
841+
swapStrategy, _, err := k.setupSwapStrategy(p, p.GetSpreadFactor(cacheCtx), tokenInDenom, osmomath.ZeroBigDec())
842842
if err != nil {
843843
return sdk.Coin{}, sdk.Coin{}, err
844844
}

0 commit comments

Comments
 (0)