-
Notifications
You must be signed in to change notification settings - Fork 607
/
test_suite.go
446 lines (368 loc) · 14.9 KB
/
test_suite.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
package apptesting
import (
"encoding/json"
"fmt"
"testing"
"time"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
cdctypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/store/rootmulti"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
"github.com/cosmos/cosmos-sdk/x/authz"
authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec"
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
"github.com/cosmos/cosmos-sdk/x/staking"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto/ed25519"
"github.com/tendermint/tendermint/libs/log"
tmtypes "github.com/tendermint/tendermint/proto/tendermint/types"
dbm "github.com/tendermint/tm-db"
"github.com/osmosis-labs/osmosis/v15/app"
"github.com/osmosis-labs/osmosis/v15/x/gamm/pool-models/balancer"
gammtypes "github.com/osmosis-labs/osmosis/v15/x/gamm/types"
lockupkeeper "github.com/osmosis-labs/osmosis/v15/x/lockup/keeper"
lockuptypes "github.com/osmosis-labs/osmosis/v15/x/lockup/types"
minttypes "github.com/osmosis-labs/osmosis/v15/x/mint/types"
poolmanagertypes "github.com/osmosis-labs/osmosis/v15/x/poolmanager/types"
)
type KeeperTestHelper struct {
suite.Suite
App *app.OsmosisApp
Ctx sdk.Context
QueryHelper *baseapp.QueryServiceTestHelper
TestAccs []sdk.AccAddress
}
var (
SecondaryDenom = "uion"
SecondaryAmount = sdk.NewInt(100000000)
)
// Setup sets up basic environment for suite (App, Ctx, and test accounts)
func (s *KeeperTestHelper) Setup() {
s.App = app.Setup(false)
s.Ctx = s.App.BaseApp.NewContext(false, tmtypes.Header{Height: 1, ChainID: "osmosis-1", Time: time.Now().UTC()})
s.QueryHelper = &baseapp.QueryServiceTestHelper{
GRPCQueryRouter: s.App.GRPCQueryRouter(),
Ctx: s.Ctx,
}
s.SetEpochStartTime()
s.TestAccs = CreateRandomAccounts(3)
s.SetupConcentratedLiquidityDenomsAndPoolCreation()
}
func (s *KeeperTestHelper) SetupTestForInitGenesis() {
// Setting to True, leads to init genesis not running
s.App = app.Setup(true)
s.Ctx = s.App.BaseApp.NewContext(true, tmtypes.Header{})
}
func (s *KeeperTestHelper) SetEpochStartTime() {
epochsKeeper := s.App.EpochsKeeper
for _, epoch := range epochsKeeper.AllEpochInfos(s.Ctx) {
epoch.StartTime = s.Ctx.BlockTime()
epochsKeeper.DeleteEpochInfo(s.Ctx, epoch.Identifier)
err := epochsKeeper.AddEpochInfo(s.Ctx, epoch)
if err != nil {
panic(err)
}
}
}
// CreateTestContext creates a test context.
func (s *KeeperTestHelper) CreateTestContext() sdk.Context {
ctx, _ := s.CreateTestContextWithMultiStore()
return ctx
}
// CreateTestContextWithMultiStore creates a test context and returns it together with multi store.
func (s *KeeperTestHelper) CreateTestContextWithMultiStore() (sdk.Context, sdk.CommitMultiStore) {
db := dbm.NewMemDB()
logger := log.NewNopLogger()
ms := rootmulti.NewStore(db, logger)
return sdk.NewContext(ms, tmtypes.Header{}, false, logger), ms
}
// CreateTestContext creates a test context.
func (s *KeeperTestHelper) Commit() {
oldHeight := s.Ctx.BlockHeight()
oldHeader := s.Ctx.BlockHeader()
s.App.Commit()
newHeader := tmtypes.Header{Height: oldHeight + 1, ChainID: oldHeader.ChainID, Time: oldHeader.Time.Add(time.Second)}
s.App.BeginBlock(abci.RequestBeginBlock{Header: newHeader})
s.Ctx = s.App.GetBaseApp().NewContext(false, newHeader)
}
// FundAcc funds target address with specified amount.
func (s *KeeperTestHelper) FundAcc(acc sdk.AccAddress, amounts sdk.Coins) {
err := simapp.FundAccount(s.App.BankKeeper, s.Ctx, acc, amounts)
s.Require().NoError(err)
}
// FundModuleAcc funds target modules with specified amount.
func (s *KeeperTestHelper) FundModuleAcc(moduleName string, amounts sdk.Coins) {
err := simapp.FundModuleAccount(s.App.BankKeeper, s.Ctx, moduleName, amounts)
s.Require().NoError(err)
}
func (s *KeeperTestHelper) MintCoins(coins sdk.Coins) {
err := s.App.BankKeeper.MintCoins(s.Ctx, minttypes.ModuleName, coins)
s.Require().NoError(err)
}
// SetupValidator sets up a validator and returns the ValAddress.
func (s *KeeperTestHelper) SetupValidator(bondStatus stakingtypes.BondStatus) sdk.ValAddress {
valPub := secp256k1.GenPrivKey().PubKey()
valAddr := sdk.ValAddress(valPub.Address())
bondDenom := s.App.StakingKeeper.GetParams(s.Ctx).BondDenom
selfBond := sdk.NewCoins(sdk.Coin{Amount: sdk.NewInt(100), Denom: bondDenom})
s.FundAcc(sdk.AccAddress(valAddr), selfBond)
stakingHandler := staking.NewHandler(*s.App.StakingKeeper)
stakingCoin := sdk.NewCoin(sdk.DefaultBondDenom, selfBond[0].Amount)
ZeroCommission := stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec())
msg, err := stakingtypes.NewMsgCreateValidator(valAddr, valPub, stakingCoin, stakingtypes.Description{}, ZeroCommission, sdk.OneInt())
s.Require().NoError(err)
res, err := stakingHandler(s.Ctx, msg)
s.Require().NoError(err)
s.Require().NotNil(res)
val, found := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr)
s.Require().True(found)
val = val.UpdateStatus(bondStatus)
s.App.StakingKeeper.SetValidator(s.Ctx, val)
consAddr, err := val.GetConsAddr()
s.Suite.Require().NoError(err)
signingInfo := slashingtypes.NewValidatorSigningInfo(
consAddr,
s.Ctx.BlockHeight(),
0,
time.Unix(0, 0),
false,
0,
)
s.App.SlashingKeeper.SetValidatorSigningInfo(s.Ctx, consAddr, signingInfo)
return valAddr
}
// SetupMultipleValidators setups "numValidator" validators and returns their address in string
func (s *KeeperTestHelper) SetupMultipleValidators(numValidator int) []string {
valAddrs := []string{}
for i := 0; i < numValidator; i++ {
valAddr := s.SetupValidator(stakingtypes.Bonded)
valAddrs = append(valAddrs, valAddr.String())
}
return valAddrs
}
// BeginNewBlock starts a new block.
func (s *KeeperTestHelper) BeginNewBlock(executeNextEpoch bool) {
var valAddr []byte
validators := s.App.StakingKeeper.GetAllValidators(s.Ctx)
if len(validators) >= 1 {
valAddrFancy, err := validators[0].GetConsAddr()
s.Require().NoError(err)
valAddr = valAddrFancy.Bytes()
} else {
valAddrFancy := s.SetupValidator(stakingtypes.Bonded)
validator, _ := s.App.StakingKeeper.GetValidator(s.Ctx, valAddrFancy)
valAddr2, _ := validator.GetConsAddr()
valAddr = valAddr2.Bytes()
}
s.BeginNewBlockWithProposer(executeNextEpoch, valAddr)
}
// BeginNewBlockWithProposer begins a new block with a proposer.
func (s *KeeperTestHelper) BeginNewBlockWithProposer(executeNextEpoch bool, proposer sdk.ValAddress) {
validator, found := s.App.StakingKeeper.GetValidator(s.Ctx, proposer)
s.Assert().True(found)
valConsAddr, err := validator.GetConsAddr()
s.Require().NoError(err)
valAddr := valConsAddr.Bytes()
epochIdentifier := s.App.SuperfluidKeeper.GetEpochIdentifier(s.Ctx)
epoch := s.App.EpochsKeeper.GetEpochInfo(s.Ctx, epochIdentifier)
newBlockTime := s.Ctx.BlockTime().Add(5 * time.Second)
if executeNextEpoch {
newBlockTime = s.Ctx.BlockTime().Add(epoch.Duration).Add(time.Second)
}
header := tmtypes.Header{Height: s.Ctx.BlockHeight() + 1, Time: newBlockTime}
newCtx := s.Ctx.WithBlockTime(newBlockTime).WithBlockHeight(s.Ctx.BlockHeight() + 1)
s.Ctx = newCtx
lastCommitInfo := abci.LastCommitInfo{
Votes: []abci.VoteInfo{{
Validator: abci.Validator{Address: valAddr, Power: 1000},
SignedLastBlock: true,
}},
}
reqBeginBlock := abci.RequestBeginBlock{Header: header, LastCommitInfo: lastCommitInfo}
fmt.Println("beginning block ", s.Ctx.BlockHeight())
s.App.BeginBlocker(s.Ctx, reqBeginBlock)
s.Ctx = s.App.NewContext(false, reqBeginBlock.Header)
}
// EndBlock ends the block, and runs commit
func (s *KeeperTestHelper) EndBlock() {
reqEndBlock := abci.RequestEndBlock{Height: s.Ctx.BlockHeight()}
s.App.EndBlocker(s.Ctx, reqEndBlock)
}
func (s *KeeperTestHelper) RunMsg(msg sdk.Msg) (*sdk.Result, error) {
// cursed that we have to copy this internal logic from SDK
router := s.App.GetBaseApp().MsgServiceRouter()
if handler := router.Handler(msg); handler != nil {
// ADR 031 request type routing
return handler(s.Ctx, msg)
}
s.FailNow("msg %v could not be ran", msg)
return nil, fmt.Errorf("msg %v could not be ran", msg)
}
// AllocateRewardsToValidator allocates reward tokens to a distribution module then allocates rewards to the validator address.
func (s *KeeperTestHelper) AllocateRewardsToValidator(valAddr sdk.ValAddress, rewardAmt sdk.Int) {
validator, found := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr)
s.Require().True(found)
// allocate reward tokens to distribution module
coins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, rewardAmt)}
err := simapp.FundModuleAccount(s.App.BankKeeper, s.Ctx, distrtypes.ModuleName, coins)
s.Require().NoError(err)
// allocate rewards to validator
s.Ctx = s.Ctx.WithBlockHeight(s.Ctx.BlockHeight() + 1)
decTokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(20000)}}
s.App.DistrKeeper.AllocateTokensToValidator(s.Ctx, validator, decTokens)
}
// SetupGammPoolsWithBondDenomMultiplier uses given multipliers to set initial pool supply of bond denom.
func (s *KeeperTestHelper) SetupGammPoolsWithBondDenomMultiplier(multipliers []sdk.Dec) []gammtypes.CFMMPoolI {
bondDenom := s.App.StakingKeeper.BondDenom(s.Ctx)
// TODO: use sdk crypto instead of tendermint to generate address
acc1 := sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address().Bytes())
params := s.App.GAMMKeeper.GetParams(s.Ctx)
pools := []gammtypes.CFMMPoolI{}
for index, multiplier := range multipliers {
token := fmt.Sprintf("token%d", index)
uosmoAmount := gammtypes.InitPoolSharesSupply.ToDec().Mul(multiplier).RoundInt()
s.FundAcc(acc1, sdk.NewCoins(
sdk.NewCoin(bondDenom, uosmoAmount.Mul(sdk.NewInt(10))),
sdk.NewInt64Coin(token, 100000),
).Add(params.PoolCreationFee...))
var (
defaultFutureGovernor = ""
// pool assets
defaultFooAsset = balancer.PoolAsset{
Weight: sdk.NewInt(100),
Token: sdk.NewCoin(bondDenom, uosmoAmount),
}
defaultBarAsset = balancer.PoolAsset{
Weight: sdk.NewInt(100),
Token: sdk.NewCoin(token, sdk.NewInt(10000)),
}
poolAssets = []balancer.PoolAsset{defaultFooAsset, defaultBarAsset}
)
poolParams := balancer.PoolParams{
SwapFee: sdk.NewDecWithPrec(1, 2),
ExitFee: sdk.Dec(sdk.ZeroInt()),
}
msg := balancer.NewMsgCreateBalancerPool(acc1, poolParams, poolAssets, defaultFutureGovernor)
poolId, err := s.App.PoolManagerKeeper.CreatePool(s.Ctx, msg)
s.Require().NoError(err)
pool, err := s.App.GAMMKeeper.GetPoolAndPoke(s.Ctx, poolId)
s.Require().NoError(err)
pools = append(pools, pool)
}
return pools
}
// SwapAndSetSpotPrice runs a swap to set Spot price of a pool using arbitrary values
// returns spot price after the arbitrary swap.
func (s *KeeperTestHelper) SwapAndSetSpotPrice(poolId uint64, fromAsset sdk.Coin, toAsset sdk.Coin) sdk.Dec {
// create a dummy account
acc1 := sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address().Bytes())
// fund dummy account with tokens to swap
coins := sdk.Coins{sdk.NewInt64Coin(fromAsset.Denom, 100000000000000)}
s.FundAcc(acc1, coins)
route := []poolmanagertypes.SwapAmountOutRoute{
{
PoolId: poolId,
TokenInDenom: fromAsset.Denom,
},
}
_, err := s.App.PoolManagerKeeper.RouteExactAmountOut(
s.Ctx,
acc1,
route,
fromAsset.Amount,
sdk.NewCoin(toAsset.Denom,
toAsset.Amount.Quo(sdk.NewInt(4))))
s.Require().NoError(err)
spotPrice, err := s.App.GAMMKeeper.CalculateSpotPrice(s.Ctx, poolId, fromAsset.Denom, toAsset.Denom)
s.Require().NoError(err)
return spotPrice
}
// LockTokens funds an account, locks tokens and returns a lockID.
func (s *KeeperTestHelper) LockTokens(addr sdk.AccAddress, coins sdk.Coins, duration time.Duration) (lockID uint64) {
msgServer := lockupkeeper.NewMsgServerImpl(s.App.LockupKeeper)
s.FundAcc(addr, coins)
msgResponse, err := msgServer.LockTokens(sdk.WrapSDKContext(s.Ctx), lockuptypes.NewMsgLockTokens(addr, duration, coins))
s.Require().NoError(err)
return msgResponse.ID
}
// BuildTx builds a transaction.
func (s *KeeperTestHelper) BuildTx(
txBuilder client.TxBuilder,
msgs []sdk.Msg,
sigV2 signing.SignatureV2,
memo string, txFee sdk.Coins,
gasLimit uint64,
) authsigning.Tx {
err := txBuilder.SetMsgs(msgs[0])
s.Require().NoError(err)
err = txBuilder.SetSignatures(sigV2)
s.Require().NoError(err)
txBuilder.SetMemo(memo)
txBuilder.SetFeeAmount(txFee)
txBuilder.SetGasLimit(gasLimit)
return txBuilder.GetTx()
}
// StateNotAltered validates that app state is not altered. Fails if it is.
func (s *KeeperTestHelper) StateNotAltered() {
oldState := s.App.ExportState(s.Ctx)
s.App.Commit()
newState := s.App.ExportState(s.Ctx)
s.Require().Equal(oldState, newState)
}
// CreateRandomAccounts is a function return a list of randomly generated AccAddresses
func CreateRandomAccounts(numAccts int) []sdk.AccAddress {
testAddrs := make([]sdk.AccAddress, numAccts)
for i := 0; i < numAccts; i++ {
pk := ed25519.GenPrivKey().PubKey()
testAddrs[i] = sdk.AccAddress(pk.Address())
}
return testAddrs
}
func TestMessageAuthzSerialization(t *testing.T, msg sdk.Msg) {
someDate := time.Date(1, 1, 1, 1, 1, 1, 1, time.UTC)
const (
mockGranter string = "cosmos1abc"
mockGrantee string = "cosmos1xyz"
)
var (
mockMsgGrant authz.MsgGrant
mockMsgRevoke authz.MsgRevoke
mockMsgExec authz.MsgExec
)
// Authz: Grant Msg
typeURL := sdk.MsgTypeURL(msg)
grant, err := authz.NewGrant(someDate, authz.NewGenericAuthorization(typeURL), someDate.Add(time.Hour))
require.NoError(t, err)
msgGrant := authz.MsgGrant{Granter: mockGranter, Grantee: mockGrantee, Grant: grant}
msgGrantBytes := json.RawMessage(sdk.MustSortJSON(authzcodec.ModuleCdc.MustMarshalJSON(&msgGrant)))
err = authzcodec.ModuleCdc.UnmarshalJSON(msgGrantBytes, &mockMsgGrant)
require.NoError(t, err)
// Authz: Revoke Msg
msgRevoke := authz.MsgRevoke{Granter: mockGranter, Grantee: mockGrantee, MsgTypeUrl: typeURL}
msgRevokeByte := json.RawMessage(sdk.MustSortJSON(authzcodec.ModuleCdc.MustMarshalJSON(&msgRevoke)))
err = authzcodec.ModuleCdc.UnmarshalJSON(msgRevokeByte, &mockMsgRevoke)
require.NoError(t, err)
// Authz: Exec Msg
msgAny, err := cdctypes.NewAnyWithValue(msg)
require.NoError(t, err)
msgExec := authz.MsgExec{Grantee: mockGrantee, Msgs: []*cdctypes.Any{msgAny}}
execMsgByte := json.RawMessage(sdk.MustSortJSON(authzcodec.ModuleCdc.MustMarshalJSON(&msgExec)))
err = authzcodec.ModuleCdc.UnmarshalJSON(execMsgByte, &mockMsgExec)
require.NoError(t, err)
require.Equal(t, msgExec.Msgs[0].Value, mockMsgExec.Msgs[0].Value)
}
func GenerateTestAddrs() (string, string) {
pk1 := ed25519.GenPrivKey().PubKey()
validAddr := sdk.AccAddress(pk1.Address()).String()
invalidAddr := sdk.AccAddress("invalid").String()
return validAddr, invalidAddr
}