Skip to content

Commit

Permalink
chore: CL apptesting helpers for SQS (backport #6822) (#6865)
Browse files Browse the repository at this point in the history
* chore: CL apptesting helpers for SQS (#6822)

Closes: #XXX

## What is the purpose of the change

This PR moves CL test helpers into the `apptesting` package so that these heleprs can be reused in SQS.

This is partial transfer of #6785 where the CL apptesting suite is already in-use

(cherry picked from commit 3ac7787)

# Conflicts:
#	x/concentrated-liquidity/keeper_test.go
#	x/concentrated-liquidity/lp_test.go
#	x/concentrated-liquidity/swaps_test.go

* updates

* merge conflicts

---------

Co-authored-by: Roman <[email protected]>
  • Loading branch information
mergify[bot] and p0mvn authored Nov 30, 2023
1 parent 26e3e16 commit a77e482
Show file tree
Hide file tree
Showing 12 changed files with 1,589 additions and 818 deletions.
848 changes: 841 additions & 7 deletions app/apptesting/concentrated_liquidity.go

Large diffs are not rendered by default.

22 changes: 13 additions & 9 deletions app/apptesting/pool_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,21 +31,25 @@ func (s *KeeperTestHelper) RunBasicSwap(poolId uint64) {
}

// CreatePoolFromType creates a basic pool of the given type for testing.
func (s *KeeperTestHelper) CreatePoolFromType(poolType poolmanagertypes.PoolType) {
func (s *KeeperTestHelper) CreatePoolFromType(poolType poolmanagertypes.PoolType) uint64 {
switch poolType {
case poolmanagertypes.Balancer:
s.PrepareBalancerPool()
return
balancerPoolID := s.PrepareBalancerPool()
return balancerPoolID
case poolmanagertypes.Stableswap:
s.PrepareBasicStableswapPool()
return
stableswapPoolID := s.PrepareBasicStableswapPool()
return stableswapPoolID
case poolmanagertypes.Concentrated:
s.PrepareConcentratedPool()
return
concentratedPool := s.PrepareConcentratedPool()
return concentratedPool.GetId()
case poolmanagertypes.CosmWasm:
s.PrepareCosmWasmPool()
return
cosmwasmPool := s.PrepareCosmWasmPool()
return cosmwasmPool.GetId()
default:
s.FailNow(fmt.Sprintf("unsupported pool type for this operation (%s)", poolmanagertypes.PoolType_name[int32(poolType)]))
}

return 0
}

// CreatePoolFromTypeWithCoins creates a pool with the given type and initialized with the given coins.
Expand Down
8 changes: 4 additions & 4 deletions x/concentrated-liquidity/fuzz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ func (s *KeeperTestSuite) individualFuzz(r *rand.Rand, fuzzNum int, numSwaps int
s.CreateFullRangePosition(pool, defaultCoins)

// Refetch pool
pool, err := s.clk.GetPoolById(s.Ctx, pool.GetId())
pool, err := s.Clk.GetPoolById(s.Ctx, pool.GetId())
s.Require().NoError(err)

fmt.Printf("SINGLE FUZZ START: %d. initialAmt0 %s initialAmt1 %s \n", fuzzNum, initialAmt0, initialAmt1)
Expand Down Expand Up @@ -146,7 +146,7 @@ func (s *KeeperTestSuite) fuzzTestWithSeed(r *rand.Rand, poolId uint64, numSwaps
}

func (s *KeeperTestSuite) randomSwap(r *rand.Rand, poolId uint64) (fatalErr bool) {
pool, err := s.clk.GetPoolById(s.Ctx, poolId)
pool, err := s.Clk.GetPoolById(s.Ctx, poolId)
s.Require().NoError(err)

updateStrategy := func() (swapStrategy int, zfo bool) {
Expand Down Expand Up @@ -292,7 +292,7 @@ func (s *KeeperTestSuite) swap(pool types.ConcentratedPoolExtension, swapInFunde
// // Execute swap
fmt.Printf("swap in: %s\n", swapInFunded)
cacheCtx, writeOutGivenIn := s.Ctx.CacheContext()
_, tokenOut, _, err := s.clk.SwapOutAmtGivenIn(cacheCtx, s.TestAccs[0], pool, swapInFunded, swapOutDenom, pool.GetSpreadFactor(s.Ctx), osmomath.ZeroBigDec())
_, tokenOut, _, err := s.Clk.SwapOutAmtGivenIn(cacheCtx, s.TestAccs[0], pool, swapInFunded, swapOutDenom, pool.GetSpreadFactor(s.Ctx), osmomath.ZeroBigDec())
if errors.As(err, &types.InvalidAmountCalculatedError{}) {
// If the swap we're about to execute will not generate enough output, we skip the swap.
// it would error for a real user though. This is good though, since that user would just be burning funds.
Expand All @@ -311,7 +311,7 @@ func (s *KeeperTestSuite) swap(pool types.ConcentratedPoolExtension, swapInFunde
// We expect the returned amountIn to be roughly equal to the original swapInFunded.
cacheCtx, _ = s.Ctx.CacheContext()
fmt.Printf("swap out: %s\n", tokenOut)
amountInSwapResult, _, _, err := s.clk.SwapInAmtGivenOut(cacheCtx, s.TestAccs[0], pool, tokenOut, swapInFunded.Denom, pool.GetSpreadFactor(s.Ctx), osmomath.ZeroBigDec())
amountInSwapResult, _, _, err := s.Clk.SwapInAmtGivenOut(cacheCtx, s.TestAccs[0], pool, tokenOut, swapInFunded.Denom, pool.GetSpreadFactor(s.Ctx), osmomath.ZeroBigDec())
if errors.As(err, &types.InvalidAmountCalculatedError{}) {
// If the swap we're about to execute will not generate enough output, we skip the swap.
// it would error for a real user though. This is good though, since that user would just be burning funds.
Expand Down
50 changes: 25 additions & 25 deletions x/concentrated-liquidity/incentives_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -484,7 +484,7 @@ func (s *KeeperTestSuite) TestCreateAndGetUptimeAccumulatorValues() {
}

func (s *KeeperTestSuite) getAllIncentiveRecordsForPool(poolId uint64) []types.IncentiveRecord {
records, err := s.clk.GetAllIncentiveRecordsForPool(s.Ctx, poolId)
records, err := s.Clk.GetAllIncentiveRecordsForPool(s.Ctx, poolId)
s.Require().NoError(err)
return records
}
Expand Down Expand Up @@ -718,7 +718,7 @@ func (s *KeeperTestSuite) TestCalcAccruedIncentivesForAccum() {

// If incentives are fully emitted, we ensure they are cleared from state
if tc.recordsCleared {
err := s.clk.SetMultipleIncentiveRecords(s.Ctx, updatedPoolRecords)
err := s.Clk.SetMultipleIncentiveRecords(s.Ctx, updatedPoolRecords)
s.Require().NoError(err)

updatedRecordsInState := s.getAllIncentiveRecordsForPool(tc.poolId)
Expand Down Expand Up @@ -764,7 +764,7 @@ func (s *KeeperTestSuite) TestUpdateUptimeAccumulatorsToNow() {
s.Require().ErrorContains(err, tc.expectedError.Error())

// Ensure accumulators remain unchanged
newUptimeAccumValues, err := s.clk.GetUptimeAccumulatorValues(ctx, poolId)
newUptimeAccumValues, err := s.Clk.GetUptimeAccumulatorValues(ctx, poolId)
s.Require().NoError(err)
s.Require().Equal(initUptimeAccumValues, newUptimeAccumValues)

Expand All @@ -778,7 +778,7 @@ func (s *KeeperTestSuite) TestUpdateUptimeAccumulatorsToNow() {
s.Require().NoError(err)

// Get updated pool for testing purposes
clPool, err := s.clk.GetPoolById(ctx, tc.poolId)
clPool, err := s.Clk.GetPoolById(ctx, tc.poolId)
s.Require().NoError(err)

// Calculate expected uptime deltas using qualifying liquidity deltas.
Expand All @@ -800,7 +800,7 @@ func (s *KeeperTestSuite) TestUpdateUptimeAccumulatorsToNow() {
}

// Get new uptime accum values for comparison
newUptimeAccumValues, err := s.clk.GetUptimeAccumulatorValues(ctx, tc.poolId)
newUptimeAccumValues, err := s.Clk.GetUptimeAccumulatorValues(ctx, tc.poolId)
s.Require().NoError(err)

// Ensure that each accumulator value changes by the correct amount
Expand All @@ -816,7 +816,7 @@ func (s *KeeperTestSuite) TestUpdateUptimeAccumulatorsToNow() {
s.Require().Equal(ctx.BlockTime(), clPool.GetLastLiquidityUpdate())

// Ensure that pool's IncentiveRecords are updated to reflect emitted incentives
updatedIncentiveRecords, err := s.clk.GetAllIncentiveRecordsForPool(ctx, tc.poolId)
updatedIncentiveRecords, err := s.Clk.GetAllIncentiveRecordsForPool(ctx, tc.poolId)
s.Require().NoError(err)
s.Require().Equal(tc.expectedIncentiveRecords, updatedIncentiveRecords)

Expand Down Expand Up @@ -1399,9 +1399,9 @@ func (s *KeeperTestSuite) TestGetUptimeGrowthRange() {
}

func (s *KeeperTestSuite) TestGetUptimeGrowthErrors() {
_, err := s.clk.GetUptimeGrowthInsideRange(s.Ctx, defaultPoolId, 0, 0)
_, err := s.Clk.GetUptimeGrowthInsideRange(s.Ctx, defaultPoolId, 0, 0)
s.Require().Error(err)
_, err = s.clk.GetUptimeGrowthOutsideRange(s.Ctx, defaultPoolId, 0, 0)
_, err = s.Clk.GetUptimeGrowthOutsideRange(s.Ctx, defaultPoolId, 0, 0)
s.Require().Error(err)
}

Expand Down Expand Up @@ -2822,7 +2822,7 @@ func (s *KeeperTestSuite) TestQueryAndClaimAllIncentives() {
}

// Initialize position
err := s.clk.InitOrUpdatePosition(s.Ctx, validPoolId, defaultSender, DefaultLowerTick, DefaultUpperTick, tc.numShares, joinTime, tc.positionIdCreate)
err := s.Clk.InitOrUpdatePosition(s.Ctx, validPoolId, defaultSender, DefaultLowerTick, DefaultUpperTick, tc.numShares, joinTime, tc.positionIdCreate)
s.Require().NoError(err)

clPool.SetCurrentTick(DefaultCurrTick)
Expand All @@ -2834,7 +2834,7 @@ func (s *KeeperTestSuite) TestQueryAndClaimAllIncentives() {
s.addUptimeGrowthInsideRange(s.Ctx, validPoolId, defaultSender, DefaultCurrTick, DefaultLowerTick, DefaultUpperTick, tc.growthInside)
}

err = s.clk.SetPool(s.Ctx, clPool)
err = s.Clk.SetPool(s.Ctx, clPool)
s.Require().NoError(err)

preCommunityPoolBalance := bankKeeper.GetAllBalances(s.Ctx, accountKeeper.GetModuleAddress(distributiontypes.ModuleName))
Expand All @@ -2843,14 +2843,14 @@ func (s *KeeperTestSuite) TestQueryAndClaimAllIncentives() {
initSenderBalances := s.App.BankKeeper.GetAllBalances(s.Ctx, defaultSender)
initPoolBalances := s.App.BankKeeper.GetAllBalances(s.Ctx, clPool.GetAddress())

largestSupportedUptime := s.clk.GetLargestSupportedUptimeDuration(s.Ctx)
largestSupportedUptime := s.Clk.GetLargestSupportedUptimeDuration(s.Ctx)
if !tc.forfeitIncentives {
// Let enough time elapse for the position to accrue rewards for all supported uptimes.
s.Ctx = s.Ctx.WithBlockTime(s.Ctx.BlockTime().Add(largestSupportedUptime))
}

// --- System under test ---
amountClaimedQuery, amountForfeitedQuery, err := s.clk.GetClaimableIncentives(s.Ctx, tc.positionIdClaim)
amountClaimedQuery, amountForfeitedQuery, err := s.Clk.GetClaimableIncentives(s.Ctx, tc.positionIdClaim)

// Pull new balances for comparison
newSenderBalances := s.App.BankKeeper.GetAllBalances(s.Ctx, defaultSender)
Expand All @@ -2864,7 +2864,7 @@ func (s *KeeperTestSuite) TestQueryAndClaimAllIncentives() {
s.Require().Equal(initSenderBalances, newSenderBalances)
s.Require().Equal(initPoolBalances, newPoolBalances)

amountClaimed, amountForfeited, err := s.clk.PrepareClaimAllIncentivesForPosition(s.Ctx, tc.positionIdClaim)
amountClaimed, amountForfeited, err := s.Clk.PrepareClaimAllIncentivesForPosition(s.Ctx, tc.positionIdClaim)

// --- Assertions ---

Expand Down Expand Up @@ -2980,7 +2980,7 @@ func (s *KeeperTestSuite) TestPrepareClaimAllIncentivesForPosition() {
pool := s.PrepareConcentratedPool()

// Set up position
positionOneData, err := s.clk.CreatePosition(s.Ctx, pool.GetId(), s.TestAccs[0], requiredBalances, osmomath.ZeroInt(), osmomath.ZeroInt(), DefaultLowerTick, DefaultUpperTick)
positionOneData, err := s.Clk.CreatePosition(s.Ctx, pool.GetId(), s.TestAccs[0], requiredBalances, osmomath.ZeroInt(), osmomath.ZeroInt(), DefaultLowerTick, DefaultUpperTick)
s.Require().NoError(err)

// Set incentives for pool to ensure accumulators work correctly
Expand All @@ -2993,18 +2993,18 @@ func (s *KeeperTestSuite) TestPrepareClaimAllIncentivesForPosition() {
},
MinUptime: tc.minUptimeIncentiveRecord,
}
err = s.clk.SetMultipleIncentiveRecords(s.Ctx, []types.IncentiveRecord{testIncentiveRecord})
err = s.Clk.SetMultipleIncentiveRecords(s.Ctx, []types.IncentiveRecord{testIncentiveRecord})
s.Require().NoError(err)

s.Ctx = s.Ctx.WithBlockTime(s.Ctx.BlockTime().Add(tc.blockTimeElapsed))

// Update the uptime accumulators to the current block time.
// This is done to determine the exact amount of incentives we expect to be forfeited, if any.
err = s.clk.UpdatePoolUptimeAccumulatorsToNow(s.Ctx, pool.GetId())
err = s.Clk.UpdatePoolUptimeAccumulatorsToNow(s.Ctx, pool.GetId())
s.Require().NoError(err)

// Retrieve the uptime accumulators for the pool.
uptimeAccumulatorsPreClaim, err := s.clk.GetUptimeAccumulators(s.Ctx, pool.GetId())
uptimeAccumulatorsPreClaim, err := s.Clk.GetUptimeAccumulators(s.Ctx, pool.GetId())
s.Require().NoError(err)

expectedForfeitedIncentives := sdk.NewCoins()
Expand All @@ -3031,15 +3031,15 @@ func (s *KeeperTestSuite) TestPrepareClaimAllIncentivesForPosition() {
}

// System under test
collectedInc, forfeitedIncentives, err := s.clk.PrepareClaimAllIncentivesForPosition(s.Ctx, positionOneData.ID)
collectedInc, forfeitedIncentives, err := s.Clk.PrepareClaimAllIncentivesForPosition(s.Ctx, positionOneData.ID)
s.Require().NoError(err)
s.Require().Equal(tc.expectedCoins.String(), collectedInc.String())
s.Require().Equal(expectedForfeitedIncentives.String(), forfeitedIncentives.String())

// The difference accumulator value should have increased if we forfeited incentives by claiming.
uptimeAccumsDiffPostClaim := sdk.NewDecCoins()
if tc.blockTimeElapsed < tc.minUptimeIncentiveRecord {
uptimeAccumulatorsPostClaim, err := s.clk.GetUptimeAccumulators(s.Ctx, pool.GetId())
uptimeAccumulatorsPostClaim, err := s.Clk.GetUptimeAccumulators(s.Ctx, pool.GetId())
s.Require().NoError(err)
for i, acc := range uptimeAccumulatorsPostClaim {
totalSharesAccum := acc.GetTotalShares()
Expand Down Expand Up @@ -3079,7 +3079,7 @@ func (s *KeeperTestSuite) TestFunctional_ClaimIncentives_LiquidityChange_Varying
requiredBalances := sdk.NewCoins(sdk.NewCoin(ETH, DefaultAmt0), sdk.NewCoin(USDC, DefaultAmt1))

// Set test authorized uptime params.
clParams := s.clk.GetParams(s.Ctx)
clParams := s.Clk.GetParams(s.Ctx)
clParams.AuthorizedUptimes = []time.Duration{time.Nanosecond, testFullChargeDuration}
s.App.ConcentratedLiquidityKeeper.SetParams(s.Ctx, clParams)

Expand Down Expand Up @@ -3338,12 +3338,12 @@ func (s *KeeperTestSuite) TestGetLargestAuthorizedAndSupportedUptimes() {
s.Run(name, func() {
s.SetupTest()

clParams := s.clk.GetParams(s.Ctx)
clParams := s.Clk.GetParams(s.Ctx)
clParams.AuthorizedUptimes = tc.preSetAuthorizedParams
s.clk.SetParams(s.Ctx, clParams)
s.Clk.SetParams(s.Ctx, clParams)

actualAuthorized := s.clk.GetLargestAuthorizedUptimeDuration(s.Ctx)
actualSupported := s.clk.GetLargestSupportedUptimeDuration(s.Ctx)
actualAuthorized := s.Clk.GetLargestAuthorizedUptimeDuration(s.Ctx)
actualSupported := s.Clk.GetLargestSupportedUptimeDuration(s.Ctx)

s.Require().Equal(tc.expectedAuthorized, actualAuthorized)
s.Require().Equal(longestSupportedUptime, actualSupported)
Expand All @@ -3357,7 +3357,7 @@ var defaultGlobalRewardGrowth = sdk.NewDecCoins(oneEth.Add(oneEth))

func (s *KeeperTestSuite) prepareSpreadRewardsAccumulator() *accum.AccumulatorObject {
pool := s.PrepareConcentratedPool()
testAccumulator, err := s.clk.GetSpreadRewardAccumulator(s.Ctx, pool.GetId())
testAccumulator, err := s.Clk.GetSpreadRewardAccumulator(s.Ctx, pool.GetId())
s.Require().NoError(err)
return testAccumulator
}
Expand Down
12 changes: 6 additions & 6 deletions x/concentrated-liquidity/invariant_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func (s *KeeperTestSuite) assertGlobalInvariants(expectedGlobalRewardValues Expe
// * Total pool incentives across all pools
func (s *KeeperTestSuite) getAllPositionsAndPoolBalances(ctx sdk.Context) ([]model.Position, sdk.Coins, sdk.Coins, sdk.Coins) {
// Get total spread rewards distributed to all pools
allPools, err := s.clk.GetPools(ctx)
allPools, err := s.Clk.GetPools(ctx)
totalPoolAssets, totalSpreadRewards, totalIncentives := sdk.NewCoins(), sdk.NewCoins(), sdk.NewCoins()

// Sum up pool balances across all pools
Expand All @@ -46,7 +46,7 @@ func (s *KeeperTestSuite) getAllPositionsAndPoolBalances(ctx sdk.Context) ([]mod
}

// Get all positions in state
allPoolPositions, err := s.clk.GetAllPositions(ctx)
allPoolPositions, err := s.Clk.GetAllPositions(ctx)
s.Require().NoError(err)

return allPoolPositions, totalPoolAssets, totalSpreadRewards, totalIncentives
Expand Down Expand Up @@ -82,7 +82,7 @@ func (s *KeeperTestSuite) assertTotalRewardsInvariant(expectedGlobalRewardValues
initialBalance := s.App.BankKeeper.GetAllBalances(cachedCtx, owner)

// Collect spread rewards.
collectedSpread, err := s.clk.CollectSpreadRewards(cachedCtx, owner, position.PositionId)
collectedSpread, err := s.Clk.CollectSpreadRewards(cachedCtx, owner, position.PositionId)
s.Require().NoError(err)

// Collect incentives.
Expand All @@ -92,7 +92,7 @@ func (s *KeeperTestSuite) assertTotalRewardsInvariant(expectedGlobalRewardValues
//
// Balancer full range incentives are also not factored in because they are claimed and sent to
// gauge immediately upon distribution.
collectedIncentives, _, err := s.clk.CollectIncentives(cachedCtx, owner, position.PositionId)
collectedIncentives, _, err := s.Clk.CollectIncentives(cachedCtx, owner, position.PositionId)
s.Require().NoError(err)

// Ensure position owner's balance was updated correctly
Expand Down Expand Up @@ -168,11 +168,11 @@ func (s *KeeperTestSuite) assertWithdrawAllInvariant() {
s.Require().NoError(err)

// Withdraw all assets from position
amt0Withdrawn, amt1Withdrawn, err := s.clk.WithdrawPosition(cachedCtx, owner, position.PositionId, position.Liquidity)
amt0Withdrawn, amt1Withdrawn, err := s.Clk.WithdrawPosition(cachedCtx, owner, position.PositionId, position.Liquidity)
s.Require().NoError(err)

// Convert withdrawn assets to coins
positionPool, err := s.clk.GetPoolById(cachedCtx, position.PoolId)
positionPool, err := s.Clk.GetPoolById(cachedCtx, position.PoolId)
s.Require().NoError(err)
withdrawn := sdk.NewCoins(
sdk.NewCoin(positionPool.GetToken0(), amt0Withdrawn),
Expand Down
Loading

0 comments on commit a77e482

Please sign in to comment.