From d2e40963ed570ec009f378e0c8c06defc6f2c29d Mon Sep 17 00:00:00 2001 From: Marko Date: Mon, 11 Mar 2024 11:22:16 +0100 Subject: [PATCH] refactor(modules): adopt appmodulev2.Hasgenesis (#19627) Co-authored-by: Julien Robert --- CHANGELOG.md | 1 + UPGRADING.md | 6 +- core/appmodule/genesis.go | 11 +- core/appmodule/module.go | 8 +- core/appmodule/v2/genesis.go | 2 +- .../building-modules/01-module-manager.md | 8 +- go.mod | 2 + go.sum | 4 +- orm/model/ormdb/module.go | 4 +- runtime/app.go | 2 +- simapp/app.go | 8 +- simapp/app_test.go | 4 +- simapp/export.go | 2 +- simapp/simd/cmd/testnet.go | 2 +- store/snapshots/helpers_test.go | 1 - store/snapshots/store.go | 4 +- tests/integration/evidence/genesis_test.go | 23 ++- .../evidence/keeper/infraction_test.go | 2 +- tests/integration/gov/genesis_test.go | 31 +-- testutil/integration/router.go | 4 +- testutil/mock/types_mock_appmodule.go | 79 ++++---- testutil/mock/types_module_module.go | 180 +++--------------- types/module/core_module.go | 52 +++-- types/module/mock_appmodule_test.go | 11 +- types/module/module.go | 73 +++---- types/module/module_test.go | 44 ++--- x/accounts/module.go | 38 ++-- x/auth/module.go | 28 +-- x/authz/keeper/genesis.go | 9 +- x/authz/keeper/genesis_test.go | 4 +- x/authz/module/module.go | 23 ++- x/bank/CHANGELOG.md | 9 +- x/bank/keeper/genesis.go | 11 +- x/bank/keeper/genesis_test.go | 23 ++- x/bank/keeper/keeper.go | 2 +- x/bank/module.go | 27 ++- x/circuit/keeper/genesis.go | 20 +- x/circuit/keeper/genesis_test.go | 6 +- x/circuit/module.go | 28 +-- x/crisis/depinject.go | 2 +- x/crisis/module.go | 30 +-- x/distribution/keeper/genesis.go | 67 +++---- x/distribution/module.go | 28 +-- x/evidence/CHANGELOG.md | 1 + x/evidence/depinject.go | 2 +- x/evidence/genesis.go | 18 +- x/evidence/module.go | 31 +-- x/feegrant/module/module.go | 26 +-- x/genutil/client/cli/gentx.go | 2 +- x/genutil/client/cli/init.go | 3 +- x/genutil/client/cli/init_test.go | 25 ++- x/genutil/client/cli/validate_genesis.go | 6 +- x/genutil/depinject.go | 4 +- x/genutil/module.go | 21 +- x/gov/genesis.go | 25 +-- x/gov/module.go | 25 +-- x/gov/testutil/expected_keepers_mocks.go | 6 +- x/group/keeper/genesis.go | 18 +- x/group/keeper/genesis_test.go | 3 +- x/group/module/module.go | 21 +- x/mint/keeper/genesis.go | 16 +- x/mint/keeper/genesis_test.go | 6 +- x/mint/module.go | 28 +-- x/nft/keeper/genesis.go | 9 +- x/nft/keeper/keeper_test.go | 3 +- x/nft/module/module.go | 23 ++- x/protocolpool/module.go | 38 ++-- x/slashing/keeper/genesis.go | 15 +- x/slashing/keeper/genesis_test.go | 3 +- x/slashing/module.go | 33 ++-- x/staking/module.go | 16 +- x/upgrade/module.go | 26 +-- 72 files changed, 684 insertions(+), 692 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b042e458585d..4e96570e82c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -143,6 +143,7 @@ Every module contains its own CHANGELOG.md. Please refer to the module you are i * (types) [#19652](https://github.com/cosmos/cosmos-sdk/pull/19652) * Moved`types/module.HasRegisterInterfaces` to `cosmossdk.io/core`. * Moved `RegisterInterfaces` and `RegisterImplementations` from `InterfaceRegistry` to `cosmossdk.io/core/registry.LegacyRegistry` interface. +* (types) [#19627](https://github.com/cosmos/cosmos-sdk/pull/19627) All genesis interfaces now don't take `codec.JsonCodec`. Every module has the codec already, passing it created an unneeded dependency. Additionally, to reflect this change, the module manager does not take a codec either. ### Client Breaking Changes diff --git a/UPGRADING.md b/UPGRADING.md index 2d04c35f6806..1519b8f80efc 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -182,16 +182,16 @@ Previous module migrations have been removed. It is required to migrate to v0.50 ##### Genesis Interface -All genesis interfaces have been migrated to take context.Context instead of sdk.Context. +All genesis interfaces have been migrated to take context.Context instead of sdk.Context. Secondly, the codec is no longer passed in by the framework. The codec is now passed in by the module. ```go // InitGenesis performs genesis initialization for the authz module. -func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { +func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) error { } // ExportGenesis returns the exported genesis state as raw bytes for the authz // module. -func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json.RawMessage { +func (am AppModule) ExportGenesis(ctx context.Context) (json.RawMessage, error) { } ``` diff --git a/core/appmodule/genesis.go b/core/appmodule/genesis.go index 7f955a467749..dcc7fe8a992a 100644 --- a/core/appmodule/genesis.go +++ b/core/appmodule/genesis.go @@ -3,13 +3,18 @@ package appmodule import ( "context" "io" + + appmodule "cosmossdk.io/core/appmodule/v2" ) -// HasGenesis is the extension interface that modules should implement to handle +// HasGenesis defines a custom genesis handling API implementation. +type HasGenesis = appmodule.HasGenesis + +// HasGenesisAuto is the extension interface that modules should implement to handle // genesis data and state initialization. // WARNING: This interface is experimental and may change at any time. -type HasGenesis interface { - AppModule +type HasGenesisAuto interface { + appmodule.AppModule // DefaultGenesis writes the default genesis for this module to the target. DefaultGenesis(GenesisTarget) error diff --git a/core/appmodule/module.go b/core/appmodule/module.go index e36e271eab6f..4646d11d17b3 100644 --- a/core/appmodule/module.go +++ b/core/appmodule/module.go @@ -57,7 +57,7 @@ type ResponsePreBlock interface { // HasPreBlocker is the extension interface that modules should implement to run // custom logic before BeginBlock. type HasPreBlocker interface { - AppModule + appmodule.AppModule // PreBlock is method that will be run before BeginBlock. PreBlock(context.Context) (ResponsePreBlock, error) } @@ -91,12 +91,12 @@ type HasMsgHandler interface { // HasPrepareCheckState is an extension interface that contains information about the AppModule // and PrepareCheckState. type HasPrepareCheckState interface { - AppModule + appmodule.AppModule PrepareCheckState(context.Context) error } -// HasPrecommit is an extension interface that contains information about the AppModule and Precommit. +// HasPrecommit is an extension interface that contains information about the appmodule.AppModule and Precommit. type HasPrecommit interface { - AppModule + appmodule.AppModule Precommit(context.Context) error } diff --git a/core/appmodule/v2/genesis.go b/core/appmodule/v2/genesis.go index d457ac89d8c3..d32745d13f52 100644 --- a/core/appmodule/v2/genesis.go +++ b/core/appmodule/v2/genesis.go @@ -10,7 +10,7 @@ import ( // migration of existing modules to the new app module API. It is intended to be replaced by collections type HasGenesis interface { AppModule - DefaultGenesis() Message + DefaultGenesis() json.RawMessage ValidateGenesis(data json.RawMessage) error InitGenesis(ctx context.Context, data json.RawMessage) error ExportGenesis(ctx context.Context) (json.RawMessage, error) diff --git a/docs/build/building-modules/01-module-manager.md b/docs/build/building-modules/01-module-manager.md index 61a3fe66fea6..bce8cea7f6dc 100644 --- a/docs/build/building-modules/01-module-manager.md +++ b/docs/build/building-modules/01-module-manager.md @@ -30,6 +30,8 @@ There are 2 main application module interfaces: The above interfaces are mostly embedding smaller interfaces (extension interfaces), that defines specific functionalities: + + * (legacy) `module.HasName`: Allows the module to provide its own name for legacy purposes. * (legacy) [`module.HasGenesisBasics`](#modulehasgenesisbasics): The legacy interface for stateless genesis methods. * (legacy) [`module.HasGenesis`](#modulehasgenesis) for inter-dependent genesis-related module functionalities. @@ -270,9 +272,9 @@ The module manager is used throughout the application whenever an action on a co * `SetOrderMigrations(moduleNames ...string)`: Sets the order of migrations to be run. If not set then migrations will be run with an order defined in `DefaultMigrationsOrder`. * `RegisterInvariants(ir sdk.InvariantRegistry)`: Registers the [invariants](./07-invariants.md) of module implementing the `HasInvariants` interface. * `RegisterServices(cfg Configurator)`: Registers the services of modules implementing the `HasServices` interface. -* `InitGenesis(ctx context.Context, cdc codec.JSONCodec, genesisData map[string]json.RawMessage)`: Calls the [`InitGenesis`](./08-genesis.md#initgenesis) function of each module when the application is first started, in the order defined in `OrderInitGenesis`. Returns an `abci.ResponseInitChain` to the underlying consensus engine, which can contain validator updates. -* `ExportGenesis(ctx context.Context, cdc codec.JSONCodec)`: Calls the [`ExportGenesis`](./08-genesis.md#exportgenesis) function of each module, in the order defined in `OrderExportGenesis`. The export constructs a genesis file from a previously existing state, and is mainly used when a hard-fork upgrade of the chain is required. -* `ExportGenesisForModules(ctx context.Context, cdc codec.JSONCodec, modulesToExport []string)`: Behaves the same as `ExportGenesis`, except takes a list of modules to export. +* `InitGenesis(ctx context.Context, genesisData map[string]json.RawMessage)`: Calls the [`InitGenesis`](./08-genesis.md#initgenesis) function of each module when the application is first started, in the order defined in `OrderInitGenesis`. Returns an `abci.ResponseInitChain` to the underlying consensus engine, which can contain validator updates. +* `ExportGenesis(ctx context.Context)`: Calls the [`ExportGenesis`](./08-genesis.md#exportgenesis) function of each module, in the order defined in `OrderExportGenesis`. The export constructs a genesis file from a previously existing state, and is mainly used when a hard-fork upgrade of the chain is required. +* `ExportGenesisForModules(ctx context.Context, modulesToExport []string)`: Behaves the same as `ExportGenesis`, except takes a list of modules to export. * `BeginBlock(ctx context.Context) error`: At the beginning of each block, this function is called from [`BaseApp`](../../learn/advanced/00-baseapp.md#beginblock) and, in turn, calls the [`BeginBlock`](./06-beginblock-endblock.md) function of each modules implementing the `appmodule.HasBeginBlocker` interface, in the order defined in `OrderBeginBlockers`. It creates a child [context](../../learn/advanced/02-context.md) with an event manager to aggregate [events](../../learn/advanced/08-events.md) emitted from each modules. * `EndBlock(ctx context.Context) error`: At the end of each block, this function is called from [`BaseApp`](../../learn/advanced/00-baseapp.md#endblock) and, in turn, calls the [`EndBlock`](./06-beginblock-endblock.md) function of each modules implementing the `appmodule.HasEndBlocker` interface, in the order defined in `OrderEndBlockers`. It creates a child [context](../../learn/advanced/02-context.md) with an event manager to aggregate [events](../../learn/advanced/08-events.md) emitted from all modules. The function returns an `abci` which contains the aforementioned events, as well as validator set updates (if any). * `EndBlock(context.Context) ([]abci.ValidatorUpdate, error)`: At the end of each block, this function is called from [`BaseApp`](../../learn/advanced/00-baseapp.md#endblock) and, in turn, calls the [`EndBlock`](./06-beginblock-endblock.md) function of each modules implementing the `module.HasABCIEndBlock` interface, in the order defined in `OrderEndBlockers`. It creates a child [context](../../learn/advanced/02-context.md) with an event manager to aggregate [events](../../learn/advanced/08-events.md) emitted from all modules. The function returns an `abci` which contains the aforementioned events, as well as validator set updates (if any). diff --git a/go.mod b/go.mod index 558d07d39423..55e1683242a2 100644 --- a/go.mod +++ b/go.mod @@ -189,6 +189,8 @@ replace ( cosmossdk.io/x/staking => ./x/staking ) +replace github.com/cosmos/iavl => github.com/cosmos/iavl v1.0.1 // TODO remove + // Below are the long-lived replace of the Cosmos SDK replace ( // use cosmos fork of keyring diff --git a/go.sum b/go.sum index 0cf76f2fc524..fb685aaddda5 100644 --- a/go.sum +++ b/go.sum @@ -146,8 +146,8 @@ github.com/cosmos/gogogateway v1.2.0/go.mod h1:iQpLkGWxYcnCdz5iAdLcRBSw3h7NXeOkZ github.com/cosmos/gogoproto v1.4.2/go.mod h1:cLxOsn1ljAHSV527CHOtaIP91kK6cCrZETRBrkzItWU= github.com/cosmos/gogoproto v1.4.11 h1:LZcMHrx4FjUgrqQSWeaGC1v/TeuVFqSLa43CC6aWR2g= github.com/cosmos/gogoproto v1.4.11/go.mod h1:/g39Mh8m17X8Q/GDEs5zYTSNaNnInBSohtaxzQnYq1Y= -github.com/cosmos/iavl v1.0.0 h1:bw6t0Mv/mVCJvlMTOPHWLs5uUE3BRBfVWCRelOzl+so= -github.com/cosmos/iavl v1.0.0/go.mod h1:CmTGqMnRnucjxbjduneZXT+0vPgNElYvdefjX2q9tYc= +github.com/cosmos/iavl v1.0.1 h1:D+mYbcRO2wptYzOM1Hxl9cpmmHU1ZEt9T2Wv5nZTeUw= +github.com/cosmos/iavl v1.0.1/go.mod h1:8xIUkgVvwvVrBu81scdPty+/Dx9GqwHnAvXz4cwF7RY= github.com/cosmos/ics23/go v0.10.0 h1:iXqLLgp2Lp+EdpIuwXTYIQU+AiHj9mOC2X9ab++bZDM= github.com/cosmos/ics23/go v0.10.0/go.mod h1:ZfJSmng/TBNTBkFemHHHj5YY7VAU/MBU980F4VU1NG0= github.com/cosmos/keyring v1.2.0 h1:8C1lBP9xhImmIabyXW4c3vFjjLiBdGCmfLUfeZlV1Yo= diff --git a/orm/model/ormdb/module.go b/orm/model/ormdb/module.go index 95ba640c7585..605e641729ad 100644 --- a/orm/model/ormdb/module.go +++ b/orm/model/ormdb/module.go @@ -39,7 +39,7 @@ type ModuleDB interface { // func NewAppModule(keeper keeper.Keeper) AppModule { // return AppModule{HasGenesis: keeper.GenesisHandler()} // } - GenesisHandler() appmodule.HasGenesis + GenesisHandler() appmodule.HasGenesis // TODO should be appmodule.HasGenesisAuto with core v1 private() } @@ -212,7 +212,7 @@ func (m moduleDB) GetTable(message proto.Message) ormtable.Table { return m.tablesByName[message.ProtoReflect().Descriptor().FullName()] } -func (m moduleDB) GenesisHandler() appmodule.HasGenesis { +func (m moduleDB) GenesisHandler() appmodule.HasGenesis { // TODO should be appmodule.HasGenesisAuto with core v1 return appModuleGenesisWrapper{m} } diff --git a/runtime/app.go b/runtime/app.go index d8474b0041ab..c5ac9329d9e5 100644 --- a/runtime/app.go +++ b/runtime/app.go @@ -242,7 +242,7 @@ func (a *App) LoadHeight(height int64) error { // DefaultGenesis returns a default genesis from the registered AppModule's. func (a *App) DefaultGenesis() map[string]json.RawMessage { - return a.ModuleManager.DefaultGenesis(a.cdc) + return a.ModuleManager.DefaultGenesis() } // GetStoreKeys returns all the stored store keys. diff --git a/simapp/app.go b/simapp/app.go index be410d5d70dc..59e7b03410e2 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -408,8 +408,8 @@ func NewSimApp( // NOTE: Any module instantiated in the module manager that is later modified // must be passed by reference here. app.ModuleManager = module.NewManager( - genutil.NewAppModule(app.AuthKeeper, app.StakingKeeper, app, txConfig, genutiltypes.DefaultMessageValidator), - accounts.NewAppModule(app.AccountsKeeper), + genutil.NewAppModule(appCodec, app.AuthKeeper, app.StakingKeeper, app, txConfig, genutiltypes.DefaultMessageValidator), + accounts.NewAppModule(appCodec, app.AccountsKeeper), auth.NewAppModule(appCodec, app.AuthKeeper, authsims.RandomGenesisAccounts), vesting.NewAppModule(app.AuthKeeper, app.BankKeeper), bank.NewAppModule(appCodec, app.BankKeeper, app.AuthKeeper), @@ -420,7 +420,7 @@ func NewSimApp( distr.NewAppModule(appCodec, app.DistrKeeper, app.AuthKeeper, app.BankKeeper, app.StakingKeeper, app.PoolKeeper), staking.NewAppModule(appCodec, app.StakingKeeper, app.AuthKeeper, app.BankKeeper), upgrade.NewAppModule(app.UpgradeKeeper), - evidence.NewAppModule(app.EvidenceKeeper), + evidence.NewAppModule(appCodec, app.EvidenceKeeper), authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AuthKeeper, app.BankKeeper, app.interfaceRegistry), groupmodule.NewAppModule(appCodec, app.GroupKeeper, app.AuthKeeper, app.BankKeeper, app.interfaceRegistry), nftmodule.NewAppModule(appCodec, app.NFTKeeper, app.AuthKeeper, app.BankKeeper, app.interfaceRegistry), @@ -698,7 +698,7 @@ func (app *SimApp) AutoCliOpts() autocli.AppOptions { // DefaultGenesis returns a default genesis from the registered AppModule's. func (a *SimApp) DefaultGenesis() map[string]json.RawMessage { - return a.ModuleManager.DefaultGenesis(a.appCodec) + return a.ModuleManager.DefaultGenesis() } // GetKey returns the KVStoreKey for the provided store key. diff --git a/simapp/app_test.go b/simapp/app_test.go index da8d555de983..8c1c5a8d8ef3 100644 --- a/simapp/app_test.go +++ b/simapp/app_test.go @@ -237,8 +237,8 @@ func TestInitGenesisOnMigration(t *testing.T) { t.Cleanup(mockCtrl.Finish) mockModule := mock.NewMockAppModuleWithAllExtensions(mockCtrl) mockDefaultGenesis := json.RawMessage(`{"key": "value"}`) - mockModule.EXPECT().DefaultGenesis(gomock.Eq(app.appCodec)).Times(1).Return(mockDefaultGenesis) - mockModule.EXPECT().InitGenesis(gomock.Eq(ctx), gomock.Eq(app.appCodec), gomock.Eq(mockDefaultGenesis)).Times(1) + mockModule.EXPECT().DefaultGenesis().Times(1).Return(mockDefaultGenesis) + mockModule.EXPECT().InitGenesis(gomock.Eq(ctx), gomock.Eq(mockDefaultGenesis)).Times(1) mockModule.EXPECT().ConsensusVersion().Times(1).Return(uint64(0)) app.ModuleManager.Modules["mock"] = mockModule diff --git a/simapp/export.go b/simapp/export.go index 33071033df16..4fda92cc9358 100644 --- a/simapp/export.go +++ b/simapp/export.go @@ -31,7 +31,7 @@ func (app *SimApp) ExportAppStateAndValidators(forZeroHeight bool, jailAllowedAd app.prepForZeroHeightGenesis(ctx, jailAllowedAddrs) } - genState, err := app.ModuleManager.ExportGenesisForModules(ctx, app.appCodec, modulesToExport) + genState, err := app.ModuleManager.ExportGenesisForModules(ctx, modulesToExport) if err != nil { return servertypes.ExportedApp{}, err } diff --git a/simapp/simd/cmd/testnet.go b/simapp/simd/cmd/testnet.go index 101cf5388a3e..b0c95a43a7e5 100644 --- a/simapp/simd/cmd/testnet.go +++ b/simapp/simd/cmd/testnet.go @@ -375,7 +375,7 @@ func initGenFiles( genAccounts []authtypes.GenesisAccount, genBalances []banktypes.Balance, genFiles []string, numValidators int, ) error { - appGenState := mm.DefaultGenesis(clientCtx.Codec) + appGenState := mm.DefaultGenesis() // set the accounts in the genesis state var authGenState authtypes.GenesisState diff --git a/store/snapshots/helpers_test.go b/store/snapshots/helpers_test.go index 33dcc14fa6f4..a0d1add9a85d 100644 --- a/store/snapshots/helpers_test.go +++ b/store/snapshots/helpers_test.go @@ -291,7 +291,6 @@ func (s *extSnapshotter) RestoreExtension(height uint64, format uint32, payloadR // GetTempDir returns a writable temporary director for the test to use. func GetTempDir(tb testing.TB) string { - //return "/tmp/snapshots" tb.Helper() // os.MkDir() is used instead of testing.T.TempDir() // see https://github.com/cosmos/cosmos-sdk/pull/8475 and diff --git a/store/snapshots/store.go b/store/snapshots/store.go index 35d0d6a9f609..5c82a095e6dd 100644 --- a/store/snapshots/store.go +++ b/store/snapshots/store.go @@ -223,7 +223,7 @@ func (s *Store) Prune(retain uint32) (uint64, error) { skip[height] = true continue } - err = s.Delete(height, uint32(format)) + err = s.Delete(height, format) if err != nil { return 0, errors.Wrap(err, "failed to prune snapshots") } @@ -382,7 +382,7 @@ func (s *Store) parseMetadataFilename(filename string) (height uint64, format ui return 0, 0, errors.Wrapf(err, "invalid snapshot metadata filename %s", filename) } format = uint32(f) - if filename != filepath.Base(s.pathMetadata(height, uint32(format))) { + if filename != filepath.Base(s.pathMetadata(height, format)) { return 0, 0, fmt.Errorf("invalid snapshot metadata filename %s", filename) } return height, format, nil diff --git a/tests/integration/evidence/genesis_test.go b/tests/integration/evidence/genesis_test.go index 902bc3f23d15..c2cb89c406fc 100644 --- a/tests/integration/evidence/genesis_test.go +++ b/tests/integration/evidence/genesis_test.go @@ -105,13 +105,12 @@ func (suite *GenesisTestSuite) TestInitGenesis() { tc.malleate() if tc.expPass { - suite.NotPanics(func() { - evidence.InitGenesis(suite.ctx, suite.keeper, genesisState) - }) + err := evidence.InitGenesis(suite.ctx, suite.keeper, genesisState) + suite.NoError(err) } else { - suite.Panics(func() { - evidence.InitGenesis(suite.ctx, suite.keeper, genesisState) - }) + err := evidence.InitGenesis(suite.ctx, suite.keeper, genesisState) + suite.Error(err) + } tc.posttests() @@ -151,13 +150,13 @@ func (suite *GenesisTestSuite) TestExportGenesis() { tc.malleate() if tc.expPass { - suite.NotPanics(func() { - evidence.ExportGenesis(suite.ctx, suite.keeper) - }) + + _, err := evidence.ExportGenesis(suite.ctx, suite.keeper) + suite.Require().NoError(err) + } else { - suite.Panics(func() { - evidence.ExportGenesis(suite.ctx, suite.keeper) - }) + _, err := evidence.ExportGenesis(suite.ctx, suite.keeper) + suite.Require().Error(err) } tc.posttests() diff --git a/tests/integration/evidence/keeper/infraction_test.go b/tests/integration/evidence/keeper/infraction_test.go index 5c9977d6c7c6..4dcc9b3e8298 100644 --- a/tests/integration/evidence/keeper/infraction_test.go +++ b/tests/integration/evidence/keeper/infraction_test.go @@ -141,7 +141,7 @@ func initFixture(tb testing.TB) *fixture { bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper) stakingModule := staking.NewAppModule(cdc, stakingKeeper, accountKeeper, bankKeeper) slashingModule := slashing.NewAppModule(cdc, slashingKeeper, accountKeeper, bankKeeper, stakingKeeper, cdc.InterfaceRegistry()) - evidenceModule := evidence.NewAppModule(*evidenceKeeper) + evidenceModule := evidence.NewAppModule(cdc, *evidenceKeeper) integrationApp := integration.NewIntegrationApp(newCtx, logger, keys, cdc, encodingCfg.InterfaceRegistry.SigningContext().AddressCodec(), diff --git a/tests/integration/gov/genesis_test.go b/tests/integration/gov/genesis_test.go index 265ecb66d94c..86599ff3073c 100644 --- a/tests/integration/gov/genesis_test.go +++ b/tests/integration/gov/genesis_test.go @@ -204,23 +204,26 @@ func TestImportExportQueues_ErrorUnconsistentState(t *testing.T) { suite := createTestSuite(t) app := suite.app ctx := app.BaseApp.NewContext(false) - require.Panics(t, func() { - gov.InitGenesis(ctx, suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper, &v1.GenesisState{ - Deposits: v1.Deposits{ - { - ProposalId: 1234, - Depositor: "me", - Amount: sdk.Coins{ - sdk.NewCoin( - "stake", - sdkmath.NewInt(1234), - ), - }, + + params := v1.DefaultParams() + err := gov.InitGenesis(ctx, suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper, &v1.GenesisState{ + Deposits: v1.Deposits{ + { + ProposalId: 1234, + Depositor: "me", + Amount: sdk.Coins{ + sdk.NewCoin( + "stake", + sdkmath.NewInt(1234), + ), }, }, - }) + }, + Params: ¶ms, }) - gov.InitGenesis(ctx, suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper, v1.DefaultGenesisState()) + require.Error(t, err) + err = gov.InitGenesis(ctx, suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper, v1.DefaultGenesisState()) + require.NoError(t, err) genState, err := gov.ExportGenesis(ctx, suite.GovKeeper) require.NoError(t, err) require.Equal(t, genState, v1.DefaultGenesisState()) diff --git a/testutil/integration/router.go b/testutil/integration/router.go index 45fa80dbbf44..9bf25657cff7 100644 --- a/testutil/integration/router.go +++ b/testutil/integration/router.go @@ -64,7 +64,9 @@ func NewIntegrationApp( bApp.SetInitChainer(func(ctx sdk.Context, _ *cmtabcitypes.RequestInitChain) (*cmtabcitypes.ResponseInitChain, error) { for _, mod := range modules { if m, ok := mod.(module.HasGenesis); ok { - m.InitGenesis(ctx, appCodec, m.DefaultGenesis(appCodec)) + if err := m.InitGenesis(ctx, m.DefaultGenesis()); err != nil { + return nil, err + } } } diff --git a/testutil/mock/types_mock_appmodule.go b/testutil/mock/types_mock_appmodule.go index 3d3f3c06442f..13f1c97b7124 100644 --- a/testutil/mock/types_mock_appmodule.go +++ b/testutil/mock/types_mock_appmodule.go @@ -10,11 +10,9 @@ import ( reflect "reflect" appmodule "cosmossdk.io/core/appmodule" - "cosmossdk.io/core/registry" + registry "cosmossdk.io/core/registry" types "github.com/cometbft/cometbft/abci/types" - client "github.com/cosmos/cosmos-sdk/client" - codec "github.com/cosmos/cosmos-sdk/codec" - types1 "github.com/cosmos/cosmos-sdk/types" + types0 "github.com/cosmos/cosmos-sdk/types" module "github.com/cosmos/cosmos-sdk/types/module" gomock "github.com/golang/mock/gomock" ) @@ -57,17 +55,17 @@ func (mr *MockAppModuleWithAllExtensionsMockRecorder) ConsensusVersion() *gomock } // DefaultGenesis mocks base method. -func (m *MockAppModuleWithAllExtensions) DefaultGenesis(arg0 codec.JSONCodec) json.RawMessage { +func (m *MockAppModuleWithAllExtensions) DefaultGenesis() json.RawMessage { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DefaultGenesis", arg0) + ret := m.ctrl.Call(m, "DefaultGenesis") ret0, _ := ret[0].(json.RawMessage) return ret0 } // DefaultGenesis indicates an expected call of DefaultGenesis. -func (mr *MockAppModuleWithAllExtensionsMockRecorder) DefaultGenesis(arg0 interface{}) *gomock.Call { +func (mr *MockAppModuleWithAllExtensionsMockRecorder) DefaultGenesis() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DefaultGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensions)(nil).DefaultGenesis), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DefaultGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensions)(nil).DefaultGenesis)) } // EndBlock mocks base method. @@ -86,29 +84,32 @@ func (mr *MockAppModuleWithAllExtensionsMockRecorder) EndBlock(arg0 interface{}) } // ExportGenesis mocks base method. -func (m *MockAppModuleWithAllExtensions) ExportGenesis(arg0 context.Context, arg1 codec.JSONCodec) json.RawMessage { +func (m *MockAppModuleWithAllExtensions) ExportGenesis(ctx context.Context) (json.RawMessage, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ExportGenesis", arg0, arg1) + ret := m.ctrl.Call(m, "ExportGenesis", ctx) ret0, _ := ret[0].(json.RawMessage) - return ret0 + ret1, _ := ret[1].(error) + return ret0, ret1 } // ExportGenesis indicates an expected call of ExportGenesis. -func (mr *MockAppModuleWithAllExtensionsMockRecorder) ExportGenesis(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockAppModuleWithAllExtensionsMockRecorder) ExportGenesis(ctx interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExportGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensions)(nil).ExportGenesis), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExportGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensions)(nil).ExportGenesis), ctx) } // InitGenesis mocks base method. -func (m *MockAppModuleWithAllExtensions) InitGenesis(arg0 context.Context, arg1 codec.JSONCodec, arg2 json.RawMessage) { +func (m *MockAppModuleWithAllExtensions) InitGenesis(ctx context.Context, data json.RawMessage) error { m.ctrl.T.Helper() - m.ctrl.Call(m, "InitGenesis", arg0, arg1, arg2) + ret := m.ctrl.Call(m, "InitGenesis", ctx, data) + ret0, _ := ret[0].(error) + return ret0 } // InitGenesis indicates an expected call of InitGenesis. -func (mr *MockAppModuleWithAllExtensionsMockRecorder) InitGenesis(arg0, arg1, arg2 interface{}) *gomock.Call { +func (mr *MockAppModuleWithAllExtensionsMockRecorder) InitGenesis(ctx, data interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensions)(nil).InitGenesis), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensions)(nil).InitGenesis), ctx, data) } // IsAppModule mocks base method. @@ -162,7 +163,7 @@ func (mr *MockAppModuleWithAllExtensionsMockRecorder) RegisterInterfaces(arg0 in } // RegisterInvariants mocks base method. -func (m *MockAppModuleWithAllExtensions) RegisterInvariants(arg0 types1.InvariantRegistry) { +func (m *MockAppModuleWithAllExtensions) RegisterInvariants(arg0 types0.InvariantRegistry) { m.ctrl.T.Helper() m.ctrl.Call(m, "RegisterInvariants", arg0) } @@ -186,17 +187,17 @@ func (mr *MockAppModuleWithAllExtensionsMockRecorder) RegisterServices(arg0 inte } // ValidateGenesis mocks base method. -func (m *MockAppModuleWithAllExtensions) ValidateGenesis(arg0 codec.JSONCodec, arg1 client.TxEncodingConfig, arg2 json.RawMessage) error { +func (m *MockAppModuleWithAllExtensions) ValidateGenesis(data json.RawMessage) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ValidateGenesis", arg0, arg1, arg2) + ret := m.ctrl.Call(m, "ValidateGenesis", data) ret0, _ := ret[0].(error) return ret0 } // ValidateGenesis indicates an expected call of ValidateGenesis. -func (mr *MockAppModuleWithAllExtensionsMockRecorder) ValidateGenesis(arg0, arg1, arg2 interface{}) *gomock.Call { +func (mr *MockAppModuleWithAllExtensionsMockRecorder) ValidateGenesis(data interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensions)(nil).ValidateGenesis), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensions)(nil).ValidateGenesis), data) } // MockAppModuleWithAllExtensionsABCI is a mock of AppModuleWithAllExtensionsABCI interface. @@ -237,17 +238,17 @@ func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) ConsensusVersion() *go } // DefaultGenesis mocks base method. -func (m *MockAppModuleWithAllExtensionsABCI) DefaultGenesis(arg0 codec.JSONCodec) json.RawMessage { +func (m *MockAppModuleWithAllExtensionsABCI) DefaultGenesis() json.RawMessage { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DefaultGenesis", arg0) + ret := m.ctrl.Call(m, "DefaultGenesis") ret0, _ := ret[0].(json.RawMessage) return ret0 } // DefaultGenesis indicates an expected call of DefaultGenesis. -func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) DefaultGenesis(arg0 interface{}) *gomock.Call { +func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) DefaultGenesis() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DefaultGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensionsABCI)(nil).DefaultGenesis), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DefaultGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensionsABCI)(nil).DefaultGenesis)) } // EndBlock mocks base method. @@ -266,31 +267,31 @@ func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) EndBlock(arg0 interfac } // ExportGenesis mocks base method. -func (m *MockAppModuleWithAllExtensionsABCI) ExportGenesis(arg0 context.Context, arg1 codec.JSONCodec) json.RawMessage { +func (m *MockAppModuleWithAllExtensionsABCI) ExportGenesis(arg0 context.Context) json.RawMessage { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ExportGenesis", arg0, arg1) + ret := m.ctrl.Call(m, "ExportGenesis", arg0) ret0, _ := ret[0].(json.RawMessage) return ret0 } // ExportGenesis indicates an expected call of ExportGenesis. -func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) ExportGenesis(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) ExportGenesis(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExportGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensionsABCI)(nil).ExportGenesis), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExportGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensionsABCI)(nil).ExportGenesis), arg0) } // InitGenesis mocks base method. -func (m *MockAppModuleWithAllExtensionsABCI) InitGenesis(arg0 context.Context, arg1 codec.JSONCodec, arg2 json.RawMessage) []types.ValidatorUpdate { +func (m *MockAppModuleWithAllExtensionsABCI) InitGenesis(arg0 context.Context, arg1 json.RawMessage) []types.ValidatorUpdate { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "InitGenesis", arg0, arg1, arg2) + ret := m.ctrl.Call(m, "InitGenesis", arg0, arg1) ret0, _ := ret[0].([]types.ValidatorUpdate) return ret0 } // InitGenesis indicates an expected call of InitGenesis. -func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) InitGenesis(arg0, arg1, arg2 interface{}) *gomock.Call { +func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) InitGenesis(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensionsABCI)(nil).InitGenesis), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensionsABCI)(nil).InitGenesis), arg0, arg1) } // IsAppModule mocks base method. @@ -344,7 +345,7 @@ func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) RegisterInterfaces(arg } // RegisterInvariants mocks base method. -func (m *MockAppModuleWithAllExtensionsABCI) RegisterInvariants(arg0 types1.InvariantRegistry) { +func (m *MockAppModuleWithAllExtensionsABCI) RegisterInvariants(arg0 types0.InvariantRegistry) { m.ctrl.T.Helper() m.ctrl.Call(m, "RegisterInvariants", arg0) } @@ -368,17 +369,17 @@ func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) RegisterServices(arg0 } // ValidateGenesis mocks base method. -func (m *MockAppModuleWithAllExtensionsABCI) ValidateGenesis(arg0 codec.JSONCodec, arg1 client.TxEncodingConfig, arg2 json.RawMessage) error { +func (m *MockAppModuleWithAllExtensionsABCI) ValidateGenesis(arg0 json.RawMessage) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ValidateGenesis", arg0, arg1, arg2) + ret := m.ctrl.Call(m, "ValidateGenesis", arg0) ret0, _ := ret[0].(error) return ret0 } // ValidateGenesis indicates an expected call of ValidateGenesis. -func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) ValidateGenesis(arg0, arg1, arg2 interface{}) *gomock.Call { +func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) ValidateGenesis(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensionsABCI)(nil).ValidateGenesis), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateGenesis", reflect.TypeOf((*MockAppModuleWithAllExtensionsABCI)(nil).ValidateGenesis), arg0) } // MockCoreAppModule is a mock of CoreAppModule interface. diff --git a/testutil/mock/types_module_module.go b/testutil/mock/types_module_module.go index 044cca224fa5..b3e6283f509b 100644 --- a/testutil/mock/types_module_module.go +++ b/testutil/mock/types_module_module.go @@ -9,11 +9,11 @@ import ( json "encoding/json" reflect "reflect" - "cosmossdk.io/core/registry" + registry "cosmossdk.io/core/registry" types "github.com/cometbft/cometbft/abci/types" client "github.com/cosmos/cosmos-sdk/client" codec "github.com/cosmos/cosmos-sdk/codec" - types1 "github.com/cosmos/cosmos-sdk/types" + types0 "github.com/cosmos/cosmos-sdk/types" module "github.com/cosmos/cosmos-sdk/types/module" gomock "github.com/golang/mock/gomock" runtime "github.com/grpc-ecosystem/grpc-gateway/runtime" @@ -226,17 +226,17 @@ func (m *MockHasGenesisBasics) EXPECT() *MockHasGenesisBasicsMockRecorder { } // DefaultGenesis mocks base method. -func (m *MockHasGenesisBasics) DefaultGenesis(arg0 codec.JSONCodec) json.RawMessage { +func (m *MockHasGenesisBasics) DefaultGenesis() json.RawMessage { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DefaultGenesis", arg0) + ret := m.ctrl.Call(m, "DefaultGenesis") ret0, _ := ret[0].(json.RawMessage) return ret0 } // DefaultGenesis indicates an expected call of DefaultGenesis. -func (mr *MockHasGenesisBasicsMockRecorder) DefaultGenesis(arg0 interface{}) *gomock.Call { +func (mr *MockHasGenesisBasicsMockRecorder) DefaultGenesis() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DefaultGenesis", reflect.TypeOf((*MockHasGenesisBasics)(nil).DefaultGenesis), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DefaultGenesis", reflect.TypeOf((*MockHasGenesisBasics)(nil).DefaultGenesis)) } // Name mocks base method. @@ -254,17 +254,17 @@ func (mr *MockHasGenesisBasicsMockRecorder) Name() *gomock.Call { } // ValidateGenesis mocks base method. -func (m *MockHasGenesisBasics) ValidateGenesis(arg0 codec.JSONCodec, arg1 client.TxEncodingConfig, arg2 json.RawMessage) error { +func (m *MockHasGenesisBasics) ValidateGenesis(arg0 json.RawMessage) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ValidateGenesis", arg0, arg1, arg2) + ret := m.ctrl.Call(m, "ValidateGenesis", arg0) ret0, _ := ret[0].(error) return ret0 } // ValidateGenesis indicates an expected call of ValidateGenesis. -func (mr *MockHasGenesisBasicsMockRecorder) ValidateGenesis(arg0, arg1, arg2 interface{}) *gomock.Call { +func (mr *MockHasGenesisBasicsMockRecorder) ValidateGenesis(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateGenesis", reflect.TypeOf((*MockHasGenesisBasics)(nil).ValidateGenesis), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateGenesis", reflect.TypeOf((*MockHasGenesisBasics)(nil).ValidateGenesis), arg0) } // MockHasAminoCodec is a mock of HasAminoCodec interface. @@ -302,41 +302,6 @@ func (mr *MockHasAminoCodecMockRecorder) RegisterLegacyAminoCodec(arg0 interface return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterLegacyAminoCodec", reflect.TypeOf((*MockHasAminoCodec)(nil).RegisterLegacyAminoCodec), arg0) } -// MockHasRegisterInterfaces is a mock of HasRegisterInterfaces interface. -type MockHasRegisterInterfaces struct { - ctrl *gomock.Controller - recorder *MockHasRegisterInterfacesMockRecorder -} - -// MockHasRegisterInterfacesMockRecorder is the mock recorder for MockHasRegisterInterfaces. -type MockHasRegisterInterfacesMockRecorder struct { - mock *MockHasRegisterInterfaces -} - -// NewMockHasRegisterInterfaces creates a new mock instance. -func NewMockHasRegisterInterfaces(ctrl *gomock.Controller) *MockHasRegisterInterfaces { - mock := &MockHasRegisterInterfaces{ctrl: ctrl} - mock.recorder = &MockHasRegisterInterfacesMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockHasRegisterInterfaces) EXPECT() *MockHasRegisterInterfacesMockRecorder { - return m.recorder -} - -// RegisterInterfaces mocks base method. -func (m *MockHasRegisterInterfaces) RegisterInterfaces(arg0 registry.LegacyRegistry) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "RegisterInterfaces", arg0) -} - -// RegisterInterfaces indicates an expected call of RegisterInterfaces. -func (mr *MockHasRegisterInterfacesMockRecorder) RegisterInterfaces(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterInterfaces", reflect.TypeOf((*MockHasRegisterInterfaces)(nil).RegisterInterfaces), arg0) -} - // MockHasGRPCGateway is a mock of HasGRPCGateway interface. type MockHasGRPCGateway struct { ctrl *gomock.Controller @@ -372,97 +337,6 @@ func (mr *MockHasGRPCGatewayMockRecorder) RegisterGRPCGatewayRoutes(arg0, arg1 i return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterGRPCGatewayRoutes", reflect.TypeOf((*MockHasGRPCGateway)(nil).RegisterGRPCGatewayRoutes), arg0, arg1) } -// MockHasGenesis is a mock of HasGenesis interface. -type MockHasGenesis struct { - ctrl *gomock.Controller - recorder *MockHasGenesisMockRecorder -} - -// MockHasGenesisMockRecorder is the mock recorder for MockHasGenesis. -type MockHasGenesisMockRecorder struct { - mock *MockHasGenesis -} - -// NewMockHasGenesis creates a new mock instance. -func NewMockHasGenesis(ctrl *gomock.Controller) *MockHasGenesis { - mock := &MockHasGenesis{ctrl: ctrl} - mock.recorder = &MockHasGenesisMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockHasGenesis) EXPECT() *MockHasGenesisMockRecorder { - return m.recorder -} - -// DefaultGenesis mocks base method. -func (m *MockHasGenesis) DefaultGenesis(arg0 codec.JSONCodec) json.RawMessage { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DefaultGenesis", arg0) - ret0, _ := ret[0].(json.RawMessage) - return ret0 -} - -// DefaultGenesis indicates an expected call of DefaultGenesis. -func (mr *MockHasGenesisMockRecorder) DefaultGenesis(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DefaultGenesis", reflect.TypeOf((*MockHasGenesis)(nil).DefaultGenesis), arg0) -} - -// ExportGenesis mocks base method. -func (m *MockHasGenesis) ExportGenesis(arg0 context.Context, arg1 codec.JSONCodec) json.RawMessage { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ExportGenesis", arg0, arg1) - ret0, _ := ret[0].(json.RawMessage) - return ret0 -} - -// ExportGenesis indicates an expected call of ExportGenesis. -func (mr *MockHasGenesisMockRecorder) ExportGenesis(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExportGenesis", reflect.TypeOf((*MockHasGenesis)(nil).ExportGenesis), arg0, arg1) -} - -// InitGenesis mocks base method. -func (m *MockHasGenesis) InitGenesis(arg0 context.Context, arg1 codec.JSONCodec, arg2 json.RawMessage) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "InitGenesis", arg0, arg1, arg2) -} - -// InitGenesis indicates an expected call of InitGenesis. -func (mr *MockHasGenesisMockRecorder) InitGenesis(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitGenesis", reflect.TypeOf((*MockHasGenesis)(nil).InitGenesis), arg0, arg1, arg2) -} - -// Name mocks base method. -func (m *MockHasGenesis) Name() string { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Name") - ret0, _ := ret[0].(string) - return ret0 -} - -// Name indicates an expected call of Name. -func (mr *MockHasGenesisMockRecorder) Name() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockHasGenesis)(nil).Name)) -} - -// ValidateGenesis mocks base method. -func (m *MockHasGenesis) ValidateGenesis(arg0 codec.JSONCodec, arg1 client.TxEncodingConfig, arg2 json.RawMessage) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ValidateGenesis", arg0, arg1, arg2) - ret0, _ := ret[0].(error) - return ret0 -} - -// ValidateGenesis indicates an expected call of ValidateGenesis. -func (mr *MockHasGenesisMockRecorder) ValidateGenesis(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateGenesis", reflect.TypeOf((*MockHasGenesis)(nil).ValidateGenesis), arg0, arg1, arg2) -} - // MockHasABCIGenesis is a mock of HasABCIGenesis interface. type MockHasABCIGenesis struct { ctrl *gomock.Controller @@ -487,45 +361,45 @@ func (m *MockHasABCIGenesis) EXPECT() *MockHasABCIGenesisMockRecorder { } // DefaultGenesis mocks base method. -func (m *MockHasABCIGenesis) DefaultGenesis(arg0 codec.JSONCodec) json.RawMessage { +func (m *MockHasABCIGenesis) DefaultGenesis() json.RawMessage { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DefaultGenesis", arg0) + ret := m.ctrl.Call(m, "DefaultGenesis") ret0, _ := ret[0].(json.RawMessage) return ret0 } // DefaultGenesis indicates an expected call of DefaultGenesis. -func (mr *MockHasABCIGenesisMockRecorder) DefaultGenesis(arg0 interface{}) *gomock.Call { +func (mr *MockHasABCIGenesisMockRecorder) DefaultGenesis() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DefaultGenesis", reflect.TypeOf((*MockHasABCIGenesis)(nil).DefaultGenesis), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DefaultGenesis", reflect.TypeOf((*MockHasABCIGenesis)(nil).DefaultGenesis)) } // ExportGenesis mocks base method. -func (m *MockHasABCIGenesis) ExportGenesis(arg0 context.Context, arg1 codec.JSONCodec) json.RawMessage { +func (m *MockHasABCIGenesis) ExportGenesis(arg0 context.Context) json.RawMessage { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ExportGenesis", arg0, arg1) + ret := m.ctrl.Call(m, "ExportGenesis", arg0) ret0, _ := ret[0].(json.RawMessage) return ret0 } // ExportGenesis indicates an expected call of ExportGenesis. -func (mr *MockHasABCIGenesisMockRecorder) ExportGenesis(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockHasABCIGenesisMockRecorder) ExportGenesis(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExportGenesis", reflect.TypeOf((*MockHasABCIGenesis)(nil).ExportGenesis), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExportGenesis", reflect.TypeOf((*MockHasABCIGenesis)(nil).ExportGenesis), arg0) } // InitGenesis mocks base method. -func (m *MockHasABCIGenesis) InitGenesis(arg0 context.Context, arg1 codec.JSONCodec, arg2 json.RawMessage) []types.ValidatorUpdate { +func (m *MockHasABCIGenesis) InitGenesis(arg0 context.Context, arg1 json.RawMessage) []types.ValidatorUpdate { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "InitGenesis", arg0, arg1, arg2) + ret := m.ctrl.Call(m, "InitGenesis", arg0, arg1) ret0, _ := ret[0].([]types.ValidatorUpdate) return ret0 } // InitGenesis indicates an expected call of InitGenesis. -func (mr *MockHasABCIGenesisMockRecorder) InitGenesis(arg0, arg1, arg2 interface{}) *gomock.Call { +func (mr *MockHasABCIGenesisMockRecorder) InitGenesis(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitGenesis", reflect.TypeOf((*MockHasABCIGenesis)(nil).InitGenesis), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitGenesis", reflect.TypeOf((*MockHasABCIGenesis)(nil).InitGenesis), arg0, arg1) } // Name mocks base method. @@ -543,17 +417,17 @@ func (mr *MockHasABCIGenesisMockRecorder) Name() *gomock.Call { } // ValidateGenesis mocks base method. -func (m *MockHasABCIGenesis) ValidateGenesis(arg0 codec.JSONCodec, arg1 client.TxEncodingConfig, arg2 json.RawMessage) error { +func (m *MockHasABCIGenesis) ValidateGenesis(arg0 json.RawMessage) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ValidateGenesis", arg0, arg1, arg2) + ret := m.ctrl.Call(m, "ValidateGenesis", arg0) ret0, _ := ret[0].(error) return ret0 } // ValidateGenesis indicates an expected call of ValidateGenesis. -func (mr *MockHasABCIGenesisMockRecorder) ValidateGenesis(arg0, arg1, arg2 interface{}) *gomock.Call { +func (mr *MockHasABCIGenesisMockRecorder) ValidateGenesis(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateGenesis", reflect.TypeOf((*MockHasABCIGenesis)(nil).ValidateGenesis), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateGenesis", reflect.TypeOf((*MockHasABCIGenesis)(nil).ValidateGenesis), arg0) } // MockHasInvariants is a mock of HasInvariants interface. @@ -580,7 +454,7 @@ func (m *MockHasInvariants) EXPECT() *MockHasInvariantsMockRecorder { } // RegisterInvariants mocks base method. -func (m *MockHasInvariants) RegisterInvariants(arg0 types1.InvariantRegistry) { +func (m *MockHasInvariants) RegisterInvariants(arg0 types0.InvariantRegistry) { m.ctrl.T.Helper() m.ctrl.Call(m, "RegisterInvariants", arg0) } diff --git a/types/module/core_module.go b/types/module/core_module.go index ae3101043603..7b59b430c019 100644 --- a/types/module/core_module.go +++ b/types/module/core_module.go @@ -43,8 +43,8 @@ type coreAppModuleAdaptor struct { } // DefaultGenesis implements HasGenesis -func (c coreAppModuleAdaptor) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - if mod, ok := c.module.(appmodule.HasGenesis); ok { +func (c coreAppModuleAdaptor) DefaultGenesis() json.RawMessage { + if mod, ok := c.module.(appmodule.HasGenesisAuto); ok { target := genesis.RawJSONTarget{} err := mod.DefaultGenesis(target.Target()) if err != nil { @@ -60,15 +60,19 @@ func (c coreAppModuleAdaptor) DefaultGenesis(cdc codec.JSONCodec) json.RawMessag } if mod, ok := c.module.(HasGenesisBasics); ok { - return mod.DefaultGenesis(cdc) + return mod.DefaultGenesis() + } + + if mod, ok := c.module.(HasGenesis); ok { + return mod.DefaultGenesis() } return nil } // ValidateGenesis implements HasGenesis -func (c coreAppModuleAdaptor) ValidateGenesis(cdc codec.JSONCodec, txConfig client.TxEncodingConfig, bz json.RawMessage) error { - if mod, ok := c.module.(appmodule.HasGenesis); ok { +func (c coreAppModuleAdaptor) ValidateGenesis(bz json.RawMessage) error { + if mod, ok := c.module.(appmodule.HasGenesisAuto); ok { source, err := genesis.SourceFromRawJSON(bz) if err != nil { return err @@ -80,15 +84,19 @@ func (c coreAppModuleAdaptor) ValidateGenesis(cdc codec.JSONCodec, txConfig clie } if mod, ok := c.module.(HasGenesisBasics); ok { - return mod.ValidateGenesis(cdc, txConfig, bz) + return mod.ValidateGenesis(bz) + } + + if mod, ok := c.module.(HasGenesis); ok { + return mod.ValidateGenesis(bz) } return nil } // ExportGenesis implements HasGenesis -func (c coreAppModuleAdaptor) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json.RawMessage { - if module, ok := c.module.(appmodule.HasGenesis); ok { +func (c coreAppModuleAdaptor) ExportGenesis(ctx context.Context) json.RawMessage { + if module, ok := c.module.(appmodule.HasGenesisAuto); ok { ctx := sdk.UnwrapSDKContext(ctx).WithGasMeter(storetypes.NewInfiniteGasMeter()) // avoid race conditions target := genesis.RawJSONTarget{} err := module.ExportGenesis(ctx, target.Target()) @@ -104,16 +112,24 @@ func (c coreAppModuleAdaptor) ExportGenesis(ctx context.Context, cdc codec.JSONC return rawJSON } + if mod, ok := c.module.(HasABCIGenesis); ok { + return mod.ExportGenesis(ctx) + } + if mod, ok := c.module.(HasGenesis); ok { - return mod.ExportGenesis(ctx, cdc) + eg, err := mod.ExportGenesis(ctx) + if err != nil { + panic(err) + } + return eg } return nil } // InitGenesis implements HasGenesis -func (c coreAppModuleAdaptor) InitGenesis(ctx context.Context, cdc codec.JSONCodec, bz json.RawMessage) []abci.ValidatorUpdate { - if module, ok := c.module.(appmodule.HasGenesis); ok { +func (c coreAppModuleAdaptor) InitGenesis(ctx context.Context, bz json.RawMessage) []abci.ValidatorUpdate { + if module, ok := c.module.(appmodule.HasGenesisAuto); ok { // core API genesis source, err := genesis.SourceFromRawJSON(bz) if err != nil { @@ -126,12 +142,16 @@ func (c coreAppModuleAdaptor) InitGenesis(ctx context.Context, cdc codec.JSONCod } } - if mod, ok := c.module.(HasGenesis); ok { - mod.InitGenesis(ctx, cdc, bz) - return nil - } if mod, ok := c.module.(HasABCIGenesis); ok { - return mod.InitGenesis(ctx, cdc, bz) + return mod.InitGenesis(ctx, bz) + } + + if mod, ok := c.module.(HasGenesis); ok { + err := mod.InitGenesis(ctx, bz) + if err != nil { + panic(err) + } + } return nil } diff --git a/types/module/mock_appmodule_test.go b/types/module/mock_appmodule_test.go index 07c9c6389f51..848280147fb1 100644 --- a/types/module/mock_appmodule_test.go +++ b/types/module/mock_appmodule_test.go @@ -2,6 +2,7 @@ package module_test import ( "cosmossdk.io/core/appmodule" + appmodulev2 "cosmossdk.io/core/appmodule/v2" "github.com/cosmos/cosmos-sdk/types/module" ) @@ -11,7 +12,7 @@ import ( type AppModuleWithAllExtensions interface { module.AppModule module.HasServices - module.HasGenesis + appmodulev2.HasGenesis module.HasInvariants module.HasConsensusVersion module.HasABCIEndBlock @@ -32,10 +33,10 @@ type AppModuleWithAllExtensionsABCI interface { // CoreAppModule is solely here for the purpose of generating // mocks to be used in module tests. type CoreAppModule interface { - appmodule.AppModule - appmodule.HasGenesis - appmodule.HasBeginBlocker - appmodule.HasEndBlocker + appmodulev2.AppModule + appmodule.HasGenesisAuto + appmodulev2.HasBeginBlocker + appmodulev2.HasEndBlocker appmodule.HasPrecommit appmodule.HasPrepareCheckState } diff --git a/types/module/module.go b/types/module/module.go index 4aa36f435c6f..9bad87df98a2 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -32,6 +32,7 @@ import ( "golang.org/x/exp/maps" "cosmossdk.io/core/appmodule" + appmodulev2 "cosmossdk.io/core/appmodule/v2" "cosmossdk.io/core/genesis" "cosmossdk.io/core/registry" errorsmod "cosmossdk.io/errors" @@ -45,8 +46,9 @@ import ( // Deprecated: use the embed extension interfaces instead, when needed. type AppModuleBasic interface { + appmodulev2.HasRegisterInterfaces + HasName - HasRegisterInterfaces HasGRPCGateway HasAminoCodec } @@ -55,10 +57,10 @@ type AppModuleBasic interface { // its functionality has been moved to extension interfaces. // Deprecated: use appmodule.AppModule with a combination of extension interfaces interfaces instead. type AppModule interface { - appmodule.AppModule - HasName - HasRegisterInterfaces + + appmodulev2.AppModule + appmodulev2.HasRegisterInterfaces } // HasName allows the module to provide its own name for legacy purposes. @@ -72,8 +74,8 @@ type HasName interface { type HasGenesisBasics interface { HasName - DefaultGenesis(codec.JSONCodec) json.RawMessage - ValidateGenesis(codec.JSONCodec, client.TxEncodingConfig, json.RawMessage) error + DefaultGenesis() json.RawMessage + ValidateGenesis(json.RawMessage) error } // HasAminoCodec is the interface for modules that have amino codec registration. @@ -83,7 +85,7 @@ type HasAminoCodec interface { } // HasRegisterInterfaces is the interface for modules to register their msg types. -type HasRegisterInterfaces appmodule.HasRegisterInterfaces +type HasRegisterInterfaces appmodulev2.HasRegisterInterfaces // HasGRPCGateway is the interface for modules to register their gRPC gateway routes. type HasGRPCGateway interface { @@ -91,17 +93,13 @@ type HasGRPCGateway interface { } // HasGenesis is the extension interface for stateful genesis methods. -type HasGenesis interface { - HasGenesisBasics - InitGenesis(context.Context, codec.JSONCodec, json.RawMessage) - ExportGenesis(context.Context, codec.JSONCodec) json.RawMessage -} +type HasGenesis = appmodulev2.HasGenesis // HasABCIGenesis is the extension interface for stateful genesis methods which returns validator updates. type HasABCIGenesis interface { HasGenesisBasics - InitGenesis(context.Context, codec.JSONCodec, json.RawMessage) []abci.ValidatorUpdate - ExportGenesis(context.Context, codec.JSONCodec) json.RawMessage + InitGenesis(context.Context, json.RawMessage) []abci.ValidatorUpdate + ExportGenesis(context.Context) json.RawMessage } // HasInvariants is the interface for registering invariants. @@ -207,7 +205,7 @@ func NewManagerFromMap(moduleMap map[string]appmodule.AppModule) *Manager { func (m *Manager) SetOrderInitGenesis(moduleNames ...string) { m.assertNoForgottenModules("SetOrderInitGenesis", moduleNames, func(moduleName string) bool { module := m.Modules[moduleName] - if _, hasGenesis := module.(appmodule.HasGenesis); hasGenesis { + if _, hasGenesis := module.(appmodule.HasGenesisAuto); hasGenesis { return !hasGenesis } @@ -225,7 +223,7 @@ func (m *Manager) SetOrderInitGenesis(moduleNames ...string) { func (m *Manager) SetOrderExportGenesis(moduleNames ...string) { m.assertNoForgottenModules("SetOrderExportGenesis", moduleNames, func(moduleName string) bool { module := m.Modules[moduleName] - if _, hasGenesis := module.(appmodule.HasGenesis); hasGenesis { + if _, hasGenesis := module.(appmodule.HasGenesisAuto); hasGenesis { return !hasGenesis } @@ -324,11 +322,11 @@ func (m *Manager) RegisterInterfaces(registry registry.LegacyRegistry) { } // DefaultGenesis provides default genesis information for all modules -func (m *Manager) DefaultGenesis(cdc codec.JSONCodec) map[string]json.RawMessage { +func (m *Manager) DefaultGenesis() map[string]json.RawMessage { genesisData := make(map[string]json.RawMessage) for _, b := range m.Modules { if mod, ok := b.(HasGenesisBasics); ok { - genesisData[mod.Name()] = mod.DefaultGenesis(cdc) + genesisData[mod.Name()] = mod.DefaultGenesis() } else if mod, ok := b.(HasName); ok { genesisData[mod.Name()] = []byte("{}") } @@ -338,11 +336,11 @@ func (m *Manager) DefaultGenesis(cdc codec.JSONCodec) map[string]json.RawMessage } // ValidateGenesis performs genesis state validation for all modules -func (m *Manager) ValidateGenesis(cdc codec.JSONCodec, txEncCfg client.TxEncodingConfig, genesisData map[string]json.RawMessage) error { +func (m *Manager) ValidateGenesis(genesisData map[string]json.RawMessage) error { for _, b := range m.Modules { // first check if the module is an adapted Core API Module if mod, ok := b.(HasGenesisBasics); ok { - if err := mod.ValidateGenesis(cdc, txEncCfg, genesisData[mod.Name()]); err != nil { + if err := mod.ValidateGenesis(genesisData[mod.Name()]); err != nil { return err } } @@ -427,7 +425,7 @@ func (m *Manager) RegisterServices(cfg Configurator) error { // InitGenesis performs init genesis functionality for modules. Exactly one // module must return a non-empty validator set update to correctly initialize // the chain. -func (m *Manager) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, genesisData map[string]json.RawMessage) (*abci.ResponseInitChain, error) { +func (m *Manager) InitGenesis(ctx sdk.Context, _ codec.JSONCodec, genesisData map[string]json.RawMessage) (*abci.ResponseInitChain, error) { var validatorUpdates []abci.ValidatorUpdate ctx.Logger().Info("initializing blockchain state from genesis.json") for _, moduleName := range m.OrderInitGenesis { @@ -437,7 +435,7 @@ func (m *Manager) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, genesisData mod := m.Modules[moduleName] // we might get an adapted module, a native core API module or a legacy module - if module, ok := mod.(appmodule.HasGenesis); ok { + if module, ok := mod.(appmodule.HasGenesisAuto); ok { ctx.Logger().Debug("running initialization for module", "module", moduleName) // core API genesis source, err := genesis.SourceFromRawJSON(genesisData[moduleName]) @@ -451,10 +449,12 @@ func (m *Manager) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, genesisData } } else if module, ok := mod.(HasGenesis); ok { ctx.Logger().Debug("running initialization for module", "module", moduleName) - module.InitGenesis(ctx, cdc, genesisData[moduleName]) + if err := module.InitGenesis(ctx, genesisData[moduleName]); err != nil { + return &abci.ResponseInitChain{}, err + } } else if module, ok := mod.(HasABCIGenesis); ok { ctx.Logger().Debug("running initialization for module", "module", moduleName) - moduleValUpdates := module.InitGenesis(ctx, cdc, genesisData[moduleName]) + moduleValUpdates := module.InitGenesis(ctx, genesisData[moduleName]) // use these validator updates if provided, the module manager assumes // only one module will update the validator set @@ -478,12 +478,12 @@ func (m *Manager) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, genesisData } // ExportGenesis performs export genesis functionality for modules -func (m *Manager) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) (map[string]json.RawMessage, error) { - return m.ExportGenesisForModules(ctx, cdc, []string{}) +func (m *Manager) ExportGenesis(ctx sdk.Context) (map[string]json.RawMessage, error) { + return m.ExportGenesisForModules(ctx, []string{}) } // ExportGenesisForModules performs export genesis functionality for modules -func (m *Manager) ExportGenesisForModules(ctx sdk.Context, cdc codec.JSONCodec, modulesToExport []string) (map[string]json.RawMessage, error) { +func (m *Manager) ExportGenesisForModules(ctx sdk.Context, modulesToExport []string) (map[string]json.RawMessage, error) { if len(modulesToExport) == 0 { modulesToExport = m.OrderExportGenesis } @@ -500,10 +500,10 @@ func (m *Manager) ExportGenesisForModules(ctx sdk.Context, cdc codec.JSONCodec, channels := make(map[string]chan genesisResult) for _, moduleName := range modulesToExport { mod := m.Modules[moduleName] - if module, ok := mod.(appmodule.HasGenesis); ok { + if module, ok := mod.(appmodule.HasGenesisAuto); ok { // core API genesis channels[moduleName] = make(chan genesisResult) - go func(module appmodule.HasGenesis, ch chan genesisResult) { + go func(module appmodule.HasGenesisAuto, ch chan genesisResult) { ctx := ctx.WithGasMeter(storetypes.NewInfiniteGasMeter()) // avoid race conditions target := genesis.RawJSONTarget{} err := module.ExportGenesis(ctx, target.Target()) @@ -524,13 +524,18 @@ func (m *Manager) ExportGenesisForModules(ctx sdk.Context, cdc codec.JSONCodec, channels[moduleName] = make(chan genesisResult) go func(module HasGenesis, ch chan genesisResult) { ctx := ctx.WithGasMeter(storetypes.NewInfiniteGasMeter()) // avoid race conditions - ch <- genesisResult{module.ExportGenesis(ctx, cdc), nil} + jm, err := module.ExportGenesis(ctx) + if err != nil { + ch <- genesisResult{nil, err} + return + } + ch <- genesisResult{jm, nil} }(module, channels[moduleName]) } else if module, ok := mod.(HasABCIGenesis); ok { channels[moduleName] = make(chan genesisResult) go func(module HasABCIGenesis, ch chan genesisResult) { ctx := ctx.WithGasMeter(storetypes.NewInfiniteGasMeter()) // avoid race conditions - ch <- genesisResult{module.ExportGenesis(ctx, cdc), nil} + ch <- genesisResult{module.ExportGenesis(ctx), nil} }(module, channels[moduleName]) } } @@ -678,10 +683,12 @@ func (m Manager) RunMigrations(ctx context.Context, cfg Configurator, fromVM Ver } else { sdkCtx.Logger().Info(fmt.Sprintf("adding a new module: %s", moduleName)) if module, ok := m.Modules[moduleName].(HasGenesis); ok { - module.InitGenesis(sdkCtx, c.cdc, module.DefaultGenesis(c.cdc)) + if err := module.InitGenesis(sdkCtx, module.DefaultGenesis()); err != nil { + return nil, err + } } if module, ok := m.Modules[moduleName].(HasABCIGenesis); ok { - moduleValUpdates := module.InitGenesis(sdkCtx, c.cdc, module.DefaultGenesis(c.cdc)) + moduleValUpdates := module.InitGenesis(sdkCtx, module.DefaultGenesis()) // The module manager assumes only one module will update the // validator set, and it can't be a new module. if len(moduleValUpdates) > 0 { diff --git a/types/module/module_test.go b/types/module/module_test.go index 4853ca86e7dc..373d9cca68ca 100644 --- a/types/module/module_test.go +++ b/types/module/module_test.go @@ -177,7 +177,7 @@ func TestManager_InitGenesis(t *testing.T) { genesisData := map[string]json.RawMessage{"module1": json.RawMessage(`{"key": "value"}`)} // this should panic since the validator set is empty even after init genesis - mockAppModule1.EXPECT().InitGenesis(gomock.Eq(ctx), gomock.Eq(cdc), gomock.Eq(genesisData["module1"])).Times(1) + mockAppModule1.EXPECT().InitGenesis(gomock.Eq(ctx), gomock.Eq(genesisData["module1"])).Times(1) _, err := mm.InitGenesis(ctx, cdc, genesisData) require.ErrorContains(t, err, "validator set is empty after InitGenesis") @@ -194,16 +194,16 @@ func TestManager_InitGenesis(t *testing.T) { mockAppModuleABCI2.EXPECT().Name().Times(2).Return("module2") mmABCI := module.NewManager(mockAppModuleABCI1, mockAppModuleABCI2) // panic because more than one module returns validator set updates - mockAppModuleABCI1.EXPECT().InitGenesis(gomock.Eq(ctx), gomock.Eq(cdc), gomock.Eq(genesisData["module1"])).Times(1).Return([]abci.ValidatorUpdate{{}}) - mockAppModuleABCI2.EXPECT().InitGenesis(gomock.Eq(ctx), gomock.Eq(cdc), gomock.Eq(genesisData["module2"])).Times(1).Return([]abci.ValidatorUpdate{{}}) + mockAppModuleABCI1.EXPECT().InitGenesis(gomock.Eq(ctx), gomock.Eq(genesisData["module1"])).Times(1).Return([]abci.ValidatorUpdate{{}}) + mockAppModuleABCI2.EXPECT().InitGenesis(gomock.Eq(ctx), gomock.Eq(genesisData["module2"])).Times(1).Return([]abci.ValidatorUpdate{{}}) _, err = mmABCI.InitGenesis(ctx, cdc, genesisData) require.ErrorContains(t, err, "validator InitGenesis updates already set by a previous module") // happy path mm2 := module.NewManager(mockAppModuleABCI1, mockAppModule2, module.CoreAppModuleAdaptor("module3", mockAppModule3)) - mockAppModuleABCI1.EXPECT().InitGenesis(gomock.Eq(ctx), gomock.Eq(cdc), gomock.Eq(genesisData["module1"])).Times(1).Return([]abci.ValidatorUpdate{{}}) - mockAppModule2.EXPECT().InitGenesis(gomock.Eq(ctx), gomock.Eq(cdc), gomock.Eq(genesisData["module2"])).Times(1) + mockAppModuleABCI1.EXPECT().InitGenesis(gomock.Eq(ctx), gomock.Eq(genesisData["module1"])).Times(1).Return([]abci.ValidatorUpdate{{}}) + mockAppModule2.EXPECT().InitGenesis(gomock.Eq(ctx), gomock.Eq(genesisData["module2"])).Times(1) mockAppModule3.EXPECT().InitGenesis(gomock.Eq(ctx), gomock.Any()).Times(1).Return(nil) _, err = mm2.InitGenesis(ctx, cdc, genesisData) require.NoError(t, err) @@ -223,10 +223,8 @@ func TestManager_ExportGenesis(t *testing.T) { require.Equal(t, 3, len(mm.Modules)) ctx := sdk.NewContext(nil, false, log.NewNopLogger()) - interfaceRegistry := types.NewInterfaceRegistry() - cdc := codec.NewProtoCodec(interfaceRegistry) - mockAppModule1.EXPECT().ExportGenesis(gomock.Eq(ctx), gomock.Eq(cdc)).AnyTimes().Return(json.RawMessage(`{"key1": "value1"}`)) - mockAppModule2.EXPECT().ExportGenesis(gomock.Eq(ctx), gomock.Eq(cdc)).AnyTimes().Return(json.RawMessage(`{"key2": "value2"}`)) + mockAppModule1.EXPECT().ExportGenesis(gomock.Eq(ctx)).AnyTimes().Return(json.RawMessage(`{"key1": "value1"}`), nil) + mockAppModule2.EXPECT().ExportGenesis(gomock.Eq(ctx)).AnyTimes().Return(json.RawMessage(`{"key2": "value2"}`), nil) want := map[string]json.RawMessage{ "module1": json.RawMessage(`{"key1": "value1"}`), @@ -236,23 +234,23 @@ func TestManager_ExportGenesis(t *testing.T) { }`), } - res, err := mm.ExportGenesis(ctx, cdc) + res, err := mm.ExportGenesis(ctx) require.NoError(t, err) require.Equal(t, want, res) - res, err = mm.ExportGenesisForModules(ctx, cdc, []string{}) + res, err = mm.ExportGenesisForModules(ctx, []string{}) require.NoError(t, err) require.Equal(t, want, res) - res, err = mm.ExportGenesisForModules(ctx, cdc, []string{"module1"}) + res, err = mm.ExportGenesisForModules(ctx, []string{"module1"}) require.NoError(t, err) require.Equal(t, map[string]json.RawMessage{"module1": json.RawMessage(`{"key1": "value1"}`)}, res) - res, err = mm.ExportGenesisForModules(ctx, cdc, []string{"module2"}) + res, err = mm.ExportGenesisForModules(ctx, []string{"module2"}) require.NoError(t, err) require.NotEqual(t, map[string]json.RawMessage{"module1": json.RawMessage(`{"key1": "value1"}`)}, res) - _, err = mm.ExportGenesisForModules(ctx, cdc, []string{"module1", "modulefoo"}) + _, err = mm.ExportGenesisForModules(ctx, []string{"module1", "modulefoo"}) require.Error(t, err) } @@ -333,8 +331,6 @@ func TestCoreAPIManager_ExportGenesis(t *testing.T) { require.Equal(t, 2, len(mm.Modules)) ctx := sdk.NewContext(nil, false, log.NewNopLogger()) - interfaceRegistry := types.NewInterfaceRegistry() - cdc := codec.NewProtoCodec(interfaceRegistry) want := map[string]json.RawMessage{ "module1": json.RawMessage(`{ "someField": "someKey" @@ -344,23 +340,23 @@ func TestCoreAPIManager_ExportGenesis(t *testing.T) { }`), } - res, err := mm.ExportGenesis(ctx, cdc) + res, err := mm.ExportGenesis(ctx) require.NoError(t, err) require.Equal(t, want, res) - res, err = mm.ExportGenesisForModules(ctx, cdc, []string{}) + res, err = mm.ExportGenesisForModules(ctx, []string{}) require.NoError(t, err) require.Equal(t, want, res) - res, err = mm.ExportGenesisForModules(ctx, cdc, []string{"module1"}) + res, err = mm.ExportGenesisForModules(ctx, []string{"module1"}) require.NoError(t, err) require.Equal(t, map[string]json.RawMessage{"module1": want["module1"]}, res) - res, err = mm.ExportGenesisForModules(ctx, cdc, []string{"module2"}) + res, err = mm.ExportGenesisForModules(ctx, []string{"module2"}) require.NoError(t, err) require.NotEqual(t, map[string]json.RawMessage{"module1": want["module1"]}, res) - _, err = mm.ExportGenesisForModules(ctx, cdc, []string{"module1", "modulefoo"}) + _, err = mm.ExportGenesisForModules(ctx, []string{"module1", "modulefoo"}) require.Error(t, err) } @@ -594,7 +590,7 @@ func (MockCoreAppModule) ExportGenesis(ctx context.Context, target appmodule.Gen } var ( - _ appmodule.AppModule = MockCoreAppModule{} - _ appmodule.HasGenesis = MockCoreAppModule{} - _ appmodule.HasServices = MockCoreAppModule{} + _ appmodule.AppModule = MockCoreAppModule{} + _ appmodule.HasGenesisAuto = MockCoreAppModule{} + _ appmodule.HasServices = MockCoreAppModule{} ) diff --git a/x/accounts/module.go b/x/accounts/module.go index b60ebafb57fa..71a16cff195a 100644 --- a/x/accounts/module.go +++ b/x/accounts/module.go @@ -8,11 +8,11 @@ import ( "google.golang.org/grpc" "cosmossdk.io/core/appmodule" + appmodulev2 "cosmossdk.io/core/appmodule/v2" "cosmossdk.io/core/registry" "cosmossdk.io/x/accounts/cli" v1 "cosmossdk.io/x/accounts/v1" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/types/address" "github.com/cosmos/cosmos-sdk/types/module" @@ -36,16 +36,17 @@ var ( _ appmodule.HasServices = AppModule{} _ module.HasName = AppModule{} - _ module.HasGenesis = AppModule{} + _ appmodulev2.HasGenesis = AppModule{} _ module.HasConsensusVersion = AppModule{} ) -func NewAppModule(k Keeper) AppModule { - return AppModule{k: k} +func NewAppModule(cdc codec.Codec, k Keeper) AppModule { + return AppModule{k: k, cdc: cdc} } type AppModule struct { - k Keeper + cdc codec.Codec + k Keeper } func (m AppModule) IsAppModule() {} @@ -67,34 +68,37 @@ func (m AppModule) RegisterServices(registar grpc.ServiceRegistrar) error { // App module genesis -func (AppModule) DefaultGenesis(jsonCodec codec.JSONCodec) json.RawMessage { - return jsonCodec.MustMarshalJSON(&v1.GenesisState{}) +func (am AppModule) DefaultGenesis() json.RawMessage { + return am.cdc.MustMarshalJSON(&v1.GenesisState{}) } -func (AppModule) ValidateGenesis(jsonCodec codec.JSONCodec, config client.TxEncodingConfig, message json.RawMessage) error { +func (am AppModule) ValidateGenesis(message json.RawMessage) error { gs := &v1.GenesisState{} - if err := jsonCodec.UnmarshalJSON(message, gs); err != nil { + if err := am.cdc.UnmarshalJSON(message, gs); err != nil { return err } // Add validation logic for gs here return nil } -func (m AppModule) InitGenesis(ctx context.Context, jsonCodec codec.JSONCodec, message json.RawMessage) { +func (am AppModule) InitGenesis(ctx context.Context, message json.RawMessage) error { gs := &v1.GenesisState{} - jsonCodec.MustUnmarshalJSON(message, gs) - err := m.k.ImportState(ctx, gs) + if err := am.cdc.UnmarshalJSON(message, gs); err != nil { + return err + } + err := am.k.ImportState(ctx, gs) if err != nil { - panic(err) + return err } + return nil } -func (m AppModule) ExportGenesis(ctx context.Context, jsonCodec codec.JSONCodec) json.RawMessage { - gs, err := m.k.ExportState(ctx) +func (am AppModule) ExportGenesis(ctx context.Context) (json.RawMessage, error) { + gs, err := am.k.ExportState(ctx) if err != nil { - panic(err) + return nil, err } - return jsonCodec.MustMarshalJSON(gs) + return am.cdc.MarshalJSON(gs) } func (AppModule) GetTxCmd() *cobra.Command { diff --git a/x/auth/module.go b/x/auth/module.go index 2a94ab4bad53..d92176043dfb 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -9,6 +9,7 @@ import ( "google.golang.org/grpc" "cosmossdk.io/core/appmodule" + appmodulev2 "cosmossdk.io/core/appmodule/v2" "cosmossdk.io/core/registry" "cosmossdk.io/x/auth/keeper" "cosmossdk.io/x/auth/simulation" @@ -29,7 +30,7 @@ const ( var ( _ module.AppModuleSimulation = AppModule{} _ module.HasName = AppModule{} - _ module.HasGenesis = AppModule{} + _ appmodulev2.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasServices = AppModule{} @@ -40,6 +41,7 @@ var ( type AppModule struct { accountKeeper keeper.AccountKeeper randGenAccountsFn types.RandomGenesisAccountsFn + cdc codec.Codec } // IsAppModule implements the appmodule.AppModule interface. @@ -50,6 +52,7 @@ func NewAppModule(cdc codec.Codec, accountKeeper keeper.AccountKeeper, randGenAc return AppModule{ accountKeeper: accountKeeper, randGenAccountsFn: randGenAccountsFn, + cdc: cdc, } } @@ -104,14 +107,14 @@ func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { } // DefaultGenesis returns default genesis state as raw bytes for the auth module. -func (AppModule) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) +func (am AppModule) DefaultGenesis() json.RawMessage { + return am.cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the auth module. -func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { +func (am AppModule) ValidateGenesis(bz json.RawMessage) error { var data types.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { + if err := am.cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) } @@ -119,23 +122,22 @@ func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingCo } // InitGenesis performs genesis initialization for the auth module. -func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { +func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) error { var genesisState types.GenesisState - cdc.MustUnmarshalJSON(data, &genesisState) - err := am.accountKeeper.InitGenesis(ctx, genesisState) - if err != nil { - panic(err) + if err := am.cdc.UnmarshalJSON(data, &genesisState); err != nil { + return err } + return am.accountKeeper.InitGenesis(ctx, genesisState) } // ExportGenesis returns the exported genesis state as raw bytes for the auth // module. -func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json.RawMessage { +func (am AppModule) ExportGenesis(ctx context.Context) (json.RawMessage, error) { gs, err := am.accountKeeper.ExportGenesis(ctx) if err != nil { - panic(err) + return nil, err } - return cdc.MustMarshalJSON(gs) + return am.cdc.MarshalJSON(gs) } // ConsensusVersion implements HasConsensusVersion diff --git a/x/authz/keeper/genesis.go b/x/authz/keeper/genesis.go index d7f28d1b07c3..e014f5265748 100644 --- a/x/authz/keeper/genesis.go +++ b/x/authz/keeper/genesis.go @@ -9,7 +9,7 @@ import ( ) // InitGenesis initializes new authz genesis -func (k Keeper) InitGenesis(ctx context.Context, data *authz.GenesisState) { +func (k Keeper) InitGenesis(ctx context.Context, data *authz.GenesisState) error { now := k.environment.HeaderService.GetHeaderInfo(ctx).Time for _, entry := range data.Authorization { // ignore expired authorizations @@ -19,11 +19,11 @@ func (k Keeper) InitGenesis(ctx context.Context, data *authz.GenesisState) { grantee, err := k.authKeeper.AddressCodec().StringToBytes(entry.Grantee) if err != nil { - panic(err) + return err } granter, err := k.authKeeper.AddressCodec().StringToBytes(entry.Granter) if err != nil { - panic(err) + return err } a, ok := entry.Authorization.GetCachedValue().(authz.Authorization) @@ -33,9 +33,10 @@ func (k Keeper) InitGenesis(ctx context.Context, data *authz.GenesisState) { err = k.SaveGrant(ctx, grantee, granter, a, entry.Expiration) if err != nil { - panic(err) + return err } } + return nil } // ExportGenesis returns a GenesisState for a given context. diff --git a/x/authz/keeper/genesis_test.go b/x/authz/keeper/genesis_test.go index 78c15797d297..d913c3bef304 100644 --- a/x/authz/keeper/genesis_test.go +++ b/x/authz/keeper/genesis_test.go @@ -83,7 +83,6 @@ func (suite *GenesisTestSuite) TestImportExportGenesis() { suite.Require().NoError(err) genesis := suite.keeper.ExportGenesis(suite.ctx) - // TODO, recheck! // Clear keeper err = suite.keeper.DeleteGrant(suite.ctx, granteeAddr, granterAddr, grant.MsgTypeURL()) suite.Require().NoError(err) @@ -91,7 +90,8 @@ func (suite *GenesisTestSuite) TestImportExportGenesis() { suite.Require().NotEqual(genesis, newGenesis) suite.Require().Empty(newGenesis) - suite.keeper.InitGenesis(suite.ctx, genesis) + err = suite.keeper.InitGenesis(suite.ctx, genesis) + suite.Require().NoError(err) newGenesis = suite.keeper.ExportGenesis(suite.ctx) suite.Require().Equal(genesis, newGenesis) } diff --git a/x/authz/module/module.go b/x/authz/module/module.go index d11db1bcad8f..65a9d00a97e5 100644 --- a/x/authz/module/module.go +++ b/x/authz/module/module.go @@ -10,6 +10,7 @@ import ( "google.golang.org/grpc" "cosmossdk.io/core/appmodule" + appmodulev2 "cosmossdk.io/core/appmodule/v2" "cosmossdk.io/core/registry" "cosmossdk.io/errors" "cosmossdk.io/x/authz" @@ -32,7 +33,7 @@ var ( _ module.HasGRPCGateway = AppModule{} _ appmodule.HasRegisterInterfaces = AppModule{} _ module.AppModuleSimulation = AppModule{} - _ module.HasGenesis = AppModule{} + _ appmodulev2.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasBeginBlocker = AppModule{} @@ -109,14 +110,14 @@ func (AppModule) GetTxCmd() *cobra.Command { } // DefaultGenesis returns default genesis state as raw bytes for the authz module. -func (AppModule) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(authz.DefaultGenesisState()) +func (am AppModule) DefaultGenesis() json.RawMessage { + return am.cdc.MustMarshalJSON(authz.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the authz module. -func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { +func (am AppModule) ValidateGenesis(bz json.RawMessage) error { var data authz.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { + if err := am.cdc.UnmarshalJSON(bz, &data); err != nil { return errors.Wrapf(err, "failed to unmarshal %s genesis state", authz.ModuleName) } @@ -124,16 +125,18 @@ func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEncodin } // InitGenesis performs genesis initialization for the authz module. -func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { +func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) error { var genesisState authz.GenesisState - cdc.MustUnmarshalJSON(data, &genesisState) - am.keeper.InitGenesis(ctx, &genesisState) + if err := am.cdc.UnmarshalJSON(data, &genesisState); err != nil { + return err + } + return am.keeper.InitGenesis(ctx, &genesisState) } // ExportGenesis returns the exported genesis state as raw bytes for the authz module. -func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json.RawMessage { +func (am AppModule) ExportGenesis(ctx context.Context) (json.RawMessage, error) { gs := am.keeper.ExportGenesis(ctx) - return cdc.MustMarshalJSON(gs) + return am.cdc.MarshalJSON(gs) } // ConsensusVersion implements HasConsensusVersion. diff --git a/x/bank/CHANGELOG.md b/x/bank/CHANGELOG.md index 8a03515679fe..fc76c3c85efd 100644 --- a/x/bank/CHANGELOG.md +++ b/x/bank/CHANGELOG.md @@ -25,10 +25,6 @@ Ref: https://keepachangelog.com/en/1.0.0/ ## [Unreleased] -### Consens Breaking Changes - -* [#19188](https://github.com/cosmos/cosmos-sdk/pull/19188) Remove creation of `BaseAccount` when sending a message to an account that does not exist - ### Features * [#17569](https://github.com/cosmos/cosmos-sdk/pull/17569) Introduce a new message type, `MsgBurn`, to burn coins. @@ -41,5 +37,8 @@ Ref: https://keepachangelog.com/en/1.0.0/ * [#17569](https://github.com/cosmos/cosmos-sdk/pull/17569) `BurnCoins` takes an address instead of a module name * [#19477](https://github.com/cosmos/cosmos-sdk/pull/19477) `appmodule.Environment` is passed to bank `NewKeeper` +* [#19627](https://github.com/cosmos/cosmos-sdk/pull/19627) The genesis api has been updated to match `appmodule.HasGenesis`. -### Bug Fixes +### Consensus Breaking Changes + +* [#19188](https://github.com/cosmos/cosmos-sdk/pull/19188) Remove creation of `BaseAccount` when sending a message to an account that does not exist diff --git a/x/bank/keeper/genesis.go b/x/bank/keeper/genesis.go index 150f40389666..61a0729becab 100644 --- a/x/bank/keeper/genesis.go +++ b/x/bank/keeper/genesis.go @@ -12,9 +12,9 @@ import ( ) // InitGenesis initializes the bank module's state from a given genesis state. -func (k BaseKeeper) InitGenesis(ctx context.Context, genState *types.GenesisState) { +func (k BaseKeeper) InitGenesis(ctx context.Context, genState *types.GenesisState) error { if err := k.SetParams(ctx, genState.Params); err != nil { - panic(err) + return err } for _, se := range genState.GetAllSendEnabled() { @@ -28,13 +28,13 @@ func (k BaseKeeper) InitGenesis(ctx context.Context, genState *types.GenesisStat addr := balance.GetAddress() bz, err := k.ak.AddressCodec().StringToBytes(addr) if err != nil { - panic(err) + return err } for _, coin := range balance.Coins { err := k.Balances.Set(ctx, collections.Join(sdk.AccAddress(bz), coin.Denom), coin.Amount) if err != nil { - panic(err) + return err } } @@ -43,7 +43,7 @@ func (k BaseKeeper) InitGenesis(ctx context.Context, genState *types.GenesisStat totalSupply := totalSupplyMap.ToCoins() if !genState.Supply.Empty() && !genState.Supply.Equal(totalSupply) { - panic(fmt.Errorf("genesis supply is incorrect, expected %v, got %v", genState.Supply, totalSupply)) + return fmt.Errorf("genesis supply is incorrect, expected %v, got %v", genState.Supply, totalSupply) } for _, supply := range totalSupply { @@ -53,6 +53,7 @@ func (k BaseKeeper) InitGenesis(ctx context.Context, genState *types.GenesisStat for _, meta := range genState.DenomMetadata { k.SetDenomMetaData(ctx, meta) } + return nil } // ExportGenesis returns the bank module's genesis state. diff --git a/x/bank/keeper/genesis_test.go b/x/bank/keeper/genesis_test.go index 85f982c8465e..8798c51d5044 100644 --- a/x/bank/keeper/genesis_test.go +++ b/x/bank/keeper/genesis_test.go @@ -67,7 +67,7 @@ func (suite *KeeperTestSuite) TestInitGenesis() { g := types.DefaultGenesisState() g.DenomMetadata = []types.Metadata{m} bk := suite.bankKeeper - bk.InitGenesis(suite.ctx, g) + suite.Require().NoError(bk.InitGenesis(suite.ctx, g)) m2, found := bk.GetDenomMetaData(suite.ctx, m.Base) suite.Require().True(found) @@ -88,36 +88,35 @@ func (suite *KeeperTestSuite) TestTotalSupply() { suite.Require().NoError(err) testcases := []struct { - name string - genesis *types.GenesisState - expSupply sdk.Coins - expPanic bool - expPanicMsg string + name string + genesis *types.GenesisState + expSupply sdk.Coins + expErrMsg string }{ { "calculation NOT matching genesis Supply field", types.NewGenesisState(defaultGenesis.Params, balances, sdk.NewCoins(sdk.NewCoin("wrongcoin", sdkmath.NewInt(1))), defaultGenesis.DenomMetadata, defaultGenesis.SendEnabled), - nil, true, "genesis supply is incorrect, expected 1wrongcoin, got 21barcoin,11foocoin", + nil, "genesis supply is incorrect, expected 1wrongcoin, got 21barcoin,11foocoin", }, { "calculation matches genesis Supply field", types.NewGenesisState(defaultGenesis.Params, balances, totalSupply, defaultGenesis.DenomMetadata, defaultGenesis.SendEnabled), - totalSupply, false, "", + totalSupply, "", }, { "calculation is correct, empty genesis Supply field", types.NewGenesisState(defaultGenesis.Params, balances, nil, defaultGenesis.DenomMetadata, defaultGenesis.SendEnabled), - totalSupply, false, "", + totalSupply, "", }, } for _, tc := range testcases { tc := tc suite.Run(tc.name, func() { - if tc.expPanic { - suite.PanicsWithError(tc.expPanicMsg, func() { suite.bankKeeper.InitGenesis(suite.ctx, tc.genesis) }) + if tc.expErrMsg != "" { + suite.Require().ErrorContains(suite.bankKeeper.InitGenesis(suite.ctx, tc.genesis), tc.expErrMsg) } else { - suite.bankKeeper.InitGenesis(suite.ctx, tc.genesis) + suite.Require().NoError(suite.bankKeeper.InitGenesis(suite.ctx, tc.genesis)) totalSupply, _, err := suite.bankKeeper.GetPaginatedTotalSupply(suite.ctx, &query.PageRequest{Limit: query.PaginationMaxLimit}) suite.Require().NoError(err) diff --git a/x/bank/keeper/keeper.go b/x/bank/keeper/keeper.go index e52ae355e61f..e4d76312a419 100644 --- a/x/bank/keeper/keeper.go +++ b/x/bank/keeper/keeper.go @@ -26,7 +26,7 @@ type Keeper interface { SendKeeper WithMintCoinsRestriction(types.MintingRestrictionFn) BaseKeeper - InitGenesis(context.Context, *types.GenesisState) + InitGenesis(context.Context, *types.GenesisState) error ExportGenesis(context.Context) *types.GenesisState GetSupply(ctx context.Context, denom string) sdk.Coin diff --git a/x/bank/module.go b/x/bank/module.go index 184996dd82e4..cee6253cd31a 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -4,13 +4,13 @@ import ( "context" "encoding/json" "fmt" - "time" gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" "google.golang.org/grpc" "cosmossdk.io/core/appmodule" + appmodulev2 "cosmossdk.io/core/appmodule/v2" "cosmossdk.io/core/registry" "cosmossdk.io/x/bank/client/cli" "cosmossdk.io/x/bank/keeper" @@ -19,7 +19,6 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -34,7 +33,7 @@ var ( _ module.HasGRPCGateway = AppModule{} _ appmodule.HasRegisterInterfaces = AppModule{} _ module.AppModuleSimulation = AppModule{} - _ module.HasGenesis = AppModule{} + _ appmodulev2.HasGenesis = AppModule{} _ module.HasInvariants = AppModule{} _ appmodule.AppModule = AppModule{} @@ -119,14 +118,14 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { } // DefaultGenesis returns default genesis state as raw bytes for the bank module. -func (AppModule) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) +func (am AppModule) DefaultGenesis() json.RawMessage { + return am.cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the bank module. -func (AppModule) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error { +func (am AppModule) ValidateGenesis(bz json.RawMessage) error { var data types.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { + if err := am.cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) } @@ -134,20 +133,20 @@ func (AppModule) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingConfig, } // InitGenesis performs genesis initialization for the bank module. -func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { - start := time.Now() +func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) error { var genesisState types.GenesisState - cdc.MustUnmarshalJSON(data, &genesisState) - telemetry.MeasureSince(start, "InitGenesis", "crisis", "unmarshal") + if err := am.cdc.UnmarshalJSON(data, &genesisState); err != nil { + return err + } - am.keeper.InitGenesis(ctx, &genesisState) + return am.keeper.InitGenesis(ctx, &genesisState) } // ExportGenesis returns the exported genesis state as raw bytes for the bank // module. -func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json.RawMessage { +func (am AppModule) ExportGenesis(ctx context.Context) (json.RawMessage, error) { gs := am.keeper.ExportGenesis(ctx) - return cdc.MustMarshalJSON(gs) + return am.cdc.MarshalJSON(gs) } // ConsensusVersion implements HasConsensusVersion diff --git a/x/circuit/keeper/genesis.go b/x/circuit/keeper/genesis.go index d6747d442908..01407852da94 100644 --- a/x/circuit/keeper/genesis.go +++ b/x/circuit/keeper/genesis.go @@ -6,13 +6,13 @@ import ( "cosmossdk.io/x/circuit/types" ) -func (k *Keeper) ExportGenesis(ctx context.Context) (data *types.GenesisState) { +func (k *Keeper) ExportGenesis(ctx context.Context) (data *types.GenesisState, err error) { var ( permissions []*types.GenesisAccountPermissions disabledMsgs []string ) - err := k.Permissions.Walk(ctx, nil, func(address []byte, perm types.Permissions) (stop bool, err error) { + err = k.Permissions.Walk(ctx, nil, func(address []byte, perm types.Permissions) (stop bool, err error) { add, err := k.addressCodec.BytesToString(address) if err != nil { return true, err @@ -26,7 +26,7 @@ func (k *Keeper) ExportGenesis(ctx context.Context) (data *types.GenesisState) { return false, nil }) if err != nil { - panic(err) + return nil, err } err = k.DisableList.Walk(ctx, nil, func(msgUrl string) (stop bool, err error) { @@ -34,32 +34,34 @@ func (k *Keeper) ExportGenesis(ctx context.Context) (data *types.GenesisState) { return false, nil }) if err != nil { - panic(err) + return nil, err } return &types.GenesisState{ AccountPermissions: permissions, DisabledTypeUrls: disabledMsgs, - } + }, nil } // InitGenesis initializes the circuit module's state from a given genesis state. -func (k *Keeper) InitGenesis(ctx context.Context, genState *types.GenesisState) { +func (k *Keeper) InitGenesis(ctx context.Context, genState *types.GenesisState) error { for _, accounts := range genState.AccountPermissions { add, err := k.addressCodec.StringToBytes(accounts.Address) if err != nil { - panic(err) + return err } // Set the permissions for the account if err := k.Permissions.Set(ctx, add, *accounts.Permissions); err != nil { - panic(err) + return err } } for _, url := range genState.DisabledTypeUrls { // Set the disabled type urls if err := k.DisableList.Set(ctx, url); err != nil { - panic(err) + return err } } + + return nil } diff --git a/x/circuit/keeper/genesis_test.go b/x/circuit/keeper/genesis_test.go index cc4e3b6cbaad..e77c474923ca 100644 --- a/x/circuit/keeper/genesis_test.go +++ b/x/circuit/keeper/genesis_test.go @@ -75,9 +75,11 @@ func (s *GenesisTestSuite) TestInitExportGenesis() { DisabledTypeUrls: []string{url}, } - s.keeper.InitGenesis(s.ctx, genesisState) + err = s.keeper.InitGenesis(s.ctx, genesisState) + s.Require().NoError(err) - exported := s.keeper.ExportGenesis(s.ctx) + exported, err := s.keeper.ExportGenesis(s.ctx) + s.Require().NoError(err) bz, err := s.cdc.MarshalJSON(exported) s.Require().NoError(err) diff --git a/x/circuit/module.go b/x/circuit/module.go index 9468ce0c9f68..71dc7ca417dc 100644 --- a/x/circuit/module.go +++ b/x/circuit/module.go @@ -10,6 +10,7 @@ import ( "google.golang.org/grpc" "cosmossdk.io/core/appmodule" + appmodulev2 "cosmossdk.io/core/appmodule/v2" "cosmossdk.io/core/registry" "cosmossdk.io/x/circuit/keeper" "cosmossdk.io/x/circuit/types" @@ -27,7 +28,7 @@ var ( _ module.HasName = AppModule{} _ module.HasGRPCGateway = AppModule{} _ appmodule.HasRegisterInterfaces = AppModule{} - _ module.HasGenesis = AppModule{} + _ appmodulev2.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasServices = AppModule{} @@ -77,14 +78,14 @@ func NewAppModule(cdc codec.Codec, keeper keeper.Keeper) AppModule { func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } // DefaultGenesis returns default genesis state as raw bytes for the circuit module. -func (AppModule) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) +func (am AppModule) DefaultGenesis() json.RawMessage { + return am.cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the circuit module. -func (AppModule) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error { +func (am AppModule) ValidateGenesis(bz json.RawMessage) error { var data types.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { + if err := am.cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) } @@ -92,18 +93,23 @@ func (AppModule) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingConfig, } // InitGenesis performs genesis initialization for the circuit module. -func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { +func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) error { start := time.Now() var genesisState types.GenesisState - cdc.MustUnmarshalJSON(data, &genesisState) + if err := am.cdc.UnmarshalJSON(data, &genesisState); err != nil { + return err + } telemetry.MeasureSince(start, "InitGenesis", "crisis", "unmarshal") - am.keeper.InitGenesis(ctx, &genesisState) + return am.keeper.InitGenesis(ctx, &genesisState) } // ExportGenesis returns the exported genesis state as raw bytes for the circuit // module. -func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json.RawMessage { - gs := am.keeper.ExportGenesis(ctx) - return cdc.MustMarshalJSON(gs) +func (am AppModule) ExportGenesis(ctx context.Context) (json.RawMessage, error) { + gs, err := am.keeper.ExportGenesis(ctx) + if err != nil { + return nil, err + } + return am.cdc.MarshalJSON(gs) } diff --git a/x/crisis/depinject.go b/x/crisis/depinject.go index 4bbbd3417daa..3879333c1602 100644 --- a/x/crisis/depinject.go +++ b/x/crisis/depinject.go @@ -81,7 +81,7 @@ func ProvideModule(in ModuleInputs) ModuleOutputs { skipGenesisInvariants = cast.ToBool(in.AppOpts.Get(FlagSkipGenesisInvariants)) } - m := NewAppModule(k, skipGenesisInvariants) + m := NewAppModule(k, in.Codec, skipGenesisInvariants) return ModuleOutputs{CrisisKeeper: k, Module: m} } diff --git a/x/crisis/module.go b/x/crisis/module.go index 1707baf033d7..3773561197aa 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -10,9 +10,9 @@ import ( "google.golang.org/grpc" "cosmossdk.io/core/appmodule" + appmodulev2 "cosmossdk.io/core/appmodule/v2" "cosmossdk.io/core/registry" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/telemetry" "github.com/cosmos/cosmos-sdk/types/module" @@ -27,7 +27,7 @@ var ( _ module.HasName = AppModule{} _ module.HasAminoCodec = AppModule{} _ appmodule.HasRegisterInterfaces = AppModule{} - _ module.HasGenesis = AppModule{} + _ appmodulev2.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasEndBlocker = AppModule{} @@ -43,8 +43,8 @@ type AppModule struct { // NOTE: We store a reference to the keeper here so that after a module // manager is created, the invariants can be properly registered and // executed. - keeper *keeper.Keeper - + keeper *keeper.Keeper + cdc codec.Codec skipGenesisInvariants bool } @@ -52,10 +52,11 @@ type AppModule struct { // we will call keeper.AssertInvariants during InitGenesis (it may take a significant time) // - which doesn't impact the chain security unless 66+% of validators have a wrongly // modified genesis file. -func NewAppModule(keeper *keeper.Keeper, skipGenesisInvariants bool) AppModule { +func NewAppModule(keeper *keeper.Keeper, cdc codec.Codec, skipGenesisInvariants bool) AppModule { return AppModule{ keeper: keeper, skipGenesisInvariants: skipGenesisInvariants, + cdc: cdc, } } @@ -102,14 +103,14 @@ func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { } // DefaultGenesis returns default genesis state as raw bytes for the crisis module. -func (AppModule) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) +func (am AppModule) DefaultGenesis() json.RawMessage { + return am.cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the crisis module. -func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { +func (am AppModule) ValidateGenesis(bz json.RawMessage) error { var data types.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { + if err := am.cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) } @@ -117,22 +118,25 @@ func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingCo } // InitGenesis performs genesis initialization for the crisis module. -func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { +func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) error { start := time.Now() var genesisState types.GenesisState - cdc.MustUnmarshalJSON(data, &genesisState) + if err := am.cdc.UnmarshalJSON(data, &genesisState); err != nil { + return err + } telemetry.MeasureSince(start, "InitGenesis", "crisis", "unmarshal") am.keeper.InitGenesis(ctx, &genesisState) if !am.skipGenesisInvariants { am.keeper.AssertInvariants(ctx) } + return nil } // ExportGenesis returns the exported genesis state as raw bytes for the crisis module. -func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json.RawMessage { +func (am AppModule) ExportGenesis(ctx context.Context) (json.RawMessage, error) { gs := am.keeper.ExportGenesis(ctx) - return cdc.MustMarshalJSON(gs) + return am.cdc.MarshalJSON(gs) } // ConsensusVersion implements HasConsensusVersion diff --git a/x/distribution/keeper/genesis.go b/x/distribution/keeper/genesis.go index ce4a178401e4..e77a1475551f 100644 --- a/x/distribution/keeper/genesis.go +++ b/x/distribution/keeper/genesis.go @@ -11,29 +11,29 @@ import ( ) // InitGenesis sets distribution information for genesis -func (k Keeper) InitGenesis(ctx context.Context, data types.GenesisState) { +func (k Keeper) InitGenesis(ctx context.Context, data types.GenesisState) error { var moduleHoldings sdk.DecCoins if err := k.FeePool.Set(ctx, data.FeePool); err != nil { - panic(err) + return err } if err := k.Params.Set(ctx, data.Params); err != nil { - panic(err) + return err } for _, dwi := range data.DelegatorWithdrawInfos { delegatorAddress, err := k.authKeeper.AddressCodec().StringToBytes(dwi.DelegatorAddress) if err != nil { - panic(err) + return err } withdrawAddress, err := k.authKeeper.AddressCodec().StringToBytes(dwi.WithdrawAddress) if err != nil { - panic(err) + return err } err = k.DelegatorsWithdrawAddress.Set(ctx, delegatorAddress, withdrawAddress) if err != nil { - panic(err) + return err } } @@ -42,74 +42,74 @@ func (k Keeper) InitGenesis(ctx context.Context, data types.GenesisState) { var err error previousProposer, err = k.stakingKeeper.ConsensusAddressCodec().StringToBytes(data.PreviousProposer) if err != nil { - panic(err) + return err } } if err := k.PreviousProposer.Set(ctx, previousProposer); err != nil { - panic(err) + return err } for _, rew := range data.OutstandingRewards { valAddr, err := k.stakingKeeper.ValidatorAddressCodec().StringToBytes(rew.ValidatorAddress) if err != nil { - panic(err) + return err } err = k.ValidatorOutstandingRewards.Set(ctx, valAddr, types.ValidatorOutstandingRewards{Rewards: rew.OutstandingRewards}) if err != nil { - panic(err) + return err } moduleHoldings = moduleHoldings.Add(rew.OutstandingRewards...) } for _, acc := range data.ValidatorAccumulatedCommissions { valAddr, err := k.stakingKeeper.ValidatorAddressCodec().StringToBytes(acc.ValidatorAddress) if err != nil { - panic(err) + return err } err = k.ValidatorsAccumulatedCommission.Set(ctx, valAddr, acc.Accumulated) if err != nil { - panic(err) + return err } } for _, his := range data.ValidatorHistoricalRewards { valAddr, err := k.stakingKeeper.ValidatorAddressCodec().StringToBytes(his.ValidatorAddress) if err != nil { - panic(err) + return err } err = k.ValidatorHistoricalRewards.Set(ctx, collections.Join(sdk.ValAddress(valAddr), his.Period), his.Rewards) if err != nil { - panic(err) + return err } } for _, cur := range data.ValidatorCurrentRewards { valAddr, err := k.stakingKeeper.ValidatorAddressCodec().StringToBytes(cur.ValidatorAddress) if err != nil { - panic(err) + return err } err = k.ValidatorCurrentRewards.Set(ctx, valAddr, cur.Rewards) if err != nil { - panic(err) + return err } } for _, del := range data.DelegatorStartingInfos { valAddr, err := k.stakingKeeper.ValidatorAddressCodec().StringToBytes(del.ValidatorAddress) if err != nil { - panic(err) + return err } delegatorAddress, err := k.authKeeper.AddressCodec().StringToBytes(del.DelegatorAddress) if err != nil { - panic(err) + return err } err = k.DelegatorStartingInfo.Set(ctx, collections.Join(sdk.ValAddress(valAddr), sdk.AccAddress(delegatorAddress)), del.StartingInfo) if err != nil { - panic(err) + return err } } for _, evt := range data.ValidatorSlashEvents { valAddr, err := k.stakingKeeper.ValidatorAddressCodec().StringToBytes(evt.ValidatorAddress) if err != nil { - panic(err) + return err } err = k.ValidatorSlashEvents.Set( @@ -122,7 +122,7 @@ func (k Keeper) InitGenesis(ctx context.Context, data types.GenesisState) { evt.ValidatorSlashEvent, ) if err != nil { - panic(err) + return err } } @@ -142,18 +142,19 @@ func (k Keeper) InitGenesis(ctx context.Context, data types.GenesisState) { if !balances.Equal(moduleHoldingsInt) { panic(fmt.Sprintf("distribution module balance does not match the module holdings: %s <-> %s", balances, moduleHoldingsInt)) } + return nil } // ExportGenesis returns a GenesisState for a given context and keeper. -func (k Keeper) ExportGenesis(ctx context.Context) *types.GenesisState { +func (k Keeper) ExportGenesis(ctx context.Context) (*types.GenesisState, error) { feePool, err := k.FeePool.Get(ctx) if err != nil { - panic(err) + return nil, err } params, err := k.Params.Get(ctx) if err != nil { - panic(err) + return nil, err } var dwi []types.DelegatorWithdrawInfo @@ -165,12 +166,12 @@ func (k Keeper) ExportGenesis(ctx context.Context) *types.GenesisState { return false, nil }) if err != nil { - panic(err) + return nil, err } pp, err := k.PreviousProposer.Get(ctx) if err != nil { - panic(err) + return nil, err } outstanding := make([]types.ValidatorOutstandingRewardsRecord, 0) @@ -184,7 +185,7 @@ func (k Keeper) ExportGenesis(ctx context.Context) *types.GenesisState { }, ) if err != nil { - panic(err) + return nil, err } acc := make([]types.ValidatorAccumulatedCommissionRecord, 0) @@ -196,7 +197,7 @@ func (k Keeper) ExportGenesis(ctx context.Context) *types.GenesisState { return false, nil }) if err != nil { - panic(err) + return nil, err } his := make([]types.ValidatorHistoricalRewardsRecord, 0) @@ -211,7 +212,7 @@ func (k Keeper) ExportGenesis(ctx context.Context) *types.GenesisState { }, ) if err != nil { - panic(err) + return nil, err } cur := make([]types.ValidatorCurrentRewardsRecord, 0) @@ -225,7 +226,7 @@ func (k Keeper) ExportGenesis(ctx context.Context) *types.GenesisState { }, ) if err != nil { - panic(err) + return nil, err } dels := make([]types.DelegatorStartingInfoRecord, 0) @@ -238,7 +239,7 @@ func (k Keeper) ExportGenesis(ctx context.Context) *types.GenesisState { return false, nil }) if err != nil { - panic(err) + return nil, err } slashes := make([]types.ValidatorSlashEventRecord, 0) @@ -256,8 +257,8 @@ func (k Keeper) ExportGenesis(ctx context.Context) *types.GenesisState { }, ) if err != nil { - panic(err) + return nil, err } - return types.NewGenesisState(params, feePool, dwi, pp, outstanding, acc, his, cur, dels, slashes) + return types.NewGenesisState(params, feePool, dwi, pp, outstanding, acc, his, cur, dels, slashes), nil } diff --git a/x/distribution/module.go b/x/distribution/module.go index 3591b448b9bc..116c613190ed 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -10,6 +10,7 @@ import ( "google.golang.org/grpc" "cosmossdk.io/core/appmodule" + appmodulev2 "cosmossdk.io/core/appmodule/v2" "cosmossdk.io/core/registry" "cosmossdk.io/x/distribution/client/cli" "cosmossdk.io/x/distribution/keeper" @@ -32,7 +33,7 @@ var ( _ module.HasGRPCGateway = AppModule{} _ appmodule.HasRegisterInterfaces = AppModule{} _ module.AppModuleSimulation = AppModule{} - _ module.HasGenesis = AppModule{} + _ appmodulev2.HasGenesis = AppModule{} _ module.HasInvariants = AppModule{} _ appmodule.AppModule = AppModule{} @@ -128,14 +129,14 @@ func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { } // DefaultGenesis returns default genesis state as raw bytes for the distribution module. -func (AppModule) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) +func (am AppModule) DefaultGenesis() json.RawMessage { + return am.cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the distribution module. -func (AppModule) ValidateGenesis(cdc codec.JSONCodec, _ sdkclient.TxEncodingConfig, bz json.RawMessage) error { +func (am AppModule) ValidateGenesis(bz json.RawMessage) error { var data types.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { + if err := am.cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) } @@ -143,17 +144,22 @@ func (AppModule) ValidateGenesis(cdc codec.JSONCodec, _ sdkclient.TxEncodingConf } // InitGenesis performs genesis initialization for the distribution module. -func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { +func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) error { var genesisState types.GenesisState - cdc.MustUnmarshalJSON(data, &genesisState) - am.keeper.InitGenesis(ctx, genesisState) + if err := am.cdc.UnmarshalJSON(data, &genesisState); err != nil { + return err + } + return am.keeper.InitGenesis(ctx, genesisState) } // ExportGenesis returns the exported genesis state as raw bytes for the distribution // module. -func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json.RawMessage { - gs := am.keeper.ExportGenesis(ctx) - return cdc.MustMarshalJSON(gs) +func (am AppModule) ExportGenesis(ctx context.Context) (json.RawMessage, error) { + gs, err := am.keeper.ExportGenesis(ctx) + if err != nil { + return nil, err + } + return am.cdc.MarshalJSON(gs) } // ConsensusVersion implements HasConsensusVersion diff --git a/x/evidence/CHANGELOG.md b/x/evidence/CHANGELOG.md index f00a7953f1ec..eba342d7870d 100644 --- a/x/evidence/CHANGELOG.md +++ b/x/evidence/CHANGELOG.md @@ -28,6 +28,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### Api Breaking Changes * [#19482](https://github.com/cosmos/cosmos-sdk/pull/19482) `appmodule.Environment` is passed to `NewKeeper` instead of individual services +* [#19627](https://github.com/cosmos/cosmos-sdk/pull/19627) `NewAppModule` now takes in a `codec.Codec` as its first arguement ## [v0.1.0](https://github.com/cosmos/cosmos-sdk/releases/tag/x/evidence/v0.1.0) - 2023-11-07 diff --git a/x/evidence/depinject.go b/x/evidence/depinject.go index 49af8a23639c..335cef402ef5 100644 --- a/x/evidence/depinject.go +++ b/x/evidence/depinject.go @@ -45,7 +45,7 @@ type ModuleOutputs struct { func ProvideModule(in ModuleInputs) ModuleOutputs { k := keeper.NewKeeper(in.Cdc, in.Environment, in.StakingKeeper, in.SlashingKeeper, in.AddressCodec) - m := NewAppModule(*k, in.EvidenceHandlers...) + m := NewAppModule(in.Cdc, *k, in.EvidenceHandlers...) return ModuleOutputs{EvidenceKeeper: *k, Module: m} } diff --git a/x/evidence/genesis.go b/x/evidence/genesis.go index 3c632607ea4e..0ffe655600d9 100644 --- a/x/evidence/genesis.go +++ b/x/evidence/genesis.go @@ -2,6 +2,7 @@ package evidence import ( "context" + "errors" "fmt" "cosmossdk.io/x/evidence/exported" @@ -13,28 +14,29 @@ import ( // InitGenesis initializes the evidence module's state from a provided genesis // state. -func InitGenesis(ctx context.Context, k keeper.Keeper, gs *types.GenesisState) { +func InitGenesis(ctx context.Context, k keeper.Keeper, gs *types.GenesisState) error { if err := gs.Validate(); err != nil { - panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) + return fmt.Errorf("failed to validate %s genesis state: %s", types.ModuleName, err) } for _, e := range gs.Evidence { evi, ok := e.GetCachedValue().(exported.Evidence) if !ok { - panic("expected evidence") + return errors.New("expected evidence") } if _, err := k.Evidences.Get(ctx, evi.Hash()); err == nil { - panic(fmt.Sprintf("evidence with hash %s already exists", evi.Hash())) + return fmt.Errorf("evidence with hash %s already exists", evi.Hash()) } if err := k.Evidences.Set(ctx, evi.Hash(), evi); err != nil { - panic(err) + return err } } + return nil } // ExportGenesis returns the evidence module's exported genesis. -func ExportGenesis(ctx context.Context, k keeper.Keeper) *types.GenesisState { +func ExportGenesis(ctx context.Context, k keeper.Keeper) (*types.GenesisState, error) { gs := new(types.GenesisState) err := k.Evidences.Walk(ctx, nil, func(_ []byte, value exported.Evidence) (stop bool, err error) { anyEvi, err := codectypes.NewAnyWithValue(value) @@ -45,7 +47,7 @@ func ExportGenesis(ctx context.Context, k keeper.Keeper) *types.GenesisState { return false, nil }) if err != nil { - panic(err) + return nil, err } - return gs + return gs, nil } diff --git a/x/evidence/module.go b/x/evidence/module.go index 854ada04705a..85ae9866b078 100644 --- a/x/evidence/module.go +++ b/x/evidence/module.go @@ -10,6 +10,7 @@ import ( "google.golang.org/grpc" "cosmossdk.io/core/appmodule" + appmodulev2 "cosmossdk.io/core/appmodule/v2" "cosmossdk.io/core/registry" eviclient "cosmossdk.io/x/evidence/client" "cosmossdk.io/x/evidence/client/cli" @@ -29,7 +30,7 @@ var ( _ module.HasGRPCGateway = AppModule{} _ appmodule.HasRegisterInterfaces = AppModule{} _ module.AppModuleSimulation = AppModule{} - _ module.HasGenesis = AppModule{} + _ appmodulev2.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasBeginBlocker = AppModule{} @@ -39,15 +40,17 @@ const ConsensusVersion = 1 // AppModule implements the AppModule interface for the evidence module. type AppModule struct { + cdc codec.Codec evidenceHandlers []eviclient.EvidenceHandler keeper keeper.Keeper } // NewAppModule creates a new AppModule object. -func NewAppModule(keeper keeper.Keeper, evidenceHandlers ...eviclient.EvidenceHandler) AppModule { +func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, evidenceHandlers ...eviclient.EvidenceHandler) AppModule { return AppModule{ keeper: keeper, evidenceHandlers: evidenceHandlers, + cdc: cdc, } } @@ -94,14 +97,14 @@ func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { } // DefaultGenesis returns the evidence module's default genesis state. -func (AppModule) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) +func (am AppModule) DefaultGenesis() json.RawMessage { + return am.cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the evidence module. -func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { +func (am AppModule) ValidateGenesis(bz json.RawMessage) error { var gs types.GenesisState - if err := cdc.UnmarshalJSON(bz, &gs); err != nil { + if err := am.cdc.UnmarshalJSON(bz, &gs); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) } @@ -109,19 +112,23 @@ func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingCo } // InitGenesis performs the evidence module's genesis initialization -func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, bz json.RawMessage) { +func (am AppModule) InitGenesis(ctx context.Context, bz json.RawMessage) error { var gs types.GenesisState - err := cdc.UnmarshalJSON(bz, &gs) + err := am.cdc.UnmarshalJSON(bz, &gs) if err != nil { - panic(fmt.Sprintf("failed to unmarshal %s genesis state: %s", types.ModuleName, err)) + return err } - InitGenesis(ctx, am.keeper, &gs) + return InitGenesis(ctx, am.keeper, &gs) } // ExportGenesis returns the evidence module's exported genesis state as raw JSON bytes. -func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(ExportGenesis(ctx, am.keeper)) +func (am AppModule) ExportGenesis(ctx context.Context) (json.RawMessage, error) { + gs, err := ExportGenesis(ctx, am.keeper) + if err != nil { + return nil, err + } + return am.cdc.MarshalJSON(gs) } // ConsensusVersion implements HasConsensusVersion diff --git a/x/feegrant/module/module.go b/x/feegrant/module/module.go index d950ae6a285d..42edb16f1ded 100644 --- a/x/feegrant/module/module.go +++ b/x/feegrant/module/module.go @@ -10,6 +10,7 @@ import ( "google.golang.org/grpc" "cosmossdk.io/core/appmodule" + appmodulev2 "cosmossdk.io/core/appmodule/v2" "cosmossdk.io/core/registry" "cosmossdk.io/errors" "cosmossdk.io/x/feegrant" @@ -28,7 +29,7 @@ var ( _ module.HasGRPCGateway = AppModule{} _ appmodule.HasRegisterInterfaces = AppModule{} _ module.AppModuleSimulation = AppModule{} - _ module.HasGenesis = AppModule{} + _ appmodulev2.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasEndBlocker = AppModule{} @@ -107,14 +108,14 @@ func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { } // DefaultGenesis returns default genesis state as raw bytes for the feegrant module. -func (AppModule) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(feegrant.DefaultGenesisState()) +func (am AppModule) DefaultGenesis() json.RawMessage { + return am.cdc.MustMarshalJSON(feegrant.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the feegrant module. -func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { +func (am AppModule) ValidateGenesis(bz json.RawMessage) error { var data feegrant.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { + if err := am.cdc.UnmarshalJSON(bz, &data); err != nil { return errors.Wrapf(err, "failed to unmarshal %s genesis state", feegrant.ModuleName) } @@ -122,24 +123,27 @@ func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEncodin } // InitGenesis performs genesis initialization for the feegrant module. -func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, bz json.RawMessage) { +func (am AppModule) InitGenesis(ctx context.Context, bz json.RawMessage) error { var gs feegrant.GenesisState - cdc.MustUnmarshalJSON(bz, &gs) + if err := am.cdc.UnmarshalJSON(bz, &gs); err != nil { + return err + } err := am.keeper.InitGenesis(ctx, &gs) if err != nil { - panic(err) + return err } + return nil } // ExportGenesis returns the exported genesis state as raw bytes for the feegrant module. -func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json.RawMessage { +func (am AppModule) ExportGenesis(ctx context.Context) (json.RawMessage, error) { gs, err := am.keeper.ExportGenesis(ctx) if err != nil { - panic(err) + return nil, err } - return cdc.MustMarshalJSON(gs) + return am.cdc.MarshalJSON(gs) } // ConsensusVersion implements HasConsensusVersion diff --git a/x/genutil/client/cli/gentx.go b/x/genutil/client/cli/gentx.go index d82b0476b81a..2c44794c23f2 100644 --- a/x/genutil/client/cli/gentx.go +++ b/x/genutil/client/cli/gentx.go @@ -90,7 +90,7 @@ $ %s gentx my-key-name 1000000stake --home=/path/to/home/dir --keyring-backend=o return errors.Wrap(err, "failed to unmarshal genesis state") } - if err = mm.ValidateGenesis(cdc, txEncCfg, genesisState); err != nil { + if err = mm.ValidateGenesis(genesisState); err != nil { return errors.Wrap(err, "failed to validate genesis state") } diff --git a/x/genutil/client/cli/init.go b/x/genutil/client/cli/init.go index 227acbe25f50..da33a1060b29 100644 --- a/x/genutil/client/cli/init.go +++ b/x/genutil/client/cli/init.go @@ -76,7 +76,6 @@ func InitCmd(mm *module.Manager) *cobra.Command { Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { clientCtx := client.GetClientContextFromCmd(cmd) - cdc := clientCtx.Codec serverCtx := server.GetServerContextFromCmd(cmd) config := serverCtx.Config @@ -133,7 +132,7 @@ func InitCmd(mm *module.Manager) *cobra.Command { if defaultDenom != "" { sdk.DefaultBondDenom = defaultDenom } - appGenState := mm.DefaultGenesis(cdc) + appGenState := mm.DefaultGenesis() appState, err := json.MarshalIndent(appGenState, "", " ") if err != nil { diff --git a/x/genutil/client/cli/init_test.go b/x/genutil/client/cli/init_test.go index 82ad4ad64c7a..a958a47544e9 100644 --- a/x/genutil/client/cli/init_test.go +++ b/x/genutil/client/cli/init_test.go @@ -35,8 +35,8 @@ import ( ) var testMbm = module.NewManager( - staking.AppModule{}, - genutil.AppModule{}, + staking.NewAppModule(makeCodec(), nil, nil, nil), + genutil.NewAppModule(makeCodec(), nil, nil, nil, nil, nil), ) func TestInitCmd(t *testing.T) { @@ -71,7 +71,7 @@ func TestInitCmd(t *testing.T) { marshaler := codec.NewProtoCodec(interfaceRegistry) clientCtx := client.Context{}. WithCodec(marshaler). - WithLegacyAmino(makeCodec()). + WithLegacyAmino(makeAminoCodec()). WithHomeDir(home) ctx := context.Background() @@ -104,7 +104,7 @@ func TestInitRecover(t *testing.T) { marshaler := codec.NewProtoCodec(interfaceRegistry) clientCtx := client.Context{}. WithCodec(marshaler). - WithLegacyAmino(makeCodec()). + WithLegacyAmino(makeAminoCodec()). WithHomeDir(home) ctx := context.Background() @@ -135,7 +135,7 @@ func TestInitDefaultBondDenom(t *testing.T) { marshaler := codec.NewProtoCodec(interfaceRegistry) clientCtx := client.Context{}. WithCodec(marshaler). - WithLegacyAmino(makeCodec()). + WithLegacyAmino(makeAminoCodec()). WithHomeDir(home) ctx := context.Background() @@ -163,7 +163,7 @@ func TestEmptyState(t *testing.T) { marshaler := codec.NewProtoCodec(interfaceRegistry) clientCtx := client.Context{}. WithCodec(marshaler). - WithLegacyAmino(makeCodec()). + WithLegacyAmino(makeAminoCodec()). WithHomeDir(home) ctx := context.Background() @@ -256,7 +256,7 @@ func TestInitConfig(t *testing.T) { marshaler := codec.NewProtoCodec(interfaceRegistry) clientCtx := client.Context{}. WithCodec(marshaler). - WithLegacyAmino(makeCodec()). + WithLegacyAmino(makeAminoCodec()). WithChainID("foo"). // add chain-id to clientCtx WithHomeDir(home) @@ -302,7 +302,7 @@ func TestInitWithHeight(t *testing.T) { marshaler := codec.NewProtoCodec(interfaceRegistry) clientCtx := client.Context{}. WithCodec(marshaler). - WithLegacyAmino(makeCodec()). + WithLegacyAmino(makeAminoCodec()). WithChainID("foo"). // add chain-id to clientCtx WithHomeDir(home) @@ -334,7 +334,7 @@ func TestInitWithNegativeHeight(t *testing.T) { marshaler := codec.NewProtoCodec(interfaceRegistry) clientCtx := client.Context{}. WithCodec(marshaler). - WithLegacyAmino(makeCodec()). + WithLegacyAmino(makeAminoCodec()). WithChainID("foo"). // add chain-id to clientCtx WithHomeDir(home) @@ -356,9 +356,14 @@ func TestInitWithNegativeHeight(t *testing.T) { } // custom tx codec -func makeCodec() *codec.LegacyAmino { +func makeAminoCodec() *codec.LegacyAmino { cdc := codec.NewLegacyAmino() sdk.RegisterLegacyAminoCodec(cdc) cryptocodec.RegisterCrypto(cdc) return cdc } + +func makeCodec() codec.Codec { + interfaceRegistry := types.NewInterfaceRegistry() + return codec.NewProtoCodec(interfaceRegistry) +} diff --git a/x/genutil/client/cli/validate_genesis.go b/x/genutil/client/cli/validate_genesis.go index 71011f1f0989..232097cda5c0 100644 --- a/x/genutil/client/cli/validate_genesis.go +++ b/x/genutil/client/cli/validate_genesis.go @@ -6,7 +6,6 @@ import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/genutil/types" @@ -23,9 +22,6 @@ func ValidateGenesisCmd(mm *module.Manager) *cobra.Command { Short: "Validates the genesis file at the default location or at the location passed as an arg", RunE: func(cmd *cobra.Command, args []string) (err error) { serverCtx := server.GetServerContextFromCmd(cmd) - clientCtx := client.GetClientContextFromCmd(cmd) - - cdc := clientCtx.Codec // Load default if passed no args, otherwise load passed file var genesis string @@ -50,7 +46,7 @@ func ValidateGenesisCmd(mm *module.Manager) *cobra.Command { } if mm != nil { - if err = mm.ValidateGenesis(cdc, clientCtx.TxConfig, genState); err != nil { + if err = mm.ValidateGenesis(genState); err != nil { return fmt.Errorf("error validating genesis file %s: %w", genesis, err) } } diff --git a/x/genutil/depinject.go b/x/genutil/depinject.go index d8fb7ee6ed79..6b6f2beabfa0 100644 --- a/x/genutil/depinject.go +++ b/x/genutil/depinject.go @@ -8,6 +8,7 @@ import ( "cosmossdk.io/depinject/appconfig" "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/genutil/types" ) @@ -30,6 +31,7 @@ type ModuleInputs struct { StakingKeeper types.StakingKeeper DeliverTx genesis.TxHandler Config client.TxConfig + Cdc codec.Codec GenTxValidator types.MessageValidator `optional:"true"` } @@ -38,6 +40,6 @@ func ProvideModule(in ModuleInputs) appmodule.AppModule { in.GenTxValidator = types.DefaultMessageValidator } - m := NewAppModule(in.AccountKeeper, in.StakingKeeper, in.DeliverTx, in.Config, in.GenTxValidator) + m := NewAppModule(in.Cdc, in.AccountKeeper, in.StakingKeeper, in.DeliverTx, in.Config, in.GenTxValidator) return m } diff --git a/x/genutil/module.go b/x/genutil/module.go index 118cd2ea3d49..b16694ec2f6e 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -26,6 +26,7 @@ var ( // AppModule implements an application module for the genutil module. type AppModule struct { + cdc codec.Codec accountKeeper types.AccountKeeper stakingKeeper types.StakingKeeper deliverTx genesis.TxHandler @@ -35,6 +36,7 @@ type AppModule struct { // NewAppModule creates a new AppModule object func NewAppModule( + cdc codec.Codec, accountKeeper types.AccountKeeper, stakingKeeper types.StakingKeeper, deliverTx genesis.TxHandler, @@ -42,6 +44,7 @@ func NewAppModule( genTxValidator types.MessageValidator, ) module.AppModule { return AppModule{ + cdc: cdc, accountKeeper: accountKeeper, stakingKeeper: stakingKeeper, deliverTx: deliverTx, @@ -59,24 +62,24 @@ func (AppModule) Name() string { } // DefaultGenesis returns default genesis state as raw bytes for the genutil module. -func (AppModule) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) +func (am AppModule) DefaultGenesis() json.RawMessage { + return am.cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the genutil module. -func (b AppModule) ValidateGenesis(cdc codec.JSONCodec, txEncodingConfig client.TxEncodingConfig, bz json.RawMessage) error { +func (am AppModule) ValidateGenesis(bz json.RawMessage) error { var data types.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { + if err := am.cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) } - return types.ValidateGenesis(&data, txEncodingConfig.TxJSONDecoder(), b.genTxValidator) + return types.ValidateGenesis(&data, am.txEncodingConfig.TxJSONDecoder(), am.genTxValidator) } // InitGenesis performs genesis initialization for the genutil module. -func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState types.GenesisState - cdc.MustUnmarshalJSON(data, &genesisState) + am.cdc.MustUnmarshalJSON(data, &genesisState) validators, err := InitGenesis(ctx, am.stakingKeeper, am.deliverTx, genesisState, am.txEncodingConfig) if err != nil { panic(err) @@ -85,8 +88,8 @@ func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data j } // ExportGenesis returns the exported genesis state as raw bytes for the genutil module. -func (am AppModule) ExportGenesis(_ context.Context, cdc codec.JSONCodec) json.RawMessage { - return am.DefaultGenesis(cdc) +func (am AppModule) ExportGenesis(_ context.Context) json.RawMessage { + return am.DefaultGenesis() } // GenTxValidator returns the genutil module's genesis transaction validator. diff --git a/x/gov/genesis.go b/x/gov/genesis.go index 65fa70b4b216..09975f458bf4 100644 --- a/x/gov/genesis.go +++ b/x/gov/genesis.go @@ -13,20 +13,20 @@ import ( ) // InitGenesis - store genesis parameters -func InitGenesis(ctx context.Context, ak types.AccountKeeper, bk types.BankKeeper, k *keeper.Keeper, data *v1.GenesisState) { +func InitGenesis(ctx context.Context, ak types.AccountKeeper, bk types.BankKeeper, k *keeper.Keeper, data *v1.GenesisState) error { err := k.ProposalID.Set(ctx, data.StartingProposalId) if err != nil { - panic(err) + return err } err = k.Params.Set(ctx, *data.Params) if err != nil { - panic(err) + return err } err = k.Constitution.Set(ctx, data.Constitution) if err != nil { - panic(err) + return err } // check if the deposits pool account exists @@ -39,7 +39,7 @@ func InitGenesis(ctx context.Context, ak types.AccountKeeper, bk types.BankKeepe for _, deposit := range data.Deposits { err := k.SetDeposit(ctx, *deposit) if err != nil { - panic(err) + return err } totalDeposits = totalDeposits.Add(deposit.Amount...) } @@ -47,11 +47,11 @@ func InitGenesis(ctx context.Context, ak types.AccountKeeper, bk types.BankKeepe for _, vote := range data.Votes { addr, err := ak.AddressCodec().StringToBytes(vote.Voter) if err != nil { - panic(err) + return err } err = k.Votes.Set(ctx, collections.Join(vote.ProposalId, sdk.AccAddress(addr)), *vote) if err != nil { - panic(err) + return err } } @@ -60,16 +60,16 @@ func InitGenesis(ctx context.Context, ak types.AccountKeeper, bk types.BankKeepe case v1.StatusDepositPeriod: err := k.InactiveProposalsQueue.Set(ctx, collections.Join(*proposal.DepositEndTime, proposal.Id), proposal.Id) if err != nil { - panic(err) + return err } case v1.StatusVotingPeriod: err := k.ActiveProposalsQueue.Set(ctx, collections.Join(*proposal.VotingEndTime, proposal.Id), proposal.Id) if err != nil { - panic(err) + return err } } if err := k.Proposals.Set(ctx, proposal.Id, *proposal); err != nil { - panic(err) + return err } } @@ -83,6 +83,7 @@ func InitGenesis(ctx context.Context, ak types.AccountKeeper, bk types.BankKeepe if !balance.Equal(totalDeposits) { panic(fmt.Sprintf("expected module account was %s but we got %s", balance.String(), totalDeposits.String())) } + return nil } // ExportGenesis - output genesis parameters @@ -117,7 +118,7 @@ func ExportGenesis(ctx context.Context, k *keeper.Keeper) (*v1.GenesisState, err return false, nil }) if err != nil { - panic(err) + return nil, err } // export proposals votes @@ -127,7 +128,7 @@ func ExportGenesis(ctx context.Context, k *keeper.Keeper) (*v1.GenesisState, err return false, nil }) if err != nil { - panic(err) + return nil, err } return &v1.GenesisState{ diff --git a/x/gov/module.go b/x/gov/module.go index f169e4b8c754..aa5069183b86 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -10,6 +10,7 @@ import ( "google.golang.org/grpc" "cosmossdk.io/core/appmodule" + appmodulev2 "cosmossdk.io/core/appmodule/v2" "cosmossdk.io/core/registry" govclient "cosmossdk.io/x/gov/client" "cosmossdk.io/x/gov/client/cli" @@ -34,7 +35,7 @@ var ( _ module.HasGRPCGateway = AppModule{} _ appmodule.HasRegisterInterfaces = AppModule{} _ module.AppModuleSimulation = AppModule{} - _ module.HasGenesis = AppModule{} + _ appmodulev2.HasGenesis = AppModule{} _ module.HasInvariants = AppModule{} _ appmodule.AppModule = AppModule{} @@ -159,14 +160,14 @@ func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { } // DefaultGenesis returns default genesis state as raw bytes for the gov module. -func (AppModule) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(v1.DefaultGenesisState()) +func (am AppModule) DefaultGenesis() json.RawMessage { + return am.cdc.MustMarshalJSON(v1.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the gov module. -func (am AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { +func (am AppModule) ValidateGenesis(bz json.RawMessage) error { var data v1.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { + if err := am.cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", govtypes.ModuleName, err) } @@ -174,19 +175,21 @@ func (am AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodin } // InitGenesis performs genesis initialization for the gov module. -func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { +func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) error { var genesisState v1.GenesisState - cdc.MustUnmarshalJSON(data, &genesisState) - InitGenesis(ctx, am.accountKeeper, am.bankKeeper, am.keeper, &genesisState) + if err := am.cdc.UnmarshalJSON(data, &genesisState); err != nil { + return err + } + return InitGenesis(ctx, am.accountKeeper, am.bankKeeper, am.keeper, &genesisState) } // ExportGenesis returns the exported genesis state as raw bytes for the gov module. -func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json.RawMessage { +func (am AppModule) ExportGenesis(ctx context.Context) (json.RawMessage, error) { gs, err := ExportGenesis(ctx, am.keeper) if err != nil { - panic(err) + return nil, err } - return cdc.MustMarshalJSON(gs) + return am.cdc.MarshalJSON(gs) } // ConsensusVersion implements HasConsensusVersion diff --git a/x/gov/testutil/expected_keepers_mocks.go b/x/gov/testutil/expected_keepers_mocks.go index 78c9e669385f..3784d76377cd 100644 --- a/x/gov/testutil/expected_keepers_mocks.go +++ b/x/gov/testutil/expected_keepers_mocks.go @@ -574,9 +574,11 @@ func (mr *MockBankKeeperMockRecorder) HasSupply(ctx, denom interface{}) *gomock. } // InitGenesis mocks base method. -func (m *MockBankKeeper) InitGenesis(arg0 context.Context, arg1 *types.GenesisState) { +func (m *MockBankKeeper) InitGenesis(arg0 context.Context, arg1 *types.GenesisState) error { m.ctrl.T.Helper() - m.ctrl.Call(m, "InitGenesis", arg0, arg1) + ret := m.ctrl.Call(m, "InitGenesis", arg0, arg1) + ret0, _ := ret[0].(error) + return ret0 } // InitGenesis indicates an expected call of InitGenesis. diff --git a/x/group/keeper/genesis.go b/x/group/keeper/genesis.go index f378f3775799..70d61ff69230 100644 --- a/x/group/keeper/genesis.go +++ b/x/group/keeper/genesis.go @@ -4,8 +4,6 @@ import ( "context" "encoding/json" - abci "github.com/cometbft/cometbft/abci/types" - "cosmossdk.io/errors" "cosmossdk.io/x/group" @@ -13,37 +11,37 @@ import ( ) // InitGenesis initializes the group module's genesis state. -func (k Keeper) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { +func (k Keeper) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) error { var genesisState group.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) store := k.environment.KVStoreService.OpenKVStore(ctx) if err := k.groupTable.Import(store, genesisState.Groups, genesisState.GroupSeq); err != nil { - panic(errors.Wrap(err, "groups")) + return errors.Wrap(err, "groups") } if err := k.groupMemberTable.Import(store, genesisState.GroupMembers, 0); err != nil { - panic(errors.Wrap(err, "group members")) + return errors.Wrap(err, "group members") } if err := k.groupPolicyTable.Import(store, genesisState.GroupPolicies, 0); err != nil { - panic(errors.Wrap(err, "group policies")) + return errors.Wrap(err, "group policies") } if err := k.groupPolicySeq.InitVal(store, genesisState.GroupPolicySeq); err != nil { - panic(errors.Wrap(err, "group policy account seq")) + return errors.Wrap(err, "group policy account seq") } if err := k.proposalTable.Import(store, genesisState.Proposals, genesisState.ProposalSeq); err != nil { - panic(errors.Wrap(err, "proposals")) + return errors.Wrap(err, "proposals") } if err := k.voteTable.Import(store, genesisState.Votes, 0); err != nil { - panic(errors.Wrap(err, "votes")) + return errors.Wrap(err, "votes") } - return []abci.ValidatorUpdate{} + return nil } // ExportGenesis returns the group module's exported genesis. diff --git a/x/group/keeper/genesis_test.go b/x/group/keeper/genesis_test.go index 0af3c8678d86..967867a1f271 100644 --- a/x/group/keeper/genesis_test.go +++ b/x/group/keeper/genesis_test.go @@ -145,7 +145,8 @@ func (s *GenesisTestSuite) TestInitExportGenesis() { group.ModuleName: genesisBytes, } - s.keeper.InitGenesis(sdkCtx, cdc, genesisData[group.ModuleName]) + err = s.keeper.InitGenesis(sdkCtx, cdc, genesisData[group.ModuleName]) + s.Require().NoError(err) for i, g := range genesisState.Groups { res, err := s.keeper.GroupInfo(ctx, &group.QueryGroupInfoRequest{ diff --git a/x/group/module/module.go b/x/group/module/module.go index 4a232b9c142f..ab323da0b01f 100644 --- a/x/group/module/module.go +++ b/x/group/module/module.go @@ -10,6 +10,7 @@ import ( "google.golang.org/grpc" "cosmossdk.io/core/appmodule" + appmodulev2 "cosmossdk.io/core/appmodule/v2" "cosmossdk.io/core/registry" "cosmossdk.io/x/group" "cosmossdk.io/x/group/client/cli" @@ -33,7 +34,7 @@ var ( _ module.HasGRPCGateway = AppModule{} _ appmodule.HasRegisterInterfaces = AppModule{} _ module.AppModuleSimulation = AppModule{} - _ module.HasGenesis = AppModule{} + _ appmodulev2.HasGenesis = AppModule{} _ module.HasInvariants = AppModule{} _ appmodule.AppModule = AppModule{} @@ -124,28 +125,28 @@ func (am AppModule) EndBlock(ctx context.Context) error { } // DefaultGenesis returns default genesis state as raw bytes for the group module. -func (AppModule) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(group.NewGenesisState()) +func (am AppModule) DefaultGenesis() json.RawMessage { + return am.cdc.MustMarshalJSON(group.NewGenesisState()) } // ValidateGenesis performs genesis state validation for the group module. -func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { +func (am AppModule) ValidateGenesis(bz json.RawMessage) error { var data group.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { + if err := am.cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", group.ModuleName, err) } return data.Validate() } // InitGenesis performs genesis initialization for the group module. -func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { - am.keeper.InitGenesis(ctx, cdc, data) +func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) error { + return am.keeper.InitGenesis(ctx, am.cdc, data) } // ExportGenesis returns the exported genesis state as raw bytes for the group module. -func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json.RawMessage { - gs := am.keeper.ExportGenesis(ctx, cdc) - return cdc.MustMarshalJSON(gs) +func (am AppModule) ExportGenesis(ctx context.Context) (json.RawMessage, error) { + gs := am.keeper.ExportGenesis(ctx, am.cdc) + return am.cdc.MarshalJSON(gs) } // GenerateGenesisState creates a randomized GenState of the group module. diff --git a/x/mint/keeper/genesis.go b/x/mint/keeper/genesis.go index 57b2faf5adb9..446b9066512d 100644 --- a/x/mint/keeper/genesis.go +++ b/x/mint/keeper/genesis.go @@ -7,29 +7,31 @@ import ( ) // InitGenesis new mint genesis -func (keeper Keeper) InitGenesis(ctx context.Context, ak types.AccountKeeper, data *types.GenesisState) { +func (keeper Keeper) InitGenesis(ctx context.Context, ak types.AccountKeeper, data *types.GenesisState) error { if err := keeper.Minter.Set(ctx, data.Minter); err != nil { - panic(err) + return err } if err := keeper.Params.Set(ctx, data.Params); err != nil { - panic(err) + return err } ak.GetModuleAccount(ctx, types.ModuleName) + + return nil } // ExportGenesis returns a GenesisState for a given context and keeper. -func (keeper Keeper) ExportGenesis(ctx context.Context) *types.GenesisState { +func (keeper Keeper) ExportGenesis(ctx context.Context) (*types.GenesisState, error) { minter, err := keeper.Minter.Get(ctx) if err != nil { - panic(err) + return nil, err } params, err := keeper.Params.Get(ctx) if err != nil { - panic(err) + return nil, err } - return types.NewGenesisState(minter, params) + return types.NewGenesisState(minter, params), nil } diff --git a/x/mint/keeper/genesis_test.go b/x/mint/keeper/genesis_test.go index 5fc6e9e03678..4dce9bf881da 100644 --- a/x/mint/keeper/genesis_test.go +++ b/x/mint/keeper/genesis_test.go @@ -73,7 +73,8 @@ func (s *GenesisTestSuite) TestImportExportGenesis() { uint64(60*60*8766/5), ) - s.keeper.InitGenesis(s.sdkCtx, s.accountKeeper, genesisState) + err := s.keeper.InitGenesis(s.sdkCtx, s.accountKeeper, genesisState) + s.Require().NoError(err) minter, err := s.keeper.Minter.Get(s.sdkCtx) s.Require().Equal(genesisState.Minter, minter) @@ -87,6 +88,7 @@ func (s *GenesisTestSuite) TestImportExportGenesis() { s.Require().Equal(genesisState.Params, params) s.Require().NoError(err) - genesisState2 := s.keeper.ExportGenesis(s.sdkCtx) + genesisState2, err := s.keeper.ExportGenesis(s.sdkCtx) + s.Require().NoError(err) s.Require().Equal(genesisState, genesisState2) } diff --git a/x/mint/module.go b/x/mint/module.go index 8f228900c8d8..2336c6306ef0 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -9,6 +9,7 @@ import ( "google.golang.org/grpc" "cosmossdk.io/core/appmodule" + appmodulev2 "cosmossdk.io/core/appmodule/v2" "cosmossdk.io/core/registry" "cosmossdk.io/x/mint/keeper" "cosmossdk.io/x/mint/simulation" @@ -29,7 +30,7 @@ var ( _ module.HasGRPCGateway = AppModule{} _ appmodule.HasRegisterInterfaces = AppModule{} _ module.AppModuleSimulation = AppModule{} - _ module.HasGenesis = AppModule{} + _ appmodulev2.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasBeginBlocker = AppModule{} @@ -113,14 +114,14 @@ func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { } // DefaultGenesis returns default genesis state as raw bytes for the mint module. -func (AppModule) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) +func (am AppModule) DefaultGenesis() json.RawMessage { + return am.cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the mint module. -func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { +func (am AppModule) ValidateGenesis(bz json.RawMessage) error { var data types.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { + if err := am.cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) } @@ -128,18 +129,23 @@ func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingCo } // InitGenesis performs genesis initialization for the mint module. -func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { +func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) error { var genesisState types.GenesisState - cdc.MustUnmarshalJSON(data, &genesisState) + if err := am.cdc.UnmarshalJSON(data, &genesisState); err != nil { + return err + } - am.keeper.InitGenesis(ctx, am.authKeeper, &genesisState) + return am.keeper.InitGenesis(ctx, am.authKeeper, &genesisState) } // ExportGenesis returns the exported genesis state as raw bytes for the mint // module. -func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json.RawMessage { - gs := am.keeper.ExportGenesis(ctx) - return cdc.MustMarshalJSON(gs) +func (am AppModule) ExportGenesis(ctx context.Context) (json.RawMessage, error) { + gs, err := am.keeper.ExportGenesis(ctx) + if err != nil { + return nil, err + } + return am.cdc.MarshalJSON(gs) } // ConsensusVersion implements HasConsensusVersion diff --git a/x/nft/keeper/genesis.go b/x/nft/keeper/genesis.go index b0a435dafb44..5e5dcae184fd 100644 --- a/x/nft/keeper/genesis.go +++ b/x/nft/keeper/genesis.go @@ -9,24 +9,25 @@ import ( // InitGenesis initializes the nft module's genesis state from a given // genesis state. -func (k Keeper) InitGenesis(ctx context.Context, data *nft.GenesisState) { +func (k Keeper) InitGenesis(ctx context.Context, data *nft.GenesisState) error { for _, class := range data.Classes { if err := k.SaveClass(ctx, *class); err != nil { - panic(err) + return err } } for _, entry := range data.Entries { for _, nft := range entry.Nfts { owner, err := k.ac.StringToBytes(entry.Owner) if err != nil { - panic(err) + return err } if err := k.Mint(ctx, *nft, owner); err != nil { - panic(err) + return err } } } + return nil } // ExportGenesis returns a GenesisState for a given context. diff --git a/x/nft/keeper/keeper_test.go b/x/nft/keeper/keeper_test.go index 823553727bd5..e3ac2dfd0563 100644 --- a/x/nft/keeper/keeper_test.go +++ b/x/nft/keeper/keeper_test.go @@ -386,7 +386,8 @@ func (s *TestSuite) TestInitGenesis() { Nfts: []*nft.NFT{&expNFT}, }}, } - s.nftKeeper.InitGenesis(s.ctx, expGenesis) + err := s.nftKeeper.InitGenesis(s.ctx, expGenesis) + s.Require().NoError(err) actual, has := s.nftKeeper.GetClass(s.ctx, testClassID) s.Require().True(has) diff --git a/x/nft/module/module.go b/x/nft/module/module.go index b782d14c39fb..9a5ca47effa0 100644 --- a/x/nft/module/module.go +++ b/x/nft/module/module.go @@ -8,6 +8,7 @@ import ( "google.golang.org/grpc" "cosmossdk.io/core/appmodule" + appmodulev2 "cosmossdk.io/core/appmodule/v2" "cosmossdk.io/core/registry" "cosmossdk.io/errors" "cosmossdk.io/x/nft" @@ -26,7 +27,7 @@ var ( _ module.HasGRPCGateway = AppModule{} _ appmodule.HasRegisterInterfaces = AppModule{} _ module.AppModuleSimulation = AppModule{} - _ module.HasGenesis = AppModule{} + _ appmodulev2.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} ) @@ -83,14 +84,14 @@ func (AppModule) RegisterGRPCGatewayRoutes(clientCtx sdkclient.Context, mux *gwr } // DefaultGenesis returns default genesis state as raw bytes for the nft module. -func (AppModule) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(nft.DefaultGenesisState()) +func (am AppModule) DefaultGenesis() json.RawMessage { + return am.cdc.MustMarshalJSON(nft.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the nft module. -func (am AppModule) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { +func (am AppModule) ValidateGenesis(bz json.RawMessage) error { var data nft.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { + if err := am.cdc.UnmarshalJSON(bz, &data); err != nil { return errors.Wrapf(err, "failed to unmarshal %s genesis state", nft.ModuleName) } @@ -98,16 +99,18 @@ func (am AppModule) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEnco } // InitGenesis performs genesis initialization for the nft module. -func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { +func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) error { var genesisState nft.GenesisState - cdc.MustUnmarshalJSON(data, &genesisState) - am.keeper.InitGenesis(ctx, &genesisState) + if err := am.cdc.UnmarshalJSON(data, &genesisState); err != nil { + return err + } + return am.keeper.InitGenesis(ctx, &genesisState) } // ExportGenesis returns the exported genesis state as raw bytes for the nft module. -func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json.RawMessage { +func (am AppModule) ExportGenesis(ctx context.Context) (json.RawMessage, error) { gs := am.keeper.ExportGenesis(ctx) - return cdc.MustMarshalJSON(gs) + return am.cdc.MarshalJSON(gs) } // ConsensusVersion implements HasConsensusVersion diff --git a/x/protocolpool/module.go b/x/protocolpool/module.go index 03c56baed7ac..4539e9b1ab28 100644 --- a/x/protocolpool/module.go +++ b/x/protocolpool/module.go @@ -9,6 +9,7 @@ import ( "google.golang.org/grpc" "cosmossdk.io/core/appmodule" + appmodulev2 "cosmossdk.io/core/appmodule/v2" "cosmossdk.io/core/registry" "cosmossdk.io/x/protocolpool/keeper" "cosmossdk.io/x/protocolpool/types" @@ -22,13 +23,13 @@ import ( const ConsensusVersion = 1 var ( - _ module.HasName = AppModule{} - _ module.HasAminoCodec = AppModule{} - _ module.HasGRPCGateway = AppModule{} - _ appmodule.HasRegisterInterfaces = AppModule{} - _ module.AppModule = AppModule{} - _ module.AppModuleSimulation = AppModule{} - _ module.HasGenesis = AppModule{} + _ module.HasName = AppModule{} + _ module.HasAminoCodec = AppModule{} + _ module.HasGRPCGateway = AppModule{} + _ module.HasRegisterInterfaces = AppModule{} + _ module.AppModule = AppModule{} + _ module.AppModuleSimulation = AppModule{} + _ appmodulev2.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasServices = AppModule{} @@ -84,14 +85,14 @@ func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { } // DefaultGenesis returns default genesis state as raw bytes for the protocolpool module. -func (AppModule) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) +func (am AppModule) DefaultGenesis() json.RawMessage { + return am.cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the protocolpool module. -func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { +func (am AppModule) ValidateGenesis(bz json.RawMessage) error { var data types.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { + if err := am.cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) } @@ -99,21 +100,24 @@ func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingCo } // InitGenesis performs genesis initialization for the protocolpool module. -func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { +func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) error { var genesisState types.GenesisState - cdc.MustUnmarshalJSON(data, &genesisState) + if err := am.cdc.UnmarshalJSON(data, &genesisState); err != nil { + return err + } if err := am.keeper.InitGenesis(ctx, &genesisState); err != nil { - panic(err) + return err } + return nil } // ExportGenesis returns the exported genesis state as raw bytes for the protocolpool module. -func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json.RawMessage { +func (am AppModule) ExportGenesis(ctx context.Context) (json.RawMessage, error) { gs, err := am.keeper.ExportGenesis(ctx) if err != nil { - panic(err) + return nil, err } - return cdc.MustMarshalJSON(gs) + return am.cdc.MarshalJSON(gs) } // ConsensusVersion implements HasConsensusVersion diff --git a/x/slashing/keeper/genesis.go b/x/slashing/keeper/genesis.go index d0528fa0a0eb..ac4af63f0054 100644 --- a/x/slashing/keeper/genesis.go +++ b/x/slashing/keeper/genesis.go @@ -10,7 +10,7 @@ import ( // InitGenesis initializes default parameters and the keeper's address to // pubkey map. -func (keeper Keeper) InitGenesis(ctx context.Context, stakingKeeper types.StakingKeeper, data *types.GenesisState) { +func (keeper Keeper) InitGenesis(ctx context.Context, stakingKeeper types.StakingKeeper, data *types.GenesisState) error { err := stakingKeeper.IterateValidators(ctx, func(index int64, validator sdk.ValidatorI) bool { consPk, err := validator.ConsPubKey() @@ -26,36 +26,37 @@ func (keeper Keeper) InitGenesis(ctx context.Context, stakingKeeper types.Stakin }, ) if err != nil { - panic(err) + return err } for _, info := range data.SigningInfos { address, err := keeper.sk.ConsensusAddressCodec().StringToBytes(info.Address) if err != nil { - panic(err) + return err } err = keeper.ValidatorSigningInfo.Set(ctx, address, info.ValidatorSigningInfo) if err != nil { - panic(err) + return err } } for _, array := range data.MissedBlocks { address, err := keeper.sk.ConsensusAddressCodec().StringToBytes(array.Address) if err != nil { - panic(err) + return err } for _, missed := range array.MissedBlocks { if err := keeper.SetMissedBlockBitmapValue(ctx, address, missed.Index, missed.Missed); err != nil { - panic(err) + return err } } } if err := keeper.Params.Set(ctx, data.Params); err != nil { - panic(err) + return err } + return nil } // ExportGenesis writes the current store values diff --git a/x/slashing/keeper/genesis_test.go b/x/slashing/keeper/genesis_test.go index eee5bfe98d57..c8ba1131da7c 100644 --- a/x/slashing/keeper/genesis_test.go +++ b/x/slashing/keeper/genesis_test.go @@ -50,7 +50,8 @@ func (s *KeeperTestSuite) TestExportAndInitGenesis() { // Initialize genesis with genesis state before tombstone s.stakingKeeper.EXPECT().IterateValidators(ctx, gomock.Any()).Return(nil) - keeper.InitGenesis(ctx, s.stakingKeeper, genesisState) + err = keeper.InitGenesis(ctx, s.stakingKeeper, genesisState) + s.Require().NoError(err) // Validator isTombstoned should return false as GenesisState is initialized ok = keeper.IsTombstoned(ctx, consAddr1) diff --git a/x/slashing/module.go b/x/slashing/module.go index 6c78a386166d..875727d62c0b 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -9,6 +9,7 @@ import ( "google.golang.org/grpc" "cosmossdk.io/core/appmodule" + appmodulev2 "cosmossdk.io/core/appmodule/v2" "cosmossdk.io/core/registry" "cosmossdk.io/x/slashing/keeper" "cosmossdk.io/x/slashing/simulation" @@ -25,12 +26,12 @@ import ( const ConsensusVersion = 4 var ( - _ module.HasName = AppModule{} - _ module.HasAminoCodec = AppModule{} - _ module.HasGRPCGateway = AppModule{} - _ appmodule.HasRegisterInterfaces = AppModule{} - _ module.AppModuleSimulation = AppModule{} - _ module.HasGenesis = AppModule{} + _ module.HasName = AppModule{} + _ module.HasAminoCodec = AppModule{} + _ module.HasGRPCGateway = AppModule{} + _ module.HasRegisterInterfaces = AppModule{} + _ module.AppModuleSimulation = AppModule{} + _ appmodulev2.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasBeginBlocker = AppModule{} @@ -121,14 +122,14 @@ func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { } // DefaultGenesis returns default genesis state as raw bytes for the slashing module. -func (AppModule) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) +func (am AppModule) DefaultGenesis() json.RawMessage { + return am.cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the slashing module. -func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { +func (am AppModule) ValidateGenesis(bz json.RawMessage) error { var data types.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { + if err := am.cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) } @@ -136,16 +137,18 @@ func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingCo } // InitGenesis performs genesis initialization for the slashing module. -func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { +func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) error { var genesisState types.GenesisState - cdc.MustUnmarshalJSON(data, &genesisState) - am.keeper.InitGenesis(ctx, am.stakingKeeper, &genesisState) + if err := am.cdc.UnmarshalJSON(data, &genesisState); err != nil { + return err + } + return am.keeper.InitGenesis(ctx, am.stakingKeeper, &genesisState) } // ExportGenesis returns the exported genesis state as raw bytes for the slashing module. -func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json.RawMessage { +func (am AppModule) ExportGenesis(ctx context.Context) (json.RawMessage, error) { gs := am.keeper.ExportGenesis(ctx) - return cdc.MustMarshalJSON(gs) + return am.cdc.MarshalJSON(gs) } // ConsensusVersion implements HasConsensusVersion diff --git a/x/staking/module.go b/x/staking/module.go index d3d28ce25043..bbeefee67e85 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -131,14 +131,14 @@ func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { } // DefaultGenesis returns default genesis state as raw bytes for the staking module. -func (AppModule) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) +func (am AppModule) DefaultGenesis() json.RawMessage { + return am.cdc.MustMarshalJSON(types.DefaultGenesisState()) } // ValidateGenesis performs genesis state validation for the staking module. -func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { +func (am AppModule) ValidateGenesis(bz json.RawMessage) error { var data types.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { + if err := am.cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) } @@ -146,18 +146,18 @@ func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingCo } // InitGenesis performs genesis initialization for the staking module. -func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState types.GenesisState - cdc.MustUnmarshalJSON(data, &genesisState) + am.cdc.MustUnmarshalJSON(data, &genesisState) return am.keeper.InitGenesis(ctx, &genesisState) } // ExportGenesis returns the exported genesis state as raw bytes for the staking // module. -func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(am.keeper.ExportGenesis(ctx)) +func (am AppModule) ExportGenesis(ctx context.Context) json.RawMessage { + return am.cdc.MustMarshalJSON(am.keeper.ExportGenesis(ctx)) } // ConsensusVersion implements HasConsensusVersion diff --git a/x/upgrade/module.go b/x/upgrade/module.go index 7ddebb6bc1e8..7b0f1a53f32e 100644 --- a/x/upgrade/module.go +++ b/x/upgrade/module.go @@ -10,6 +10,7 @@ import ( "google.golang.org/grpc" "cosmossdk.io/core/appmodule" + appmodulev2 "cosmossdk.io/core/appmodule/v2" "cosmossdk.io/core/registry" "cosmossdk.io/x/upgrade/client/cli" "cosmossdk.io/x/upgrade/keeper" @@ -28,11 +29,11 @@ func init() { const ConsensusVersion uint64 = 3 var ( - _ module.HasName = AppModule{} - _ module.HasAminoCodec = AppModule{} - _ module.HasGRPCGateway = AppModule{} - _ appmodule.HasRegisterInterfaces = AppModule{} - _ module.HasGenesis = AppModule{} + _ module.HasName = AppModule{} + _ module.HasAminoCodec = AppModule{} + _ module.HasGRPCGateway = AppModule{} + _ module.HasRegisterInterfaces = AppModule{} + _ appmodulev2.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasPreBlocker = AppModule{} @@ -105,24 +106,24 @@ func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { } // DefaultGenesis is an empty object -func (AppModule) DefaultGenesis(_ codec.JSONCodec) json.RawMessage { +func (AppModule) DefaultGenesis() json.RawMessage { return []byte("{}") } // ValidateGenesis is always successful, as we ignore the value -func (AppModule) ValidateGenesis(_ codec.JSONCodec, _ client.TxEncodingConfig, _ json.RawMessage) error { +func (AppModule) ValidateGenesis(_ json.RawMessage) error { return nil } // InitGenesis is ignored, no sense in serializing future upgrades -func (am AppModule) InitGenesis(ctx context.Context, _ codec.JSONCodec, _ json.RawMessage) { +func (am AppModule) InitGenesis(ctx context.Context, _ json.RawMessage) error { // set version map automatically if available if versionMap := am.keeper.GetInitVersionMap(); versionMap != nil { // chains can still use a custom init chainer for setting the version map // this means that we need to combine the manually wired modules version map with app wiring enabled modules version map moduleVM, err := am.keeper.GetModuleVersionMap(ctx) if err != nil { - panic(err) + return err } for name, version := range moduleVM { @@ -133,14 +134,15 @@ func (am AppModule) InitGenesis(ctx context.Context, _ codec.JSONCodec, _ json.R err = am.keeper.SetModuleVersionMap(ctx, versionMap) if err != nil { - panic(err) + return err } } + return nil } // ExportGenesis is always empty, as InitGenesis does nothing either -func (am AppModule) ExportGenesis(_ context.Context, cdc codec.JSONCodec) json.RawMessage { - return am.DefaultGenesis(cdc) +func (am AppModule) ExportGenesis(_ context.Context) (json.RawMessage, error) { + return am.DefaultGenesis(), nil } // ConsensusVersion implements HasConsensusVersion