Skip to content

Commit

Permalink
Reintroduce #1719 random tests (backport #1791) (#1794)
Browse files Browse the repository at this point in the history
* Reintroduce #1719 random tests (#1791)

* Add joon's random tests

* Move file its in

* Use ctx for v10 state machine compatibility

* Change bounds, comment on rounding behavior

Co-authored-by: Dev Ojha <[email protected]>
Co-authored-by: Dev Ojha <[email protected]>
(cherry picked from commit 97934d4)

# Conflicts:
#	x/gamm/pool-models/balancer/amm_joinpool_test.go

* Fix merge conflict

Co-authored-by: Matt, Park <[email protected]>
Co-authored-by: Dev Ojha <[email protected]>
  • Loading branch information
3 people authored Jun 12, 2022
1 parent f140a9d commit 7ca72c5
Show file tree
Hide file tree
Showing 2 changed files with 114 additions and 0 deletions.
109 changes: 109 additions & 0 deletions x/gamm/pool-models/balancer/amm_joinpool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package balancer_test
import (
"errors"
"fmt"
"math/rand"
"testing"
time "time"

sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
Expand Down Expand Up @@ -1025,3 +1027,110 @@ func assertExpectedLiquidity(t *testing.T, expectLiq, tokensJoined, liquidity sd
require.Equal(t, tokensJoined, liquidity)
}
}

// Tests selecting a random amount of coins to LP, and then that ExitPool(JoinPool(tokens))
// preserves the pools number of LP shares, and returns fewer coins to the acter than they started with.
func (suite *KeeperTestSuite) TestRandomizedJoinPoolExitPoolInvariants() {
type testCase struct {
initialTokensDenomIn int64
initialTokensDenomOut int64

percentRatio int64

numShares sdk.Int
}

const (
denomOut = "denomOut"
denomIn = "denomIn"
)

now := int64(time.Now().Unix())
rng := rand.NewSource(now)
suite.T().Logf("Using random source of %d\n", now)

// generate test case with randomized initial assets and join/exit ratio
newCase := func() (tc *testCase) {
tc = new(testCase)
tc.initialTokensDenomIn = rng.Int63() % (1 << 62)
tc.initialTokensDenomOut = rng.Int63() % (1 << 62)

// 1%~100% of initial assets
tc.percentRatio = rng.Int63()%100 + 1

return tc
}

swapFeeDec := sdk.ZeroDec()
exitFeeDec := sdk.ZeroDec()

// create pool with randomized initial token amounts
// and randomized ratio of join/exit
createPool := func(tc *testCase) (pool *balancer.Pool) {
poolAssetOut := balancer.PoolAsset{
Token: sdk.NewInt64Coin(denomOut, tc.initialTokensDenomOut),
Weight: sdk.NewInt(5),
}

poolAssetIn := balancer.PoolAsset{
Token: sdk.NewInt64Coin(denomIn, tc.initialTokensDenomIn),
Weight: sdk.NewInt(5),
}

pool = createTestPool(suite.T(), swapFeeDec, exitFeeDec, poolAssetOut, poolAssetIn).(*balancer.Pool)
suite.Require().NotNil(pool)

return pool
}

// joins with predetermined ratio
joinPool := func(pool types.PoolI, tc *testCase) {
tokensIn := sdk.Coins{
sdk.NewCoin(denomIn, sdk.NewInt(tc.initialTokensDenomIn).MulRaw(tc.percentRatio).QuoRaw(100)),
sdk.NewCoin(denomOut, sdk.NewInt(tc.initialTokensDenomOut).MulRaw(tc.percentRatio).QuoRaw(100)),
}
numShares, err := pool.JoinPool(suite.Ctx, tokensIn, swapFeeDec)
suite.Require().NoError(err)
tc.numShares = numShares
}

// exits for same amount of shares minted
exitPool := func(pool types.PoolI, tc *testCase) {
_, err := pool.ExitPool(suite.Ctx, tc.numShares, exitFeeDec)
suite.Require().NoError(err)
}

invariantJoinExitInversePreserve := func(
beforeCoins, afterCoins sdk.Coins,
beforeShares, afterShares sdk.Int,
) {
// test token amount has been preserved
suite.Require().True(
!beforeCoins.IsAnyGT(afterCoins),
"Coins has not been preserved before and after join-exit\nbefore:\t%s\nafter:\t%s",
beforeCoins, afterCoins,
)
// test share amount has been preserved
suite.Require().True(
beforeShares.Equal(afterShares),
"Shares has not been preserved before and after join-exit\nbefore:\t%s\nafter:\t%s",
beforeShares, afterShares,
)
}

testPoolInvariants := func() {
tc := newCase()
pool := createPool(tc)
originalCoins, originalShares := pool.GetTotalPoolLiquidity(sdk.Context{}), pool.GetTotalShares()
joinPool(pool, tc)
exitPool(pool, tc)
invariantJoinExitInversePreserve(
originalCoins, pool.GetTotalPoolLiquidity(sdk.Context{}),
originalShares, pool.GetTotalShares(),
)
}

for i := 0; i < 50000; i++ {
testPoolInvariants()
}
}
5 changes: 5 additions & 0 deletions x/gamm/pool-models/internal/cfmm_common/lp.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,9 @@ func MaximalExactRatioJoin(p types.PoolI, ctx sdk.Context, tokensIn sdk.Coins) (
totalShares := p.GetTotalShares()

for i, coin := range tokensIn {
// Note: QuoInt implements floor division, unlike Quo
// This is because it calls the native golang routine big.Int.Quo
// https://pkg.go.dev/math/big#Int.Quo
shareRatio := coin.Amount.ToDec().QuoInt(poolLiquidity.AmountOfNoDenomValidation(coin.Denom))
if shareRatio.LT(minShareRatio) {
minShareRatio = shareRatio
Expand All @@ -125,6 +128,8 @@ func MaximalExactRatioJoin(p types.PoolI, ctx sdk.Context, tokensIn sdk.Coins) (
}

remCoins = sdk.Coins{}
// critically we round down here (TruncateInt), to ensure that the returned LP shares
// are always less than or equal to % liquidity added.
numShares = minShareRatio.MulInt(totalShares).TruncateInt()

// if we have multiple share values, calculate remainingCoins
Expand Down

0 comments on commit 7ca72c5

Please sign in to comment.