From aee2a7df066c8cee190370c18d303f1cf6689454 Mon Sep 17 00:00:00 2001 From: Dreamer Date: Wed, 13 Mar 2024 14:41:00 +0800 Subject: [PATCH 1/3] replace simapp with IrisApp --- go.mod | 2 +- modules/guardian/client/cli/cli_test.go | 6 +- .../guardian/client/testutil/test_helpers.go | 10 +- modules/guardian/genesis_test.go | 4 +- modules/guardian/keeper/keeper_test.go | 6 +- modules/mint/abci_test.go | 6 +- modules/mint/client/cli/cli_test.go | 4 +- modules/mint/client/rest/grpc_query_test.go | 2 +- modules/mint/keeper/keeper_test.go | 6 +- modules/mint/simulation/decoder_test.go | 9 +- simapp/app.go | 722 ------------------ simapp/encoding.go | 19 - simapp/export.go | 206 ----- testutil/app.go | 59 ++ testutil/export.go | 13 + {simapp => testutil}/genesis.go | 9 +- {simapp => testutil}/test_helpers.go | 192 +---- 17 files changed, 127 insertions(+), 1148 deletions(-) delete mode 100644 simapp/app.go delete mode 100644 simapp/encoding.go delete mode 100644 simapp/export.go create mode 100644 testutil/app.go create mode 100644 testutil/export.go rename {simapp => testutil}/genesis.go (68%) rename {simapp => testutil}/test_helpers.go (66%) diff --git a/go.mod b/go.mod index 6aaf16a1e..981a78eb3 100644 --- a/go.mod +++ b/go.mod @@ -39,7 +39,6 @@ require ( ) require ( - cosmossdk.io/simapp v0.0.0-20230608160436-666c345ad23d github.com/gogo/protobuf v1.3.2 github.com/olebedev/config v0.0.0-20190528211619-364964f3a8e4 github.com/pkg/errors v0.9.1 @@ -52,6 +51,7 @@ require ( require ( cloud.google.com/go/compute/metadata v0.2.3 // indirect cosmossdk.io/log v1.3.1 // indirect + cosmossdk.io/simapp v0.0.0-20230608160436-666c345ad23d // indirect cosmossdk.io/tools/rosetta v0.2.1 // indirect github.com/btcsuite/btcd/btcutil v1.1.3 // indirect github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1 // indirect diff --git a/modules/guardian/client/cli/cli_test.go b/modules/guardian/client/cli/cli_test.go index 57d54c60c..a88a68ed2 100644 --- a/modules/guardian/client/cli/cli_test.go +++ b/modules/guardian/client/cli/cli_test.go @@ -18,7 +18,7 @@ import ( guardiancli "github.com/irisnet/irishub/v3/modules/guardian/client/cli" guardiantestutil "github.com/irisnet/irishub/v3/modules/guardian/client/testutil" guardiantypes "github.com/irisnet/irishub/v3/modules/guardian/types" - "github.com/irisnet/irishub/v3/simapp" + apptestutil "github.com/irisnet/irishub/v3/testutil" ) var privKey cryptotypes.PrivKey @@ -35,7 +35,7 @@ type IntegrationTestSuite struct { func (s *IntegrationTestSuite) SetupSuite() { s.T().Log("setting up integration test suite") - cfg := simapp.NewConfig() + cfg := apptestutil.NewConfig() cfg.NumValidators = 1 privKey, pubKey, addr = testdata.KeyTestPubAddr() @@ -90,7 +90,7 @@ func (s *IntegrationTestSuite) TestGuardian() { ), } - result := simapp.ExecTxCmdWithResult(s.T(), s.network, clientCtx, bankcli.NewSendTxCmd(), args) + result := apptestutil.ExecTxCmdWithResult(s.T(), s.network, clientCtx, bankcli.NewSendTxCmd(), args) s.Require().Equal(uint32(0), result.TxResult.Code, result.TxResult.Log) //------test GetCmdQuerySupers()------------- diff --git a/modules/guardian/client/testutil/test_helpers.go b/modules/guardian/client/testutil/test_helpers.go index 7b938185b..0a43e8337 100644 --- a/modules/guardian/client/testutil/test_helpers.go +++ b/modules/guardian/client/testutil/test_helpers.go @@ -14,10 +14,10 @@ import ( "github.com/cosmos/cosmos-sdk/testutil/network" guardiancli "github.com/irisnet/irishub/v3/modules/guardian/client/cli" - "github.com/irisnet/irishub/v3/simapp" + apptestutil "github.com/irisnet/irishub/v3/testutil" ) -// MsgRedelegateExec creates a redelegate message. +// CreateSuperExec creates a new super func CreateSuperExec( t *testing.T, network *network.Network, @@ -30,9 +30,10 @@ func CreateSuperExec( } args = append(args, extraArgs...) - return simapp.ExecTxCmdWithResult(t, network, clientCtx, guardiancli.GetCmdCreateSuper(), args) + return apptestutil.ExecTxCmdWithResult(t, network, clientCtx, guardiancli.GetCmdCreateSuper(), args) } +// DeleteSuperExec deletes a super func DeleteSuperExec( t *testing.T, network *network.Network, @@ -45,9 +46,10 @@ func DeleteSuperExec( } args = append(args, extraArgs...) - return simapp.ExecTxCmdWithResult(t, network, clientCtx, guardiancli.GetCmdDeleteSuper(), args) + return apptestutil.ExecTxCmdWithResult(t, network, clientCtx, guardiancli.GetCmdDeleteSuper(), args) } +// QuerySupersExec queries supers func QuerySupersExec(clientCtx client.Context, extraArgs ...string) (testutil.BufferWriter, error) { args := []string{ fmt.Sprintf("--%s=json", cli.OutputFlag), diff --git a/modules/guardian/genesis_test.go b/modules/guardian/genesis_test.go index 3313fe5ef..5c14656b4 100644 --- a/modules/guardian/genesis_test.go +++ b/modules/guardian/genesis_test.go @@ -13,7 +13,7 @@ import ( "github.com/irisnet/irishub/v3/modules/guardian" "github.com/irisnet/irishub/v3/modules/guardian/keeper" "github.com/irisnet/irishub/v3/modules/guardian/types" - "github.com/irisnet/irishub/v3/simapp" + "github.com/irisnet/irishub/v3/testutil" ) type TestSuite struct { @@ -25,7 +25,7 @@ type TestSuite struct { } func (suite *TestSuite) SetupTest() { - app := simapp.Setup(suite.T(), false) + app := testutil.Setup(suite.T(), false) suite.cdc = codec.NewAminoCodec(app.LegacyAmino()) suite.ctx = app.BaseApp.NewContext(false, tmproto.Header{}) diff --git a/modules/guardian/keeper/keeper_test.go b/modules/guardian/keeper/keeper_test.go index 98aae202b..2df51a87a 100644 --- a/modules/guardian/keeper/keeper_test.go +++ b/modules/guardian/keeper/keeper_test.go @@ -15,7 +15,7 @@ import ( "github.com/irisnet/irishub/v3/modules/guardian/keeper" "github.com/irisnet/irishub/v3/modules/guardian/types" - "github.com/irisnet/irishub/v3/simapp" + "github.com/irisnet/irishub/v3/testutil" ) var ( @@ -37,11 +37,11 @@ type KeeperTestSuite struct { cdc *codec.LegacyAmino ctx sdk.Context keeper keeper.Keeper - app *simapp.SimApp + app *testutil.AppBuilder } func (suite *KeeperTestSuite) SetupTest() { - app := simapp.Setup(suite.T(), false) + app := testutil.Setup(suite.T(), false) suite.app = app suite.cdc = app.LegacyAmino() diff --git a/modules/mint/abci_test.go b/modules/mint/abci_test.go index 0b507f719..8a0907603 100644 --- a/modules/mint/abci_test.go +++ b/modules/mint/abci_test.go @@ -12,7 +12,7 @@ import ( "github.com/irisnet/irishub/v3/modules/mint" "github.com/irisnet/irishub/v3/modules/mint/types" - "github.com/irisnet/irishub/v3/simapp" + apptestutil "github.com/irisnet/irishub/v3/testutil" ) func TestBeginBlocker(t *testing.T) { @@ -29,8 +29,8 @@ func TestBeginBlocker(t *testing.T) { } // returns context and an app with updated mint keeper -func createTestApp(t *testing.T, isCheckTx bool) (*simapp.SimApp, sdk.Context) { - app := simapp.Setup(t, false) +func createTestApp(t *testing.T, isCheckTx bool) (*apptestutil.AppBuilder, sdk.Context) { + app := apptestutil.Setup(t, false) ctx := app.BaseApp.NewContext(isCheckTx, tmproto.Header{Height: 2}) app.MintKeeper.SetParams(ctx, types.NewParams( diff --git a/modules/mint/client/cli/cli_test.go b/modules/mint/client/cli/cli_test.go index 4fcf0fd57..a49c19842 100644 --- a/modules/mint/client/cli/cli_test.go +++ b/modules/mint/client/cli/cli_test.go @@ -9,7 +9,7 @@ import ( minttestutil "github.com/irisnet/irishub/v3/modules/mint/client/testutil" minttypes "github.com/irisnet/irishub/v3/modules/mint/types" - "github.com/irisnet/irishub/v3/simapp" + "github.com/irisnet/irishub/v3/testutil" ) type IntegrationTestSuite struct { @@ -22,7 +22,7 @@ type IntegrationTestSuite struct { func (s *IntegrationTestSuite) SetupSuite() { s.T().Log("setting up integration test suite") - cfg := simapp.NewConfig() + cfg := testutil.NewConfig() cfg.NumValidators = 1 var err error diff --git a/modules/mint/client/rest/grpc_query_test.go b/modules/mint/client/rest/grpc_query_test.go index 90e9677de..2ee88af4d 100644 --- a/modules/mint/client/rest/grpc_query_test.go +++ b/modules/mint/client/rest/grpc_query_test.go @@ -11,7 +11,7 @@ package rest_test // "github.com/cosmos/cosmos-sdk/types/rest" // minttypes "github.com/irisnet/irishub/v3/modules/mint/types" -// "github.com/irisnet/irishub/v3/simapp" +// "github.com/irisnet/irishub/v3/testutil" // ) // type IntegrationTestSuite struct { diff --git a/modules/mint/keeper/keeper_test.go b/modules/mint/keeper/keeper_test.go index ade97df81..7646a8baa 100644 --- a/modules/mint/keeper/keeper_test.go +++ b/modules/mint/keeper/keeper_test.go @@ -13,7 +13,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/irisnet/irishub/v3/modules/mint/types" - "github.com/irisnet/irishub/v3/simapp" + apptestutil "github.com/irisnet/irishub/v3/testutil" ) type KeeperTestSuite struct { @@ -21,11 +21,11 @@ type KeeperTestSuite struct { cdc *codec.LegacyAmino ctx sdk.Context - app *simapp.SimApp + app *apptestutil.AppBuilder } func (suite *KeeperTestSuite) SetupTest() { - app := simapp.Setup(suite.T(), false) + app := apptestutil.Setup(suite.T(), false) suite.cdc = app.LegacyAmino() suite.ctx = app.BaseApp.NewContext(false, tmproto.Header{}) diff --git a/modules/mint/simulation/decoder_test.go b/modules/mint/simulation/decoder_test.go index f1b2f1ffb..e512768cc 100644 --- a/modules/mint/simulation/decoder_test.go +++ b/modules/mint/simulation/decoder_test.go @@ -8,21 +8,22 @@ import ( "github.com/stretchr/testify/require" sdkmath "cosmossdk.io/math" + "github.com/cosmos/cosmos-sdk/types/kv" "github.com/irisnet/irishub/v3/modules/mint/simulation" "github.com/irisnet/irishub/v3/modules/mint/types" - "github.com/irisnet/irishub/v3/simapp" + "github.com/irisnet/irishub/v3/testutil" ) func TestDecodeStore(t *testing.T) { minter := types.NewMinter(time.Now().UTC(), sdkmath.NewIntWithDecimal(2, 9)) - cdc, _ := simapp.MakeCodecs() - dec := simulation.NewDecodeStore(cdc) + ec := testutil.MakeCodecs() + dec := simulation.NewDecodeStore(ec.Marshaler) kvPairs := kv.Pairs{ Pairs: []kv.Pair{ - {Key: types.MinterKey, Value: cdc.MustMarshal(&minter)}, + {Key: types.MinterKey, Value: ec.Marshaler.MustMarshal(&minter)}, {Key: []byte{0x99}, Value: []byte{0x99}}, }, } diff --git a/simapp/app.go b/simapp/app.go deleted file mode 100644 index be458b358..000000000 --- a/simapp/app.go +++ /dev/null @@ -1,722 +0,0 @@ -package simapp - -import ( - "encoding/json" - "io" - - dbm "github.com/cometbft/cometbft-db" - abci "github.com/cometbft/cometbft/abci/types" - tmjson "github.com/cometbft/cometbft/libs/json" - "github.com/cometbft/cometbft/libs/log" - tmos "github.com/cometbft/cometbft/libs/os" - - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/client" - nodeservice "github.com/cosmos/cosmos-sdk/client/grpc/node" - "github.com/cosmos/cosmos-sdk/client/grpc/tmservice" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/server/api" - "github.com/cosmos/cosmos-sdk/server/config" - servertypes "github.com/cosmos/cosmos-sdk/server/types" - "github.com/cosmos/cosmos-sdk/store/streaming" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/version" - "github.com/cosmos/cosmos-sdk/x/auth" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation" - authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - "github.com/cosmos/cosmos-sdk/x/bank" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/capability" - capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" - capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - "github.com/cosmos/cosmos-sdk/x/consensus" - consensuskeeper "github.com/cosmos/cosmos-sdk/x/consensus/keeper" - consensustypes "github.com/cosmos/cosmos-sdk/x/consensus/types" - "github.com/cosmos/cosmos-sdk/x/crisis" - crisiskeeper "github.com/cosmos/cosmos-sdk/x/crisis/keeper" - crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" - distr "github.com/cosmos/cosmos-sdk/x/distribution" - distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - "github.com/cosmos/cosmos-sdk/x/genutil" - genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/params" - paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" - paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/cosmos/cosmos-sdk/x/slashing" - slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper" - slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - "github.com/cosmos/ibc-go/v7/modules/apps/transfer" - - simappparams "cosmossdk.io/simapp/params" - - "github.com/irisnet/irishub/v3/client/lite" - "github.com/irisnet/irishub/v3/modules/guardian" - guardiankeeper "github.com/irisnet/irishub/v3/modules/guardian/keeper" - guardiantypes "github.com/irisnet/irishub/v3/modules/guardian/types" - "github.com/irisnet/irishub/v3/modules/mint" - mintkeeper "github.com/irisnet/irishub/v3/modules/mint/keeper" - minttypes "github.com/irisnet/irishub/v3/modules/mint/types" - iristypes "github.com/irisnet/irishub/v3/types" - - tibcmttransfer "github.com/bianjieai/tibc-go/modules/tibc/apps/mt_transfer" - tibcnfttransfer "github.com/bianjieai/tibc-go/modules/tibc/apps/nft_transfer" -) - -const appName = "SimApp" - -var ( - // ModuleBasics defines the module BasicManager is in charge of setting up basic, - // non-dependant module elements, such as codec registration - // and genesis verification. - ModuleBasics = module.NewBasicManager( - auth.AppModuleBasic{}, - genutil.AppModuleBasic{}, - bank.AppModuleBasic{}, - capability.AppModuleBasic{}, - staking.AppModuleBasic{}, - distr.AppModuleBasic{}, - params.AppModuleBasic{}, - slashing.AppModuleBasic{}, - vesting.AppModuleBasic{}, - consensus.AppModuleBasic{}, - crisis.AppModuleBasic{}, - - guardian.AppModuleBasic{}, - mint.AppModuleBasic{}, - ) - - // module account permissions - maccPerms = map[string][]string{ - authtypes.FeeCollectorName: nil, - distrtypes.ModuleName: nil, - minttypes.ModuleName: {authtypes.Minter}, - stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, - stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, - } -) - -var ( - _ runtime.AppI = (*SimApp)(nil) - _ servertypes.Application = (*SimApp)(nil) -) - -// SimApp extends an ABCI application, but with most of its parameters exported. -// They are exported for convenience in creating helper functions, as object -// capabilities aren't needed for testing. -type SimApp struct { - *baseapp.BaseApp - legacyAmino *codec.LegacyAmino - appCodec codec.Codec - interfaceRegistry types.InterfaceRegistry - configurator module.Configurator - txConfig client.TxConfig - - invCheckPeriod uint - - // keys to access the substores - keys map[string]*storetypes.KVStoreKey - tkeys map[string]*storetypes.TransientStoreKey - memKeys map[string]*storetypes.MemoryStoreKey - - // cosmos - AccountKeeper authkeeper.AccountKeeper - BankKeeper bankkeeper.Keeper - CapabilityKeeper *capabilitykeeper.Keeper - StakingKeeper *stakingkeeper.Keeper - SlashingKeeper slashingkeeper.Keeper - CrisisKeeper *crisiskeeper.Keeper - DistrKeeper distrkeeper.Keeper - ParamsKeeper paramskeeper.Keeper - ConsensusParamsKeeper consensuskeeper.Keeper - - GuardianKeeper guardiankeeper.Keeper - MintKeeper mintkeeper.Keeper - - // the module manager - mm *module.Manager - - // simulation manager - sm *module.SimulationManager - - transferModule transfer.AppModule - nfttransferModule tibcnfttransfer.AppModule - mttransferModule tibcmttransfer.AppModule -} - -// NewSimApp returns a reference to an initialized IrisApp. -func NewSimApp( - logger log.Logger, - db dbm.DB, - traceStore io.Writer, - loadLatest bool, - skipUpgradeHeights map[int64]bool, - homePath string, - invCheckPeriod uint, - encodingConfig simappparams.EncodingConfig, - appOpts servertypes.AppOptions, - baseAppOptions ...func(*baseapp.BaseApp), -) *SimApp { - - // TODO: Remove cdc in favor of appCodec once all modules are migrated. - appCodec := encodingConfig.Codec - legacyAmino := encodingConfig.Amino - interfaceRegistry := encodingConfig.InterfaceRegistry - - bApp := baseapp.NewBaseApp( - appName, - logger, - db, - encodingConfig.TxConfig.TxDecoder(), - baseAppOptions...) - bApp.SetCommitMultiStoreTracer(traceStore) - bApp.SetVersion(version.Version) - bApp.SetInterfaceRegistry(interfaceRegistry) - - keys := sdk.NewKVStoreKeys( - authtypes.StoreKey, - banktypes.StoreKey, - stakingtypes.StoreKey, - distrtypes.StoreKey, - slashingtypes.StoreKey, - crisistypes.StoreKey, - consensustypes.StoreKey, - paramstypes.StoreKey, - capabilitytypes.StoreKey, - guardiantypes.StoreKey, - minttypes.StoreKey, - ) - tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey) - memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) - - // configure state listening capabilities using AppOptions - // we are doing nothing with the returned streamingServices and waitGroup in this case - if _, _, err := streaming.LoadStreamingServices(bApp, appOpts, appCodec, logger, keys); err != nil { - tmos.Exit(err.Error()) - } - - app := &SimApp{ - BaseApp: bApp, - legacyAmino: legacyAmino, - appCodec: appCodec, - interfaceRegistry: interfaceRegistry, - invCheckPeriod: invCheckPeriod, - keys: keys, - tkeys: tkeys, - memKeys: memKeys, - txConfig: encodingConfig.TxConfig, - } - - app.ParamsKeeper = initParamsKeeper( - appCodec, - legacyAmino, - keys[paramstypes.StoreKey], - tkeys[paramstypes.TStoreKey], - ) - - app.ConsensusParamsKeeper = consensuskeeper.NewKeeper( - appCodec, - keys[consensustypes.StoreKey], - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - // set the BaseApp's parameter store - bApp.SetParamStore(&app.ConsensusParamsKeeper) - - // add capability keeper and ScopeToModule for ibc module - app.CapabilityKeeper = capabilitykeeper.NewKeeper( - appCodec, - keys[capabilitytypes.StoreKey], - memKeys[capabilitytypes.MemStoreKey], - ) - - app.AccountKeeper = authkeeper.NewAccountKeeper( - appCodec, - keys[authtypes.StoreKey], - authtypes.ProtoBaseAccount, - maccPerms, - iristypes.Bech32PrefixAccAddr, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - - app.BankKeeper = bankkeeper.NewBaseKeeper( - appCodec, - keys[banktypes.StoreKey], - app.AccountKeeper, - app.BlockedModuleAccountAddrs(), - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - - app.StakingKeeper = stakingkeeper.NewKeeper( - appCodec, - keys[stakingtypes.StoreKey], - app.AccountKeeper, - app.BankKeeper, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - - app.MintKeeper = mintkeeper.NewKeeper( - appCodec, - keys[minttypes.StoreKey], - app.AccountKeeper, - app.BankKeeper, - authtypes.FeeCollectorName, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - - app.DistrKeeper = distrkeeper.NewKeeper( - appCodec, - keys[distrtypes.StoreKey], - app.AccountKeeper, - app.BankKeeper, - app.StakingKeeper, - authtypes.FeeCollectorName, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - - app.SlashingKeeper = slashingkeeper.NewKeeper( - appCodec, - legacyAmino, - keys[slashingtypes.StoreKey], - app.StakingKeeper, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - - app.CrisisKeeper = crisiskeeper.NewKeeper( - appCodec, - keys[crisistypes.StoreKey], - invCheckPeriod, - app.BankKeeper, - authtypes.FeeCollectorName, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - - // register the staking hooks - // NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks - app.StakingKeeper.SetHooks( - stakingtypes.NewMultiStakingHooks(app.DistrKeeper.Hooks(), app.SlashingKeeper.Hooks()), - ) - - app.GuardianKeeper = guardiankeeper.NewKeeper( - appCodec, - keys[guardiantypes.StoreKey], - ) - - /**** Module Options ****/ - var skipGenesisInvariants = false - opt := appOpts.Get(crisis.FlagSkipGenesisInvariants) - if opt, ok := opt.(bool); ok { - skipGenesisInvariants = opt - } - - // NOTE: Any module instantiated in the module manager that is later modified - // must be passed by reference here. - app.mm = module.NewManager( - genutil.NewAppModule( - app.AccountKeeper, app.StakingKeeper, app.BaseApp.DeliverTx, - encodingConfig.TxConfig, - ), - auth.NewAppModule( - appCodec, - app.AccountKeeper, - authsims.RandomGenesisAccounts, - app.GetSubspace(authtypes.ModuleName), - ), - vesting.NewAppModule(app.AccountKeeper, app.BankKeeper), - bank.NewAppModule( - appCodec, - app.BankKeeper, - app.AccountKeeper, - app.GetSubspace(banktypes.ModuleName), - ), - capability.NewAppModule(appCodec, *app.CapabilityKeeper, false), - crisis.NewAppModule( - app.CrisisKeeper, - skipGenesisInvariants, - app.GetSubspace(crisistypes.ModuleName), - ), - mint.NewAppModule(appCodec, app.MintKeeper, app.GetSubspace(minttypes.ModuleName)), - slashing.NewAppModule( - appCodec, - app.SlashingKeeper, - app.AccountKeeper, - app.BankKeeper, - app.StakingKeeper, - app.GetSubspace(slashingtypes.ModuleName), - ), - distr.NewAppModule( - appCodec, - app.DistrKeeper, - app.AccountKeeper, - app.BankKeeper, - app.StakingKeeper, - app.GetSubspace(distrtypes.ModuleName), - ), - staking.NewAppModule( - appCodec, - app.StakingKeeper, - app.AccountKeeper, - app.BankKeeper, - app.GetSubspace(stakingtypes.ModuleName), - ), - consensus.NewAppModule(appCodec, app.ConsensusParamsKeeper), - vesting.NewAppModule(app.AccountKeeper, app.BankKeeper), - - params.NewAppModule(app.ParamsKeeper), - guardian.NewAppModule(appCodec, app.GuardianKeeper), - ) - - // During begin block slashing happens after distr.BeginBlocker so that - // there is nothing left over in the validator fee pool, so as to keep the - // CanWithdrawInvariant invariant. - // NOTE: staking module is required if HistoricalEntries param > 0 - app.mm.SetOrderBeginBlockers( - upgradetypes.ModuleName, - capabilitytypes.ModuleName, - authtypes.ModuleName, - banktypes.ModuleName, - distrtypes.ModuleName, - stakingtypes.ModuleName, - slashingtypes.ModuleName, - crisistypes.ModuleName, - genutiltypes.ModuleName, - paramstypes.ModuleName, - vestingtypes.ModuleName, - consensustypes.ModuleName, - - minttypes.ModuleName, - guardiantypes.ModuleName, - ) - app.mm.SetOrderEndBlockers( - //sdk module - upgradetypes.ModuleName, - capabilitytypes.ModuleName, - authtypes.ModuleName, - banktypes.ModuleName, - distrtypes.ModuleName, - stakingtypes.ModuleName, - slashingtypes.ModuleName, - crisistypes.ModuleName, - genutiltypes.ModuleName, - paramstypes.ModuleName, - vestingtypes.ModuleName, - consensustypes.ModuleName, - - //self module - guardiantypes.ModuleName, - minttypes.ModuleName, - ) - - // NOTE: The genutils module must occur after staking so that pools are - // properly initialized with tokens from genesis accounts. - // NOTE: Capability module must occur first so that it can initialize any capabilities - // so that other modules that want to create or claim capabilities afterwards in InitChain - // can do so safely. - app.mm.SetOrderInitGenesis( - //sdk module - upgradetypes.ModuleName, - capabilitytypes.ModuleName, - authtypes.ModuleName, - banktypes.ModuleName, - distrtypes.ModuleName, - stakingtypes.ModuleName, - slashingtypes.ModuleName, - crisistypes.ModuleName, - genutiltypes.ModuleName, - paramstypes.ModuleName, - vestingtypes.ModuleName, - consensustypes.ModuleName, - - //self module - guardiantypes.ModuleName, - minttypes.ModuleName, - ) - - cfg := module.NewConfigurator(appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter()) - app.mm.RegisterInvariants(app.CrisisKeeper) - app.mm.RegisterServices(cfg) - - // create the simulation manager and define the order of the modules for deterministic simulations - // - // NOTE: this is not required apps that don't use the simulator for fuzz testing - // transactions - app.sm = module.NewSimulationManager( - auth.NewAppModule( - appCodec, - app.AccountKeeper, - authsims.RandomGenesisAccounts, - app.GetSubspace(authtypes.ModuleName), - ), - bank.NewAppModule( - appCodec, - app.BankKeeper, - app.AccountKeeper, - app.GetSubspace(banktypes.ModuleName), - ), - capability.NewAppModule(appCodec, *app.CapabilityKeeper, false), - mint.NewAppModule(appCodec, app.MintKeeper, app.GetSubspace(minttypes.ModuleName)), - staking.NewAppModule( - appCodec, - app.StakingKeeper, - app.AccountKeeper, - app.BankKeeper, - app.GetSubspace(stakingtypes.ModuleName), - ), - distr.NewAppModule( - appCodec, - app.DistrKeeper, - app.AccountKeeper, - app.BankKeeper, - app.StakingKeeper, - app.GetSubspace(distrtypes.ModuleName), - ), - slashing.NewAppModule( - appCodec, - app.SlashingKeeper, - app.AccountKeeper, - app.BankKeeper, - app.StakingKeeper, - app.GetSubspace(slashingtypes.ModuleName), - ), - params.NewAppModule(app.ParamsKeeper), - guardian.NewAppModule(appCodec, app.GuardianKeeper), - ) - - app.sm.RegisterStoreDecoders() - - // initialize stores - app.MountKVStores(keys) - app.MountTransientStores(tkeys) - app.MountMemoryStores(memKeys) - - //app.SetAnteHandler(anteHandler) - app.SetInitChainer(app.InitChainer) - app.SetBeginBlocker(app.BeginBlocker) - app.SetEndBlocker(app.EndBlocker) - - if loadLatest { - if err := app.LoadLatestVersion(); err != nil { - tmos.Exit(err.Error()) - } - - // Initialize and seal the capability keeper so all persistent capabilities - // are loaded in-memory and prevent any further modules from creating scoped - // sub-keepers. - // This must be done during creation of baseapp rather than in InitChain so - // that in-memory capabilities get regenerated on app restart. - // Note that since this reads from the store, we can only perform it when - // `loadLatest` is set to true. - app.CapabilityKeeper.Seal() - } - return app -} - -// MakeCodecs constructs the *std.Codec and *codec.LegacyAmino instances used by -// irisapp. It is useful for tests and clients who do not want to construct the -// full irisapp -func MakeCodecs() (codec.Codec, *codec.LegacyAmino) { - config := MakeTestEncodingConfig() - return config.Codec, config.Amino -} - -// Name returns the name of the App -func (app *SimApp) Name() string { return app.BaseApp.Name() } - -// BeginBlocker application updates every begin block -func (app *SimApp) BeginBlocker( - ctx sdk.Context, - req abci.RequestBeginBlock, -) abci.ResponseBeginBlock { - return app.mm.BeginBlock(ctx, req) -} - -// EndBlocker application updates every end block -func (app *SimApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { - return app.mm.EndBlock(ctx, req) -} - -// InitChainer application update at chain initialization -func (app *SimApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { - var genesisState GenesisState - if err := tmjson.Unmarshal(req.AppStateBytes, &genesisState); err != nil { - panic(err) - } - return app.mm.InitGenesis(ctx, app.appCodec, genesisState) -} - -// LoadHeight loads a particular height -func (app *SimApp) LoadHeight(height int64) error { - return app.LoadVersion(height) -} - -// ModuleAccountAddrs returns all the app's module account addresses. -func (app *SimApp) ModuleAccountAddrs() map[string]bool { - modAccAddrs := make(map[string]bool) - for acc := range maccPerms { - modAccAddrs[authtypes.NewModuleAddress(acc).String()] = true - } - - return modAccAddrs -} - -// BlockedModuleAccountAddrs returns all the app's blocked module account -// addresses. -func (app *SimApp) BlockedModuleAccountAddrs() map[string]bool { - modAccAddrs := app.ModuleAccountAddrs() - - // remove module accounts that are ALLOWED to received funds - // - // TODO: Blocked on updating to v0.46.x - // delete(modAccAddrs, authtypes.NewModuleAddress(grouptypes.ModuleName).String()) - delete(modAccAddrs, authtypes.NewModuleAddress(govtypes.ModuleName).String()) - - return modAccAddrs -} - -// LegacyAmino returns SimApp's amino codec. -// -// NOTE: This is solely to be used for testing purposes as it may be desirable -// for modules to register their own custom testing types. -func (app *SimApp) LegacyAmino() *codec.LegacyAmino { - return app.legacyAmino -} - -// TxConfig returns SimApp's TxConfig -func (app *SimApp) TxConfig() client.TxConfig { - return app.txConfig -} - -// DefaultGenesis returns a default genesis from the registered AppModuleBasic's. -func (app *SimApp) DefaultGenesis() map[string]json.RawMessage { - return ModuleBasics.DefaultGenesis(app.AppCodec()) -} - -// AppCodec returns IrisApp's app codec. -// -// NOTE: This is solely to be used for testing purposes as it may be desirable -// for modules to register their own custom testing types. -func (app *SimApp) AppCodec() codec.Codec { - return app.appCodec -} - -// InterfaceRegistry returns IrisApp's InterfaceRegistry -func (app *SimApp) InterfaceRegistry() types.InterfaceRegistry { - return app.interfaceRegistry -} - -// GetKey returns the KVStoreKey for the provided store key. -// -// NOTE: This is solely to be used for testing purposes. -func (app *SimApp) GetKey(storeKey string) *storetypes.KVStoreKey { - return app.keys[storeKey] -} - -// GetTKey returns the TransientStoreKey for the provided store key. -// -// NOTE: This is solely to be used for testing purposes. -func (app *SimApp) GetTKey(storeKey string) *storetypes.TransientStoreKey { - return app.tkeys[storeKey] -} - -// GetMemKey returns the MemStoreKey for the provided mem key. -// -// NOTE: This is solely used for testing purposes. -func (app *SimApp) GetMemKey(storeKey string) *storetypes.MemoryStoreKey { - return app.memKeys[storeKey] -} - -// GetSubspace returns a param subspace for a given module name. -// -// NOTE: This is solely to be used for testing purposes. -func (app *SimApp) GetSubspace(moduleName string) paramstypes.Subspace { - subspace, _ := app.ParamsKeeper.GetSubspace(moduleName) - return subspace -} - -// SimulationManager implements the SimulationApp interface -func (app *SimApp) SimulationManager() *module.SimulationManager { - return app.sm -} - -// RegisterAPIRoutes registers all application module routes with the provided API server. -func (app *SimApp) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig) { - clientCtx := apiSvr.ClientCtx - // Register new tx routes from grpc-gateway. - authtx.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) - // Register new tendermint queries routes from grpc-gateway. - tmservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) - - // Register grpc-gateway routes for all modules. - ModuleBasics.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) - - // register swagger API from root so that other applications can override easily - if apiConfig.Swagger { - lite.RegisterSwaggerAPI(clientCtx, apiSvr.Router) - } -} - -// RegisterTxService implements the Application.RegisterTxService method. -func (app *SimApp) RegisterTxService(clientCtx client.Context) { - authtx.RegisterTxService( - app.BaseApp.GRPCQueryRouter(), - clientCtx, - app.BaseApp.Simulate, - app.interfaceRegistry, - ) -} - -// RegisterTendermintService implements the Application.RegisterTendermintService method. -func (app *SimApp) RegisterTendermintService(clientCtx client.Context) { - tmservice.RegisterTendermintService( - clientCtx, - app.BaseApp.GRPCQueryRouter(), - app.interfaceRegistry, - app.Query, - ) -} - -// RegisterNodeService registers the node gRPC service. -func (app *SimApp) RegisterNodeService(clientCtx client.Context) { - nodeservice.RegisterNodeService(clientCtx, app.GRPCQueryRouter()) -} - -// GetMaccPerms returns a copy of the module account permissions -func GetMaccPerms() map[string][]string { - dupMaccPerms := make(map[string][]string) - for k, v := range maccPerms { - dupMaccPerms[k] = v - } - return dupMaccPerms -} - -// initParamsKeeper init params keeper and its subspaces -func initParamsKeeper( - appCodec codec.BinaryCodec, - legacyAmino *codec.LegacyAmino, - key, tkey storetypes.StoreKey, -) paramskeeper.Keeper { - paramsKeeper := paramskeeper.NewKeeper(appCodec, legacyAmino, key, tkey) - - paramsKeeper.Subspace(authtypes.ModuleName) - paramsKeeper.Subspace(banktypes.ModuleName) - paramsKeeper.Subspace(stakingtypes.ModuleName) - paramsKeeper.Subspace(minttypes.ModuleName) - paramsKeeper.Subspace(distrtypes.ModuleName) - paramsKeeper.Subspace(slashingtypes.ModuleName) - paramsKeeper.Subspace(crisistypes.ModuleName) - - return paramsKeeper -} diff --git a/simapp/encoding.go b/simapp/encoding.go deleted file mode 100644 index 61cb2018e..000000000 --- a/simapp/encoding.go +++ /dev/null @@ -1,19 +0,0 @@ -package simapp - -import ( - simappparams "cosmossdk.io/simapp/params" - "github.com/cosmos/cosmos-sdk/std" -) - -// MakeTestEncodingConfig creates an EncodingConfig for testing. -// This function should be used only internally (in the SDK). -// App user should'nt create new codecs - use the app.AppCodec instead. -// [DEPRECATED] -func MakeTestEncodingConfig() simappparams.EncodingConfig { - encodingConfig := simappparams.MakeTestEncodingConfig() - std.RegisterLegacyAminoCodec(encodingConfig.Amino) - std.RegisterInterfaces(encodingConfig.InterfaceRegistry) - ModuleBasics.RegisterLegacyAminoCodec(encodingConfig.Amino) - ModuleBasics.RegisterInterfaces(encodingConfig.InterfaceRegistry) - return encodingConfig -} diff --git a/simapp/export.go b/simapp/export.go deleted file mode 100644 index bbd8db02c..000000000 --- a/simapp/export.go +++ /dev/null @@ -1,206 +0,0 @@ -package simapp - -import ( - "encoding/json" - "log" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - - servertypes "github.com/cosmos/cosmos-sdk/server/types" - sdk "github.com/cosmos/cosmos-sdk/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" -) - -// ExportAppStateAndValidators exports the state of the application for a genesis -// file. -func (app *SimApp) ExportAppStateAndValidators( - forZeroHeight bool, jailAllowedAddrs []string, modulesToExport []string, -) (servertypes.ExportedApp, error) { - // as if they could withdraw from the start of the next block - ctx := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()}) - - // We export at last height + 1, because that's the height at which - // Tendermint will start InitChain. - height := app.LastBlockHeight() + 1 - if forZeroHeight { - height = 0 - app.prepForZeroHeightGenesis(ctx, jailAllowedAddrs) - } - - genState := app.mm.ExportGenesisForModules(ctx, app.appCodec, modulesToExport) - appState, err := json.MarshalIndent(genState, "", " ") - if err != nil { - return servertypes.ExportedApp{}, err - } - - validators, err := staking.WriteValidators(ctx, app.StakingKeeper) - return servertypes.ExportedApp{ - AppState: appState, - Validators: validators, - Height: height, - ConsensusParams: app.BaseApp.GetConsensusParams(ctx), - }, err -} - -// prepare for fresh start at zero height -// NOTE zero height genesis is a temporary feature which will be deprecated -// -// in favour of export at a block height -func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []string) { - applyAllowedAddrs := false - - // check if there is a allowed address list - if len(jailAllowedAddrs) > 0 { - applyAllowedAddrs = true - } - - allowedAddrsMap := make(map[string]bool) - - for _, addr := range jailAllowedAddrs { - _, err := sdk.ValAddressFromBech32(addr) - if err != nil { - log.Fatal(err) - } - allowedAddrsMap[addr] = true - } - - /* Just to be safe, assert the invariants on current state. */ - app.CrisisKeeper.AssertInvariants(ctx) - - /* Handle fee distribution state. */ - - // withdraw all validator commission - app.StakingKeeper.IterateValidators( - ctx, - func(_ int64, val stakingtypes.ValidatorI) (stop bool) { - _, _ = app.DistrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator()) - return false - }, - ) - - // withdraw all delegator rewards - dels := app.StakingKeeper.GetAllDelegations(ctx) - for _, delegation := range dels { - valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) - if err != nil { - panic(err) - } - - delAddr, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) - if err != nil { - panic(err) - } - _, _ = app.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr) - } - - // clear validator slash events - app.DistrKeeper.DeleteAllValidatorSlashEvents(ctx) - - // clear validator historical rewards - app.DistrKeeper.DeleteAllValidatorHistoricalRewards(ctx) - - // set context height to zero - height := ctx.BlockHeight() - ctx = ctx.WithBlockHeight(0) - - // reinitialize all validators - app.StakingKeeper.IterateValidators( - ctx, - func(_ int64, val stakingtypes.ValidatorI) (stop bool) { - // donate any unwithdrawn outstanding reward fraction tokens to the community pool - scraps := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, val.GetOperator()) - feePool := app.DistrKeeper.GetFeePool(ctx) - feePool.CommunityPool = feePool.CommunityPool.Add(scraps...) - app.DistrKeeper.SetFeePool(ctx, feePool) - - app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()) - return false - }, - ) - - // reinitialize all delegations - for _, del := range dels { - valAddr, err := sdk.ValAddressFromBech32(del.ValidatorAddress) - if err != nil { - panic(err) - } - delAddr, err := sdk.AccAddressFromBech32(del.DelegatorAddress) - if err != nil { - panic(err) - } - app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr) - app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr) - } - - // reset context height - ctx = ctx.WithBlockHeight(height) - - /* Handle staking state. */ - - // iterate through redelegations, reset creation height - app.StakingKeeper.IterateRedelegations( - ctx, - func(_ int64, red stakingtypes.Redelegation) (stop bool) { - for i := range red.Entries { - red.Entries[i].CreationHeight = 0 - } - app.StakingKeeper.SetRedelegation(ctx, red) - return false - }, - ) - - // iterate through unbonding delegations, reset creation height - app.StakingKeeper.IterateUnbondingDelegations( - ctx, - func(_ int64, ubd stakingtypes.UnbondingDelegation) (stop bool) { - for i := range ubd.Entries { - ubd.Entries[i].CreationHeight = 0 - } - app.StakingKeeper.SetUnbondingDelegation(ctx, ubd) - return false - }, - ) - - // Iterate through validators by power descending, reset bond heights, and - // update bond intra-tx counters. - store := ctx.KVStore(app.keys[stakingtypes.StoreKey]) - iter := sdk.KVStoreReversePrefixIterator(store, stakingtypes.ValidatorsKey) - counter := int16(0) - - for ; iter.Valid(); iter.Next() { - addr := sdk.ValAddress(stakingtypes.AddressFromValidatorsKey(iter.Key())) - validator, found := app.StakingKeeper.GetValidator(ctx, addr) - if !found { - panic("expected validator, not found") - } - - validator.UnbondingHeight = 0 - if applyAllowedAddrs && !allowedAddrsMap[addr.String()] { - validator.Jailed = true - } - - app.StakingKeeper.SetValidator(ctx, validator) - counter++ - } - - iter.Close() - - _, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) - if err != nil { - log.Fatal(err) - } - - /* Handle slashing state. */ - - // reset start height on signing infos - app.SlashingKeeper.IterateValidatorSigningInfos( - ctx, - func(addr sdk.ConsAddress, info slashingtypes.ValidatorSigningInfo) (stop bool) { - info.StartHeight = 0 - app.SlashingKeeper.SetValidatorSigningInfo(ctx, addr, info) - return false - }, - ) -} diff --git a/testutil/app.go b/testutil/app.go new file mode 100644 index 000000000..08d02a1b0 --- /dev/null +++ b/testutil/app.go @@ -0,0 +1,59 @@ +package testutil + +import ( + "encoding/json" + + dbm "github.com/cometbft/cometbft-db" + "github.com/cometbft/cometbft/libs/log" + + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/runtime" + servertypes "github.com/cosmos/cosmos-sdk/server/types" + + "github.com/irisnet/irishub/v3/app" + "github.com/irisnet/irishub/v3/app/params" +) + +var ( + _ runtime.AppI = (*AppBuilder)(nil) + _ servertypes.Application = (*AppBuilder)(nil) +) + +// AppBuilder extends an ABCI application, but with most of its parameters exported. +// They are exported for convenience in creating helper functions, as object +// capabilities aren't needed for testing. +type AppBuilder struct { + *app.IrisApp +} + +func (ab AppBuilder) build( + appOpts servertypes.AppOptions, + baseAppOptions ...func(*baseapp.BaseApp), +) *app.IrisApp { + db := dbm.NewMemDB() + encCdc := app.RegisterEncodingConfig() + if appOpts == nil { + appOpts = EmptyAppOptions{} + } + app := app.NewIrisApp( + log.NewNopLogger(), + db, + nil, + true, + encCdc, + appOpts, + baseAppOptions..., + ) + return app +} + +// MakeCodecs returns the application codec and tx codec +func MakeCodecs() params.EncodingConfig { + return app.RegisterEncodingConfig() +} + +// DefaultGenesis returns default genesis state as raw bytes +func DefaultGenesis(cdc codec.JSONCodec) map[string]json.RawMessage { + return app.ModuleBasics.DefaultGenesis(cdc) +} diff --git a/testutil/export.go b/testutil/export.go new file mode 100644 index 000000000..b7f6626ce --- /dev/null +++ b/testutil/export.go @@ -0,0 +1,13 @@ +package testutil + +import ( + servertypes "github.com/cosmos/cosmos-sdk/server/types" +) + +// ExportAppStateAndValidators exports the state of the application for a genesis +// file. +func (app *AppBuilder) ExportAppStateAndValidators( + forZeroHeight bool, jailAllowedAddrs []string, modulesToExport []string, +) (servertypes.ExportedApp, error) { + return app.IrisApp.ExportAppStateAndValidators(false, jailAllowedAddrs, modulesToExport) +} diff --git a/simapp/genesis.go b/testutil/genesis.go similarity index 68% rename from simapp/genesis.go rename to testutil/genesis.go index a002aead9..fbc124902 100644 --- a/simapp/genesis.go +++ b/testutil/genesis.go @@ -1,9 +1,7 @@ -package simapp +package testutil import ( "encoding/json" - - "github.com/cosmos/cosmos-sdk/codec" ) // GenesisState of the blockchain is represented here as a map of raw json @@ -14,8 +12,3 @@ import ( // the ModuleBasicManager which populates json from each BasicModule // object provided to it during init. type GenesisState map[string]json.RawMessage - -// NewDefaultGenesisState generates the default state for the application. -func NewDefaultGenesisState(cdc codec.JSONCodec) GenesisState { - return ModuleBasics.DefaultGenesis(cdc) -} diff --git a/simapp/test_helpers.go b/testutil/test_helpers.go similarity index 66% rename from simapp/test_helpers.go rename to testutil/test_helpers.go index bb340bda9..defc8f6a3 100644 --- a/simapp/test_helpers.go +++ b/testutil/test_helpers.go @@ -1,13 +1,11 @@ -package simapp +package testutil import ( - "bytes" "context" "encoding/hex" "encoding/json" "fmt" "os" - "strconv" "strings" "testing" "time" @@ -16,9 +14,7 @@ import ( "github.com/spf13/cobra" "github.com/stretchr/testify/require" - dbm "github.com/cometbft/cometbft-db" abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/libs/log" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" coretypes "github.com/cometbft/cometbft/rpc/core/types" tmtypes "github.com/cometbft/cometbft/types" @@ -29,7 +25,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" servertypes "github.com/cosmos/cosmos-sdk/server/types" pruningtypes "github.com/cosmos/cosmos-sdk/store/pruning/types" @@ -43,32 +38,11 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - minttypes "github.com/irisnet/irishub/v3/modules/mint/types" - iristypes "github.com/irisnet/irishub/v3/types" + "github.com/irisnet/irishub/v3/app" ) -func setup(withGenesis bool, invCheckPeriod uint) (*SimApp, GenesisState) { - db := dbm.NewMemDB() - encCdc := MakeTestEncodingConfig() - app := NewSimApp( - log.NewNopLogger(), - db, - nil, - true, - map[int64]bool{}, - iristypes.DefaultNodeHome, - invCheckPeriod, - encCdc, - EmptyAppOptions{}, - ) - if withGenesis { - return app, NewDefaultGenesisState(encCdc.Codec) - } - return app, GenesisState{} -} - // Setup initializes a new SimApp. A Nop logger is set in SimApp. -func Setup(t *testing.T, _ bool) *SimApp { +func Setup(t *testing.T, _ bool) *AppBuilder { t.Helper() privVal := mock.NewPV() @@ -91,36 +65,26 @@ func Setup(t *testing.T, _ bool) *SimApp { Address: acc.GetAddress().String(), Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000000000000))), } - - app := SetupWithGenesisValSet(t, valSet, []authtypes.GenesisAccount{acc}, balance) - - return app + return SetupWithGenesisValSet(t, valSet, []authtypes.GenesisAccount{acc}, balance) } // NewConfig returns a new app config func NewConfig() network.Config { cfg := network.DefaultConfig(NewTestNetworkFixture) - encCfg := MakeTestEncodingConfig() // redundant - cfg.Codec = encCfg.Codec + encCfg := app.RegisterEncodingConfig() + cfg.Codec = encCfg.Marshaler cfg.TxConfig = encCfg.TxConfig cfg.LegacyAmino = encCfg.Amino cfg.InterfaceRegistry = encCfg.InterfaceRegistry cfg.AppConstructor = func(val network.ValidatorI) servertypes.Application { - return NewSimApp( - val.GetCtx().Logger, - dbm.NewMemDB(), + builder := &AppBuilder{} + return builder.build( nil, - true, - nil, - iristypes.DefaultNodeHome, - 0, - encCfg, - EmptyAppOptions{}, bam.SetMinGasPrices(val.GetAppConfig().MinGasPrices), bam.SetChainID(cfg.ChainID), ) } - cfg.GenesisState = NewDefaultGenesisState(cfg.Codec) + cfg.GenesisState = app.ModuleBasics.DefaultGenesis(cfg.Codec) return cfg } @@ -133,16 +97,19 @@ func SetupWithGenesisValSet( valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance, -) *SimApp { +) *AppBuilder { t.Helper() - app, genesisState := setup(true, 5) + builder := &AppBuilder{} + app := builder.build(nil) + genesisState, err := GenesisStateWithValSet( app.AppCodec(), - genesisState, + app.DefaultGenesis(), valSet, genAccs, - balances...) + balances..., + ) require.NoError(t, err) stateBytes, err := json.MarshalIndent(genesisState, "", " ") @@ -166,7 +133,7 @@ func SetupWithGenesisValSet( NextValidatorsHash: valSet.Hash(), }}) - return app + return &AppBuilder{app} } // GenesisStateWithValSet returns a new genesis state with the validator set @@ -256,95 +223,6 @@ func GenesisStateWithValSet(codec codec.Codec, genesisState map[string]json.RawM return genesisState, nil } -// GenerateAccountStrategy is a strategy used by addTestAddrs() in order to generated addresses in random order -type GenerateAccountStrategy func(int) []sdk.AccAddress - -// createRandomAccounts is a strategy used by addTestAddrs() in order to generated addresses in random order. -func createRandomAccounts(accNum int) []sdk.AccAddress { - testAddrs := make([]sdk.AccAddress, accNum) - for i := 0; i < accNum; i++ { - pk := ed25519.GenPrivKey().PubKey() - testAddrs[i] = sdk.AccAddress(pk.Address()) - } - - return testAddrs -} - -// createIncrementalAccounts is a strategy used by addTestAddrs() in order to generated addresses in ascending order. -func createIncrementalAccounts(accNum int) []sdk.AccAddress { - var addresses []sdk.AccAddress - var buffer bytes.Buffer - - // start at 100 so we can make up to 999 test addresses with valid test addresses - for i := 100; i < (accNum + 100); i++ { - numString := strconv.Itoa(i) - buffer.WriteString("A58856F0FD53BF058B4909A21AEC019107BA6") //base address string - - buffer.WriteString(numString) //adding on final two digits to make addresses unique - res, _ := sdk.AccAddressFromHexUnsafe(buffer.String()) - bech := res.String() - addr, _ := TestAddr(buffer.String(), bech) - - addresses = append(addresses, addr) - buffer.Reset() - } - - return addresses -} - -func addTestAddrs( - app *SimApp, - ctx sdk.Context, - accNum int, - accAmt sdk.Int, - strategy GenerateAccountStrategy, -) []sdk.AccAddress { - testAddrs := strategy(accNum) - - initCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), accAmt)) - - // fill all the addresses with some coins, set the loose pool tokens simultaneously - for _, addr := range testAddrs { - saveAccount(app, ctx, addr, initCoins) - } - - return testAddrs -} - -// saveAccount saves the provided account into the simapp with balance based on initCoins. -func saveAccount(app *SimApp, ctx sdk.Context, addr sdk.AccAddress, initCoins sdk.Coins) { - acc := app.AccountKeeper.NewAccountWithAddress(ctx, addr) - app.AccountKeeper.SetAccount(ctx, acc) - if err := app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, initCoins); err != nil { - panic(err) - } - if err := app.BankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, addr, initCoins); err != nil { - panic(err) - } -} - -// TestAddr creates a test address -func TestAddr(addr string, bech string) (sdk.AccAddress, error) { - res, err := sdk.AccAddressFromHexUnsafe(addr) - if err != nil { - return nil, err - } - bechexpected := res.String() - if bech != bechexpected { - return nil, fmt.Errorf("bech encoding doesn't match reference") - } - - bechres, err := sdk.AccAddressFromBech32(bech) - if err != nil { - return nil, err - } - if !bytes.Equal(bechres, res) { - return nil, err - } - - return res, nil -} - // EmptyAppOptions is a stub implementing AppOptions type EmptyAppOptions struct{} @@ -361,45 +239,25 @@ func NewTestNetworkFixture() network.TestFixture { } defer os.RemoveAll(dir) - encodingConfig := MakeTestEncodingConfig() - - app := NewSimApp( - log.NewNopLogger(), - dbm.NewMemDB(), - nil, - true, - nil, - iristypes.DefaultNodeHome, - 0, - encodingConfig, // redundant - simtestutil.NewAppOptionsWithFlagHome(dir), - ) - appCtr := func(val network.ValidatorI) servertypes.Application { - return NewSimApp( - val.GetCtx().Logger, - dbm.NewMemDB(), - nil, - true, - nil, - iristypes.DefaultNodeHome, - 0, - encodingConfig, // redundant + builder := &AppBuilder{} + return builder.build( simtestutil.NewAppOptionsWithFlagHome(val.GetCtx().Config.RootDir), bam.SetPruning(pruningtypes.NewPruningOptionsFromString(val.GetAppConfig().Pruning)), bam.SetMinGasPrices(val.GetAppConfig().MinGasPrices), bam.SetChainID(val.GetCtx().Viper.GetString(flags.FlagChainID)), ) } + ec := MakeCodecs() return network.TestFixture{ AppConstructor: appCtr, - GenesisState: app.DefaultGenesis(), + GenesisState: DefaultGenesis(ec.Marshaler), EncodingConfig: testutil.TestEncodingConfig{ - InterfaceRegistry: app.InterfaceRegistry(), - Codec: app.AppCodec(), - TxConfig: app.TxConfig(), - Amino: app.LegacyAmino(), + InterfaceRegistry: ec.InterfaceRegistry, + Codec: ec.Marshaler, + TxConfig: ec.TxConfig, + Amino: ec.Amino, }, } } From ece68a537381a3d21d262b7d0d210e492a42a838 Mon Sep 17 00:00:00 2001 From: Dreamer Date: Wed, 13 Mar 2024 18:38:39 +0800 Subject: [PATCH 2/3] clean code --- modules/guardian/client/cli/cli_test.go | 2 +- .../guardian/client/testutil/test_helpers.go | 4 +-- modules/guardian/genesis_test.go | 2 +- modules/guardian/keeper/grpc_query_test.go | 8 ++--- modules/guardian/keeper/keeper_test.go | 7 ++-- modules/mint/abci_test.go | 4 +-- modules/mint/keeper/keeper_test.go | 7 ++-- testutil/app.go | 14 ++++---- testutil/export.go | 13 -------- testutil/genesis.go | 14 -------- testutil/test_helpers.go | 33 +++++++++---------- 11 files changed, 37 insertions(+), 71 deletions(-) delete mode 100644 testutil/export.go delete mode 100644 testutil/genesis.go diff --git a/modules/guardian/client/cli/cli_test.go b/modules/guardian/client/cli/cli_test.go index a88a68ed2..3616bbe9e 100644 --- a/modules/guardian/client/cli/cli_test.go +++ b/modules/guardian/client/cli/cli_test.go @@ -90,7 +90,7 @@ func (s *IntegrationTestSuite) TestGuardian() { ), } - result := apptestutil.ExecTxCmdWithResult(s.T(), s.network, clientCtx, bankcli.NewSendTxCmd(), args) + result := apptestutil.ExecCommand(s.T(), s.network, clientCtx, bankcli.NewSendTxCmd(), args) s.Require().Equal(uint32(0), result.TxResult.Code, result.TxResult.Log) //------test GetCmdQuerySupers()------------- diff --git a/modules/guardian/client/testutil/test_helpers.go b/modules/guardian/client/testutil/test_helpers.go index 0a43e8337..b698ff655 100644 --- a/modules/guardian/client/testutil/test_helpers.go +++ b/modules/guardian/client/testutil/test_helpers.go @@ -30,7 +30,7 @@ func CreateSuperExec( } args = append(args, extraArgs...) - return apptestutil.ExecTxCmdWithResult(t, network, clientCtx, guardiancli.GetCmdCreateSuper(), args) + return apptestutil.ExecCommand(t, network, clientCtx, guardiancli.GetCmdCreateSuper(), args) } // DeleteSuperExec deletes a super @@ -46,7 +46,7 @@ func DeleteSuperExec( } args = append(args, extraArgs...) - return apptestutil.ExecTxCmdWithResult(t, network, clientCtx, guardiancli.GetCmdDeleteSuper(), args) + return apptestutil.ExecCommand(t, network, clientCtx, guardiancli.GetCmdDeleteSuper(), args) } // QuerySupersExec queries supers diff --git a/modules/guardian/genesis_test.go b/modules/guardian/genesis_test.go index 5c14656b4..b7aab312a 100644 --- a/modules/guardian/genesis_test.go +++ b/modules/guardian/genesis_test.go @@ -25,7 +25,7 @@ type TestSuite struct { } func (suite *TestSuite) SetupTest() { - app := testutil.Setup(suite.T(), false) + app := testutil.CreateApp(suite.T()) suite.cdc = codec.NewAminoCodec(app.LegacyAmino()) suite.ctx = app.BaseApp.NewContext(false, tmproto.Header{}) diff --git a/modules/guardian/keeper/grpc_query_test.go b/modules/guardian/keeper/grpc_query_test.go index ad6be59e6..062321796 100644 --- a/modules/guardian/keeper/grpc_query_test.go +++ b/modules/guardian/keeper/grpc_query_test.go @@ -10,19 +10,17 @@ import ( ) func (suite *KeeperTestSuite) TestGRPCQuerySupers() { - app, ctx := suite.app, suite.ctx _, _, addr := testdata.KeyTestPubAddr() guardian := types.NewSuper("test", types.Ordinary, addr, addr) - queryHelper := baseapp.NewQueryServerTestHelper(ctx, app.InterfaceRegistry()) - types.RegisterQueryServer(queryHelper, app.GuardianKeeper) + queryHelper := baseapp.NewQueryServerTestHelper(suite.ctx, suite.ifr) + types.RegisterQueryServer(queryHelper, suite.keeper) queryClient := types.NewQueryClient(queryHelper) _, err := queryClient.Supers(gocontext.Background(), &types.QuerySupersRequest{}) suite.Require().NoError(err) - app.GuardianKeeper.AddSuper(ctx, guardian) - + suite.keeper.AddSuper(suite.ctx, guardian) supersResp, err := queryClient.Supers(gocontext.Background(), &types.QuerySupersRequest{}) suite.Require().NoError(err) suite.Len(supersResp.Supers, 1) diff --git a/modules/guardian/keeper/keeper_test.go b/modules/guardian/keeper/keeper_test.go index 2df51a87a..1503fc403 100644 --- a/modules/guardian/keeper/keeper_test.go +++ b/modules/guardian/keeper/keeper_test.go @@ -9,6 +9,7 @@ import ( tmproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -35,16 +36,16 @@ type KeeperTestSuite struct { suite.Suite cdc *codec.LegacyAmino + ifr codectypes.InterfaceRegistry ctx sdk.Context keeper keeper.Keeper - app *testutil.AppBuilder } func (suite *KeeperTestSuite) SetupTest() { - app := testutil.Setup(suite.T(), false) + app := testutil.CreateApp(suite.T()) - suite.app = app suite.cdc = app.LegacyAmino() + suite.ifr = app.InterfaceRegistry() suite.ctx = app.BaseApp.NewContext(false, tmproto.Header{}) suite.keeper = app.GuardianKeeper } diff --git a/modules/mint/abci_test.go b/modules/mint/abci_test.go index 8a0907603..17b76ae6c 100644 --- a/modules/mint/abci_test.go +++ b/modules/mint/abci_test.go @@ -29,8 +29,8 @@ func TestBeginBlocker(t *testing.T) { } // returns context and an app with updated mint keeper -func createTestApp(t *testing.T, isCheckTx bool) (*apptestutil.AppBuilder, sdk.Context) { - app := apptestutil.Setup(t, false) +func createTestApp(t *testing.T, isCheckTx bool) (*apptestutil.AppWrapper, sdk.Context) { + app := apptestutil.CreateApp(t) ctx := app.BaseApp.NewContext(isCheckTx, tmproto.Header{Height: 2}) app.MintKeeper.SetParams(ctx, types.NewParams( diff --git a/modules/mint/keeper/keeper_test.go b/modules/mint/keeper/keeper_test.go index 7646a8baa..69a9ec88f 100644 --- a/modules/mint/keeper/keeper_test.go +++ b/modules/mint/keeper/keeper_test.go @@ -9,7 +9,6 @@ import ( tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/irisnet/irishub/v3/modules/mint/types" @@ -19,15 +18,13 @@ import ( type KeeperTestSuite struct { suite.Suite - cdc *codec.LegacyAmino ctx sdk.Context - app *apptestutil.AppBuilder + app *apptestutil.AppWrapper } func (suite *KeeperTestSuite) SetupTest() { - app := apptestutil.Setup(suite.T(), false) + app := apptestutil.CreateApp(suite.T()) - suite.cdc = app.LegacyAmino() suite.ctx = app.BaseApp.NewContext(false, tmproto.Header{}) suite.app = app diff --git a/testutil/app.go b/testutil/app.go index 08d02a1b0..194d35c43 100644 --- a/testutil/app.go +++ b/testutil/app.go @@ -16,21 +16,21 @@ import ( ) var ( - _ runtime.AppI = (*AppBuilder)(nil) - _ servertypes.Application = (*AppBuilder)(nil) + _ runtime.AppI = (*AppWrapper)(nil) + _ servertypes.Application = (*AppWrapper)(nil) ) -// AppBuilder extends an ABCI application, but with most of its parameters exported. +// AppWrapper extends an ABCI application, but with most of its parameters exported. // They are exported for convenience in creating helper functions, as object // capabilities aren't needed for testing. -type AppBuilder struct { +type AppWrapper struct { *app.IrisApp } -func (ab AppBuilder) build( +func setup( appOpts servertypes.AppOptions, baseAppOptions ...func(*baseapp.BaseApp), -) *app.IrisApp { +) *AppWrapper { db := dbm.NewMemDB() encCdc := app.RegisterEncodingConfig() if appOpts == nil { @@ -45,7 +45,7 @@ func (ab AppBuilder) build( appOpts, baseAppOptions..., ) - return app + return &AppWrapper{app} } // MakeCodecs returns the application codec and tx codec diff --git a/testutil/export.go b/testutil/export.go deleted file mode 100644 index b7f6626ce..000000000 --- a/testutil/export.go +++ /dev/null @@ -1,13 +0,0 @@ -package testutil - -import ( - servertypes "github.com/cosmos/cosmos-sdk/server/types" -) - -// ExportAppStateAndValidators exports the state of the application for a genesis -// file. -func (app *AppBuilder) ExportAppStateAndValidators( - forZeroHeight bool, jailAllowedAddrs []string, modulesToExport []string, -) (servertypes.ExportedApp, error) { - return app.IrisApp.ExportAppStateAndValidators(false, jailAllowedAddrs, modulesToExport) -} diff --git a/testutil/genesis.go b/testutil/genesis.go deleted file mode 100644 index fbc124902..000000000 --- a/testutil/genesis.go +++ /dev/null @@ -1,14 +0,0 @@ -package testutil - -import ( - "encoding/json" -) - -// GenesisState of the blockchain is represented here as a map of raw json -// messages key'd by a identifier string. -// The identifier is used to determine which module genesis information belongs -// to so it may be appropriately routed during init chain. -// Within this application default genesis information is retrieved from -// the ModuleBasicManager which populates json from each BasicModule -// object provided to it during init. -type GenesisState map[string]json.RawMessage diff --git a/testutil/test_helpers.go b/testutil/test_helpers.go index defc8f6a3..efbd98a07 100644 --- a/testutil/test_helpers.go +++ b/testutil/test_helpers.go @@ -41,8 +41,8 @@ import ( "github.com/irisnet/irishub/v3/app" ) -// Setup initializes a new SimApp. A Nop logger is set in SimApp. -func Setup(t *testing.T, _ bool) *AppBuilder { +// CreateApp initializes a new SimApp. A Nop logger is set in SimApp. +func CreateApp(t *testing.T) *AppWrapper { t.Helper() privVal := mock.NewPV() @@ -65,7 +65,7 @@ func Setup(t *testing.T, _ bool) *AppBuilder { Address: acc.GetAddress().String(), Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000000000000))), } - return SetupWithGenesisValSet(t, valSet, []authtypes.GenesisAccount{acc}, balance) + return CreateAppWithGenesisValSet(t, valSet, []authtypes.GenesisAccount{acc}, balance) } // NewConfig returns a new app config @@ -77,8 +77,7 @@ func NewConfig() network.Config { cfg.LegacyAmino = encCfg.Amino cfg.InterfaceRegistry = encCfg.InterfaceRegistry cfg.AppConstructor = func(val network.ValidatorI) servertypes.Application { - builder := &AppBuilder{} - return builder.build( + return setup( nil, bam.SetMinGasPrices(val.GetAppConfig().MinGasPrices), bam.SetChainID(cfg.ChainID), @@ -88,22 +87,21 @@ func NewConfig() network.Config { return cfg } -// SetupWithGenesisValSet initializes a new SimApp with a validator set and genesis accounts +// CreateAppWithGenesisValSet initializes a new SimApp with a validator set and genesis accounts // that also act as delegators. For simplicity, each validator is bonded with a delegation // of one consensus engine unit (10^6) in the default token of the simapp from first genesis // account. A Nop logger is set in SimApp. -func SetupWithGenesisValSet( +func CreateAppWithGenesisValSet( t *testing.T, valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance, -) *AppBuilder { +) *AppWrapper { t.Helper() - builder := &AppBuilder{} - app := builder.build(nil) + app := setup(nil) - genesisState, err := GenesisStateWithValSet( + genesisState, err := genesisStateWithValSet( app.AppCodec(), app.DefaultGenesis(), valSet, @@ -133,11 +131,11 @@ func SetupWithGenesisValSet( NextValidatorsHash: valSet.Hash(), }}) - return &AppBuilder{app} + return app } -// GenesisStateWithValSet returns a new genesis state with the validator set -func GenesisStateWithValSet(codec codec.Codec, genesisState map[string]json.RawMessage, +// genesisStateWithValSet returns a new genesis state with the validator set +func genesisStateWithValSet(codec codec.Codec, genesisState map[string]json.RawMessage, valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance, ) (map[string]json.RawMessage, error) { @@ -240,8 +238,7 @@ func NewTestNetworkFixture() network.TestFixture { defer os.RemoveAll(dir) appCtr := func(val network.ValidatorI) servertypes.Application { - builder := &AppBuilder{} - return builder.build( + return setup( simtestutil.NewAppOptionsWithFlagHome(val.GetCtx().Config.RootDir), bam.SetPruning(pruningtypes.NewPruningOptionsFromString(val.GetAppConfig().Pruning)), bam.SetMinGasPrices(val.GetAppConfig().MinGasPrices), @@ -262,8 +259,8 @@ func NewTestNetworkFixture() network.TestFixture { } } -// ExecTxCmdWithResult executes a tx command and returns the result -func ExecTxCmdWithResult( +// ExecCommand executes a tx command and returns the result +func ExecCommand( t *testing.T, network *network.Network, clientCtx client.Context, From de969d9ee013768883b9040b009208d8d0d0489f Mon Sep 17 00:00:00 2001 From: Dreamer Date: Thu, 14 Mar 2024 10:53:11 +0800 Subject: [PATCH 3/3] fix simulate error --- app/sim_test.go | 93 +++++++++++++++++++------------------------------ 1 file changed, 36 insertions(+), 57 deletions(-) diff --git a/app/sim_test.go b/app/sim_test.go index c3f92c1bc..8523f77b3 100644 --- a/app/sim_test.go +++ b/app/sim_test.go @@ -19,6 +19,7 @@ import ( tokentypes "github.com/irisnet/irismod/modules/token/types" "github.com/stretchr/testify/require" + "github.com/irisnet/irishub/v3/app/params" iristypes "github.com/irisnet/irishub/v3/types" dbm "github.com/cometbft/cometbft-db" @@ -98,15 +99,7 @@ func TestFullAppSimulation(t *testing.T) { encfg := RegisterEncodingConfig() - app := NewIrisApp( - logger, - db, - nil, - true, - encfg, - EmptyAppOptions{}, - fauxMerkleModeOpt, - ) + app := createApp(logger, db, encfg, fauxMerkleModeOpt) require.Equal(t, "IrisApp", app.Name()) // run randomized simulation @@ -136,6 +129,8 @@ func TestAppImportExport(t *testing.T) { config := simcli.NewConfigFromFlags() config.ChainID = AppChainID + sdk.DefaultBondDenom = iristypes.NativeToken.Symbol + db, dir, logger, skip, err := simtestutil.SetupSimulation( config, "goleveldb-app-sim", @@ -155,15 +150,7 @@ func TestAppImportExport(t *testing.T) { }() encfg := RegisterEncodingConfig() - app := NewIrisApp( - logger, - db, - nil, - true, - encfg, - EmptyAppOptions{}, - fauxMerkleModeOpt, - ) + app := createApp(logger, db, encfg, fauxMerkleModeOpt) require.Equal(t, "IrisApp", app.Name()) // Run randomized simulation @@ -209,15 +196,7 @@ func TestAppImportExport(t *testing.T) { require.NoError(t, os.RemoveAll(newDir)) }() - newApp := NewIrisApp( - log.NewNopLogger(), - newDB, - nil, - true, - encfg, - EmptyAppOptions{}, - fauxMerkleModeOpt, - ) + newApp := createApp(logger, db, encfg, fauxMerkleModeOpt) require.Equal(t, "IrisApp", newApp.Name()) var genesisState iristypes.GenesisState @@ -244,11 +223,13 @@ func TestAppImportExport(t *testing.T) { storeKeysPrefixes := []StoreKeysPrefixes{ {app.AppKeepers.KvStoreKeys()[authtypes.StoreKey], newApp.AppKeepers.KvStoreKeys()[authtypes.StoreKey], [][]byte{}}, - {app.AppKeepers.KvStoreKeys()[stakingtypes.StoreKey], newApp.AppKeepers.KvStoreKeys()[stakingtypes.StoreKey], + { + app.AppKeepers.KvStoreKeys()[stakingtypes.StoreKey], newApp.AppKeepers.KvStoreKeys()[stakingtypes.StoreKey], [][]byte{ stakingtypes.UnbondingQueueKey, stakingtypes.RedelegationQueueKey, stakingtypes.ValidatorQueueKey, stakingtypes.HistoricalInfoKey, - }}, // ordering may change but it doesn't matter + }, + }, // ordering may change but it doesn't matter {app.AppKeepers.KvStoreKeys()[slashingtypes.StoreKey], newApp.AppKeepers.KvStoreKeys()[slashingtypes.StoreKey], [][]byte{}}, {app.AppKeepers.KvStoreKeys()[minttypes.StoreKey], newApp.AppKeepers.KvStoreKeys()[minttypes.StoreKey], [][]byte{}}, {app.AppKeepers.KvStoreKeys()[distrtypes.StoreKey], newApp.AppKeepers.KvStoreKeys()[distrtypes.StoreKey], [][]byte{}}, @@ -267,7 +248,7 @@ func TestAppImportExport(t *testing.T) { // check irismod module {app.AppKeepers.KvStoreKeys()[tokentypes.StoreKey], newApp.AppKeepers.KvStoreKeys()[tokentypes.StoreKey], [][]byte{}}, {app.AppKeepers.KvStoreKeys()[oracletypes.StoreKey], newApp.AppKeepers.KvStoreKeys()[oracletypes.StoreKey], [][]byte{}}, - //mt.Supply is InitSupply, can be not equal to TotalSupply + // mt.Supply is InitSupply, can be not equal to TotalSupply {app.AppKeepers.KvStoreKeys()[mttypes.StoreKey], newApp.AppKeepers.KvStoreKeys()[mttypes.StoreKey], [][]byte{mttypes.PrefixMT}}, {app.AppKeepers.KvStoreKeys()[nfttypes.StoreKey], newApp.AppKeepers.KvStoreKeys()[nfttypes.StoreKey], [][]byte{{0x05}}}, { @@ -334,15 +315,7 @@ func TestAppSimulationAfterImport(t *testing.T) { require.NoError(t, os.RemoveAll(dir)) }() - app := NewIrisApp( - logger, - db, - nil, - true, - encfg, - EmptyAppOptions{}, - fauxMerkleModeOpt, - ) + app := createApp(logger, db, encfg, fauxMerkleModeOpt) require.Equal(t, "IrisApp", app.Name()) // Run randomized simulation @@ -393,15 +366,7 @@ func TestAppSimulationAfterImport(t *testing.T) { require.NoError(t, os.RemoveAll(newDir)) }() - newApp := NewIrisApp( - log.NewNopLogger(), - newDB, - nil, - true, - encfg, - EmptyAppOptions{}, - fauxMerkleModeOpt, - ) + newApp := createApp(logger, db, encfg, fauxMerkleModeOpt) require.Equal(t, "IrisApp", newApp.Name()) newApp.InitChain(abci.RequestInitChain{ @@ -428,6 +393,7 @@ func TestAppStateDeterminism(t *testing.T) { if !simcli.FlagEnabledValue { t.Skip("skipping application simulation") } + sdk.DefaultBondDenom = iristypes.NativeToken.Symbol config := simcli.NewConfigFromFlags() config.InitialBlockHeight = 1 @@ -453,15 +419,7 @@ func TestAppStateDeterminism(t *testing.T) { } db := dbm.NewMemDB() - app := NewIrisApp( - logger, - db, - nil, - true, - encfg, - EmptyAppOptions{}, - interBlockCacheOpt(), - ) + app := createApp(logger, db, encfg, interBlockCacheOpt()) fmt.Printf( "running non-determinism simulation; seed %d: %d/%d, attempt: %d/%d\n", @@ -516,3 +474,24 @@ type EmptyAppOptions struct{} func (ao EmptyAppOptions) Get(o string) interface{} { return nil } + +func createApp( + logger log.Logger, + db dbm.DB, + encodingConfig params.EncodingConfig, + baseAppOptions ...func(*baseapp.BaseApp), +) *IrisApp { + if baseAppOptions == nil { + baseAppOptions = []func(*baseapp.BaseApp){} + } + baseAppOptions = append(baseAppOptions, baseapp.SetChainID(AppChainID)) + return NewIrisApp( + logger, + db, + nil, + true, + encodingConfig, + EmptyAppOptions{}, + baseAppOptions..., + ) +}