diff --git a/CHANGELOG.md b/CHANGELOG.md index 12968844377a..1a210fd6dacf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -56,6 +56,10 @@ Every module contains its own CHANGELOG.md. Please refer to the module you are i ### Improvements +* (types) [#19512](https://github.com/cosmos/cosmos-sdk/pull/19512) The notion of basic manager does not exist anymore. + * The module manager now can do everything that the basic manager was doing. + * `AppModuleBasic` has been deprecated for extension interfaces. Modules can now implement `HasRegisterInterfaces`, `HasGRPCGateway` and `HasAminoCodec` when relevant. + * SDK modules now directly implement those extension interfaces on `AppModule` instead of `AppModuleBasic`. * (client/keys) [#18950](https://github.com/cosmos/cosmos-sdk/pull/18950) Improve ` keys add`, ` keys import` and ` keys rename` by checking name validation. * (client/keys) [#18745](https://github.com/cosmos/cosmos-sdk/pull/18745) Improve ` keys export` and ` keys mnemonic` by adding --yes option to skip interactive confirmation. * (client/keys) [#18743](https://github.com/cosmos/cosmos-sdk/pull/18743) Improve ` keys add -i` by hiding inputting of bip39 passphrase. @@ -100,6 +104,10 @@ Every module contains its own CHANGELOG.md. Please refer to the module you are i ### API Breaking Changes +* (types) [#19512](https://github.com/cosmos/cosmos-sdk/pull/19512) Remove basic manager and all related functions (`module.BasicManager`, `module.NewBasicManager`, `module.NewBasicManagerFromManager`, `NewGenesisOnlyAppModule`). + * The module manager now can do everything that the basic manager was doing. + * When using runtime, just inject the module manager when needed using your app config. + * All `AppModuleBasic` structs have been removed. * (x/consensus) [#19488](https://github.com/cosmos/cosmos-sdk/pull/19488) Consensus module creation takes `appmodule.Environment` instead of individual services. * (server) [#18303](https://github.com/cosmos/cosmos-sdk/pull/18303) `x/genutil` now handles the application export. `server.AddCommands` does not take an `AppExporter` but instead `genutilcli.Commands` does. * (x/gov/testutil) [#17986](https://github.com/cosmos/cosmos-sdk/pull/18036) `MsgDeposit` has been removed because of AutoCLI migration. diff --git a/UPGRADING.md b/UPGRADING.md index d63715fa2008..8ed75edacba2 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -10,11 +10,6 @@ Note, always read the **SimApp** section for more information on application wir In this section we describe the changes made in Cosmos SDK' SimApp. **These changes are directly applicable to your application wiring.** -#### AnteHandlers - -The GasConsumptionDecorator and IncreaseSequenceDecorator have been merged with the SigVerificationDecorator, so you'll -need to remove them both from your app.go code, they will yield to unresolvable symbols when compiling. - #### Client (`root.go`) The `client` package has been refactored to make use of the address codecs (address, validator address, consensus address, etc.). @@ -33,16 +28,32 @@ clientCtx = clientCtx. Refer to SimApp `root_v2.go` and `root.go` for an example with an app v2 and a legacy app. -### Core +#### Server (`app.go`) -`appmodule.Environment` interface was introduced to fetch different services from the application. This can be used as an alternative to using `sdk.UnwrapContext(ctx)` to fetch the services. It needs to be passed into a module at instantiation. +##### Module Manager -Circuit Breaker is used as an example. +The basic module manager has been deleted. It was not necessary anymore and was simplified to use the `module.Manager` directly. +It can be removed from your `app.go`. -```go -app.CircuitKeeper = circuitkeeper.NewKeeper(runtime.NewEnvironment((keys[circuittypes.StoreKey])), appCodec, authtypes.NewModuleAddress(govtypes.ModuleName).String(), app.AuthKeeper.AddressCodec()) +For depinject users, it isn't necessary anymore to supply a `map[string]module.AppModuleBasic` for customizing the app module basic instantiation. +The custom parameters (such as genutil message validator or gov proposal handler, or evidence handler) can directly be supplied. +When requiring a module manager in `root.go`, inject `*module.Manager` using `depinject.Inject`. + +For non depinject users, simply call `RegisterLegacyAminoCodec` and `RegisterInterfaces` on the module manager: + +```diff +-app.BasicModuleManager = module.NewBasicManagerFromManager(...) +-app.BasicModuleManager.RegisterLegacyAminoCodec(legacyAmino) +-app.BasicModuleManager.RegisterInterfaces(interfaceRegistry) ++app.ModuleManager.RegisterLegacyAminoCodec(legacyAmino) ++app.ModuleManager.RegisterInterfaces(interfaceRegistry) ``` +##### AnteHandlers + +The `GasConsumptionDecorator` and `IncreaseSequenceDecorator` have been merged with the SigVerificationDecorator, so you'll +need to remove them both from your app.go code, they will yield to unresolvable symbols when compiling. + #### Unordered Transactions The Cosmos SDK now supports unordered transactions. This means that transactions @@ -129,26 +140,35 @@ If you were depending on `cosmossdk.io/api/tendermint`, please use the buf gener #### `**all**` -##### Params +##### Core API -Previous module migrations have been removed. It is required to migrate to v0.50 prior to upgrading to v0.51 for not missing any module migrations. +Core API has been introduced for modules since v0.47. With the deprecation of `sdk.Context`, we strongly recommend to use the `cosmossdk.io/core/appmodule` interfaces for the modules. This will allow the modules to work out of the box with server/v2 and baseapp, as well as limit their dependencies on the SDK. -##### Core API +Additionally, the `appmodule.Environment` interface is introduced to fetch different services from the application. +This should be used as an alternative to using `sdk.UnwrapContext(ctx)` to fetch the services. +It needs to be passed into a module at instantiation. -Core API has been introduces for modules in v0.47. With the deprecation of `sdk.Context`, we strongly recommend to use the `cosmossdk.io/core/appmodule` interfaces for the modules. This will allow the modules to work out of the box with server/v2 and baseapp, as well as limit their dependencies on the SDK. +`x/circuit` is used as an example.: + +```go +app.CircuitKeeper = circuitkeeper.NewKeeper(runtime.NewEnvironment((keys[circuittypes.StoreKey])), appCodec, authtypes.NewModuleAddress(govtypes.ModuleName).String(), app.AuthKeeper.AddressCodec()) +``` ##### Dependency Injection Previously `cosmossdk.io/core` held functions `Invoke`, `Provide` and `Register` were moved to `cosmossdk.io/depinject/appconfig`. All modules using dependency injection must update their imports. +##### Params + +Previous module migrations have been removed. It is required to migrate to v0.50 prior to upgrading to v0.51 for not missing any module migrations. + ##### Genesis Interface All genesis interfaces have been migrated to take context.Context instead of sdk.Context. -```golang -// InitGenesis performs genesis initialization for the authz module. It returns -// no validator updates. +```go +// InitGenesis performs genesis initialization for the authz module. func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { } diff --git a/baseapp/msg_service_router.go b/baseapp/msg_service_router.go index f2857affcead..fe4488d2673c 100644 --- a/baseapp/msg_service_router.go +++ b/baseapp/msg_service_router.go @@ -163,7 +163,7 @@ func (msr *MsgServiceRouter) registerMsgServiceHandler(sd *grpc.ServiceDesc, met return fmt.Errorf( "type_url %s has not been registered yet. "+ "Before calling RegisterService, you must register all interfaces by calling the `RegisterInterfaces` "+ - "method on module.BasicManager. Each module should call `msgservice.RegisterMsgServiceDesc` inside its "+ + "method on module.Manager. Each module should call `msgservice.RegisterMsgServiceDesc` inside its "+ "`RegisterInterfaces` method with the `_Msg_serviceDesc` generated by proto-gen", requestTypeName, ) diff --git a/client/grpc_query_test.go b/client/grpc_query_test.go index f63c3f52f985..7aaf78a85445 100644 --- a/client/grpc_query_test.go +++ b/client/grpc_query_test.go @@ -39,7 +39,7 @@ func (s *IntegrationTestSuite) SetupSuite() { keys := storetypes.NewKVStoreKeys(countertypes.StoreKey) cms := integration.CreateMultiStore(keys, logger) s.ctx = sdk.NewContext(cms, true, logger) - cfg := moduletestutil.MakeTestEncodingConfig(counter.AppModuleBasic{}) + cfg := moduletestutil.MakeTestEncodingConfig(counter.AppModule{}) s.cdc = cfg.Codec queryHelper := baseapp.NewQueryServerTestHelper(s.ctx, cfg.InterfaceRegistry) diff --git a/client/tx/aux_builder_test.go b/client/tx/aux_builder_test.go index 9ff27743d9df..f177ba730a89 100644 --- a/client/tx/aux_builder_test.go +++ b/client/tx/aux_builder_test.go @@ -32,7 +32,7 @@ var ( ) func TestAuxTxBuilder(t *testing.T) { - counterModule := counter.AppModuleBasic{} + counterModule := counter.AppModule{} cdc := moduletestutil.MakeTestEncodingConfig(counterModule).Codec reg := codectypes.NewInterfaceRegistry() diff --git a/client/v2/autocli/common_test.go b/client/v2/autocli/common_test.go index ea2948cd525f..c75eaa5b17a4 100644 --- a/client/v2/autocli/common_test.go +++ b/client/v2/autocli/common_test.go @@ -51,7 +51,7 @@ func initFixture(t *testing.T) *fixture { clientConn, err := grpc.Dial(listener.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials())) assert.NilError(t, err) - encodingConfig := moduletestutil.MakeTestEncodingConfig(bank.AppModuleBasic{}) + encodingConfig := moduletestutil.MakeTestEncodingConfig(bank.AppModule{}) kr, err := sdkkeyring.New(sdk.KeyringServiceName(), sdkkeyring.BackendMemory, home, nil, encodingConfig.Codec) assert.NilError(t, err) diff --git a/client/v2/go.mod b/client/v2/go.mod index e15b4123ad29..0149861f0716 100644 --- a/client/v2/go.mod +++ b/client/v2/go.mod @@ -174,7 +174,7 @@ require ( replace github.com/cosmos/cosmos-sdk => ./../../ replace ( - cosmossdk.io/api => ../../api + cosmossdk.io/api => ./../../api cosmossdk.io/core => ./../../core cosmossdk.io/depinject => ./../../depinject cosmossdk.io/x/accounts => ./../../x/accounts diff --git a/docs/architecture/adr-020-protobuf-transaction-encoding.md b/docs/architecture/adr-020-protobuf-transaction-encoding.md index b3b294b226dc..db9a52b6fbd8 100644 --- a/docs/architecture/adr-020-protobuf-transaction-encoding.md +++ b/docs/architecture/adr-020-protobuf-transaction-encoding.md @@ -349,7 +349,7 @@ type TxBuilder interface { ``` We then update `Context` to have new fields: `Codec`, `TxGenerator`, -and `AccountRetriever`, and we update `AppModuleBasic.GetTxCmd` to take +and `AccountRetriever`, and we update `AppModule.GetTxCmd` to take a `Context` which should have all of these fields pre-populated. Each client method should then use one of the `Init` methods to re-initialize diff --git a/docs/architecture/adr-032-typed-events.md b/docs/architecture/adr-032-typed-events.md index 037781917b3d..1c043038d437 100644 --- a/docs/architecture/adr-032-typed-events.md +++ b/docs/architecture/adr-032-typed-events.md @@ -261,7 +261,7 @@ func TxEmitter(ctx context.Context, cliCtx client.Context, ehs ...EventHandler) } // PublishChainTxEvents events using cmtclient. Waits on context shutdown signals to exit. -func PublishChainTxEvents(ctx context.Context, client cmtclient.EventsClient, bus pubsub.Bus, mb module.BasicManager) (err error) { +func PublishChainTxEvents(ctx context.Context, client cmtclient.EventsClient, bus pubsub.Bus) (err error) { // Subscribe to transaction events txch, err := client.Subscribe(ctx, "txevents", "tm.event='Tx'", 100) if err != nil { @@ -289,12 +289,12 @@ func PublishChainTxEvents(ctx context.Context, client cmtclient.EventsClient, bu if !evt.Result.IsOK() { continue } - // range over events, parse them using the basic manager and + // range over events and parse them // send them to the pubsub bus for _, abciEv := range events { typedEvent, err := sdk.ParseTypedEvent(abciEv) if err != nil { - return er + return err } if err := bus.Publish(typedEvent); err != nil { bus.Close() diff --git a/docs/architecture/adr-033-protobuf-inter-module-comm.md b/docs/architecture/adr-033-protobuf-inter-module-comm.md index b99333a3eb0b..4f2769e6770f 100644 --- a/docs/architecture/adr-033-protobuf-inter-module-comm.md +++ b/docs/architecture/adr-033-protobuf-inter-module-comm.md @@ -264,7 +264,7 @@ type Configurator interface { The `ModuleKey` is passed to modules in the `RegisterService` method itself so that `RegisterServices` serves as a single entry point for configuring module services. This is intended to also have the side-effect of greatly reducing boilerplate in -`app.go`. For now, `ModuleKey`s will be created based on `AppModuleBasic.Name()`, but a more flexible system may be +`app.go`. For now, `ModuleKey`s will be created based on `AppModule.Name()`, but a more flexible system may be introduced in the future. The `ModuleManager` will handle creation of module accounts behind the scenes. Because modules do not get direct access to each other anymore, modules may have unfulfilled dependencies. To make sure @@ -344,7 +344,7 @@ Other future improvements may include: * optimizes inter-module calls - for instance caching resolved methods after first invocation * combining `StoreKey`s and `ModuleKey`s into a single interface so that modules have a single OCAPs handle * code generation which makes inter-module communication more performant -* decoupling `ModuleKey` creation from `AppModuleBasic.Name()` so that app's can override root module account names +* decoupling `ModuleKey` creation from `AppModule.Name()` so that app's can override root module account names * inter-module hooks and plugins ## Alternatives diff --git a/docs/architecture/adr-063-core-module-api.md b/docs/architecture/adr-063-core-module-api.md index 0abc251fa760..1615a590eb21 100644 --- a/docs/architecture/adr-063-core-module-api.md +++ b/docs/architecture/adr-063-core-module-api.md @@ -463,10 +463,10 @@ module manager and follow the Cosmos SDK's existing [0-based versioning](https:/ versioning as well as runtime modularity, new officially supported runtime modules will be created under the `cosmossdk.io/runtime` prefix. For each supported consensus engine a semantically-versioned go module should be created with a runtime implementation for that consensus engine. For example: -- `cosmossdk.io/runtime/comet` -- `cosmossdk.io/runtime/comet/v2` -- `cosmossdk.io/runtime/rollkit` -- etc. +* `cosmossdk.io/runtime/comet` +* `cosmossdk.io/runtime/comet/v2` +* `cosmossdk.io/runtime/rollkit` +* etc. These runtime modules should attempt to be semantically versioned even if the underlying consensus engine is not. Also, because a runtime module is also a first class Cosmos SDK module, it should have a protobuf module config type. diff --git a/docs/build/building-modules/01-module-manager.md b/docs/build/building-modules/01-module-manager.md index 10ded2437248..61a3fe66fea6 100644 --- a/docs/build/building-modules/01-module-manager.md +++ b/docs/build/building-modules/01-module-manager.md @@ -27,15 +27,13 @@ For legacy reason modules can still implement interfaces from the SDK `module` p There are 2 main application module interfaces: * [`appmodule.AppModule` / `module.AppModule`](#appmodule) for inter-dependent module functionalities (except genesis-related functionalities). -* (legacy) [`module.AppModuleBasic`](#appmodulebasic) for independent module functionalities. New modules can use `module.CoreAppModuleBasicAdaptor` instead. 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. -* [`module.HasGenesis`](#modulehasgenesis) for inter-dependent genesis-related module functionalities. -* [`module.HasABCIGenesis`](#modulehasabcigenesis) for inter-dependent genesis-related module functionalities. -* [`appmodule.HasGenesis` / `module.HasGenesis`](#appmodulehasgenesis): The extension interface for stateful genesis methods. +* (legacy) [`module.HasGenesis`](#modulehasgenesis) for inter-dependent genesis-related module functionalities. +* (legacy) [`module.HasABCIGenesis`](#modulehasabcigenesis) for inter-dependent genesis-related module functionalities. * [`appmodule.HasPreBlocker`](#haspreblocker): The extension interface that contains information about the `AppModule` and `PreBlock`. * [`appmodule.HasBeginBlocker`](#hasbeginblocker): The extension interface that contains information about the `AppModule` and `BeginBlock`. * [`appmodule.HasEndBlocker`](#hasendblocker): The extension interface that contains information about the `AppModule` and `EndBlock`. @@ -46,31 +44,34 @@ The above interfaces are mostly embedding smaller interfaces (extension interfac * (legacy) [`module.HasInvariants`](#hasinvariants): The extension interface for registering invariants. * (legacy) [`module.HasConsensusVersion`](#hasconsensusversion): The extension interface for declaring a module consensus version. -The `AppModuleBasic` interface exists to define independent methods of the module, i.e. those that do not depend on other modules in the application. This allows for the construction of the basic application structure early in the application definition, generally in the `init()` function of the [main application file](https://docs.cosmos.network/main/learn/beginner/app-anatomy). - The `AppModule` interface exists to define inter-dependent module methods. Many modules need to interact with other modules, typically through [`keeper`s](./06-keeper.md), which means there is a need for an interface where modules list their `keeper`s and other methods that require a reference to another module's object. `AppModule` interface extension, such as `HasBeginBlocker` and `HasEndBlocker`, also enables the module manager to set the order of execution between module's methods like `BeginBlock` and `EndBlock`, which is important in cases where the order of execution between modules matters in the context of the application. The usage of extension interfaces allows modules to define only the functionalities they need. For example, a module that does not need an `EndBlock` does not need to define the `HasEndBlocker` interface and thus the `EndBlock` method. `AppModule` and `AppModuleGenesis` are voluntarily small interfaces, that can take advantage of the `Module` patterns without having to define many placeholder functions. -### `AppModuleBasic` +### `HasAminoCodec` -:::note -Use `module.CoreAppModuleBasicAdaptor` instead for creating an `AppModuleBasic` from an `appmodule.AppModule`. -::: +```go reference +// TODO +``` -The `AppModuleBasic` interface defines the independent methods modules need to implement. +* `RegisterLegacyAminoCodec(*codec.LegacyAmino)`: Registers the `amino` codec for the module, which is used to marshal and unmarshal structs to/from `[]byte` in order to persist them in the module's `KVStore`. + +### `HasRegisterInterfaces` ```go reference -https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/types/module/module.go#L56-L66 +// TODO ``` -Let us go through the methods: - -* `RegisterLegacyAminoCodec(*codec.LegacyAmino)`: Registers the `amino` codec for the module, which is used to marshal and unmarshal structs to/from `[]byte` in order to persist them in the module's `KVStore`. * `RegisterInterfaces(codectypes.InterfaceRegistry)`: Registers a module's interface types and their concrete implementations as `proto.Message`. + +### `HasGRPCGateway` + +```go reference +// TODO +``` + * `RegisterGRPCGatewayRoutes(client.Context, *runtime.ServeMux)`: Registers gRPC routes for the module. -All the `AppModuleBasic` of an application are managed by the [`BasicManager`](#basicmanager). ### `HasName` @@ -83,7 +84,7 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/types/module/module.go ### Genesis :::tip -For easily creating an `AppModule` that only has genesis functionalities, use `module.GenesisOnlyAppModule`. +For easily creating an `AppModule` that only has genesis functionalities, implement `module.HasGenesis/HasABCIGenesis` and `module.HasName`. ::: #### `module.HasGenesisBasics` @@ -113,16 +114,6 @@ https://github.com/cosmos/cosmos-sdk/blob/6ce2505/types/module/module.go#L184-L1 https://github.com/cosmos/cosmos-sdk/blob/6ce2505/types/module/module.go#L191-L196 ``` -#### `appmodule.HasGenesis` - -:::warning -`appmodule.HasGenesis` is experimental and should be considered unstable, it is recommended to not use this interface at this time. -::: - -```go reference -https://github.com/cosmos/cosmos-sdk/blob/6ce2505/core/appmodule/genesis.go#L8-L25 -``` - ### `AppModule` The `AppModule` interface defines a module. Modules can declare their functionalities by implementing extensions interfaces. @@ -238,49 +229,24 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/core/appmodule/module. ### Implementing the Application Module Interfaces +// TODO reword! + Typically, the various application module interfaces are implemented in a file called `module.go`, located in the module's folder (e.g. `./x/module/module.go`). -Almost every module needs to implement the `AppModuleBasic` and `AppModule` interfaces. If the module is only used for genesis, it will implement `AppModuleGenesis` instead of `AppModule`. The concrete type that implements the interface can add parameters that are required for the implementation of the various methods of the interface. For example, the `Route()` function often calls a `NewMsgServerImpl(k keeper)` function defined in `keeper/msg_server.go` and therefore needs to pass the module's [`keeper`](./06-keeper.md) as a parameter. +Almost every module needs to implement the `AppModule` interfaces. If the module is only used for genesis, it will implement `AppModuleGenesis` instead of `AppModule`. The concrete type that implements the interface can add parameters that are required for the implementation of the various methods of the interface. For example, the `Route()` function often calls a `NewMsgServerImpl(k keeper)` function defined in `keeper/msg_server.go` and therefore needs to pass the module's [`keeper`](./06-keeper.md) as a parameter. ```go // example type AppModule struct { - AppModuleBasic keeper Keeper } ``` In the example above, you can see that the `AppModule` concrete type references an `AppModuleBasic`, and not an `AppModuleGenesis`. That is because `AppModuleGenesis` only needs to be implemented in modules that focus on genesis-related functionalities. In most modules, the concrete `AppModule` type will have a reference to an `AppModuleBasic` and implement the two added methods of `AppModuleGenesis` directly in the `AppModule` type. -If no parameter is required (which is often the case for `AppModuleBasic`), just declare an empty concrete type like so: - -```go -type AppModuleBasic struct{} -``` - -## Module Managers - -Module managers are used to manage collections of `AppModuleBasic` and `AppModule`. - -### `BasicManager` +## Module Manager -The `BasicManager` is a structure that lists all the `AppModuleBasic` of an application: - -```go reference -https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/types/module/module.go#L82 -``` - -It implements the following methods: - -* `NewBasicManager(modules ...AppModuleBasic)`: Constructor function. It takes a list of the application's `AppModuleBasic` and builds a new `BasicManager`. This function is generally called in the `init()` function of [`app.go`](../../learn/beginner/00-app-anatomy.md#core-application-file) to quickly initialize the independent elements of the application's modules (click [here](https://github.com/cosmos/gaia/blob/main/app/app.go#L59-L74) to see an example). -* `NewBasicManagerFromManager(manager *Manager, customModuleBasics map[string]AppModuleBasic)`: Constructor function. It creates a new `BasicManager` from a `Manager`. The `BasicManager` will contain all `AppModuleBasic` from the `AppModule` manager using `CoreAppModuleBasicAdaptor` whenever possible. Module's `AppModuleBasic` can be overridden by passing a custom AppModuleBasic map -* `RegisterLegacyAminoCodec(cdc *codec.LegacyAmino)`: Registers the [`codec.LegacyAmino`s](../../learn/advanced/05-encoding.md#amino) of each of the application's `AppModuleBasic`. This function is usually called early on in the [application's construction](../../learn/beginner/00-app-anatomy.md#constructor). -* `RegisterInterfaces(registry codectypes.InterfaceRegistry)`: Registers interface types and implementations of each of the application's `AppModuleBasic`. -* `DefaultGenesis(cdc codec.JSONCodec)`: Provides default genesis information for modules in the application by calling the [`DefaultGenesis(cdc codec.JSONCodec)`](./08-genesis.md#defaultgenesis) function of each module. It only calls the modules that implements the `HasGenesisBasics` interfaces. -* `ValidateGenesis(cdc codec.JSONCodec, txEncCfg client.TxEncodingConfig, genesis map[string]json.RawMessage)`: Validates the genesis information modules by calling the [`ValidateGenesis(codec.JSONCodec, client.TxEncodingConfig, json.RawMessage)`](./08-genesis.md#validategenesis) function of modules implementing the `HasGenesisBasics` interface. -* `RegisterGRPCGatewayRoutes(clientCtx client.Context, rtr *runtime.ServeMux)`: Registers gRPC routes for modules. -* `AddTxCommands(rootTxCmd *cobra.Command)`: Adds modules' transaction commands (defined as `GetTxCmd() *cobra.Command`) to the application's [`rootTxCommand`](../../learn/advanced/07-cli.md#transaction-commands). This function is usually called function from the `main.go` function of the [application's command-line interface](../../learn/advanced/07-cli.md). -* `AddQueryCommands(rootQueryCmd *cobra.Command)`: Adds modules' query commands (defined as `GetQueryCmd() *cobra.Command`) to the application's [`rootQueryCommand`](../../learn/advanced/07-cli.md#query-commands). This function is usually called function from the `main.go` function of the [application's command-line interface](../../learn/advanced/07-cli.md). +The module manager is used to manage collections of `appmodule.AppModule` and `AppModule` and all the extensions interfaces. ### `Manager` @@ -312,6 +278,11 @@ The module manager is used throughout the application whenever an action on a co * `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). * `Precommit(ctx context.Context)`: During [`Commit`](../../learn/advanced/00-baseapp.md#commit), this function is called from `BaseApp` immediately before the [`deliverState`](../../learn/advanced/00-baseapp.md#state-updates) is written to the underlying [`rootMultiStore`](../../learn/advanced/04-store.md#commitmultistore) and, in turn calls the `Precommit` function of each modules implementing the `HasPrecommit` interface, in the order defined in `OrderPrecommiters`. It creates a child [context](../../learn/advanced/02-context.md) where the underlying `CacheMultiStore` is that of the newly committed block's [`finalizeblockstate`](../../learn/advanced/00-baseapp.md#state-updates). * `PrepareCheckState(ctx context.Context)`: During [`Commit`](../../learn/advanced/00-baseapp.md#commit), this function is called from `BaseApp` immediately after the [`deliverState`](../../learn/advanced/00-baseapp.md#state-updates) is written to the underlying [`rootMultiStore`](../../learn/advanced/04-store.md#commitmultistore) and, in turn calls the `PrepareCheckState` function of each module implementing the `HasPrepareCheckState` interface, in the order defined in `OrderPrepareCheckStaters`. It creates a child [context](../../learn/advanced/02-context.md) where the underlying `CacheMultiStore` is that of the next block's [`checkState`](../../learn/advanced/00-baseapp.md#state-updates). Writes to this state will be present in the [`checkState`](../../learn/advanced/00-baseapp.md#state-updates) of the next block, and therefore this method can be used to prepare the `checkState` for the next block. +* (Optional) `RegisterLegacyAminoCodec(cdc *codec.LegacyAmino)`: Registers the [`codec.LegacyAmino`s](../../learn/advanced/05-encoding.md#amino) of each of the application module. This function is usually called early on in the [application's construction](../../learn/beginner/00-app-anatomy.md#constructor). +* `RegisterInterfaces(registry codectypes.InterfaceRegistry)`: Registers interface types and implementations of each of the application's `AppModule`. +* (Optional) `RegisterGRPCGatewayRoutes(clientCtx client.Context, rtr *runtime.ServeMux)`: Registers gRPC routes for modules. +* `DefaultGenesis(cdc codec.JSONCodec)`: Provides default genesis information for modules in the application by calling the [`DefaultGenesis(cdc codec.JSONCodec)`](./08-genesis.md#defaultgenesis) function of each module. It only calls the modules that implements the `HasGenesisBasics` interfaces. +* `ValidateGenesis(cdc codec.JSONCodec, txEncCfg client.TxEncodingConfig, genesis map[string]json.RawMessage)`: Validates the genesis information modules by calling the [`ValidateGenesis(codec.JSONCodec, client.TxEncodingConfig, json.RawMessage)`](./08-genesis.md#validategenesis) function of modules implementing the `HasGenesisBasics` interface. Here's an example of a concrete integration within an `simapp`: diff --git a/docs/build/building-modules/02-messages-and-queries.md b/docs/build/building-modules/02-messages-and-queries.md index 573c35cd770e..0751c96d6c9b 100644 --- a/docs/build/building-modules/02-messages-and-queries.md +++ b/docs/build/building-modules/02-messages-and-queries.md @@ -84,7 +84,7 @@ The Cosmos SDK uses Protobuf definitions to generate client and server code: A `RegisterMsgServer` method is also generated and should be used to register the module's `MsgServer` implementation in `RegisterServices` method from the [`AppModule` interface](./01-module-manager.md#appmodule). -In order for clients (CLI and grpc-gateway) to have these URLs registered, the Cosmos SDK provides the function `RegisterMsgServiceDesc(registry codectypes.InterfaceRegistry, sd *grpc.ServiceDesc)` that should be called inside module's [`RegisterInterfaces`](01-module-manager.md#appmodulebasic) method, using the proto-generated `&_Msg_serviceDesc` as `*grpc.ServiceDesc` argument. +In order for clients (CLI and grpc-gateway) to have these URLs registered, the Cosmos SDK provides the function `RegisterMsgServiceDesc(registry codectypes.InterfaceRegistry, sd *grpc.ServiceDesc)` that should be called inside module's [`RegisterInterfaces`](01-module-manager.md#hasregisterinterfaces) method, using the proto-generated `&_Msg_serviceDesc` as `*grpc.ServiceDesc` argument. ## Queries diff --git a/docs/build/building-modules/09-module-interfaces.md b/docs/build/building-modules/09-module-interfaces.md index 61dd78ae6869..c579aa82df36 100644 --- a/docs/build/building-modules/09-module-interfaces.md +++ b/docs/build/building-modules/09-module-interfaces.md @@ -64,84 +64,13 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/bank/module.go#L84-L This section is being rewritten. Refer to [AutoCLI](https://docs.cosmos.network/main/core/autocli) while this section is being updated. ::: - - ## gRPC [gRPC](https://grpc.io/) is a Remote Procedure Call (RPC) framework. RPC is the preferred way for external clients like wallets and exchanges to interact with a blockchain. In addition to providing an ABCI query pathway, the Cosmos SDK provides a gRPC proxy server that routes gRPC query requests to ABCI query requests. -In order to do that, modules must implement `RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux)` on `AppModuleBasic` to wire the client gRPC requests to the correct handler inside the module. +In order to do that, modules must implement the `module.HasGRPCGateway` interface on `AppModule` to wire the client gRPC requests to the correct handler inside the module. Here's an example from the `x/auth` module: diff --git a/docs/build/building-modules/11-structure.md b/docs/build/building-modules/11-structure.md index 9a40d4e55393..ca0eede565f7 100644 --- a/docs/build/building-modules/11-structure.md +++ b/docs/build/building-modules/11-structure.md @@ -79,7 +79,7 @@ x/{module_name} * `client/`: The module's CLI client functionality implementation and the module's CLI testing suite. * `exported/`: The module's exported types - typically interface types. If a module relies on keepers from another module, it is expected to receive the keepers as interface contracts through the `expected_keepers.go` file (see below) in order to avoid a direct dependency on the module implementing the keepers. However, these interface contracts can define methods that operate on and/or return types that are specific to the module that is implementing the keepers and this is where `exported/` comes into play. The interface types that are defined in `exported/` use canonical types, allowing for the module to receive the keepers as interface contracts through the `expected_keepers.go` file. This pattern allows for code to remain DRY and also alleviates import cycle chaos. * `keeper/`: The module's `Keeper` and `MsgServer` implementation. -* `module/`: The module's `AppModule` and `AppModuleBasic` implementation. +* `module/`: The module's `AppModule` implementation. * `abci.go`: The module's `BeginBlocker` and `EndBlocker` implementations (this file is only required if `BeginBlocker` and/or `EndBlocker` need to be defined). * `autocli.go`: The module [autocli](https://docs.cosmos.network/main/core/autocli) options. * `simulation/`: The module's [simulation](./14-simulator.md) package defines functions used by the blockchain simulator application (`simapp`). diff --git a/docs/learn/beginner/00-app-anatomy.md b/docs/learn/beginner/00-app-anatomy.md index da40c099db59..15e055ff449e 100644 --- a/docs/learn/beginner/00-app-anatomy.md +++ b/docs/learn/beginner/00-app-anatomy.md @@ -55,7 +55,7 @@ The first thing defined in `app.go` is the `type` of the application. It is gene * **A list of module's `keeper`s.** Each module defines an abstraction called [`keeper`](../../build/building-modules/06-keeper.md), which handles reads and writes for this module's store(s). The `keeper`'s methods of one module can be called from other modules (if authorized), which is why they are declared in the application's type and exported as interfaces to other modules so that the latter can only access the authorized functions. * **A reference to an [`appCodec`](../advanced/05-encoding.md).** The application's `appCodec` is used to serialize and deserialize data structures in order to store them, as stores can only persist `[]bytes`. The default codec is [Protocol Buffers](../advanced/05-encoding.md). * **A reference to a [`legacyAmino`](../advanced/05-encoding.md) codec.** Some parts of the Cosmos SDK have not been migrated to use the `appCodec` above, and are still hardcoded to use Amino. Other parts explicitly use Amino for backwards compatibility. For these reasons, the application still holds a reference to the legacy Amino codec. Please note that the Amino codec will be removed from the SDK in the upcoming releases. -* **A reference to a [module manager](../../build/building-modules/01-module-manager.md#manager)** and a [basic module manager](../../build/building-modules/01-module-manager.md#basicmanager). The module manager is an object that contains a list of the application's modules. It facilitates operations related to these modules, like registering their [`Msg` service](../advanced/00-baseapp.md#msg-services) and [gRPC `Query` service](../advanced/00-baseapp.md#grpc-query-services), or setting the order of execution between modules for various functions like [`InitChainer`](#initchainer), [`PreBlocker`](#preblocker) and [`BeginBlocker` and `EndBlocker`](#beginblocker-and-endblocker). +* **A reference to a [module manager](../../build/building-modules/01-module-manager.md#manager)**. The module manager is an object that contains a list of the application's modules. It facilitates operations related to these modules, like registering their [`Msg` service](../advanced/00-baseapp.md#msg-services) and [gRPC `Query` service](../advanced/00-baseapp.md#grpc-query-services), or setting the order of execution between modules for various functions like [`InitChainer`](#initchainer), [`PreBlocker`](#preblocker) and [`BeginBlocker` and `EndBlocker`](#beginblocker-and-endblocker). See an example of application type definition from `simapp`, the Cosmos SDK's own app used for demo and testing purposes: @@ -73,7 +73,7 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/server/types/app.go#L6 Here are the main actions performed by this function: -* Instantiate a new [`codec`](../advanced/05-encoding.md) and initialize the `codec` of each of the application's modules using the [basic manager](../../build/building-modules/01-module-manager.md#basicmanager). +* Instantiate a new [`codec`](../advanced/05-encoding.md) and initialize the `codec` of each of the application's modules using the module manager. * Instantiate a new application with a reference to a `baseapp` instance, a codec, and all the appropriate store keys. * Instantiate all the [`keeper`](#keeper) objects defined in the application's `type` using the `NewKeeper` function of each of the application's modules. Note that keepers must be instantiated in the correct order, as the `NewKeeper` of one module might require a reference to another module's `keeper`. * Instantiate the application's [module manager](../../build/building-modules/01-module-manager.md#manager) with the [`AppModule`](#application-module-interface) object of each of the application's modules. @@ -165,7 +165,7 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/simapp/params/encoding ### Application Module Interface -Modules must implement [interfaces](../../build/building-modules/01-module-manager.md#application-module-interfaces) defined in the Cosmos SDK, [`AppModuleBasic`](../../build/building-modules/01-module-manager.md#appmodulebasic) and [`AppModule`](../../build/building-modules/01-module-manager.md#appmodule). The former implements basic non-dependent elements of the module, such as the `codec`, while the latter handles the bulk of the module methods (including methods that require references to other modules' `keeper`s). Both the `AppModule` and `AppModuleBasic` types are, by convention, defined in a file called `module.go`. +Modules must implement [interfaces](../../build/building-modules/01-module-manager.md#application-module-interfaces) defined in the Cosmos SDK and [`AppModule`](../../build/building-modules/01-module-manager.md#appmodule). `AppModule` handles the bulk of the module methods (including methods that require references to other modules' `keeper`s). `AppModule` is, by convention, defined in a file called `module.go`. `AppModule` exposes a collection of useful methods on the module that facilitates the composition of modules into a coherent application. These methods are called from the [`module manager`](../../build/building-modules/01-module-manager.md#manager), which manages the application's collection of modules. @@ -235,7 +235,7 @@ Generally, the [commands related to a module](../../build/building-modules/09-mo Each module can expose gRPC endpoints called [service methods](https://grpc.io/docs/what-is-grpc/core-concepts/#service-definition), which are defined in the [module's Protobuf `query.proto` file](#grpc-query-services). A service method is defined by its name, input arguments, and output response. The module then needs to perform the following actions: -* Define a `RegisterGRPCGatewayRoutes` method on `AppModuleBasic` to wire the client gRPC requests to the correct handler inside the module. +* (Optional) Define a `RegisterGRPCGatewayRoutes` method on `AppModule` to wire the client gRPC requests to the correct handler inside the module. * For each service method, define a corresponding handler. The handler implements the core logic necessary to serve the gRPC request, and is located in the `keeper/grpc_query.go` file. #### gRPC-gateway REST Endpoints diff --git a/runtime/app.go b/runtime/app.go index 8730c511ecd9..268f3c90f8d6 100644 --- a/runtime/app.go +++ b/runtime/app.go @@ -47,7 +47,6 @@ type App struct { interfaceRegistry codectypes.InterfaceRegistry cdc codec.Codec amino *codec.LegacyAmino - basicManager module.BasicManager baseAppOptions []BaseAppOption msgServiceRouter *baseapp.MsgServiceRouter appConfig *appv1alpha1.Config @@ -67,14 +66,12 @@ func (a *App) RegisterModules(modules ...module.AppModule) error { return fmt.Errorf("AppModule named %q already exists", name) } - if _, ok := a.basicManager[name]; ok { - return fmt.Errorf("AppModuleBasic named %q already exists", name) - } - a.ModuleManager.Modules[name] = appModule - a.basicManager[name] = appModule appModule.RegisterInterfaces(a.interfaceRegistry) - appModule.RegisterLegacyAminoCodec(a.amino) + + if mod, ok := appModule.(module.HasAminoCodec); ok { + mod.RegisterLegacyAminoCodec(a.amino) + } if mod, ok := appModule.(module.HasServices); ok { mod.RegisterServices(a.configurator) @@ -208,7 +205,7 @@ func (a *App) RegisterAPIRoutes(apiSvr *api.Server, _ config.APIConfig) { nodeservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) // Register grpc-gateway routes for all modules. - a.basicManager.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) + a.ModuleManager.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) } // RegisterTxService implements the Application.RegisterTxService method. @@ -242,9 +239,9 @@ func (a *App) LoadHeight(height int64) error { return a.LoadVersion(height) } -// DefaultGenesis returns a default genesis from the registered AppModuleBasic's. +// DefaultGenesis returns a default genesis from the registered AppModule's. func (a *App) DefaultGenesis() map[string]json.RawMessage { - return a.basicManager.DefaultGenesis(a.cdc) + return a.ModuleManager.DefaultGenesis(a.cdc) } // GetStoreKeys returns all the stored store keys. diff --git a/runtime/builder.go b/runtime/builder.go index 72bf965f7082..805b814a4956 100644 --- a/runtime/builder.go +++ b/runtime/builder.go @@ -18,7 +18,7 @@ type AppBuilder struct { app *App } -// DefaultGenesis returns a default genesis from the registered AppModuleBasic's. +// DefaultGenesis returns a default genesis from the registered modules. func (a *AppBuilder) DefaultGenesis() map[string]json.RawMessage { return a.app.DefaultGenesis() } diff --git a/runtime/module.go b/runtime/module.go index 23ccb67d2957..e00063df8642 100644 --- a/runtime/module.go +++ b/runtime/module.go @@ -14,7 +14,6 @@ import ( stakingmodulev1 "cosmossdk.io/api/cosmos/staking/module/v1" "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" - "cosmossdk.io/core/event" "cosmossdk.io/core/genesis" "cosmossdk.io/core/store" "cosmossdk.io/depinject" @@ -70,8 +69,7 @@ func init() { ProvideEnvironment, ProvideMemoryStoreService, ProvideTransientStoreService, - ProvideEventService, - ProvideBasicManager, + ProvideModuleManager, ProvideAppVersionModifier, ProvideAddressCodec, ), @@ -111,7 +109,6 @@ func ProvideApp(interfaceRegistry codectypes.InterfaceRegistry) ( interfaceRegistry: interfaceRegistry, cdc: cdc, amino: amino, - basicManager: module.BasicManager{}, msgServiceRouter: msgServiceRouter, } appBuilder := &AppBuilder{app} @@ -122,15 +119,14 @@ func ProvideApp(interfaceRegistry codectypes.InterfaceRegistry) ( type AppInputs struct { depinject.In - AppConfig *appv1alpha1.Config - Config *runtimev1alpha1.Module - AppBuilder *AppBuilder - Modules map[string]appmodule.AppModule - CustomModuleBasics map[string]module.AppModuleBasic `optional:"true"` - BaseAppOptions []BaseAppOption - InterfaceRegistry codectypes.InterfaceRegistry - LegacyAmino *codec.LegacyAmino - Logger log.Logger + Logger log.Logger + AppConfig *appv1alpha1.Config + Config *runtimev1alpha1.Module + AppBuilder *AppBuilder + ModuleManager *module.Manager + BaseAppOptions []BaseAppOption + InterfaceRegistry codectypes.InterfaceRegistry + LegacyAmino *codec.LegacyAmino } func SetupAppBuilder(inputs AppInputs) { @@ -139,21 +135,9 @@ func SetupAppBuilder(inputs AppInputs) { app.config = inputs.Config app.appConfig = inputs.AppConfig app.logger = inputs.Logger - app.ModuleManager = module.NewManagerFromMap(inputs.Modules) - - for name, mod := range inputs.Modules { - if customBasicMod, ok := inputs.CustomModuleBasics[name]; ok { - app.basicManager[name] = customBasicMod - customBasicMod.RegisterInterfaces(inputs.InterfaceRegistry) - customBasicMod.RegisterLegacyAminoCodec(inputs.LegacyAmino) - continue - } - - coreAppModuleBasic := module.CoreAppModuleBasicAdaptor(name, mod) - app.basicManager[name] = coreAppModuleBasic - coreAppModuleBasic.RegisterInterfaces(inputs.InterfaceRegistry) - coreAppModuleBasic.RegisterLegacyAminoCodec(inputs.LegacyAmino) - } + app.ModuleManager = inputs.ModuleManager + app.ModuleManager.RegisterInterfaces(inputs.InterfaceRegistry) + app.ModuleManager.RegisterLegacyAminoCodec(inputs.LegacyAmino) } func ProvideInterfaceRegistry(addressCodec address.Codec, validatorAddressCodec ValidatorAddressCodec, customGetSigners []signing.CustomGetSigner) (codectypes.InterfaceRegistry, error) { @@ -220,6 +204,10 @@ func ProvideMemoryStoreKey(key depinject.ModuleKey, app *AppBuilder) *storetypes return storeKey } +func ProvideModuleManager(modules map[string]appmodule.AppModule) *module.Manager { + return module.NewManagerFromMap(modules) +} + func ProvideGenesisTxHandler(appBuilder *AppBuilder) genesis.TxHandler { return appBuilder.app } @@ -240,14 +228,6 @@ func ProvideTransientStoreService(key depinject.ModuleKey, app *AppBuilder) stor return transientStoreService{key: storeKey} } -func ProvideEventService() event.Service { - return EventService{} -} - -func ProvideBasicManager(app *AppBuilder) module.BasicManager { - return app.app.basicManager -} - func ProvideAppVersionModifier(app *AppBuilder) baseapp.AppVersionModifier { return app.app } diff --git a/server/util_test.go b/server/util_test.go index 3d79b24fc6c4..bd9865363179 100644 --- a/server/util_test.go +++ b/server/util_test.go @@ -458,7 +458,7 @@ func TestEmptyMinGasPrices(t *testing.T) { serverCtx.Config.SetRoot(tempDir) ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - cmd := genutilcli.InitCmd(module.NewBasicManager()) + cmd := genutilcli.InitCmd(module.NewManager()) cmd.SetArgs([]string{"appnode-test"}) err = cmd.ExecuteContext(ctx) require.NoError(t, err) diff --git a/simapp/app.go b/simapp/app.go index 78aa6896baa8..b2e47f60c405 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -56,7 +56,6 @@ import ( feegrantkeeper "cosmossdk.io/x/feegrant/keeper" feegrantmodule "cosmossdk.io/x/feegrant/module" "cosmossdk.io/x/gov" - govclient "cosmossdk.io/x/gov/client" govkeeper "cosmossdk.io/x/gov/keeper" govtypes "cosmossdk.io/x/gov/types" govv1beta1 "cosmossdk.io/x/gov/types/v1beta1" @@ -168,14 +167,10 @@ type SimApp struct { CircuitKeeper circuitkeeper.Keeper PoolKeeper poolkeeper.Keeper - // the module manager + // managers ModuleManager *module.Manager - BasicModuleManager module.BasicManager - UnorderedTxManager *unorderedtx.Manager - - // simulation manager - sm *module.SimulationManager + sm *module.SimulationManager // module configurator configurator module.Configurator // nolint:staticcheck // SA1019: Configurator is deprecated but still used in runtime v1. @@ -414,10 +409,7 @@ 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, - ), + genutil.NewAppModule(app.AuthKeeper, app.StakingKeeper, app, txConfig, genutiltypes.DefaultMessageValidator), accounts.NewAppModule(app.AccountsKeeper), auth.NewAppModule(appCodec, app.AuthKeeper, authsims.RandomGenesisAccounts), vesting.NewAppModule(app.AuthKeeper, app.BankKeeper), @@ -428,7 +420,7 @@ func NewSimApp( slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AuthKeeper, app.BankKeeper, app.StakingKeeper, app.interfaceRegistry), 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, app.AuthKeeper.AddressCodec()), + upgrade.NewAppModule(app.UpgradeKeeper), evidence.NewAppModule(app.EvidenceKeeper), authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AuthKeeper, app.BankKeeper, app.interfaceRegistry), groupmodule.NewAppModule(appCodec, app.GroupKeeper, app.AuthKeeper, app.BankKeeper, app.interfaceRegistry), @@ -437,21 +429,8 @@ func NewSimApp( circuit.NewAppModule(appCodec, app.CircuitKeeper), protocolpool.NewAppModule(appCodec, app.PoolKeeper, app.AuthKeeper, app.BankKeeper), ) - - // BasicModuleManager defines the module BasicManager is in charge of setting up basic, - // non-dependant module elements, such as codec registration and genesis verification. - // By default it is composed of all the module from the module manager. - // Additionally, app module basics can be overwritten by passing them as argument. - app.BasicModuleManager = module.NewBasicManagerFromManager( - app.ModuleManager, - map[string]module.AppModuleBasic{ - genutiltypes.ModuleName: genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator), - govtypes.ModuleName: gov.NewAppModuleBasic( - []govclient.ProposalHandler{}, - ), - }) - app.BasicModuleManager.RegisterLegacyAminoCodec(legacyAmino) - app.BasicModuleManager.RegisterInterfaces(interfaceRegistry) + app.ModuleManager.RegisterLegacyAminoCodec(legacyAmino) + app.ModuleManager.RegisterInterfaces(interfaceRegistry) // NOTE: upgrade module is required to be prioritized app.ModuleManager.SetOrderPreBlockers( @@ -718,9 +697,9 @@ func (app *SimApp) AutoCliOpts() autocli.AppOptions { } } -// DefaultGenesis returns a default genesis from the registered AppModuleBasic's. +// DefaultGenesis returns a default genesis from the registered AppModule's. func (a *SimApp) DefaultGenesis() map[string]json.RawMessage { - return a.BasicModuleManager.DefaultGenesis(a.appCodec) + return a.ModuleManager.DefaultGenesis(a.appCodec) } // GetKey returns the KVStoreKey for the provided store key. @@ -759,7 +738,7 @@ func (app *SimApp) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APICon nodeservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) // Register grpc-gateway routes for all modules. - app.BasicModuleManager.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) + app.ModuleManager.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) // register swagger API from root so that other applications can override easily if err := server.RegisterSwaggerAPI(apiSvr.ClientCtx, apiSvr.Router, apiConfig.Swagger); err != nil { diff --git a/simapp/app_config.go b/simapp/app_config.go index d45075c1af74..2208330f8ee1 100644 --- a/simapp/app_config.go +++ b/simapp/app_config.go @@ -44,6 +44,7 @@ import ( evidencetypes "cosmossdk.io/x/evidence/types" "cosmossdk.io/x/feegrant" _ "cosmossdk.io/x/feegrant/module" // import for side-effects + _ "cosmossdk.io/x/gov" // import for side-effects govtypes "cosmossdk.io/x/gov/types" "cosmossdk.io/x/group" _ "cosmossdk.io/x/group/module" // import for side-effects diff --git a/simapp/app_v2.go b/simapp/app_v2.go index 3b42c12c1043..25d2c78ff3c7 100644 --- a/simapp/app_v2.go +++ b/simapp/app_v2.go @@ -26,10 +26,7 @@ import ( distrkeeper "cosmossdk.io/x/distribution/keeper" evidencekeeper "cosmossdk.io/x/evidence/keeper" feegrantkeeper "cosmossdk.io/x/feegrant/keeper" - "cosmossdk.io/x/gov" - govclient "cosmossdk.io/x/gov/client" govkeeper "cosmossdk.io/x/gov/keeper" - govtypes "cosmossdk.io/x/gov/types" groupkeeper "cosmossdk.io/x/group/keeper" mintkeeper "cosmossdk.io/x/mint/keeper" nftkeeper "cosmossdk.io/x/nft/keeper" @@ -52,8 +49,6 @@ import ( testdata_pulsar "github.com/cosmos/cosmos-sdk/testutil/testdata/testpb" "github.com/cosmos/cosmos-sdk/types/module" consensuskeeper "github.com/cosmos/cosmos-sdk/x/consensus/keeper" - "github.com/cosmos/cosmos-sdk/x/genutil" - genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" ) // DefaultNodeHome default home directories for the application daemon @@ -110,17 +105,7 @@ func init() { // AppConfig returns the default app config. func AppConfig() depinject.Config { return depinject.Configs( - // appconfig.LoadYAML(AppConfigYAML), - appConfig, - depinject.Supply( - // supply custom module basics - map[string]module.AppModuleBasic{ - genutiltypes.ModuleName: genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator), - govtypes.ModuleName: gov.NewAppModuleBasic( - []govclient.ProposalHandler{}, - ), - }, - ), + appConfig, // Alternatively use appconfig.LoadYAML(AppConfigYAML) ) } diff --git a/simapp/genesis.go b/simapp/genesis.go index 69fa46b90efa..4d62a3987073 100644 --- a/simapp/genesis.go +++ b/simapp/genesis.go @@ -9,6 +9,6 @@ import ( // The identifier is used to determine which module genesis information belongs // to so it may be appropriately routed during init chain. // Within this application default genesis information is retrieved from -// the ModuleBasicManager which populates json from each BasicModule +// the module manager which populates json from each module // object provided to it during init. type GenesisState map[string]json.RawMessage diff --git a/simapp/simd/cmd/commands.go b/simapp/simd/cmd/commands.go index ae4bc424689a..40de6d208cf8 100644 --- a/simapp/simd/cmd/commands.go +++ b/simapp/simd/cmd/commands.go @@ -37,14 +37,14 @@ func initRootCmd( txConfig client.TxConfig, interfaceRegistry codectypes.InterfaceRegistry, appCodec codec.Codec, - basicManager module.BasicManager, + moduleManager *module.Manager, ) { cfg := sdk.GetConfig() cfg.Seal() rootCmd.AddCommand( - genutilcli.InitCmd(basicManager), - NewTestnetCmd(basicManager, banktypes.GenesisBalancesIterator{}), + genutilcli.InitCmd(moduleManager), + NewTestnetCmd(moduleManager, banktypes.GenesisBalancesIterator{}), debug.Cmd(), confixcmd.ConfigCommand(), pruning.Cmd(newApp), @@ -56,7 +56,7 @@ func initRootCmd( // add keybase, auxiliary RPC, query, genesis, and tx child commands rootCmd.AddCommand( server.StatusCommand(), - genesisCommand(txConfig, basicManager, appExport), + genesisCommand(txConfig, moduleManager, appExport), queryCommand(), txCommand(), keys.Commands(), @@ -65,8 +65,8 @@ func initRootCmd( } // genesisCommand builds genesis-related `simd genesis` command. Users may provide application specific commands as a parameter -func genesisCommand(txConfig client.TxConfig, basicManager module.BasicManager, appExport servertypes.AppExporter, cmds ...*cobra.Command) *cobra.Command { - cmd := genutilcli.Commands(txConfig, basicManager, appExport) +func genesisCommand(txConfig client.TxConfig, moduleManager *module.Manager, appExport servertypes.AppExporter, cmds ...*cobra.Command) *cobra.Command { + cmd := genutilcli.Commands(txConfig, moduleManager, appExport) for _, subCmd := range cmds { cmd.AddCommand(subCmd) diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 24ed158ee4b6..f15e3d0c4966 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -103,7 +103,7 @@ func NewRootCmd() *cobra.Command { }, } - initRootCmd(rootCmd, encodingConfig.TxConfig, encodingConfig.InterfaceRegistry, encodingConfig.Codec, tempApp.BasicModuleManager) + initRootCmd(rootCmd, encodingConfig.TxConfig, encodingConfig.InterfaceRegistry, encodingConfig.Codec, tempApp.ModuleManager) // autocli opts customClientTemplate, customClientConfig := initClientConfig() diff --git a/simapp/simd/cmd/root_v2.go b/simapp/simd/cmd/root_v2.go index 3b207a1a0155..edbf0ea2cf50 100644 --- a/simapp/simd/cmd/root_v2.go +++ b/simapp/simd/cmd/root_v2.go @@ -31,9 +31,9 @@ import ( // NewRootCmd creates a new root command for simd. It is called once in the main function. func NewRootCmd() *cobra.Command { var ( - autoCliOpts autocli.AppOptions - moduleBasicManager module.BasicManager - clientCtx client.Context + autoCliOpts autocli.AppOptions + moduleManager *module.Manager + clientCtx client.Context ) if err := depinject.Inject( @@ -48,7 +48,7 @@ func NewRootCmd() *cobra.Command { ), ), &autoCliOpts, - &moduleBasicManager, + &moduleManager, &clientCtx, ); err != nil { panic(err) @@ -86,7 +86,7 @@ func NewRootCmd() *cobra.Command { }, } - initRootCmd(rootCmd, clientCtx.TxConfig, clientCtx.InterfaceRegistry, clientCtx.Codec, moduleBasicManager) + initRootCmd(rootCmd, clientCtx.TxConfig, clientCtx.InterfaceRegistry, clientCtx.Codec, moduleManager) if err := autoCliOpts.EnhanceRootCommand(rootCmd); err != nil { panic(err) diff --git a/simapp/simd/cmd/testnet.go b/simapp/simd/cmd/testnet.go index 3455bcf904de..101cf5388a3e 100644 --- a/simapp/simd/cmd/testnet.go +++ b/simapp/simd/cmd/testnet.go @@ -96,7 +96,7 @@ func addTestnetFlagsToCmd(cmd *cobra.Command) { // NewTestnetCmd creates a root testnet command with subcommands to run an in-process testnet or initialize // validator configuration files for running a multi-validator testnet in a separate process -func NewTestnetCmd(mbm module.BasicManager, genBalIterator banktypes.GenesisBalancesIterator) *cobra.Command { +func NewTestnetCmd(mm *module.Manager, genBalIterator banktypes.GenesisBalancesIterator) *cobra.Command { testnetCmd := &cobra.Command{ Use: "testnet", Short: "subcommands for starting or configuring local testnets", @@ -106,13 +106,13 @@ func NewTestnetCmd(mbm module.BasicManager, genBalIterator banktypes.GenesisBala } testnetCmd.AddCommand(testnetStartCmd()) - testnetCmd.AddCommand(testnetInitFilesCmd(mbm, genBalIterator)) + testnetCmd.AddCommand(testnetInitFilesCmd(mm, genBalIterator)) return testnetCmd } // testnetInitFilesCmd returns a cmd to initialize all files for CometBFT testnet and application -func testnetInitFilesCmd(mbm module.BasicManager, genBalIterator banktypes.GenesisBalancesIterator) *cobra.Command { +func testnetInitFilesCmd(mm *module.Manager, genBalIterator banktypes.GenesisBalancesIterator) *cobra.Command { cmd := &cobra.Command{ Use: "init-files", Short: "Initialize config directories & files for a multi-validator testnet running locally via separate processes (e.g. Docker Compose or similar)", @@ -148,7 +148,7 @@ Example: args.numValidators, _ = cmd.Flags().GetInt(flagNumValidators) args.algo, _ = cmd.Flags().GetString(flags.FlagKeyType) - return initTestnetFiles(clientCtx, cmd, config, mbm, genBalIterator, clientCtx.TxConfig.SigningContext().ValidatorAddressCodec(), args) + return initTestnetFiles(clientCtx, cmd, config, mm, genBalIterator, clientCtx.TxConfig.SigningContext().ValidatorAddressCodec(), args) }, } @@ -207,7 +207,7 @@ func initTestnetFiles( clientCtx client.Context, cmd *cobra.Command, nodeConfig *cmtconfig.Config, - mbm module.BasicManager, + mm *module.Manager, genBalIterator banktypes.GenesisBalancesIterator, valAddrCodec runtime.ValidatorAddressCodec, args initArgs, @@ -354,7 +354,7 @@ func initTestnetFiles( } } - if err := initGenFiles(clientCtx, mbm, args.chainID, genAccounts, genBalances, genFiles, args.numValidators); err != nil { + if err := initGenFiles(clientCtx, mm, args.chainID, genAccounts, genBalances, genFiles, args.numValidators); err != nil { return err } @@ -371,11 +371,11 @@ func initTestnetFiles( } func initGenFiles( - clientCtx client.Context, mbm module.BasicManager, chainID string, + clientCtx client.Context, mm *module.Manager, chainID string, genAccounts []authtypes.GenesisAccount, genBalances []banktypes.Balance, genFiles []string, numValidators int, ) error { - appGenState := mbm.DefaultGenesis(clientCtx.Codec) + appGenState := mm.DefaultGenesis(clientCtx.Codec) // set the accounts in the genesis state var authGenState authtypes.GenesisState diff --git a/simapp/simd/cmd/testnet_test.go b/simapp/simd/cmd/testnet_test.go index bf5b10058fe6..60ba6126fb97 100644 --- a/simapp/simd/cmd/testnet_test.go +++ b/simapp/simd/cmd/testnet_test.go @@ -8,43 +8,50 @@ import ( "github.com/spf13/viper" "github.com/stretchr/testify/require" + "cosmossdk.io/depinject" "cosmossdk.io/log" "cosmossdk.io/x/auth" - "cosmossdk.io/x/bank" banktypes "cosmossdk.io/x/bank/types" - "cosmossdk.io/x/distribution" - "cosmossdk.io/x/mint" "cosmossdk.io/x/staking" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/server" + "github.com/cosmos/cosmos-sdk/testutil/configurator" "github.com/cosmos/cosmos-sdk/types/module" moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/consensus" - "github.com/cosmos/cosmos-sdk/x/genutil" genutiltest "github.com/cosmos/cosmos-sdk/x/genutil/client/testutil" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" ) func Test_TestnetCmd(t *testing.T) { - moduleBasic := module.NewBasicManager( - auth.AppModuleBasic{}, - genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator), - bank.AppModuleBasic{}, - staking.AppModuleBasic{}, - mint.AppModuleBasic{}, - distribution.AppModuleBasic{}, - consensus.AppModuleBasic{}, + config := configurator.NewAppConfig( + configurator.AuthModule(), + configurator.BankModule(), + configurator.GenutilModule(), + configurator.StakingModule(), + configurator.ConsensusModule(), + configurator.TxModule(), + configurator.MintModule(), ) + var moduleManager *module.Manager + err := depinject.Inject( + depinject.Configs(config, + depinject.Supply(log.NewNopLogger()), + ), + &moduleManager, + ) + require.NoError(t, err) + require.NotNil(t, moduleManager) + require.Len(t, moduleManager.Modules, 7) home := t.TempDir() - encodingConfig := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}, staking.AppModuleBasic{}) + encodingConfig := moduletestutil.MakeTestEncodingConfig(auth.AppModule{}, staking.AppModule{}) logger := log.NewNopLogger() cfg, err := genutiltest.CreateDefaultCometConfig(home) require.NoError(t, err) - err = genutiltest.ExecInitCmd(moduleBasic, home, encodingConfig.Codec) + err = genutiltest.ExecInitCmd(moduleManager, home, encodingConfig.Codec) require.NoError(t, err) serverCtx := server.NewContext(viper.New(), cfg, logger) @@ -56,7 +63,7 @@ func Test_TestnetCmd(t *testing.T) { ctx := context.Background() ctx = context.WithValue(ctx, server.ServerContextKey, serverCtx) ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx) - cmd := testnetInitFilesCmd(moduleBasic, banktypes.GenesisBalancesIterator{}) + cmd := testnetInitFilesCmd(moduleManager, banktypes.GenesisBalancesIterator{}) cmd.SetArgs([]string{fmt.Sprintf("--%s=test", flags.FlagKeyringBackend), fmt.Sprintf("--output-dir=%s", home)}) err = cmd.ExecuteContext(ctx) require.NoError(t, err) diff --git a/tests/integration/auth/client/cli/suite_test.go b/tests/integration/auth/client/cli/suite_test.go index f0dc6afdeca8..454ff4e1b82e 100644 --- a/tests/integration/auth/client/cli/suite_test.go +++ b/tests/integration/auth/client/cli/suite_test.go @@ -56,7 +56,7 @@ func TestCLITestSuite(t *testing.T) { } func (s *CLITestSuite) SetupSuite() { - s.encCfg = testutilmod.MakeTestEncodingConfig(auth.AppModuleBasic{}, bank.AppModuleBasic{}, gov.AppModuleBasic{}) + s.encCfg = testutilmod.MakeTestEncodingConfig(auth.AppModule{}, bank.AppModule{}, gov.AppModule{}) s.kr = keyring.NewInMemory(s.encCfg.Codec) s.baseCtx = client.Context{}. WithKeyring(s.kr). diff --git a/tests/integration/bank/keeper/deterministic_test.go b/tests/integration/bank/keeper/deterministic_test.go index 92a9abd7966d..0cc58318230e 100644 --- a/tests/integration/bank/keeper/deterministic_test.go +++ b/tests/integration/bank/keeper/deterministic_test.go @@ -63,7 +63,7 @@ type deterministicFixture struct { func initDeterministicFixture(t *testing.T) *deterministicFixture { t.Helper() keys := storetypes.NewKVStoreKeys(authtypes.StoreKey, banktypes.StoreKey) - cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}, bank.AppModuleBasic{}).Codec + cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModule{}, bank.AppModule{}).Codec logger := log.NewTestLogger(t) cms := integration.CreateMultiStore(keys, logger) diff --git a/tests/integration/distribution/keeper/msg_server_test.go b/tests/integration/distribution/keeper/msg_server_test.go index 1c65b37cbdf9..073f0bb5896d 100644 --- a/tests/integration/distribution/keeper/msg_server_test.go +++ b/tests/integration/distribution/keeper/msg_server_test.go @@ -66,7 +66,7 @@ func initFixture(t *testing.T) *fixture { keys := storetypes.NewKVStoreKeys( authtypes.StoreKey, banktypes.StoreKey, distrtypes.StoreKey, pooltypes.StoreKey, stakingtypes.StoreKey, ) - cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}, distribution.AppModuleBasic{}, protocolpool.AppModuleBasic{}).Codec + cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModule{}, distribution.AppModule{}, protocolpool.AppModule{}).Codec logger := log.NewTestLogger(t) cms := integration.CreateMultiStore(keys, logger) diff --git a/tests/integration/evidence/keeper/infraction_test.go b/tests/integration/evidence/keeper/infraction_test.go index 12c6c0b9add0..1da4a4235288 100644 --- a/tests/integration/evidence/keeper/infraction_test.go +++ b/tests/integration/evidence/keeper/infraction_test.go @@ -87,7 +87,7 @@ func initFixture(tb testing.TB) *fixture { keys := storetypes.NewKVStoreKeys( authtypes.StoreKey, banktypes.StoreKey, consensusparamtypes.StoreKey, evidencetypes.StoreKey, stakingtypes.StoreKey, slashingtypes.StoreKey, ) - cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}, evidence.AppModuleBasic{}).Codec + cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModule{}, evidence.AppModule{}).Codec logger := log.NewTestLogger(tb) cms := integration.CreateMultiStore(keys, logger) diff --git a/tests/integration/example/example_test.go b/tests/integration/example/example_test.go index 8d4fa86aba51..71a9acb8770c 100644 --- a/tests/integration/example/example_test.go +++ b/tests/integration/example/example_test.go @@ -29,7 +29,7 @@ import ( func Example() { // in this example we are testing the integration of the following modules: // - mint, which directly depends on auth, bank and staking - encodingCfg := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}, mint.AppModuleBasic{}) + encodingCfg := moduletestutil.MakeTestEncodingConfig(auth.AppModule{}, mint.AppModule{}) keys := storetypes.NewKVStoreKeys(authtypes.StoreKey, minttypes.StoreKey) authority := authtypes.NewModuleAddress("gov").String() @@ -118,7 +118,7 @@ func Example() { // That module has no dependency on other modules. func Example_oneModule() { // in this example we are testing the integration of the auth module: - encodingCfg := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}) + encodingCfg := moduletestutil.MakeTestEncodingConfig(auth.AppModule{}) keys := storetypes.NewKVStoreKeys(authtypes.StoreKey) authority := authtypes.NewModuleAddress("gov").String() diff --git a/tests/integration/gov/keeper/keeper_test.go b/tests/integration/gov/keeper/keeper_test.go index 7881ccdf9da7..81986763f6a0 100644 --- a/tests/integration/gov/keeper/keeper_test.go +++ b/tests/integration/gov/keeper/keeper_test.go @@ -52,7 +52,7 @@ func initFixture(tb testing.TB) *fixture { keys := storetypes.NewKVStoreKeys( authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, pooltypes.StoreKey, types.StoreKey, ) - cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}, bank.AppModuleBasic{}, gov.AppModuleBasic{}).Codec + cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModule{}, bank.AppModule{}, gov.AppModule{}).Codec logger := log.NewTestLogger(tb) cms := integration.CreateMultiStore(keys, logger) diff --git a/tests/integration/slashing/keeper/keeper_test.go b/tests/integration/slashing/keeper/keeper_test.go index 31ddf5de6e73..7ef26ef130d9 100644 --- a/tests/integration/slashing/keeper/keeper_test.go +++ b/tests/integration/slashing/keeper/keeper_test.go @@ -56,7 +56,7 @@ func initFixture(tb testing.TB) *fixture { keys := storetypes.NewKVStoreKeys( authtypes.StoreKey, banktypes.StoreKey, slashingtypes.StoreKey, stakingtypes.StoreKey, ) - cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}).Codec + cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModule{}).Codec logger := log.NewTestLogger(tb) cms := integration.CreateMultiStore(keys, logger) diff --git a/tests/integration/staking/keeper/common_test.go b/tests/integration/staking/keeper/common_test.go index d4cff3506bad..8c4e7233df2a 100644 --- a/tests/integration/staking/keeper/common_test.go +++ b/tests/integration/staking/keeper/common_test.go @@ -103,7 +103,7 @@ func initFixture(tb testing.TB) *fixture { keys := storetypes.NewKVStoreKeys( authtypes.StoreKey, banktypes.StoreKey, types.StoreKey, ) - cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}, staking.AppModuleBasic{}).Codec + cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModule{}, staking.AppModule{}).Codec logger := log.NewTestLogger(tb) cms := integration.CreateMultiStore(keys, logger) diff --git a/tests/integration/staking/keeper/deterministic_test.go b/tests/integration/staking/keeper/deterministic_test.go index 50826745c36f..c7fc7bed5e3f 100644 --- a/tests/integration/staking/keeper/deterministic_test.go +++ b/tests/integration/staking/keeper/deterministic_test.go @@ -68,7 +68,7 @@ func initDeterministicFixture(t *testing.T) *deterministicFixture { keys := storetypes.NewKVStoreKeys( authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, ) - cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}, distribution.AppModuleBasic{}).Codec + cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModule{}, distribution.AppModule{}).Codec logger := log.NewTestLogger(t) cms := integration.CreateMultiStore(keys, logger) diff --git a/tests/integration/tx/aminojson/aminojson_test.go b/tests/integration/tx/aminojson/aminojson_test.go index 47ff120867d8..c66d43e7c991 100644 --- a/tests/integration/tx/aminojson/aminojson_test.go +++ b/tests/integration/tx/aminojson/aminojson_test.go @@ -92,10 +92,10 @@ import ( // by the mutation of genOpts passed to the generator. func TestAminoJSON_Equivalence(t *testing.T) { encCfg := testutil.MakeTestEncodingConfig( - auth.AppModuleBasic{}, authzmodule.AppModuleBasic{}, bank.AppModuleBasic{}, consensus.AppModuleBasic{}, - distribution.AppModuleBasic{}, evidence.AppModuleBasic{}, feegrantmodule.AppModuleBasic{}, - gov.AppModuleBasic{}, groupmodule.AppModuleBasic{}, mint.AppModuleBasic{}, - slashing.AppModuleBasic{}, staking.AppModuleBasic{}, upgrade.AppModuleBasic{}, vesting.AppModuleBasic{}) + auth.AppModule{}, authzmodule.AppModule{}, bank.AppModule{}, consensus.AppModule{}, + distribution.AppModule{}, evidence.AppModule{}, feegrantmodule.AppModule{}, + gov.AppModule{}, groupmodule.AppModule{}, mint.AppModule{}, + slashing.AppModule{}, staking.AppModule{}, upgrade.AppModule{}, vesting.AppModule{}) legacytx.RegressionTestingAminoCodec = encCfg.Amino aj := aminojson.NewEncoder(aminojson.EncoderOptions{DoNotSortFields: true}) @@ -208,9 +208,9 @@ func newAny(t *testing.T, msg proto.Message) *anypb.Any { // TestAminoJSON_LegacyParity tests that the Encoder encoder produces the same output as the Encoder encoder. func TestAminoJSON_LegacyParity(t *testing.T) { - encCfg := testutil.MakeTestEncodingConfig(auth.AppModuleBasic{}, authzmodule.AppModuleBasic{}, - bank.AppModuleBasic{}, distribution.AppModuleBasic{}, slashing.AppModuleBasic{}, staking.AppModuleBasic{}, - vesting.AppModuleBasic{}, gov.AppModuleBasic{}) + encCfg := testutil.MakeTestEncodingConfig(auth.AppModule{}, authzmodule.AppModule{}, + bank.AppModule{}, distribution.AppModule{}, slashing.AppModule{}, staking.AppModule{}, + vesting.AppModule{}, gov.AppModule{}) legacytx.RegressionTestingAminoCodec = encCfg.Amino aj := aminojson.NewEncoder(aminojson.EncoderOptions{DoNotSortFields: true}) @@ -512,8 +512,8 @@ func TestAminoJSON_LegacyParity(t *testing.T) { } func TestSendAuthorization(t *testing.T) { - encCfg := testutil.MakeTestEncodingConfig(auth.AppModuleBasic{}, authzmodule.AppModuleBasic{}, - distribution.AppModuleBasic{}, bank.AppModuleBasic{}) + encCfg := testutil.MakeTestEncodingConfig(auth.AppModule{}, authzmodule.AppModule{}, + distribution.AppModule{}, bank.AppModule{}) aj := aminojson.NewEncoder(aminojson.EncoderOptions{}) @@ -562,7 +562,7 @@ func TestSendAuthorization(t *testing.T) { } func TestDecimalMutation(t *testing.T) { - encCfg := testutil.MakeTestEncodingConfig(staking.AppModuleBasic{}) + encCfg := testutil.MakeTestEncodingConfig(staking.AppModule{}) rates := &stakingtypes.CommissionRates{} rateBz, _ := encCfg.Amino.MarshalJSON(rates) require.Equal(t, `{"rate":"0","max_rate":"0","max_change_rate":"0"}`, string(rateBz)) diff --git a/tests/integration/tx/decode_test.go b/tests/integration/tx/decode_test.go index 9e7095e0d10f..8e228951823f 100644 --- a/tests/integration/tx/decode_test.go +++ b/tests/integration/tx/decode_test.go @@ -43,10 +43,10 @@ import ( // TestDecode tests that the tx decoder can decode all the txs in the test suite. func TestDecode(t *testing.T) { encCfg := testutil.MakeTestEncodingConfig( - auth.AppModuleBasic{}, authzmodule.AppModuleBasic{}, bank.AppModuleBasic{}, consensus.AppModuleBasic{}, - distribution.AppModuleBasic{}, evidence.AppModuleBasic{}, feegrantmodule.AppModuleBasic{}, - gov.AppModuleBasic{}, groupmodule.AppModuleBasic{}, mint.AppModuleBasic{}, - slashing.AppModuleBasic{}, staking.AppModuleBasic{}, upgrade.AppModuleBasic{}, vesting.AppModuleBasic{}) + auth.AppModule{}, authzmodule.AppModule{}, bank.AppModule{}, consensus.AppModule{}, + distribution.AppModule{}, evidence.AppModule{}, feegrantmodule.AppModule{}, + gov.AppModule{}, groupmodule.AppModule{}, mint.AppModule{}, + slashing.AppModule{}, staking.AppModule{}, upgrade.AppModule{}, vesting.AppModule{}) legacytx.RegressionTestingAminoCodec = encCfg.Amino fee := sdk.NewCoins(sdk.NewCoin("stake", math.NewInt(100))) diff --git a/testutil/integration/router.go b/testutil/integration/router.go index fcf147a28820..2784118eb2a2 100644 --- a/testutil/integration/router.go +++ b/testutil/integration/router.go @@ -52,8 +52,7 @@ func NewIntegrationApp( interfaceRegistry := codectypes.NewInterfaceRegistry() moduleManager := module.NewManagerFromMap(modules) - basicModuleManager := module.NewBasicManagerFromManager(moduleManager, nil) - basicModuleManager.RegisterInterfaces(interfaceRegistry) + moduleManager.RegisterInterfaces(interfaceRegistry) txConfig := authtx.NewTxConfig(codec.NewProtoCodec(interfaceRegistry), authtx.DefaultSignModes) bApp := baseapp.NewBaseApp(appName, logger, db, txConfig.TxDecoder(), baseapp.SetChainID(appName)) diff --git a/testutil/mock/types_mock_appmodule.go b/testutil/mock/types_mock_appmodule.go index 87682dbf133e..144576e2bf6a 100644 --- a/testutil/mock/types_mock_appmodule.go +++ b/testutil/mock/types_mock_appmodule.go @@ -17,7 +17,6 @@ import ( types1 "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" ) // MockAppModuleWithAllExtensions is a mock of AppModuleWithAllExtensions interface. @@ -150,18 +149,6 @@ func (mr *MockAppModuleWithAllExtensionsMockRecorder) Name() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockAppModuleWithAllExtensions)(nil).Name)) } -// RegisterGRPCGatewayRoutes mocks base method. -func (m *MockAppModuleWithAllExtensions) RegisterGRPCGatewayRoutes(arg0 client.Context, arg1 *runtime.ServeMux) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "RegisterGRPCGatewayRoutes", arg0, arg1) -} - -// RegisterGRPCGatewayRoutes indicates an expected call of RegisterGRPCGatewayRoutes. -func (mr *MockAppModuleWithAllExtensionsMockRecorder) RegisterGRPCGatewayRoutes(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterGRPCGatewayRoutes", reflect.TypeOf((*MockAppModuleWithAllExtensions)(nil).RegisterGRPCGatewayRoutes), arg0, arg1) -} - // RegisterInterfaces mocks base method. func (m *MockAppModuleWithAllExtensions) RegisterInterfaces(arg0 types0.InterfaceRegistry) { m.ctrl.T.Helper() @@ -186,18 +173,6 @@ func (mr *MockAppModuleWithAllExtensionsMockRecorder) RegisterInvariants(arg0 in return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterInvariants", reflect.TypeOf((*MockAppModuleWithAllExtensions)(nil).RegisterInvariants), arg0) } -// RegisterLegacyAminoCodec mocks base method. -func (m *MockAppModuleWithAllExtensions) RegisterLegacyAminoCodec(arg0 *codec.LegacyAmino) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "RegisterLegacyAminoCodec", arg0) -} - -// RegisterLegacyAminoCodec indicates an expected call of RegisterLegacyAminoCodec. -func (mr *MockAppModuleWithAllExtensionsMockRecorder) RegisterLegacyAminoCodec(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterLegacyAminoCodec", reflect.TypeOf((*MockAppModuleWithAllExtensions)(nil).RegisterLegacyAminoCodec), arg0) -} - // RegisterServices mocks base method. func (m *MockAppModuleWithAllExtensions) RegisterServices(arg0 module.Configurator) { m.ctrl.T.Helper() @@ -356,18 +331,6 @@ func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) Name() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockAppModuleWithAllExtensionsABCI)(nil).Name)) } -// RegisterGRPCGatewayRoutes mocks base method. -func (m *MockAppModuleWithAllExtensionsABCI) RegisterGRPCGatewayRoutes(arg0 client.Context, arg1 *runtime.ServeMux) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "RegisterGRPCGatewayRoutes", arg0, arg1) -} - -// RegisterGRPCGatewayRoutes indicates an expected call of RegisterGRPCGatewayRoutes. -func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) RegisterGRPCGatewayRoutes(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterGRPCGatewayRoutes", reflect.TypeOf((*MockAppModuleWithAllExtensionsABCI)(nil).RegisterGRPCGatewayRoutes), arg0, arg1) -} - // RegisterInterfaces mocks base method. func (m *MockAppModuleWithAllExtensionsABCI) RegisterInterfaces(arg0 types0.InterfaceRegistry) { m.ctrl.T.Helper() @@ -392,18 +355,6 @@ func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) RegisterInvariants(arg return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterInvariants", reflect.TypeOf((*MockAppModuleWithAllExtensionsABCI)(nil).RegisterInvariants), arg0) } -// RegisterLegacyAminoCodec mocks base method. -func (m *MockAppModuleWithAllExtensionsABCI) RegisterLegacyAminoCodec(arg0 *codec.LegacyAmino) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "RegisterLegacyAminoCodec", arg0) -} - -// RegisterLegacyAminoCodec indicates an expected call of RegisterLegacyAminoCodec. -func (mr *MockAppModuleWithAllExtensionsABCIMockRecorder) RegisterLegacyAminoCodec(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterLegacyAminoCodec", reflect.TypeOf((*MockAppModuleWithAllExtensionsABCI)(nil).RegisterLegacyAminoCodec), arg0) -} - // RegisterServices mocks base method. func (m *MockAppModuleWithAllExtensionsABCI) RegisterServices(arg0 module.Configurator) { m.ctrl.T.Helper() diff --git a/testutil/mock/types_module_module.go b/testutil/mock/types_module_module.go index 534fb5f450b1..eabd3384d611 100644 --- a/testutil/mock/types_module_module.go +++ b/testutil/mock/types_module_module.go @@ -19,77 +19,77 @@ import ( runtime "github.com/grpc-ecosystem/grpc-gateway/runtime" ) -// MockAppModuleBasic is a mock of AppModuleBasic interface. -type MockAppModuleBasic struct { +// MockAppModule is a mock of AppModule interface. +type MockAppModule struct { ctrl *gomock.Controller - recorder *MockAppModuleBasicMockRecorder + recorder *MockAppModuleMockRecorder } -// MockAppModuleBasicMockRecorder is the mock recorder for MockAppModuleBasic. -type MockAppModuleBasicMockRecorder struct { - mock *MockAppModuleBasic +// MockAppModuleMockRecorder is the mock recorder for MockAppModule. +type MockAppModuleMockRecorder struct { + mock *MockAppModule } -// NewMockAppModuleBasic creates a new mock instance. -func NewMockAppModuleBasic(ctrl *gomock.Controller) *MockAppModuleBasic { - mock := &MockAppModuleBasic{ctrl: ctrl} - mock.recorder = &MockAppModuleBasicMockRecorder{mock} +// NewMockAppModule creates a new mock instance. +func NewMockAppModule(ctrl *gomock.Controller) *MockAppModule { + mock := &MockAppModule{ctrl: ctrl} + mock.recorder = &MockAppModuleMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAppModuleBasic) EXPECT() *MockAppModuleBasicMockRecorder { +func (m *MockAppModule) EXPECT() *MockAppModuleMockRecorder { return m.recorder } -// Name mocks base method. -func (m *MockAppModuleBasic) Name() string { +// IsAppModule mocks base method. +func (m *MockAppModule) IsAppModule() { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Name") - ret0, _ := ret[0].(string) - return ret0 + m.ctrl.Call(m, "IsAppModule") } -// Name indicates an expected call of Name. -func (mr *MockAppModuleBasicMockRecorder) Name() *gomock.Call { +// IsAppModule indicates an expected call of IsAppModule. +func (mr *MockAppModuleMockRecorder) IsAppModule() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockAppModuleBasic)(nil).Name)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsAppModule", reflect.TypeOf((*MockAppModule)(nil).IsAppModule)) } -// RegisterGRPCGatewayRoutes mocks base method. -func (m *MockAppModuleBasic) RegisterGRPCGatewayRoutes(arg0 client.Context, arg1 *runtime.ServeMux) { +// IsOnePerModuleType mocks base method. +func (m *MockAppModule) IsOnePerModuleType() { m.ctrl.T.Helper() - m.ctrl.Call(m, "RegisterGRPCGatewayRoutes", arg0, arg1) + m.ctrl.Call(m, "IsOnePerModuleType") } -// RegisterGRPCGatewayRoutes indicates an expected call of RegisterGRPCGatewayRoutes. -func (mr *MockAppModuleBasicMockRecorder) RegisterGRPCGatewayRoutes(arg0, arg1 interface{}) *gomock.Call { +// IsOnePerModuleType indicates an expected call of IsOnePerModuleType. +func (mr *MockAppModuleMockRecorder) IsOnePerModuleType() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterGRPCGatewayRoutes", reflect.TypeOf((*MockAppModuleBasic)(nil).RegisterGRPCGatewayRoutes), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsOnePerModuleType", reflect.TypeOf((*MockAppModule)(nil).IsOnePerModuleType)) } -// RegisterInterfaces mocks base method. -func (m *MockAppModuleBasic) RegisterInterfaces(arg0 types0.InterfaceRegistry) { +// Name mocks base method. +func (m *MockAppModule) Name() string { m.ctrl.T.Helper() - m.ctrl.Call(m, "RegisterInterfaces", arg0) + ret := m.ctrl.Call(m, "Name") + ret0, _ := ret[0].(string) + return ret0 } -// RegisterInterfaces indicates an expected call of RegisterInterfaces. -func (mr *MockAppModuleBasicMockRecorder) RegisterInterfaces(arg0 interface{}) *gomock.Call { +// Name indicates an expected call of Name. +func (mr *MockAppModuleMockRecorder) Name() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterInterfaces", reflect.TypeOf((*MockAppModuleBasic)(nil).RegisterInterfaces), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockAppModule)(nil).Name)) } -// RegisterLegacyAminoCodec mocks base method. -func (m *MockAppModuleBasic) RegisterLegacyAminoCodec(arg0 *codec.LegacyAmino) { +// RegisterInterfaces mocks base method. +func (m *MockAppModule) RegisterInterfaces(arg0 types0.InterfaceRegistry) { m.ctrl.T.Helper() - m.ctrl.Call(m, "RegisterLegacyAminoCodec", arg0) + m.ctrl.Call(m, "RegisterInterfaces", arg0) } -// RegisterLegacyAminoCodec indicates an expected call of RegisterLegacyAminoCodec. -func (mr *MockAppModuleBasicMockRecorder) RegisterLegacyAminoCodec(arg0 interface{}) *gomock.Call { +// RegisterInterfaces indicates an expected call of RegisterInterfaces. +func (mr *MockAppModuleMockRecorder) RegisterInterfaces(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterLegacyAminoCodec", reflect.TypeOf((*MockAppModuleBasic)(nil).RegisterLegacyAminoCodec), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterInterfaces", reflect.TypeOf((*MockAppModule)(nil).RegisterInterfaces), arg0) } // MockHasName is a mock of HasName interface. @@ -166,6 +166,20 @@ func (mr *MockHasGenesisBasicsMockRecorder) DefaultGenesis(arg0 interface{}) *go return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DefaultGenesis", reflect.TypeOf((*MockHasGenesisBasics)(nil).DefaultGenesis), arg0) } +// Name mocks base method. +func (m *MockHasGenesisBasics) 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 *MockHasGenesisBasicsMockRecorder) Name() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockHasGenesisBasics)(nil).Name)) +} + // ValidateGenesis mocks base method. func (m *MockHasGenesisBasics) ValidateGenesis(arg0 codec.JSONCodec, arg1 client.TxEncodingConfig, arg2 json.RawMessage) error { m.ctrl.T.Helper() @@ -180,6 +194,111 @@ func (mr *MockHasGenesisBasicsMockRecorder) ValidateGenesis(arg0, arg1, arg2 int return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateGenesis", reflect.TypeOf((*MockHasGenesisBasics)(nil).ValidateGenesis), arg0, arg1, arg2) } +// MockHasAminoCodec is a mock of HasAminoCodec interface. +type MockHasAminoCodec struct { + ctrl *gomock.Controller + recorder *MockHasAminoCodecMockRecorder +} + +// MockHasAminoCodecMockRecorder is the mock recorder for MockHasAminoCodec. +type MockHasAminoCodecMockRecorder struct { + mock *MockHasAminoCodec +} + +// NewMockHasAminoCodec creates a new mock instance. +func NewMockHasAminoCodec(ctrl *gomock.Controller) *MockHasAminoCodec { + mock := &MockHasAminoCodec{ctrl: ctrl} + mock.recorder = &MockHasAminoCodecMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockHasAminoCodec) EXPECT() *MockHasAminoCodecMockRecorder { + return m.recorder +} + +// RegisterLegacyAminoCodec mocks base method. +func (m *MockHasAminoCodec) RegisterLegacyAminoCodec(arg0 *codec.LegacyAmino) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "RegisterLegacyAminoCodec", arg0) +} + +// RegisterLegacyAminoCodec indicates an expected call of RegisterLegacyAminoCodec. +func (mr *MockHasAminoCodecMockRecorder) RegisterLegacyAminoCodec(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + 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 types0.InterfaceRegistry) { + 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 + recorder *MockHasGRPCGatewayMockRecorder +} + +// MockHasGRPCGatewayMockRecorder is the mock recorder for MockHasGRPCGateway. +type MockHasGRPCGatewayMockRecorder struct { + mock *MockHasGRPCGateway +} + +// NewMockHasGRPCGateway creates a new mock instance. +func NewMockHasGRPCGateway(ctrl *gomock.Controller) *MockHasGRPCGateway { + mock := &MockHasGRPCGateway{ctrl: ctrl} + mock.recorder = &MockHasGRPCGatewayMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockHasGRPCGateway) EXPECT() *MockHasGRPCGatewayMockRecorder { + return m.recorder +} + +// RegisterGRPCGatewayRoutes mocks base method. +func (m *MockHasGRPCGateway) RegisterGRPCGatewayRoutes(arg0 client.Context, arg1 *runtime.ServeMux) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "RegisterGRPCGatewayRoutes", arg0, arg1) +} + +// RegisterGRPCGatewayRoutes indicates an expected call of RegisterGRPCGatewayRoutes. +func (mr *MockHasGRPCGatewayMockRecorder) RegisterGRPCGatewayRoutes(arg0, arg1 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + 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 @@ -243,6 +362,20 @@ func (mr *MockHasGenesisMockRecorder) InitGenesis(arg0, arg1, arg2 interface{}) 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() @@ -322,69 +455,8 @@ func (mr *MockHasABCIGenesisMockRecorder) InitGenesis(arg0, arg1, arg2 interface return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitGenesis", reflect.TypeOf((*MockHasABCIGenesis)(nil).InitGenesis), arg0, arg1, arg2) } -// ValidateGenesis mocks base method. -func (m *MockHasABCIGenesis) 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 *MockHasABCIGenesisMockRecorder) ValidateGenesis(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateGenesis", reflect.TypeOf((*MockHasABCIGenesis)(nil).ValidateGenesis), arg0, arg1, arg2) -} - -// MockAppModule is a mock of AppModule interface. -type MockAppModule struct { - ctrl *gomock.Controller - recorder *MockAppModuleMockRecorder -} - -// MockAppModuleMockRecorder is the mock recorder for MockAppModule. -type MockAppModuleMockRecorder struct { - mock *MockAppModule -} - -// NewMockAppModule creates a new mock instance. -func NewMockAppModule(ctrl *gomock.Controller) *MockAppModule { - mock := &MockAppModule{ctrl: ctrl} - mock.recorder = &MockAppModuleMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAppModule) EXPECT() *MockAppModuleMockRecorder { - return m.recorder -} - -// IsAppModule mocks base method. -func (m *MockAppModule) IsAppModule() { - m.ctrl.T.Helper() - m.ctrl.Call(m, "IsAppModule") -} - -// IsAppModule indicates an expected call of IsAppModule. -func (mr *MockAppModuleMockRecorder) IsAppModule() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsAppModule", reflect.TypeOf((*MockAppModule)(nil).IsAppModule)) -} - -// IsOnePerModuleType mocks base method. -func (m *MockAppModule) IsOnePerModuleType() { - m.ctrl.T.Helper() - m.ctrl.Call(m, "IsOnePerModuleType") -} - -// IsOnePerModuleType indicates an expected call of IsOnePerModuleType. -func (mr *MockAppModuleMockRecorder) IsOnePerModuleType() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsOnePerModuleType", reflect.TypeOf((*MockAppModule)(nil).IsOnePerModuleType)) -} - // Name mocks base method. -func (m *MockAppModule) Name() string { +func (m *MockHasABCIGenesis) Name() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Name") ret0, _ := ret[0].(string) @@ -392,45 +464,23 @@ func (m *MockAppModule) Name() string { } // Name indicates an expected call of Name. -func (mr *MockAppModuleMockRecorder) Name() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockAppModule)(nil).Name)) -} - -// RegisterGRPCGatewayRoutes mocks base method. -func (m *MockAppModule) RegisterGRPCGatewayRoutes(arg0 client.Context, arg1 *runtime.ServeMux) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "RegisterGRPCGatewayRoutes", arg0, arg1) -} - -// RegisterGRPCGatewayRoutes indicates an expected call of RegisterGRPCGatewayRoutes. -func (mr *MockAppModuleMockRecorder) RegisterGRPCGatewayRoutes(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterGRPCGatewayRoutes", reflect.TypeOf((*MockAppModule)(nil).RegisterGRPCGatewayRoutes), arg0, arg1) -} - -// RegisterInterfaces mocks base method. -func (m *MockAppModule) RegisterInterfaces(arg0 types0.InterfaceRegistry) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "RegisterInterfaces", arg0) -} - -// RegisterInterfaces indicates an expected call of RegisterInterfaces. -func (mr *MockAppModuleMockRecorder) RegisterInterfaces(arg0 interface{}) *gomock.Call { +func (mr *MockHasABCIGenesisMockRecorder) Name() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterInterfaces", reflect.TypeOf((*MockAppModule)(nil).RegisterInterfaces), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockHasABCIGenesis)(nil).Name)) } -// RegisterLegacyAminoCodec mocks base method. -func (m *MockAppModule) RegisterLegacyAminoCodec(arg0 *codec.LegacyAmino) { +// ValidateGenesis mocks base method. +func (m *MockHasABCIGenesis) ValidateGenesis(arg0 codec.JSONCodec, arg1 client.TxEncodingConfig, arg2 json.RawMessage) error { m.ctrl.T.Helper() - m.ctrl.Call(m, "RegisterLegacyAminoCodec", arg0) + ret := m.ctrl.Call(m, "ValidateGenesis", arg0, arg1, arg2) + ret0, _ := ret[0].(error) + return ret0 } -// RegisterLegacyAminoCodec indicates an expected call of RegisterLegacyAminoCodec. -func (mr *MockAppModuleMockRecorder) RegisterLegacyAminoCodec(arg0 interface{}) *gomock.Call { +// ValidateGenesis indicates an expected call of ValidateGenesis. +func (mr *MockHasABCIGenesisMockRecorder) ValidateGenesis(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterLegacyAminoCodec", reflect.TypeOf((*MockAppModule)(nil).RegisterLegacyAminoCodec), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateGenesis", reflect.TypeOf((*MockHasABCIGenesis)(nil).ValidateGenesis), arg0, arg1, arg2) } // MockHasInvariants is a mock of HasInvariants interface. @@ -616,18 +666,6 @@ func (mr *MockHasABCIEndBlockMockRecorder) Name() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockHasABCIEndBlock)(nil).Name)) } -// RegisterGRPCGatewayRoutes mocks base method. -func (m *MockHasABCIEndBlock) RegisterGRPCGatewayRoutes(arg0 client.Context, arg1 *runtime.ServeMux) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "RegisterGRPCGatewayRoutes", arg0, arg1) -} - -// RegisterGRPCGatewayRoutes indicates an expected call of RegisterGRPCGatewayRoutes. -func (mr *MockHasABCIEndBlockMockRecorder) RegisterGRPCGatewayRoutes(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterGRPCGatewayRoutes", reflect.TypeOf((*MockHasABCIEndBlock)(nil).RegisterGRPCGatewayRoutes), arg0, arg1) -} - // RegisterInterfaces mocks base method. func (m *MockHasABCIEndBlock) RegisterInterfaces(arg0 types0.InterfaceRegistry) { m.ctrl.T.Helper() @@ -639,144 +677,3 @@ func (mr *MockHasABCIEndBlockMockRecorder) RegisterInterfaces(arg0 interface{}) mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterInterfaces", reflect.TypeOf((*MockHasABCIEndBlock)(nil).RegisterInterfaces), arg0) } - -// RegisterLegacyAminoCodec mocks base method. -func (m *MockHasABCIEndBlock) RegisterLegacyAminoCodec(arg0 *codec.LegacyAmino) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "RegisterLegacyAminoCodec", arg0) -} - -// RegisterLegacyAminoCodec indicates an expected call of RegisterLegacyAminoCodec. -func (mr *MockHasABCIEndBlockMockRecorder) RegisterLegacyAminoCodec(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterLegacyAminoCodec", reflect.TypeOf((*MockHasABCIEndBlock)(nil).RegisterLegacyAminoCodec), arg0) -} - -// MockgenesisOnlyModule is a mock of genesisOnlyModule interface. -type MockgenesisOnlyModule struct { - ctrl *gomock.Controller - recorder *MockgenesisOnlyModuleMockRecorder -} - -// MockgenesisOnlyModuleMockRecorder is the mock recorder for MockgenesisOnlyModule. -type MockgenesisOnlyModuleMockRecorder struct { - mock *MockgenesisOnlyModule -} - -// NewMockgenesisOnlyModule creates a new mock instance. -func NewMockgenesisOnlyModule(ctrl *gomock.Controller) *MockgenesisOnlyModule { - mock := &MockgenesisOnlyModule{ctrl: ctrl} - mock.recorder = &MockgenesisOnlyModuleMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockgenesisOnlyModule) EXPECT() *MockgenesisOnlyModuleMockRecorder { - return m.recorder -} - -// DefaultGenesis mocks base method. -func (m *MockgenesisOnlyModule) 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 *MockgenesisOnlyModuleMockRecorder) DefaultGenesis(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DefaultGenesis", reflect.TypeOf((*MockgenesisOnlyModule)(nil).DefaultGenesis), arg0) -} - -// ExportGenesis mocks base method. -func (m *MockgenesisOnlyModule) 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 *MockgenesisOnlyModuleMockRecorder) ExportGenesis(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExportGenesis", reflect.TypeOf((*MockgenesisOnlyModule)(nil).ExportGenesis), arg0, arg1) -} - -// InitGenesis mocks base method. -func (m *MockgenesisOnlyModule) InitGenesis(arg0 context.Context, arg1 codec.JSONCodec, arg2 json.RawMessage) []types.ValidatorUpdate { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "InitGenesis", arg0, arg1, arg2) - ret0, _ := ret[0].([]types.ValidatorUpdate) - return ret0 -} - -// InitGenesis indicates an expected call of InitGenesis. -func (mr *MockgenesisOnlyModuleMockRecorder) InitGenesis(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitGenesis", reflect.TypeOf((*MockgenesisOnlyModule)(nil).InitGenesis), arg0, arg1, arg2) -} - -// Name mocks base method. -func (m *MockgenesisOnlyModule) 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 *MockgenesisOnlyModuleMockRecorder) Name() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockgenesisOnlyModule)(nil).Name)) -} - -// RegisterGRPCGatewayRoutes mocks base method. -func (m *MockgenesisOnlyModule) RegisterGRPCGatewayRoutes(arg0 client.Context, arg1 *runtime.ServeMux) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "RegisterGRPCGatewayRoutes", arg0, arg1) -} - -// RegisterGRPCGatewayRoutes indicates an expected call of RegisterGRPCGatewayRoutes. -func (mr *MockgenesisOnlyModuleMockRecorder) RegisterGRPCGatewayRoutes(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterGRPCGatewayRoutes", reflect.TypeOf((*MockgenesisOnlyModule)(nil).RegisterGRPCGatewayRoutes), arg0, arg1) -} - -// RegisterInterfaces mocks base method. -func (m *MockgenesisOnlyModule) RegisterInterfaces(arg0 types0.InterfaceRegistry) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "RegisterInterfaces", arg0) -} - -// RegisterInterfaces indicates an expected call of RegisterInterfaces. -func (mr *MockgenesisOnlyModuleMockRecorder) RegisterInterfaces(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterInterfaces", reflect.TypeOf((*MockgenesisOnlyModule)(nil).RegisterInterfaces), arg0) -} - -// RegisterLegacyAminoCodec mocks base method. -func (m *MockgenesisOnlyModule) RegisterLegacyAminoCodec(arg0 *codec.LegacyAmino) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "RegisterLegacyAminoCodec", arg0) -} - -// RegisterLegacyAminoCodec indicates an expected call of RegisterLegacyAminoCodec. -func (mr *MockgenesisOnlyModuleMockRecorder) RegisterLegacyAminoCodec(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterLegacyAminoCodec", reflect.TypeOf((*MockgenesisOnlyModule)(nil).RegisterLegacyAminoCodec), arg0) -} - -// ValidateGenesis mocks base method. -func (m *MockgenesisOnlyModule) 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 *MockgenesisOnlyModuleMockRecorder) ValidateGenesis(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateGenesis", reflect.TypeOf((*MockgenesisOnlyModule)(nil).ValidateGenesis), arg0, arg1, arg2) -} diff --git a/types/mempool/mempool_test.go b/types/mempool/mempool_test.go index 003b5953c705..bab941ae611b 100644 --- a/types/mempool/mempool_test.go +++ b/types/mempool/mempool_test.go @@ -236,7 +236,7 @@ func (s *MempoolTestSuite) TestSampleTxs() { } func unmarshalTx(txBytes []byte) (sdk.Tx, error) { - cfg := moduletestutil.MakeTestEncodingConfig(counter.AppModuleBasic{}) + cfg := moduletestutil.MakeTestEncodingConfig(counter.AppModule{}) return cfg.TxConfig.TxJSONDecoder()(txBytes) } diff --git a/types/module/core_module.go b/types/module/core_module.go index de2d816ab1cf..fa81659a16f0 100644 --- a/types/module/core_module.go +++ b/types/module/core_module.go @@ -19,33 +19,31 @@ import ( ) var ( - _ appmodule.AppModule = coreAppModuleBasicAdaptor{} - - _ AppModuleBasic = coreAppModuleBasicAdaptor{} - _ HasABCIGenesis = coreAppModuleBasicAdaptor{} - _ HasServices = coreAppModuleBasicAdaptor{} + _ appmodule.AppModule = coreAppModuleAdaptor{} + + _ HasName = coreAppModuleAdaptor{} + _ HasAminoCodec = coreAppModuleAdaptor{} + _ HasGRPCGateway = coreAppModuleAdaptor{} + _ HasRegisterInterfaces = coreAppModuleAdaptor{} + _ HasABCIGenesis = coreAppModuleAdaptor{} + _ HasServices = coreAppModuleAdaptor{} ) // CoreAppModuleAdaptor wraps the core API module as an AppModule that this version of the SDK can use. func CoreAppModuleAdaptor(name string, module appmodule.AppModule) AppModule { - return coreAppModuleBasicAdaptor{ + return coreAppModuleAdaptor{ name: name, module: module, } } -// CoreAppModuleBasicAdaptor wraps the core API module as an AppModule that this version of the SDK can use. -func CoreAppModuleBasicAdaptor(name string, module appmodule.AppModule) AppModule { - return CoreAppModuleAdaptor(name, module) -} - -type coreAppModuleBasicAdaptor struct { +type coreAppModuleAdaptor struct { name string module appmodule.AppModule } // DefaultGenesis implements HasGenesis -func (c coreAppModuleBasicAdaptor) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { +func (c coreAppModuleAdaptor) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { if mod, ok := c.module.(appmodule.HasGenesis); ok { target := genesis.RawJSONTarget{} err := mod.DefaultGenesis(target.Target()) @@ -69,7 +67,7 @@ func (c coreAppModuleBasicAdaptor) DefaultGenesis(cdc codec.JSONCodec) json.RawM } // ValidateGenesis implements HasGenesis -func (c coreAppModuleBasicAdaptor) ValidateGenesis(cdc codec.JSONCodec, txConfig client.TxEncodingConfig, bz json.RawMessage) error { +func (c coreAppModuleAdaptor) ValidateGenesis(cdc codec.JSONCodec, txConfig client.TxEncodingConfig, bz json.RawMessage) error { if mod, ok := c.module.(appmodule.HasGenesis); ok { source, err := genesis.SourceFromRawJSON(bz) if err != nil { @@ -89,7 +87,7 @@ func (c coreAppModuleBasicAdaptor) ValidateGenesis(cdc codec.JSONCodec, txConfig } // ExportGenesis implements HasGenesis -func (c coreAppModuleBasicAdaptor) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json.RawMessage { +func (c coreAppModuleAdaptor) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json.RawMessage { if module, ok := c.module.(appmodule.HasGenesis); ok { ctx := sdk.UnwrapSDKContext(ctx).WithGasMeter(storetypes.NewInfiniteGasMeter()) // avoid race conditions target := genesis.RawJSONTarget{} @@ -114,7 +112,7 @@ func (c coreAppModuleBasicAdaptor) ExportGenesis(ctx context.Context, cdc codec. } // InitGenesis implements HasGenesis -func (c coreAppModuleBasicAdaptor) InitGenesis(ctx context.Context, cdc codec.JSONCodec, bz json.RawMessage) []abci.ValidatorUpdate { +func (c coreAppModuleAdaptor) InitGenesis(ctx context.Context, cdc codec.JSONCodec, bz json.RawMessage) []abci.ValidatorUpdate { if module, ok := c.module.(appmodule.HasGenesis); ok { // core API genesis source, err := genesis.SourceFromRawJSON(bz) @@ -138,13 +136,12 @@ func (c coreAppModuleBasicAdaptor) InitGenesis(ctx context.Context, cdc codec.JS return nil } -// Name implements AppModuleBasic -func (c coreAppModuleBasicAdaptor) Name() string { +// Name implements HasName +func (c coreAppModuleAdaptor) Name() string { return c.name } -// GetQueryCmd implements AppModuleBasic -func (c coreAppModuleBasicAdaptor) GetQueryCmd() *cobra.Command { +func (c coreAppModuleAdaptor) GetQueryCmd() *cobra.Command { if mod, ok := c.module.(interface { GetQueryCmd() *cobra.Command }); ok { @@ -154,8 +151,7 @@ func (c coreAppModuleBasicAdaptor) GetQueryCmd() *cobra.Command { return nil } -// GetTxCmd implements AppModuleBasic -func (c coreAppModuleBasicAdaptor) GetTxCmd() *cobra.Command { +func (c coreAppModuleAdaptor) GetTxCmd() *cobra.Command { if mod, ok := c.module.(interface { GetTxCmd() *cobra.Command }); ok { @@ -165,8 +161,8 @@ func (c coreAppModuleBasicAdaptor) GetTxCmd() *cobra.Command { return nil } -// RegisterGRPCGatewayRoutes implements AppModuleBasic -func (c coreAppModuleBasicAdaptor) RegisterGRPCGatewayRoutes(ctx client.Context, mux *runtime.ServeMux) { +// RegisterGRPCGatewayRoutes implements HasGRPCGateway +func (c coreAppModuleAdaptor) RegisterGRPCGatewayRoutes(ctx client.Context, mux *runtime.ServeMux) { if mod, ok := c.module.(interface { RegisterGRPCGatewayRoutes(context client.Context, mux *runtime.ServeMux) }); ok { @@ -174,8 +170,8 @@ func (c coreAppModuleBasicAdaptor) RegisterGRPCGatewayRoutes(ctx client.Context, } } -// RegisterInterfaces implements AppModuleBasic -func (c coreAppModuleBasicAdaptor) RegisterInterfaces(registry codectypes.InterfaceRegistry) { +// RegisterInterfaces implements HasRegisterInterfaces +func (c coreAppModuleAdaptor) RegisterInterfaces(registry codectypes.InterfaceRegistry) { if mod, ok := c.module.(interface { RegisterInterfaces(registry codectypes.InterfaceRegistry) }); ok { @@ -183,8 +179,8 @@ func (c coreAppModuleBasicAdaptor) RegisterInterfaces(registry codectypes.Interf } } -// RegisterLegacyAminoCodec implements AppModuleBasic -func (c coreAppModuleBasicAdaptor) RegisterLegacyAminoCodec(amino *codec.LegacyAmino) { +// RegisterLegacyAminoCodec implements HasAminoCodec +func (c coreAppModuleAdaptor) RegisterLegacyAminoCodec(amino *codec.LegacyAmino) { if mod, ok := c.module.(interface { RegisterLegacyAminoCodec(amino *codec.LegacyAmino) }); ok { @@ -193,7 +189,7 @@ func (c coreAppModuleBasicAdaptor) RegisterLegacyAminoCodec(amino *codec.LegacyA } // RegisterServices implements HasServices -func (c coreAppModuleBasicAdaptor) RegisterServices(cfg Configurator) { +func (c coreAppModuleAdaptor) RegisterServices(cfg Configurator) { if module, ok := c.module.(appmodule.HasServices); ok { err := module.RegisterServices(cfg) if err != nil { @@ -209,6 +205,6 @@ func (c coreAppModuleBasicAdaptor) RegisterServices(cfg Configurator) { } } -func (c coreAppModuleBasicAdaptor) IsOnePerModuleType() {} +func (c coreAppModuleAdaptor) IsOnePerModuleType() {} -func (c coreAppModuleBasicAdaptor) IsAppModule() {} +func (c coreAppModuleAdaptor) IsAppModule() {} diff --git a/types/module/module.go b/types/module/module.go index 91ccd7ab3dae..640d733fb6a2 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -1,7 +1,6 @@ /* Package module contains application module patterns and associated "manager" functionality. The module pattern has been broken down by: - - independent module functionality (AppModuleBasic) - inter-dependent module simulation functionality (AppModuleSimulation) - inter-dependent module full functionality (AppModule) @@ -11,14 +10,7 @@ module keepers are dependent on each other, thus in order to access the full set of module functionality we need to define all the keepers/params-store/keys etc. This full set of advanced functionality is defined by the AppModule interface. -Independent module functions are separated to allow for the construction of the -basic application structures required early on in the application definition -and used to enable the definition of full module functionality later in the -process. This separation is necessary, however we still want to allow for a -high level pattern for modules to follow - for instance, such that we don't -have to manually register all of the codecs for all the modules. This basic -procedure as well as other basic patterns are handled through the use of -BasicManager. +Independent module functions of modules can be accessed through a non instantiated AppModule. Lastly the interface for genesis functionality (HasGenesis & HasABCIGenesis) has been separated out from full module functionality (AppModule) so that modules which @@ -51,12 +43,22 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -// AppModuleBasic is the standard form for basic non-dependant elements of an application module. +// Deprecated: use the embed extension interfaces instead, when needed. type AppModuleBasic interface { HasName - RegisterLegacyAminoCodec(*codec.LegacyAmino) - RegisterInterfaces(types.InterfaceRegistry) - RegisterGRPCGatewayRoutes(client.Context, *runtime.ServeMux) + HasRegisterInterfaces + HasGRPCGateway + HasAminoCodec +} + +// AppModule is the form for an application module. Most of +// 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 } // HasName allows the module to provide its own name for legacy purposes. @@ -68,117 +70,26 @@ type HasName interface { // HasGenesisBasics is the legacy interface for stateless genesis methods. type HasGenesisBasics interface { + HasName + DefaultGenesis(codec.JSONCodec) json.RawMessage ValidateGenesis(codec.JSONCodec, client.TxEncodingConfig, json.RawMessage) error } -// BasicManager is a collection of AppModuleBasic -type BasicManager map[string]AppModuleBasic - -// NewBasicManager creates a new BasicManager object -func NewBasicManager(modules ...AppModuleBasic) BasicManager { - moduleMap := make(map[string]AppModuleBasic) - for _, module := range modules { - moduleMap[module.Name()] = module - } - return moduleMap -} - -// NewBasicManagerFromManager creates a new BasicManager from a Manager -// The BasicManager will contain all AppModuleBasic from the AppModule Manager -// Module's AppModuleBasic can be overridden by passing a custom AppModuleBasic map -func NewBasicManagerFromManager(manager *Manager, customModuleBasics map[string]AppModuleBasic) BasicManager { - moduleMap := make(map[string]AppModuleBasic) - for name, module := range manager.Modules { - if customBasicMod, ok := customModuleBasics[name]; ok { - moduleMap[name] = customBasicMod - continue - } - - if appModule, ok := module.(appmodule.AppModule); ok { - moduleMap[name] = CoreAppModuleBasicAdaptor(name, appModule) - continue - } - - if basicMod, ok := module.(AppModuleBasic); ok { - moduleMap[name] = basicMod - } - } - - return moduleMap -} - -// RegisterLegacyAminoCodec registers all module codecs -func (bm BasicManager) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - for _, b := range bm { - b.RegisterLegacyAminoCodec(cdc) - } -} - -// RegisterInterfaces registers all module interface types -func (bm BasicManager) RegisterInterfaces(registry types.InterfaceRegistry) { - for _, m := range bm { - m.RegisterInterfaces(registry) - } -} - -// DefaultGenesis provides default genesis information for all modules -func (bm BasicManager) DefaultGenesis(cdc codec.JSONCodec) map[string]json.RawMessage { - genesisData := make(map[string]json.RawMessage) - for _, b := range bm { - if mod, ok := b.(HasGenesisBasics); ok { - genesisData[b.Name()] = mod.DefaultGenesis(cdc) - } - } - - return genesisData -} - -// ValidateGenesis performs genesis state validation for all modules -func (bm BasicManager) ValidateGenesis(cdc codec.JSONCodec, txEncCfg client.TxEncodingConfig, genesisData map[string]json.RawMessage) error { - for _, b := range bm { - // first check if the module is an adapted Core API Module - if mod, ok := b.(HasGenesisBasics); ok { - if err := mod.ValidateGenesis(cdc, txEncCfg, genesisData[b.Name()]); err != nil { - return err - } - } - } - - return nil -} - -// RegisterGRPCGatewayRoutes registers all module rest routes -func (bm BasicManager) RegisterGRPCGatewayRoutes(clientCtx client.Context, rtr *runtime.ServeMux) { - for _, b := range bm { - b.RegisterGRPCGatewayRoutes(clientCtx, rtr) - } +// HasAminoCodec is the interface for modules that have amino codec registration. +// Deprecated: modules should not need to register their own amino codecs. +type HasAminoCodec interface { + RegisterLegacyAminoCodec(*codec.LegacyAmino) } -// AddTxCommands adds all tx commands to the rootTxCmd. -func (bm BasicManager) AddTxCommands(rootTxCmd *cobra.Command) { - for _, b := range bm { - if mod, ok := b.(interface { - GetTxCmd() *cobra.Command - }); ok { - if cmd := mod.GetTxCmd(); cmd != nil { - rootTxCmd.AddCommand(cmd) - } - } - } +// HasRegisterInterfaces is the interface for modules to register their msg types. +type HasRegisterInterfaces interface { + RegisterInterfaces(types.InterfaceRegistry) } -// AddQueryCommands adds all query commands to the rootQueryCmd. -func (bm BasicManager) AddQueryCommands(rootQueryCmd *cobra.Command) { - for _, b := range bm { - if mod, ok := b.(interface { - GetQueryCmd() *cobra.Command - }); ok { - if cmd := mod.GetQueryCmd(); cmd != nil { - rootQueryCmd.AddCommand(cmd) - } - } - } +// HasGRPCGateway is the interface for modules to register their gRPC gateway routes. +type HasGRPCGateway interface { + RegisterGRPCGatewayRoutes(client.Context, *runtime.ServeMux) } // HasGenesis is the extension interface for stateful genesis methods. @@ -195,15 +106,6 @@ type HasABCIGenesis interface { ExportGenesis(context.Context, codec.JSONCodec) json.RawMessage } -// AppModule is the form for an application module. Most of -// its functionality has been moved to extension interfaces. -// Deprecated: use appmodule.AppModule with a combination of extension interfaes interfaces instead. -type AppModule interface { - appmodule.AppModule - - AppModuleBasic -} - // HasInvariants is the interface for registering invariants. type HasInvariants interface { // RegisterInvariants registers module invariants. @@ -235,41 +137,6 @@ type HasABCIEndBlock interface { EndBlock(context.Context) ([]abci.ValidatorUpdate, error) } -var ( - _ appmodule.AppModule = (*GenesisOnlyAppModule)(nil) - _ AppModuleBasic = (*GenesisOnlyAppModule)(nil) -) - -// genesisOnlyModule is an interface need to return GenesisOnlyAppModule struct in order to wrap two interfaces -type genesisOnlyModule interface { - AppModuleBasic - HasABCIGenesis -} - -// GenesisOnlyAppModule is an AppModule that only has import/export functionality -type GenesisOnlyAppModule struct { - genesisOnlyModule -} - -// NewGenesisOnlyAppModule creates a new GenesisOnlyAppModule object -func NewGenesisOnlyAppModule(amg genesisOnlyModule) GenesisOnlyAppModule { - return GenesisOnlyAppModule{ - genesisOnlyModule: amg, - } -} - -// IsOnePerModuleType implements the depinject.OnePerModuleType interface. -func (GenesisOnlyAppModule) IsOnePerModuleType() {} - -// IsAppModule implements the appmodule.AppModule interface. -func (GenesisOnlyAppModule) IsAppModule() {} - -// RegisterInvariants is a placeholder function register no invariants -func (GenesisOnlyAppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (gam GenesisOnlyAppModule) ConsensusVersion() uint64 { return 1 } - // Manager defines a module manager that provides the high level utility for managing and executing // operations for a group of modules type Manager struct { @@ -444,6 +311,87 @@ func (m *Manager) SetOrderMigrations(moduleNames ...string) { m.OrderMigrations = moduleNames } +// RegisterLegacyAminoCodec registers all module codecs +func (m *Manager) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + for _, b := range m.Modules { + if mod, ok := b.(HasAminoCodec); ok { + mod.RegisterLegacyAminoCodec(cdc) + } + } +} + +// RegisterInterfaces registers all module interface types +func (m *Manager) RegisterInterfaces(registry types.InterfaceRegistry) { + for _, b := range m.Modules { + if mod, ok := b.(HasRegisterInterfaces); ok { + mod.RegisterInterfaces(registry) + } + } +} + +// DefaultGenesis provides default genesis information for all modules +func (m *Manager) DefaultGenesis(cdc codec.JSONCodec) 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) + } else if mod, ok := b.(HasName); ok { + genesisData[mod.Name()] = []byte("{}") + } + } + + return genesisData +} + +// ValidateGenesis performs genesis state validation for all modules +func (m *Manager) ValidateGenesis(cdc codec.JSONCodec, txEncCfg client.TxEncodingConfig, 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 { + return err + } + } + } + + return nil +} + +// RegisterGRPCGatewayRoutes registers all module rest routes +func (m *Manager) RegisterGRPCGatewayRoutes(clientCtx client.Context, rtr *runtime.ServeMux) { + for _, b := range m.Modules { + if mod, ok := b.(HasGRPCGateway); ok { + mod.RegisterGRPCGatewayRoutes(clientCtx, rtr) + } + } +} + +// AddTxCommands adds all tx commands to the rootTxCmd. +func (m *Manager) AddTxCommands(rootTxCmd *cobra.Command) { + for _, b := range m.Modules { + if mod, ok := b.(interface { + GetTxCmd() *cobra.Command + }); ok { + if cmd := mod.GetTxCmd(); cmd != nil { + rootTxCmd.AddCommand(cmd) + } + } + } +} + +// AddQueryCommands adds all query commands to the rootQueryCmd. +func (m *Manager) AddQueryCommands(rootQueryCmd *cobra.Command) { + for _, b := range m.Modules { + if mod, ok := b.(interface { + GetQueryCmd() *cobra.Command + }); ok { + if cmd := mod.GetQueryCmd(); cmd != nil { + rootQueryCmd.AddCommand(cmd) + } + } + } +} + // RegisterInvariants registers all module invariants func (m *Manager) RegisterInvariants(ir sdk.InvariantRegistry) { for _, module := range m.Modules { diff --git a/types/module/module_test.go b/types/module/module_test.go index 020f9cbc9b62..4853ca86e7dc 100644 --- a/types/module/module_test.go +++ b/types/module/module_test.go @@ -32,66 +32,6 @@ func (MockCoreAppModule) GetQueryCmd() *cobra.Command { } } -func TestBasicManager(t *testing.T) { - mockCtrl := gomock.NewController(t) - t.Cleanup(mockCtrl.Finish) - legacyAmino := codec.NewLegacyAmino() - interfaceRegistry := types.NewInterfaceRegistry() - cdc := codec.NewProtoCodec(interfaceRegistry) - - // Test with a legacy module, a mock core module that doesn't return anything, - // and a core module defined in this file - expDefaultGenesis := map[string]json.RawMessage{ - "mockAppModuleBasic1": json.RawMessage(``), - "mockCoreAppModule2": json.RawMessage(`null`), - "mockCoreAppModule3": json.RawMessage(`{ - "someField": "someKey" -}`), - } - - // legacy module - mockAppModuleBasic1 := mock.NewMockAppModuleWithAllExtensions(mockCtrl) - mockAppModuleBasic1.EXPECT().Name().AnyTimes().Return("mockAppModuleBasic1") - mockAppModuleBasic1.EXPECT().DefaultGenesis(gomock.Eq(cdc)).Times(1).Return(json.RawMessage(``)) - // Allow ValidateGenesis to be called any times because other module can fail before this one is called. - mockAppModuleBasic1.EXPECT().ValidateGenesis(gomock.Eq(cdc), gomock.Eq(nil), gomock.Eq(expDefaultGenesis["mockAppModuleBasic1"])).AnyTimes().Return(nil) - mockAppModuleBasic1.EXPECT().RegisterLegacyAminoCodec(gomock.Eq(legacyAmino)).Times(1) - mockAppModuleBasic1.EXPECT().RegisterInterfaces(gomock.Eq(interfaceRegistry)).Times(1) - - // mock core API module - mockCoreAppModule2 := mock.NewMockCoreAppModule(mockCtrl) - mockCoreAppModule2.EXPECT().DefaultGenesis(gomock.Any()).AnyTimes().Return(nil) - mockCoreAppModule2.EXPECT().ValidateGenesis(gomock.Any()).AnyTimes().Return(nil) - mockAppModule2 := module.CoreAppModuleBasicAdaptor("mockCoreAppModule2", mockCoreAppModule2) - - // mock core API module (but all methods are implemented) - mockCoreAppModule3 := module.CoreAppModuleBasicAdaptor("mockCoreAppModule3", MockCoreAppModule{}) - - mm := module.NewBasicManager(mockAppModuleBasic1, mockAppModule2, mockCoreAppModule3) - - require.Equal(t, mockAppModuleBasic1, mm["mockAppModuleBasic1"]) - require.Equal(t, mockAppModule2, mm["mockCoreAppModule2"]) - require.Equal(t, mockCoreAppModule3, mm["mockCoreAppModule3"]) - - mm.RegisterLegacyAminoCodec(legacyAmino) - mm.RegisterInterfaces(interfaceRegistry) - - require.Equal(t, expDefaultGenesis, mm.DefaultGenesis(cdc)) - - var data map[string]string - require.Equal(t, map[string]string(nil), data) - - require.ErrorIs(t, mm.ValidateGenesis(cdc, nil, expDefaultGenesis), errFoo) - - mockCmd := &cobra.Command{Use: "root"} - mm.AddTxCommands(mockCmd) - mm.AddQueryCommands(mockCmd) - require.Equal(t, 1, len(mockCmd.Commands())) - - // validate genesis returns nil - require.Nil(t, module.NewBasicManager().ValidateGenesis(cdc, nil, expDefaultGenesis)) -} - func TestAssertNoForgottenModules(t *testing.T) { mockCtrl := gomock.NewController(t) t.Cleanup(mockCtrl.Finish) @@ -101,7 +41,7 @@ func TestAssertNoForgottenModules(t *testing.T) { mockAppModule1.EXPECT().Name().Times(2).Return("module1") mm := module.NewManager( mockAppModule1, - module.CoreAppModuleBasicAdaptor("module3", mockAppModule3), + module.CoreAppModuleAdaptor("module3", mockAppModule3), ) require.NotNil(t, mm) require.Equal(t, 2, len(mm.Modules)) @@ -131,7 +71,7 @@ func TestManagerOrderSetters(t *testing.T) { mockAppModule1.EXPECT().Name().Times(2).Return("module1") mockAppModule2.EXPECT().Name().Times(2).Return("module2") - mm := module.NewManager(mockAppModule1, mockAppModule2, module.CoreAppModuleBasicAdaptor("module3", mockAppModule3)) + mm := module.NewManager(mockAppModule1, mockAppModule2, module.CoreAppModuleAdaptor("module3", mockAppModule3)) require.NotNil(t, mm) require.Equal(t, 3, len(mm.Modules)) @@ -174,7 +114,7 @@ func TestManager_RegisterInvariants(t *testing.T) { mockAppModule1.EXPECT().Name().Times(2).Return("module1") mockAppModule2.EXPECT().Name().Times(2).Return("module2") // TODO: This is not working for Core API modules yet - mm := module.NewManager(mockAppModule1, mockAppModule2, module.CoreAppModuleBasicAdaptor("mockAppModule3", mockAppModule3)) + mm := module.NewManager(mockAppModule1, mockAppModule2, module.CoreAppModuleAdaptor("mockAppModule3", mockAppModule3)) require.NotNil(t, mm) require.Equal(t, 3, len(mm.Modules)) @@ -195,7 +135,7 @@ func TestManager_RegisterQueryServices(t *testing.T) { mockAppModule1.EXPECT().Name().Times(2).Return("module1") mockAppModule2.EXPECT().Name().Times(2).Return("module2") // TODO: This is not working for Core API modules yet - mm := module.NewManager(mockAppModule1, mockAppModule2, module.CoreAppModuleBasicAdaptor("mockAppModule3", mockAppModule3)) + mm := module.NewManager(mockAppModule1, mockAppModule2, module.CoreAppModuleAdaptor("mockAppModule3", mockAppModule3)) require.NotNil(t, mm) require.Equal(t, 3, len(mm.Modules)) @@ -227,7 +167,7 @@ func TestManager_InitGenesis(t *testing.T) { mockAppModule3 := mock.NewMockCoreAppModule(mockCtrl) mockAppModule1.EXPECT().Name().Times(2).Return("module1") mockAppModule2.EXPECT().Name().Times(4).Return("module2") - mm := module.NewManager(mockAppModule1, mockAppModule2, module.CoreAppModuleBasicAdaptor("module3", mockAppModule3)) + mm := module.NewManager(mockAppModule1, mockAppModule2, module.CoreAppModuleAdaptor("module3", mockAppModule3)) require.NotNil(t, mm) require.Equal(t, 3, len(mm.Modules)) @@ -261,7 +201,7 @@ func TestManager_InitGenesis(t *testing.T) { // happy path - mm2 := module.NewManager(mockAppModuleABCI1, mockAppModule2, module.CoreAppModuleBasicAdaptor("module3", mockAppModule3)) + 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) mockAppModule3.EXPECT().InitGenesis(gomock.Eq(ctx), gomock.Any()).Times(1).Return(nil) @@ -278,7 +218,7 @@ func TestManager_ExportGenesis(t *testing.T) { mockCoreAppModule := MockCoreAppModule{} mockAppModule1.EXPECT().Name().Times(2).Return("module1") mockAppModule2.EXPECT().Name().Times(2).Return("module2") - mm := module.NewManager(mockAppModule1, mockAppModule2, module.CoreAppModuleBasicAdaptor("mockCoreAppModule", mockCoreAppModule)) + mm := module.NewManager(mockAppModule1, mockAppModule2, module.CoreAppModuleAdaptor("mockCoreAppModule", mockCoreAppModule)) require.NotNil(t, mm) require.Equal(t, 3, len(mm.Modules)) diff --git a/types/module/testutil/codec.go b/types/module/testutil/codec.go index cd3ddf206214..12bc63d9bacf 100644 --- a/types/module/testutil/codec.go +++ b/types/module/testutil/codec.go @@ -12,7 +12,7 @@ import ( ) // TestEncodingConfig defines an encoding configuration that is used for testing -// purposes. Note, MakeTestEncodingConfig takes a series of AppModuleBasic types +// purposes. Note, MakeTestEncodingConfig takes a series of AppModule types // which should only contain the relevant module being tested and any potential // dependencies. type TestEncodingConfig struct { @@ -22,7 +22,7 @@ type TestEncodingConfig struct { Amino *codec.LegacyAmino } -func MakeTestEncodingConfig(modules ...module.AppModuleBasic) TestEncodingConfig { +func MakeTestEncodingConfig(modules ...module.AppModule) TestEncodingConfig { aminoCodec := codec.NewLegacyAmino() interfaceRegistry := testutil.CodecOptions{}.NewInterfaceRegistry() codec := codec.NewProtoCodec(interfaceRegistry) @@ -34,8 +34,7 @@ func MakeTestEncodingConfig(modules ...module.AppModuleBasic) TestEncodingConfig Amino: aminoCodec, } - mb := module.NewBasicManager(modules...) - + mb := module.NewManager(modules...) std.RegisterLegacyAminoCodec(encCfg.Amino) std.RegisterInterfaces(encCfg.InterfaceRegistry) mb.RegisterLegacyAminoCodec(encCfg.Amino) diff --git a/x/accounts/go.mod b/x/accounts/go.mod index 5824216f3f8f..1008aee4cd42 100644 --- a/x/accounts/go.mod +++ b/x/accounts/go.mod @@ -12,7 +12,6 @@ require ( github.com/cosmos/cosmos-sdk v0.51.0 github.com/cosmos/gogoproto v1.4.11 github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 - github.com/grpc-ecosystem/grpc-gateway v1.16.0 github.com/spf13/cobra v1.8.0 github.com/stretchr/testify v1.8.4 golang.org/x/exp v0.0.0-20240205201215-2c58cdc269a3 @@ -85,6 +84,7 @@ require ( github.com/gorilla/mux v1.8.1 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 // indirect + github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect github.com/hashicorp/go-hclog v1.5.0 // indirect github.com/hashicorp/go-immutable-radix v1.3.1 // indirect diff --git a/x/accounts/module.go b/x/accounts/module.go index 1c5240707d18..9d5288cf31ea 100644 --- a/x/accounts/module.go +++ b/x/accounts/module.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" - "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" "google.golang.org/grpc" @@ -51,14 +50,12 @@ type AppModule struct { func (m AppModule) IsAppModule() {} -func (m AppModule) RegisterLegacyAminoCodec(_ *codec.LegacyAmino) {} +func (AppModule) Name() string { return ModuleName } func (m AppModule) RegisterInterfaces(registry types.InterfaceRegistry) { msgservice.RegisterMsgServiceDesc(registry, v1.MsgServiceDesc()) } -func (m AppModule) RegisterGRPCGatewayRoutes(_ client.Context, _ *runtime.ServeMux) {} - // App module services func (m AppModule) RegisterServices(registar grpc.ServiceRegistrar) error { @@ -100,8 +97,6 @@ func (m AppModule) ExportGenesis(ctx context.Context, jsonCodec codec.JSONCodec) return jsonCodec.MustMarshalJSON(gs) } -func (AppModule) Name() string { return ModuleName } - func (AppModule) GetTxCmd() *cobra.Command { return cli.TxCmd(ModuleName) } diff --git a/x/auth/ante/testutil_test.go b/x/auth/ante/testutil_test.go index d412d312827d..c49cebdcdf5e 100644 --- a/x/auth/ante/testutil_test.go +++ b/x/auth/ante/testutil_test.go @@ -67,7 +67,7 @@ func SetupTestSuite(t *testing.T, isCheckTx bool) *AnteTestSuite { key := storetypes.NewKVStoreKey(types.StoreKey) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) suite.ctx = testCtx.Ctx.WithIsCheckTx(isCheckTx).WithBlockHeight(1) - suite.encCfg = moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}) + suite.encCfg = moduletestutil.MakeTestEncodingConfig(auth.AppModule{}) maccPerms := map[string][]string{ "fee_collector": nil, diff --git a/x/auth/client/cli/encode_test.go b/x/auth/client/cli/encode_test.go index f6d5b61b63d0..d5b116ca733c 100644 --- a/x/auth/client/cli/encode_test.go +++ b/x/auth/client/cli/encode_test.go @@ -17,7 +17,7 @@ import ( ) func TestGetCommandEncode(t *testing.T) { - encodingConfig := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}) + encodingConfig := moduletestutil.MakeTestEncodingConfig(auth.AppModule{}) txConfig := encodingConfig.TxConfig cdc := encodingConfig.Codec @@ -47,7 +47,7 @@ func TestGetCommandEncode(t *testing.T) { } func TestGetCommandDecode(t *testing.T) { - encodingConfig := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}) + encodingConfig := moduletestutil.MakeTestEncodingConfig(auth.AppModule{}) txConfig := encodingConfig.TxConfig cdc := encodingConfig.Codec diff --git a/x/auth/client/tx_test.go b/x/auth/client/tx_test.go index b5979a8066a2..130e8af7e564 100644 --- a/x/auth/client/tx_test.go +++ b/x/auth/client/tx_test.go @@ -138,7 +138,7 @@ func TestReadTxsFromFile(t *testing.T) { func TestBatchScanner_Scan(t *testing.T) { t.Parallel() - encodingConfig := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}) + encodingConfig := moduletestutil.MakeTestEncodingConfig(auth.AppModule{}) txConfig := encodingConfig.TxConfig clientCtx := client.Context{} diff --git a/x/auth/keeper/deterministic_test.go b/x/auth/keeper/deterministic_test.go index 97074cd677b7..95bbef98b4ee 100644 --- a/x/auth/keeper/deterministic_test.go +++ b/x/auth/keeper/deterministic_test.go @@ -52,7 +52,7 @@ func TestDeterministicTestSuite(t *testing.T) { } func (suite *DeterministicTestSuite) SetupTest() { - suite.encCfg = moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}) + suite.encCfg = moduletestutil.MakeTestEncodingConfig(auth.AppModule{}) suite.Require() key := storetypes.NewKVStoreKey(types.StoreKey) diff --git a/x/auth/keeper/keeper_test.go b/x/auth/keeper/keeper_test.go index fa85083c0b97..8ed4c8d00de2 100644 --- a/x/auth/keeper/keeper_test.go +++ b/x/auth/keeper/keeper_test.go @@ -46,7 +46,7 @@ type KeeperTestSuite struct { } func (suite *KeeperTestSuite) SetupTest() { - suite.encCfg = moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}) + suite.encCfg = moduletestutil.MakeTestEncodingConfig(auth.AppModule{}) key := storetypes.NewKVStoreKey(types.StoreKey) storeService := runtime.NewKVStoreService(key) diff --git a/x/auth/module.go b/x/auth/module.go index 06df893dfc4c..a0fb08b42b19 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -8,7 +8,6 @@ import ( gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" "google.golang.org/grpc" - "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" "cosmossdk.io/x/auth/keeper" "cosmossdk.io/x/auth/simulation" @@ -28,8 +27,8 @@ const ( ) var ( - _ module.AppModuleBasic = AppModule{} _ module.AppModuleSimulation = AppModule{} + _ module.HasName = AppModule{} _ module.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} @@ -37,69 +36,45 @@ var ( _ appmodule.HasMigrations = AppModule{} ) -// AppModuleBasic defines the basic application module used by the auth module. -type AppModuleBasic struct { - ac address.Codec +// AppModule implements an application module for the auth module. +type AppModule struct { + accountKeeper keeper.AccountKeeper + randGenAccountsFn types.RandomGenesisAccountsFn +} + +// IsAppModule implements the appmodule.AppModule interface. +func (am AppModule) IsAppModule() {} + +// NewAppModule creates a new AppModule object +func NewAppModule(cdc codec.Codec, accountKeeper keeper.AccountKeeper, randGenAccountsFn types.RandomGenesisAccountsFn) AppModule { + return AppModule{ + accountKeeper: accountKeeper, + randGenAccountsFn: randGenAccountsFn, + } } // Name returns the auth module's name. -func (AppModuleBasic) Name() string { +func (AppModule) Name() string { return types.ModuleName } // RegisterLegacyAminoCodec registers the auth module's types for the given codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { +func (AppModule) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { types.RegisterLegacyAminoCodec(cdc) } -// DefaultGenesis returns default genesis state as raw bytes for the auth -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) -} - -// ValidateGenesis performs genesis state validation for the auth module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var data types.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { - return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) - } - - return types.ValidateGenesis(data) -} - // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the auth module. -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { +func (AppModule) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { panic(err) } } // RegisterInterfaces registers interfaces and implementations of the auth module. -func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { +func (AppModule) RegisterInterfaces(registry codectypes.InterfaceRegistry) { types.RegisterInterfaces(registry) } -// AppModule implements an application module for the auth module. -type AppModule struct { - AppModuleBasic - - accountKeeper keeper.AccountKeeper - randGenAccountsFn types.RandomGenesisAccountsFn -} - -// IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() {} - -// NewAppModule creates a new AppModule object -func NewAppModule(cdc codec.Codec, accountKeeper keeper.AccountKeeper, randGenAccountsFn types.RandomGenesisAccountsFn) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{ac: accountKeeper.AddressCodec()}, - accountKeeper: accountKeeper, - randGenAccountsFn: randGenAccountsFn, - } -} - // RegisterServices registers module services. func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { types.RegisterMsgServer(registrar, keeper.NewMsgServerImpl(am.accountKeeper)) @@ -108,6 +83,7 @@ func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { return nil } +// RegisterMigrations registers module migrations func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { m := keeper.NewMigrator(am.accountKeeper) if err := mr.Register(types.ModuleName, 1, m.Migrate1to2); err != nil { @@ -127,8 +103,22 @@ func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { return nil } -// InitGenesis performs genesis initialization for the auth module. It returns -// no validator updates. +// 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()) +} + +// ValidateGenesis performs genesis state validation for the auth module. +func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { + var data types.GenesisState + if err := cdc.UnmarshalJSON(bz, &data); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + + return types.ValidateGenesis(data) +} + +// InitGenesis performs genesis initialization for the auth module. func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { var genesisState types.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) @@ -148,7 +138,7 @@ func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json return cdc.MustMarshalJSON(gs) } -// ConsensusVersion implements AppModule/ConsensusVersion. +// ConsensusVersion implements HasConsensusVersion func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } // AppModuleSimulation functions diff --git a/x/auth/types/genesis_test.go b/x/auth/types/genesis_test.go index 1515fe4b757a..8a3bf204bad2 100644 --- a/x/auth/types/genesis_test.go +++ b/x/auth/types/genesis_test.go @@ -54,7 +54,7 @@ func TestValidateGenesisDuplicateAccounts(t *testing.T) { } func TestGenesisAccountIterator(t *testing.T) { - encodingConfig := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}) + encodingConfig := moduletestutil.MakeTestEncodingConfig(auth.AppModule{}) cdc := encodingConfig.Codec acc1 := types.NewBaseAccountWithAddress(sdk.AccAddress(addr1)) diff --git a/x/auth/vesting/client/cli/tx_test.go b/x/auth/vesting/client/cli/tx_test.go index 51ca0e3f20bc..aa2259101ab6 100644 --- a/x/auth/vesting/client/cli/tx_test.go +++ b/x/auth/vesting/client/cli/tx_test.go @@ -37,7 +37,7 @@ func TestMigrateTestSuite(t *testing.T) { } func (s *CLITestSuite) SetupSuite() { - s.encCfg = testutilmod.MakeTestEncodingConfig(vesting.AppModuleBasic{}) + s.encCfg = testutilmod.MakeTestEncodingConfig(vesting.AppModule{}) s.kr = keyring.NewInMemory(s.encCfg.Codec) s.baseCtx = client.Context{}. WithKeyring(s.kr). diff --git a/x/auth/vesting/module.go b/x/auth/vesting/module.go index 5075184d4192..9e5f98c3ad65 100644 --- a/x/auth/vesting/module.go +++ b/x/auth/vesting/module.go @@ -1,10 +1,6 @@ package vesting import ( - "context" - "encoding/json" - - gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" "google.golang.org/grpc" @@ -13,92 +9,60 @@ import ( "cosmossdk.io/x/auth/vesting/client/cli" "cosmossdk.io/x/auth/vesting/types" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types/module" ) var ( - _ module.AppModuleBasic = AppModule{} - _ module.HasGenesis = AppModule{} + _ module.AppModule = AppModule{} + _ module.HasName = AppModule{} _ appmodule.AppModule = AppModule{} ) -// AppModuleBasic defines the basic application module used by the sub-vesting -// module. The module itself contain no special logic or state other than message -// handling. -type AppModuleBasic struct{} +// AppModule implementing the AppModule interface. +type AppModule struct { + accountKeeper keeper.AccountKeeper + bankKeeper types.BankKeeper +} + +func NewAppModule(ak keeper.AccountKeeper, bk types.BankKeeper) AppModule { + return AppModule{ + accountKeeper: ak, + bankKeeper: bk, + } +} + +// IsAppModule implements the appmodule.AppModule interface. +func (am AppModule) IsAppModule() {} // Name returns the module's name. -func (AppModuleBasic) Name() string { +func (AppModule) Name() string { return types.ModuleName } // RegisterCodec registers the module's types with the given codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { +func (AppModule) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { types.RegisterLegacyAminoCodec(cdc) } // RegisterInterfaces registers the module's interfaces and implementations with // the given interface registry. -func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { +func (AppModule) RegisterInterfaces(registry codectypes.InterfaceRegistry) { types.RegisterInterfaces(registry) } -// DefaultGenesis returns the module's default genesis state as raw bytes. -func (AppModuleBasic) DefaultGenesis(_ codec.JSONCodec) json.RawMessage { - return []byte("{}") -} - -// ValidateGenesis performs genesis state validation. Currently, this is a no-op. -func (AppModuleBasic) ValidateGenesis(_ codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error { - return nil -} - -// RegisterGRPCGatewayRoutes registers the module's gRPC Gateway routes. Currently, this -// is a no-op. -func (AppModuleBasic) RegisterGRPCGatewayRoutes(_ client.Context, _ *gwruntime.ServeMux) {} - // GetTxCmd returns the root tx command for the vesting module. -func (amb AppModuleBasic) GetTxCmd() *cobra.Command { +func (AppModule) GetTxCmd() *cobra.Command { return cli.GetTxCmd() } -// AppModule extends the AppModuleBasic implementation by implementing the -// AppModule interface. -type AppModule struct { - AppModuleBasic - - accountKeeper keeper.AccountKeeper - bankKeeper types.BankKeeper -} - -func NewAppModule(ak keeper.AccountKeeper, bk types.BankKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - accountKeeper: ak, - bankKeeper: bk, - } -} - -// IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() {} - // RegisterServices registers module services. func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { types.RegisterMsgServer(registrar, NewMsgServerImpl(am.accountKeeper, am.bankKeeper)) return nil } -// InitGenesis performs a no-op. -func (am AppModule) InitGenesis(_ context.Context, _ codec.JSONCodec, _ json.RawMessage) {} - -// ExportGenesis is always empty, as InitGenesis does nothing either. -func (am AppModule) ExportGenesis(_ context.Context, cdc codec.JSONCodec) json.RawMessage { - return am.DefaultGenesis(cdc) -} - -// ConsensusVersion implements AppModule/ConsensusVersion. +// ConsensusVersion implements HasConsensusVersion. func (AppModule) ConsensusVersion() uint64 { return 1 } diff --git a/x/auth/vesting/types/vesting_account_test.go b/x/auth/vesting/types/vesting_account_test.go index 3c1756c59df3..ba1b289f2474 100644 --- a/x/auth/vesting/types/vesting_account_test.go +++ b/x/auth/vesting/types/vesting_account_test.go @@ -38,7 +38,7 @@ type VestingAccountTestSuite struct { } func (s *VestingAccountTestSuite) SetupTest() { - encCfg := moduletestutil.MakeTestEncodingConfig(vesting.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(vesting.AppModule{}) key := storetypes.NewKVStoreKey(authtypes.StoreKey) env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) diff --git a/x/authz/client/cli/tx_test.go b/x/authz/client/cli/tx_test.go index ca828f2a63fd..2b7df03f8052 100644 --- a/x/authz/client/cli/tx_test.go +++ b/x/authz/client/cli/tx_test.go @@ -51,7 +51,7 @@ func TestCLITestSuite(t *testing.T) { } func (s *CLITestSuite) SetupSuite() { - s.encCfg = testutilmod.MakeTestEncodingConfig(bank.AppModuleBasic{}, authz.AppModule{}) + s.encCfg = testutilmod.MakeTestEncodingConfig(bank.AppModule{}, authz.AppModule{}) s.kr = keyring.NewInMemory(s.encCfg.Codec) s.baseCtx = client.Context{}. diff --git a/x/authz/keeper/genesis_test.go b/x/authz/keeper/genesis_test.go index 4eb75158e61e..5a3d34579dd2 100644 --- a/x/authz/keeper/genesis_test.go +++ b/x/authz/keeper/genesis_test.go @@ -48,7 +48,7 @@ func (suite *GenesisTestSuite) SetupTest() { testCtx := testutil.DefaultContextWithDB(suite.T(), key, storetypes.NewTransientStoreKey("transient_test")) suite.ctx = testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1}) - suite.encCfg = moduletestutil.MakeTestEncodingConfig(authzmodule.AppModuleBasic{}) + suite.encCfg = moduletestutil.MakeTestEncodingConfig(authzmodule.AppModule{}) // gomock initializations ctrl := gomock.NewController(suite.T()) diff --git a/x/authz/keeper/keeper_test.go b/x/authz/keeper/keeper_test.go index 2abfd77139dc..0e7c5635857b 100644 --- a/x/authz/keeper/keeper_test.go +++ b/x/authz/keeper/keeper_test.go @@ -51,7 +51,7 @@ func (s *TestSuite) SetupTest() { storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) s.ctx = testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now().Round(0).UTC()}) - s.encCfg = moduletestutil.MakeTestEncodingConfig(authzmodule.AppModuleBasic{}) + s.encCfg = moduletestutil.MakeTestEncodingConfig(authzmodule.AppModule{}) s.baseApp = baseapp.NewBaseApp( "authz", diff --git a/x/authz/keys.go b/x/authz/keys.go index f0ecb467aebf..b607837e5966 100644 --- a/x/authz/keys.go +++ b/x/authz/keys.go @@ -3,10 +3,4 @@ package authz const ( // ModuleName is the module name constant used in many places ModuleName = "authz" - - // RouterKey is the message route for authz - RouterKey = ModuleName - - // QuerierRoute is the querier route for authz - QuerierRoute = ModuleName ) diff --git a/x/authz/migrations/v2/store_test.go b/x/authz/migrations/v2/store_test.go index 003cef7de1f3..d41f33cb6f2f 100644 --- a/x/authz/migrations/v2/store_test.go +++ b/x/authz/migrations/v2/store_test.go @@ -24,7 +24,7 @@ import ( ) func TestMigration(t *testing.T) { - encodingConfig := moduletestutil.MakeTestEncodingConfig(authzmodule.AppModuleBasic{}, bank.AppModuleBasic{}) + encodingConfig := moduletestutil.MakeTestEncodingConfig(authzmodule.AppModule{}, bank.AppModule{}) cdc := encodingConfig.Codec authzKey := storetypes.NewKVStoreKey("authz") diff --git a/x/authz/module/abci_test.go b/x/authz/module/abci_test.go index f4a82573886a..a73423f533d6 100644 --- a/x/authz/module/abci_test.go +++ b/x/authz/module/abci_test.go @@ -30,7 +30,7 @@ func TestExpiredGrantsQueue(t *testing.T) { key := storetypes.NewKVStoreKey(keeper.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(authzmodule.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(authzmodule.AppModule{}) ctx := testCtx.Ctx baseApp := baseapp.NewBaseApp( diff --git a/x/authz/module/module.go b/x/authz/module/module.go index 7298d4c97abc..31b7a35a1382 100644 --- a/x/authz/module/module.go +++ b/x/authz/module/module.go @@ -23,10 +23,15 @@ import ( simtypes "github.com/cosmos/cosmos-sdk/types/simulation" ) +const ConsensusVersion = 2 + var ( - _ module.AppModuleBasic = AppModule{} - _ module.AppModuleSimulation = AppModule{} - _ module.HasGenesis = AppModule{} + _ module.HasName = AppModule{} + _ module.HasAminoCodec = AppModule{} + _ module.HasGRPCGateway = AppModule{} + _ module.HasRegisterInterfaces = AppModule{} + _ module.AppModuleSimulation = AppModule{} + _ module.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasBeginBlocker = AppModule{} @@ -34,13 +39,31 @@ var ( _ appmodule.HasMigrations = AppModule{} ) -// AppModuleBasic defines the basic application module used by the authz module. -type AppModuleBasic struct { - cdc codec.Codec +// AppModule implements the sdk.AppModule interface +type AppModule struct { + cdc codec.Codec + keeper keeper.Keeper + accountKeeper authz.AccountKeeper + bankKeeper authz.BankKeeper + registry cdctypes.InterfaceRegistry } +// NewAppModule creates a new AppModule object +func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, ak authz.AccountKeeper, bk authz.BankKeeper, registry cdctypes.InterfaceRegistry) AppModule { + return AppModule{ + cdc: cdc, + keeper: keeper, + accountKeeper: ak, + bankKeeper: bk, + registry: registry, + } +} + +// IsAppModule implements the appmodule.AppModule interface. +func (AppModule) IsAppModule() {} + // Name returns the authz module's name. -func (AppModuleBasic) Name() string { +func (AppModule) Name() string { return authz.ModuleName } @@ -52,6 +75,7 @@ func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { return nil } +// RegisterMigrations registers the authz module migrations. func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { m := keeper.NewMigrator(am.keeper) if err := mr.Register(authz.ModuleName, 1, m.Migrate1to2); err != nil { @@ -62,84 +86,57 @@ func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { } // RegisterLegacyAminoCodec registers the authz module's types for the given codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { +func (AppModule) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { authz.RegisterLegacyAminoCodec(cdc) } // RegisterInterfaces registers the authz module's interface types -func (AppModuleBasic) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { +func (AppModule) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { authz.RegisterInterfaces(registry) } -// DefaultGenesis returns default genesis state as raw bytes for the authz -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(authz.DefaultGenesisState()) -} - -// ValidateGenesis performs genesis state validation for the authz module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { - var data authz.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { - return errors.Wrapf(err, "failed to unmarshal %s genesis state", authz.ModuleName) - } - - return authz.ValidateGenesis(data) -} - // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the authz module. -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx sdkclient.Context, mux *gwruntime.ServeMux) { +func (AppModule) RegisterGRPCGatewayRoutes(clientCtx sdkclient.Context, mux *gwruntime.ServeMux) { if err := authz.RegisterQueryHandlerClient(context.Background(), mux, authz.NewQueryClient(clientCtx)); err != nil { panic(err) } } // GetTxCmd returns the transaction commands for the authz module -func (ab AppModuleBasic) GetTxCmd() *cobra.Command { +func (AppModule) GetTxCmd() *cobra.Command { return cli.GetTxCmd() } -// AppModule implements the sdk.AppModule interface -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper authz.AccountKeeper - bankKeeper authz.BankKeeper - registry cdctypes.InterfaceRegistry +// 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()) } -// NewAppModule creates a new AppModule object -func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, ak authz.AccountKeeper, bk authz.BankKeeper, registry cdctypes.InterfaceRegistry) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc}, - keeper: keeper, - accountKeeper: ak, - bankKeeper: bk, - registry: registry, +// ValidateGenesis performs genesis state validation for the authz module. +func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { + var data authz.GenesisState + if err := cdc.UnmarshalJSON(bz, &data); err != nil { + return errors.Wrapf(err, "failed to unmarshal %s genesis state", authz.ModuleName) } -} -// IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() {} + return authz.ValidateGenesis(data) +} -// InitGenesis performs genesis initialization for the authz module. It returns -// no validator updates. +// InitGenesis performs genesis initialization for the authz module. func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { var genesisState authz.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) am.keeper.InitGenesis(ctx, &genesisState) } -// ExportGenesis returns the exported genesis state as raw bytes for the authz -// module. +// 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 { gs := am.keeper.ExportGenesis(ctx) return cdc.MustMarshalJSON(gs) } -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { return 2 } +// ConsensusVersion implements HasConsensusVersion. +func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } // BeginBlock returns the begin blocker for the authz module. func (am AppModule) BeginBlock(ctx context.Context) error { diff --git a/x/authz/simulation/decoder_test.go b/x/authz/simulation/decoder_test.go index 93ebcd60fdb5..5e9697443908 100644 --- a/x/authz/simulation/decoder_test.go +++ b/x/authz/simulation/decoder_test.go @@ -19,7 +19,7 @@ import ( ) func TestDecodeStore(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig(authzmodule.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(authzmodule.AppModule{}) banktypes.RegisterInterfaces(encCfg.InterfaceRegistry) dec := simulation.NewDecodeStore(encCfg.Codec) diff --git a/x/authz/simulation/genesis_test.go b/x/authz/simulation/genesis_test.go index eb7088faaf95..19c0508de678 100644 --- a/x/authz/simulation/genesis_test.go +++ b/x/authz/simulation/genesis_test.go @@ -19,7 +19,7 @@ import ( ) func TestRandomizedGenState(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig(authzmodule.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(authzmodule.AppModule{}) banktypes.RegisterInterfaces(encCfg.InterfaceRegistry) s := rand.NewSource(1) diff --git a/x/bank/client/cli/tx_test.go b/x/bank/client/cli/tx_test.go index 879b5e6a99a3..17a73e5f6725 100644 --- a/x/bank/client/cli/tx_test.go +++ b/x/bank/client/cli/tx_test.go @@ -37,7 +37,7 @@ func TestCLITestSuite(t *testing.T) { } func (s *CLITestSuite) SetupSuite() { - s.encCfg = testutilmod.MakeTestEncodingConfig(bank.AppModuleBasic{}) + s.encCfg = testutilmod.MakeTestEncodingConfig(bank.AppModule{}) s.kr = keyring.NewInMemory(s.encCfg.Codec) s.baseCtx = client.Context{}. WithKeyring(s.kr). diff --git a/x/bank/module.go b/x/bank/module.go index 7e9556fe6699..f233d0115b4c 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -29,73 +29,63 @@ import ( const ConsensusVersion = 4 var ( - _ module.AppModuleBasic = AppModule{} - _ module.AppModuleSimulation = AppModule{} - _ module.HasGenesis = AppModule{} - _ module.HasInvariants = AppModule{} + _ module.HasName = AppModule{} + _ module.HasAminoCodec = AppModule{} + _ module.HasGRPCGateway = AppModule{} + _ module.HasRegisterInterfaces = AppModule{} + _ module.AppModuleSimulation = AppModule{} + _ module.HasGenesis = AppModule{} + _ module.HasInvariants = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasServices = AppModule{} _ appmodule.HasMigrations = AppModule{} ) -// AppModuleBasic defines the basic application module used by the bank module. -type AppModuleBasic struct { - cdc codec.Codec +// AppModule implements an application module for the bank module. +type AppModule struct { + cdc codec.Codec + keeper keeper.Keeper + accountKeeper types.AccountKeeper } -// Name returns the bank module's name. -func (AppModuleBasic) Name() string { return types.ModuleName } - -// RegisterLegacyAminoCodec registers the bank module's types on the LegacyAmino codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) +// NewAppModule creates a new AppModule object +func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, accountKeeper types.AccountKeeper) AppModule { + return AppModule{ + cdc: cdc, + keeper: keeper, + accountKeeper: accountKeeper, + } } -// DefaultGenesis returns default genesis state as raw bytes for the bank -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) -} +// IsAppModule implements the appmodule.AppModule interface. +func (am AppModule) IsAppModule() {} -// ValidateGenesis performs genesis state validation for the bank module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error { - var data types.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { - return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) - } +// Name returns the bank module's name. +func (AppModule) Name() string { return types.ModuleName } - return data.Validate() +// RegisterLegacyAminoCodec registers the bank module's types on the LegacyAmino codec. +func (AppModule) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + types.RegisterLegacyAminoCodec(cdc) } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the bank module. -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { +func (AppModule) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { panic(err) } } // GetTxCmd returns the root tx command for the bank module. -func (ab AppModuleBasic) GetTxCmd() *cobra.Command { +func (AppModule) GetTxCmd() *cobra.Command { return cli.NewTxCmd() } // RegisterInterfaces registers interfaces and implementations of the bank module. -func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { +func (AppModule) RegisterInterfaces(registry codectypes.InterfaceRegistry) { types.RegisterInterfaces(registry) } -// AppModule implements an application module for the bank module. -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper -} - -// IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() {} - // RegisterServices registers module services. func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { types.RegisterMsgServer(registrar, keeper.NewMsgServerImpl(am.keeper)) @@ -104,6 +94,7 @@ func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { return nil } +// RegisterMigrations registers the bank module's migrations. func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { m := keeper.NewMigrator(am.keeper.(keeper.BaseKeeper)) @@ -122,25 +113,27 @@ func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { return nil } -// NewAppModule creates a new AppModule object -func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, accountKeeper types.AccountKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc}, - keeper: keeper, - accountKeeper: accountKeeper, - } -} - // RegisterInvariants registers the bank module invariants. func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { keeper.RegisterInvariants(ir, am.keeper) } -// QuerierRoute returns the bank module's querier route name. -func (AppModule) QuerierRoute() string { return types.RouterKey } +// 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()) +} + +// ValidateGenesis performs genesis state validation for the bank module. +func (AppModule) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error { + var data types.GenesisState + if err := cdc.UnmarshalJSON(bz, &data); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + + return data.Validate() +} -// InitGenesis performs genesis initialization for the bank module. It returns -// no validator updates. +// InitGenesis performs genesis initialization for the bank module. func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { start := time.Now() var genesisState types.GenesisState @@ -157,7 +150,7 @@ func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json return cdc.MustMarshalJSON(gs) } -// ConsensusVersion implements AppModule/ConsensusVersion. +// ConsensusVersion implements HasConsensusVersion func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } // AppModuleSimulation functions diff --git a/x/bank/testutil/expected_keepers_mocks.go b/x/bank/testutil/expected_keepers_mocks.go index 2000823388ad..058c4e2d7e36 100644 --- a/x/bank/testutil/expected_keepers_mocks.go +++ b/x/bank/testutil/expected_keepers_mocks.go @@ -65,20 +65,6 @@ func (mr *MockAccountKeeperMockRecorder) GetAccount(ctx, addr interface{}) *gomo return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccount", reflect.TypeOf((*MockAccountKeeper)(nil).GetAccount), ctx, addr) } -// GetAllAccounts mocks base method. -func (m *MockAccountKeeper) GetAllAccounts(ctx context.Context) []types0.AccountI { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAllAccounts", ctx) - ret0, _ := ret[0].([]types0.AccountI) - return ret0 -} - -// GetAllAccounts indicates an expected call of GetAllAccounts. -func (mr *MockAccountKeeperMockRecorder) GetAllAccounts(ctx interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAllAccounts", reflect.TypeOf((*MockAccountKeeper)(nil).GetAllAccounts), ctx) -} - // GetModuleAccount mocks base method. func (m *MockAccountKeeper) GetModuleAccount(ctx context.Context, moduleName string) types0.ModuleAccountI { m.ctrl.T.Helper() @@ -165,18 +151,6 @@ func (mr *MockAccountKeeperMockRecorder) HasAccount(ctx, addr interface{}) *gomo return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HasAccount", reflect.TypeOf((*MockAccountKeeper)(nil).HasAccount), ctx, addr) } -// IterateAccounts mocks base method. -func (m *MockAccountKeeper) IterateAccounts(ctx context.Context, process func(types0.AccountI) bool) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "IterateAccounts", ctx, process) -} - -// IterateAccounts indicates an expected call of IterateAccounts. -func (mr *MockAccountKeeperMockRecorder) IterateAccounts(ctx, process interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IterateAccounts", reflect.TypeOf((*MockAccountKeeper)(nil).IterateAccounts), ctx, process) -} - // NewAccount mocks base method. func (m *MockAccountKeeper) NewAccount(arg0 context.Context, arg1 types0.AccountI) types0.AccountI { m.ctrl.T.Helper() diff --git a/x/bank/types/keys.go b/x/bank/types/keys.go index 0d0b60905a1f..402b2c768a92 100644 --- a/x/bank/types/keys.go +++ b/x/bank/types/keys.go @@ -15,9 +15,6 @@ const ( // StoreKey defines the primary module store key StoreKey = ModuleName - // RouterKey defines the module's message routing key - RouterKey = ModuleName - // GovModuleName duplicates the gov module's name to avoid a cyclic dependency with x/gov. // It should be synced with the gov module's name if it is ever changed. // See: https://github.com/cosmos/cosmos-sdk/blob/b62a28aac041829da5ded4aeacfcd7a42873d1c8/x/gov/types/keys.go#L9 diff --git a/x/circuit/ante/circuit_test.go b/x/circuit/ante/circuit_test.go index 65506ffd9c41..6c1e8693f135 100644 --- a/x/circuit/ante/circuit_test.go +++ b/x/circuit/ante/circuit_test.go @@ -37,7 +37,7 @@ func (m MockCircuitBreaker) IsAllowed(ctx context.Context, typeURL string) (bool func initFixture(t *testing.T) *fixture { t.Helper() mockStoreKey := storetypes.NewKVStoreKey("test") - encCfg := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(auth.AppModule{}) mockclientCtx := client.Context{}. WithTxConfig(encCfg.TxConfig) @@ -61,8 +61,8 @@ func TestCircuitBreakerDecorator(t *testing.T) { allowed bool }{ {msg: &cbtypes.MsgAuthorizeCircuitBreaker{ - Grantee: "cosmos1qk93t4j0yyzgqgt6k5qf8deh8fq6smpn3ntu3x", - Granter: "cosmos1p9qh4ldfd6n0qehujsal4k7g0e37kel90rc4ts", + Grantee: "cosmos139f7kncmglres2nf3h4hc4tade85ekfr8sulz5", + Granter: "cosmos16wfryel63g7axeamw68630wglalcnk3l0zuadc", }, allowed: true}, {msg: testdata.NewTestMsg(addr1), allowed: false}, } diff --git a/x/circuit/keeper/genesis_test.go b/x/circuit/keeper/genesis_test.go index 9848d237997f..16f8362ba239 100644 --- a/x/circuit/keeper/genesis_test.go +++ b/x/circuit/keeper/genesis_test.go @@ -37,7 +37,7 @@ func TestGenesisTestSuite(t *testing.T) { func (s *GenesisTestSuite) SetupTest() { key := storetypes.NewKVStoreKey(types.ModuleName) testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(circuit.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(circuit.AppModule{}) sdkCtx := testCtx.Ctx s.ctx = sdkCtx diff --git a/x/circuit/keeper/keeper.go b/x/circuit/keeper/keeper.go index aa6a71a03ad6..ed18593c526e 100644 --- a/x/circuit/keeper/keeper.go +++ b/x/circuit/keeper/keeper.go @@ -6,8 +6,6 @@ import ( "cosmossdk.io/collections" "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" - "cosmossdk.io/core/event" - "cosmossdk.io/core/store" "cosmossdk.io/x/circuit/types" "github.com/cosmos/cosmos-sdk/codec" @@ -15,9 +13,8 @@ import ( // Keeper defines the circuit module's keeper. type Keeper struct { - cdc codec.BinaryCodec - storeService store.KVStoreService - eventService event.Service + cdc codec.BinaryCodec + env appmodule.Environment authority []byte @@ -37,15 +34,12 @@ func NewKeeper(env appmodule.Environment, cdc codec.BinaryCodec, authority strin panic(err) } - storeService := env.KVStoreService - - sb := collections.NewSchemaBuilder(storeService) + sb := collections.NewSchemaBuilder(env.KVStoreService) k := Keeper{ cdc: cdc, - storeService: storeService, - eventService: env.EventService, authority: auth, + env: env, addressCodec: addressCodec, Permissions: collections.NewMap( sb, diff --git a/x/circuit/keeper/keeper_test.go b/x/circuit/keeper/keeper_test.go index e77691c38d26..29464b66b72f 100644 --- a/x/circuit/keeper/keeper_test.go +++ b/x/circuit/keeper/keeper_test.go @@ -40,7 +40,7 @@ type fixture struct { func initFixture(t *testing.T) *fixture { t.Helper() - encCfg := moduletestutil.MakeTestEncodingConfig(circuit.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(circuit.AppModule{}) ac := addresscodec.NewBech32Codec("cosmos") mockStoreKey := storetypes.NewKVStoreKey("test") diff --git a/x/circuit/keeper/msg_server.go b/x/circuit/keeper/msg_server.go index 3c60cb07848b..8a1efd3dabf1 100644 --- a/x/circuit/keeper/msg_server.go +++ b/x/circuit/keeper/msg_server.go @@ -63,13 +63,12 @@ func (srv msgServer) AuthorizeCircuitBreaker(ctx context.Context, msg *types.Msg return nil, err } - err = srv.Keeper.eventService.EventManager(ctx).EmitKV( + if err = srv.Keeper.env.EventService.EventManager(ctx).EmitKV( "authorize_circuit_breaker", event.NewAttribute("granter", msg.Granter), event.NewAttribute("grantee", msg.Grantee), event.NewAttribute("permission", msg.Permissions.String()), - ) - if err != nil { + ); err != nil { return nil, err } @@ -121,12 +120,11 @@ func (srv msgServer) TripCircuitBreaker(ctx context.Context, msg *types.MsgTripC urls := strings.Join(msg.GetMsgTypeUrls(), ",") - err = srv.Keeper.eventService.EventManager(ctx).EmitKV( + if err = srv.Keeper.env.EventService.EventManager(ctx).EmitKV( "trip_circuit_breaker", event.NewAttribute("authority", msg.Authority), event.NewAttribute("msg_url", urls), - ) - if err != nil { + ); err != nil { return nil, err } @@ -180,12 +178,11 @@ func (srv msgServer) ResetCircuitBreaker(ctx context.Context, msg *types.MsgRese urls := strings.Join(msg.GetMsgTypeUrls(), ",") - err = srv.Keeper.eventService.EventManager(ctx).EmitKV( + if err = srv.Keeper.env.EventService.EventManager(ctx).EmitKV( "reset_circuit_breaker", event.NewAttribute("authority", msg.Authority), event.NewAttribute("msg_url", urls), - ) - if err != nil { + ); err != nil { return nil, err } diff --git a/x/circuit/module.go b/x/circuit/module.go index c39000ce1676..b52c1443cbb5 100644 --- a/x/circuit/module.go +++ b/x/circuit/module.go @@ -24,63 +24,39 @@ import ( const ConsensusVersion = 1 var ( - _ module.AppModuleBasic = AppModule{} - _ module.HasGenesis = AppModule{} + _ module.HasName = AppModule{} + _ module.HasGRPCGateway = AppModule{} + _ module.HasRegisterInterfaces = AppModule{} + _ module.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasServices = AppModule{} ) -// AppModuleBasic defines the basic application module used by the circuit module. -type AppModuleBasic struct { - cdc codec.Codec -} - -// Name returns the circuit module's name. -func (AppModuleBasic) Name() string { return types.ModuleName } - -// RegisterLegacyAminoCodec registers the circuit module's types on the LegacyAmino codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { -} - -// DefaultGenesis returns default genesis state as raw bytes for the circuit -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) +// AppModule implements an application module for the circuit module. +type AppModule struct { + cdc codec.Codec + keeper keeper.Keeper } -// ValidateGenesis performs genesis state validation for the circuit module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error { - var data types.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { - return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) - } +// IsAppModule implements the appmodule.AppModule interface. +func (AppModule) IsAppModule() {} - return data.Validate() -} +// Name returns the circuit module's name. +func (AppModule) Name() string { return types.ModuleName } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the circuit module. -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { +func (AppModule) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { panic(err) } } // RegisterInterfaces registers interfaces and implementations of the circuit module. -func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { +func (AppModule) RegisterInterfaces(registry codectypes.InterfaceRegistry) { types.RegisterInterfaces(registry) } -// AppModule implements an application module for the circuit module. -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper -} - -// IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() {} - // RegisterServices registers module services. func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { types.RegisterMsgServer(registrar, keeper.NewMsgServerImpl(am.keeper)) @@ -92,16 +68,30 @@ func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { // NewAppModule creates a new AppModule object func NewAppModule(cdc codec.Codec, keeper keeper.Keeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc}, - keeper: keeper, + cdc: cdc, + keeper: keeper, } } -// ConsensusVersion implements AppModule/ConsensusVersion. +// ConsensusVersion implements HasConsensusVersion func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } -// InitGenesis performs genesis initialization for the circuit module. It returns -// no validator updates. +// 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()) +} + +// ValidateGenesis performs genesis state validation for the circuit module. +func (AppModule) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error { + var data types.GenesisState + if err := cdc.UnmarshalJSON(bz, &data); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + + return data.Validate() +} + +// InitGenesis performs genesis initialization for the circuit module. func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { start := time.Now() var genesisState types.GenesisState diff --git a/x/consensus/module.go b/x/consensus/module.go index a0fcc9b161fe..de10392824d0 100644 --- a/x/consensus/module.go +++ b/x/consensus/module.go @@ -20,46 +20,51 @@ import ( const ConsensusVersion = 1 var ( - _ module.AppModuleBasic = AppModule{} + _ module.HasName = AppModule{} + _ module.HasAminoCodec = AppModule{} + _ module.HasGRPCGateway = AppModule{} + _ module.HasRegisterInterfaces = AppModule{} _ appmodule.AppModule = AppModule{} ) -// AppModuleBasic defines the basic application module used by the consensus module. -type AppModuleBasic struct { - cdc codec.Codec +// AppModule implements an application module +type AppModule struct { + cdc codec.Codec + keeper keeper.Keeper } +// NewAppModule creates a new AppModule object +func NewAppModule(cdc codec.Codec, keeper keeper.Keeper) AppModule { + return AppModule{ + cdc: cdc, + keeper: keeper, + } +} + +// IsAppModule implements the appmodule.AppModule interface. +func (AppModule) IsAppModule() {} + // Name returns the consensus module's name. -func (AppModuleBasic) Name() string { return types.ModuleName } +func (AppModule) Name() string { return types.ModuleName } // RegisterLegacyAminoCodec registers the consensus module's types on the LegacyAmino codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { +func (AppModule) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { types.RegisterLegacyAminoCodec(cdc) } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { +func (AppModule) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { panic(err) } } // RegisterInterfaces registers interfaces and implementations of the bank module. -func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { +func (AppModule) RegisterInterfaces(registry codectypes.InterfaceRegistry) { types.RegisterInterfaces(registry) } -// AppModule implements an application module -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper -} - -// IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() {} - // RegisterServices registers module services. func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { types.RegisterMsgServer(registrar, am.keeper) @@ -67,13 +72,5 @@ func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { return nil } -// NewAppModule creates a new AppModule object -func NewAppModule(cdc codec.Codec, keeper keeper.Keeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc}, - keeper: keeper, - } -} - -// ConsensusVersion implements AppModule/ConsensusVersion. +// ConsensusVersion implements HasConsensusVersion. func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } diff --git a/x/counter/module.go b/x/counter/module.go index 1a4a97befe8b..89a4dda11f21 100644 --- a/x/counter/module.go +++ b/x/counter/module.go @@ -1,13 +1,10 @@ package counter import ( - gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" "google.golang.org/grpc" "cosmossdk.io/core/appmodule" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/counter/keeper" @@ -15,32 +12,14 @@ import ( ) var ( - _ module.AppModuleBasic = AppModule{} + _ module.HasName = AppModule{} + _ module.HasRegisterInterfaces = AppModule{} _ appmodule.AppModule = AppModule{} ) -// AppModuleBasic defines the basic application module used by the consensus module. -type AppModuleBasic struct{} - -// Name returns the consensus module's name. -func (AppModuleBasic) Name() string { return types.ModuleName } - -// RegisterLegacyAminoCodec registers the consensus module's types on the LegacyAmino codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) {} - -// RegisterInterfaces registers interfaces and implementations of the bank module. -func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - // AppModule implements an application module type AppModule struct { - AppModuleBasic - keeper keeper.Keeper } @@ -57,10 +36,17 @@ func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { // NewAppModule creates a new AppModule object func NewAppModule(keeper keeper.Keeper) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, + keeper: keeper, } } -// ConsensusVersion implements AppModule/ConsensusVersion. +// ConsensusVersion implements HasConsensusVersion func (AppModule) ConsensusVersion() uint64 { return 1 } + +// Name returns the consensus module's name. +func (AppModule) Name() string { return types.ModuleName } + +// RegisterInterfaces registers interfaces and implementations of the bank module. +func (AppModule) RegisterInterfaces(registry codectypes.InterfaceRegistry) { + types.RegisterInterfaces(registry) +} diff --git a/x/crisis/keeper/genesis_test.go b/x/crisis/keeper/genesis_test.go index f97ab21f1bd9..d111beebafe0 100644 --- a/x/crisis/keeper/genesis_test.go +++ b/x/crisis/keeper/genesis_test.go @@ -37,7 +37,7 @@ func (s *GenesisTestSuite) SetupTest() { key := storetypes.NewKVStoreKey(types.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(crisis.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(crisis.AppModule{}) // gomock initializations ctrl := gomock.NewController(s.T()) diff --git a/x/crisis/keeper/keeper_test.go b/x/crisis/keeper/keeper_test.go index d958ef52af7b..4a9237d3e92f 100644 --- a/x/crisis/keeper/keeper_test.go +++ b/x/crisis/keeper/keeper_test.go @@ -26,7 +26,7 @@ func TestLogger(t *testing.T) { key := storetypes.NewKVStoreKey(types.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(crisis.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(crisis.AppModule{}) keeper := keeper.NewKeeper(encCfg.Codec, storeService, 5, supplyKeeper, "", "", addresscodec.NewBech32Codec("cosmos")) require.Equal(t, @@ -40,7 +40,7 @@ func TestInvariants(t *testing.T) { key := storetypes.NewKVStoreKey(types.StoreKey) storeService := runtime.NewKVStoreService(key) - encCfg := moduletestutil.MakeTestEncodingConfig(crisis.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(crisis.AppModule{}) keeper := keeper.NewKeeper(encCfg.Codec, storeService, 5, supplyKeeper, "", "", addresscodec.NewBech32Codec("cosmos")) require.Equal(t, keeper.InvCheckPeriod(), uint(5)) @@ -57,7 +57,7 @@ func TestAssertInvariants(t *testing.T) { key := storetypes.NewKVStoreKey(types.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(crisis.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(crisis.AppModule{}) keeper := keeper.NewKeeper(encCfg.Codec, storeService, 5, supplyKeeper, "", "", addresscodec.NewBech32Codec("cosmos")) keeper.RegisterRoute("testModule", "testRoute1", func(sdk.Context) (string, bool) { return "", false }) diff --git a/x/crisis/keeper/msg_server_test.go b/x/crisis/keeper/msg_server_test.go index a8ef22a202c6..b86fbf724528 100644 --- a/x/crisis/keeper/msg_server_test.go +++ b/x/crisis/keeper/msg_server_test.go @@ -37,7 +37,7 @@ func (s *KeeperTestSuite) SetupTest() { key := storetypes.NewKVStoreKey(types.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(crisis.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(crisis.AppModule{}) keeper := keeper.NewKeeper(encCfg.Codec, storeService, 5, supplyKeeper, "", sdk.AccAddress([]byte("addr1_______________")).String(), addresscodec.NewBech32Codec("cosmos")) s.ctx = testCtx.Ctx @@ -51,7 +51,7 @@ func (s *KeeperTestSuite) TestMsgVerifyInvariant() { err := s.keeper.ConstantFee.Set(s.ctx, constantFee) s.Require().NoError(err) - encCfg := moduletestutil.MakeTestEncodingConfig(crisis.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(crisis.AppModule{}) kr := keyring.NewInMemory(encCfg.Codec) testutil.CreateKeyringAccounts(s.T(), kr, 1) diff --git a/x/crisis/module.go b/x/crisis/module.go index ddc1510efe20..0d6864a0d353 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -6,7 +6,6 @@ import ( "fmt" "time" - gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" "google.golang.org/grpc" @@ -25,8 +24,10 @@ import ( const ConsensusVersion = 2 var ( - _ module.AppModuleBasic = AppModule{} - _ module.HasGenesis = AppModule{} + _ module.HasName = AppModule{} + _ module.HasAminoCodec = AppModule{} + _ module.HasRegisterInterfaces = AppModule{} + _ module.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasEndBlocker = AppModule{} @@ -35,52 +36,10 @@ var ( ) // Module init related flags -const ( - FlagSkipGenesisInvariants = "x-crisis-skip-assert-invariants" -) - -// AppModuleBasic defines the basic application module used by the crisis module. -type AppModuleBasic struct{} - -// Name returns the crisis module's name. -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec registers the crisis module's types on the given LegacyAmino codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis returns default genesis state as raw bytes for the crisis -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) -} - -// ValidateGenesis performs genesis state validation for the crisis module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var data types.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { - return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) - } - - return types.ValidateGenesis(&data) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the crisis module. -func (AppModuleBasic) RegisterGRPCGatewayRoutes(_ client.Context, _ *gwruntime.ServeMux) {} - -// RegisterInterfaces registers interfaces and implementations of the crisis -// module. -func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} +const FlagSkipGenesisInvariants = "x-crisis-skip-assert-invariants" // AppModule implements an application module for the crisis module. type AppModule struct { - AppModuleBasic - // 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. @@ -95,9 +54,7 @@ type AppModule struct { // modified genesis file. func NewAppModule(keeper *keeper.Keeper, skipGenesisInvariants bool) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - + keeper: keeper, skipGenesisInvariants: skipGenesisInvariants, } } @@ -105,6 +62,22 @@ func NewAppModule(keeper *keeper.Keeper, skipGenesisInvariants bool) AppModule { // IsAppModule implements the appmodule.AppModule interface. func (am AppModule) IsAppModule() {} +// Name returns the crisis module's name. +func (AppModule) Name() string { + return types.ModuleName +} + +// RegisterLegacyAminoCodec registers the crisis module's types on the given LegacyAmino codec. +func (AppModule) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + types.RegisterLegacyAminoCodec(cdc) +} + +// RegisterInterfaces registers interfaces and implementations of the crisis +// module. +func (AppModule) RegisterInterfaces(registry codectypes.InterfaceRegistry) { + types.RegisterInterfaces(registry) +} + // AddModuleInitFlags implements servertypes.ModuleInitFlags interface. func AddModuleInitFlags(startCmd *cobra.Command) { startCmd.Flags().Bool(FlagSkipGenesisInvariants, false, "Skip x/crisis invariants check on startup") @@ -117,6 +90,7 @@ func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { return nil } +// RegisterMigrations registers the crisis module migrations. func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { m := keeper.NewMigrator(am.keeper) @@ -127,8 +101,22 @@ func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { return nil } -// InitGenesis performs genesis initialization for the crisis module. It returns -// no validator updates. +// 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()) +} + +// ValidateGenesis performs genesis state validation for the crisis module. +func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { + var data types.GenesisState + if err := cdc.UnmarshalJSON(bz, &data); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + + return types.ValidateGenesis(&data) +} + +// InitGenesis performs genesis initialization for the crisis module. func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { start := time.Now() var genesisState types.GenesisState @@ -141,14 +129,13 @@ func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data j } } -// ExportGenesis returns the exported genesis state as raw bytes for the crisis -// module. +// 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 { gs := am.keeper.ExportGenesis(ctx) return cdc.MustMarshalJSON(gs) } -// ConsensusVersion implements AppModule/ConsensusVersion. +// ConsensusVersion implements HasConsensusVersion func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } // EndBlock returns the end blocker for the crisis module. It returns no validator diff --git a/x/distribution/client/cli/tx.go b/x/distribution/client/cli/tx.go index 7161e2bf0acf..8c20cb7640f4 100644 --- a/x/distribution/client/cli/tx.go +++ b/x/distribution/client/cli/tx.go @@ -34,9 +34,7 @@ func NewTxCmd() *cobra.Command { RunE: client.ValidateCmd, } - distTxCmd.AddCommand( - NewWithdrawAllRewardsCmd(), - ) + distTxCmd.AddCommand(NewWithdrawAllRewardsCmd()) return distTxCmd } diff --git a/x/distribution/keeper/allocation_test.go b/x/distribution/keeper/allocation_test.go index a0b2b039d79d..f067964415d9 100644 --- a/x/distribution/keeper/allocation_test.go +++ b/x/distribution/keeper/allocation_test.go @@ -31,7 +31,7 @@ func TestAllocateTokensToValidatorWithCommission(t *testing.T) { key := storetypes.NewKVStoreKey(disttypes.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) @@ -90,7 +90,7 @@ func TestAllocateTokensToManyValidators(t *testing.T) { key := storetypes.NewKVStoreKey(disttypes.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) @@ -221,7 +221,7 @@ func TestAllocateTokensTruncation(t *testing.T) { key := storetypes.NewKVStoreKey(disttypes.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go index ea8744cdf124..140249e62741 100644 --- a/x/distribution/keeper/delegation_test.go +++ b/x/distribution/keeper/delegation_test.go @@ -29,7 +29,7 @@ func TestCalculateRewardsBasic(t *testing.T) { key := storetypes.NewKVStoreKey(disttypes.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1}) bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) @@ -131,7 +131,7 @@ func TestCalculateRewardsAfterSlash(t *testing.T) { key := storetypes.NewKVStoreKey(disttypes.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1}) bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) @@ -236,7 +236,7 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { key := storetypes.NewKVStoreKey(disttypes.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1}) bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) @@ -362,7 +362,7 @@ func TestCalculateRewardsMultiDelegator(t *testing.T) { key := storetypes.NewKVStoreKey(disttypes.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1}) bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) @@ -461,7 +461,7 @@ func TestWithdrawDelegationRewardsBasic(t *testing.T) { key := storetypes.NewKVStoreKey(disttypes.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1}) bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) @@ -538,7 +538,7 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { key := storetypes.NewKVStoreKey(disttypes.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1}) bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) @@ -656,7 +656,7 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { key := storetypes.NewKVStoreKey(disttypes.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1}) bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) @@ -795,7 +795,7 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { key := storetypes.NewKVStoreKey(disttypes.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1}) bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) @@ -996,7 +996,7 @@ func Test100PercentCommissionReward(t *testing.T) { key := storetypes.NewKVStoreKey(disttypes.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1}) bankKeeper := distrtestutil.NewMockBankKeeper(ctrl) diff --git a/x/distribution/keeper/keeper_test.go b/x/distribution/keeper/keeper_test.go index f2cdf30a6012..65acdccab18e 100644 --- a/x/distribution/keeper/keeper_test.go +++ b/x/distribution/keeper/keeper_test.go @@ -38,7 +38,7 @@ func initFixture(t *testing.T) (sdk.Context, []sdk.AccAddress, keeper.Keeper, de key := storetypes.NewKVStoreKey(types.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) addrs := simtestutil.CreateIncrementalAccounts(2) diff --git a/x/distribution/migrations/v4/migrate_funds_test.go b/x/distribution/migrations/v4/migrate_funds_test.go index 238e6b2e10b4..2267e6bba292 100644 --- a/x/distribution/migrations/v4/migrate_funds_test.go +++ b/x/distribution/migrations/v4/migrate_funds_test.go @@ -34,7 +34,7 @@ func TestFundsMigration(t *testing.T) { ) logger := log.NewTestLogger(t) cms := integration.CreateMultiStore(keys, logger) - encCfg := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}, bank.AppModuleBasic{}, distribution.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(auth.AppModule{}, bank.AppModule{}, distribution.AppModule{}) ctx := sdk.NewContext(cms, true, logger) maccPerms := map[string][]string{ diff --git a/x/distribution/migrations/v4/migrate_test.go b/x/distribution/migrations/v4/migrate_test.go index 9f4f68691696..86001ccd12ac 100644 --- a/x/distribution/migrations/v4/migrate_test.go +++ b/x/distribution/migrations/v4/migrate_test.go @@ -19,7 +19,7 @@ import ( ) func TestMigration(t *testing.T) { - cdc := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}).Codec + cdc := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}).Codec storeKey := storetypes.NewKVStoreKey("distribution") storeService := runtime.NewKVStoreService(storeKey) tKey := storetypes.NewTransientStoreKey("transient_test") diff --git a/x/distribution/module.go b/x/distribution/module.go index e965bc54506c..2caf7ab534ee 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -27,10 +27,13 @@ import ( const ConsensusVersion = 4 var ( - _ module.AppModuleBasic = AppModule{} - _ module.AppModuleSimulation = AppModule{} - _ module.HasGenesis = AppModule{} - _ module.HasInvariants = AppModule{} + _ module.HasName = AppModule{} + _ module.HasAminoCodec = AppModule{} + _ module.HasGRPCGateway = AppModule{} + _ module.HasRegisterInterfaces = AppModule{} + _ module.AppModuleSimulation = AppModule{} + _ module.HasGenesis = AppModule{} + _ module.HasInvariants = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasBeginBlocker = AppModule{} @@ -38,83 +41,61 @@ var ( _ appmodule.HasMigrations = AppModule{} ) -// AppModuleBasic defines the basic application module used by the distribution module. -type AppModuleBasic struct { - cdc codec.Codec +// AppModule implements an application module for the distribution module. +type AppModule struct { + cdc codec.Codec + keeper keeper.Keeper + accountKeeper types.AccountKeeper + bankKeeper types.BankKeeper + stakingKeeper types.StakingKeeper + poolKeeper types.PoolKeeper } +// NewAppModule creates a new AppModule object +func NewAppModule( + cdc codec.Codec, keeper keeper.Keeper, accountKeeper types.AccountKeeper, + bankKeeper types.BankKeeper, stakingKeeper types.StakingKeeper, poolKeeper types.PoolKeeper, +) AppModule { + return AppModule{ + cdc: cdc, + keeper: keeper, + accountKeeper: accountKeeper, + bankKeeper: bankKeeper, + stakingKeeper: stakingKeeper, + poolKeeper: poolKeeper, + } +} + +// IsAppModule implements the appmodule.AppModule interface. +func (am AppModule) IsAppModule() {} + // Name returns the distribution module's name. -func (AppModuleBasic) Name() string { +func (AppModule) Name() string { return types.ModuleName } // RegisterLegacyAminoCodec registers the distribution module's types for the given codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { +func (AppModule) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { types.RegisterLegacyAminoCodec(cdc) } -// DefaultGenesis returns default genesis state as raw bytes for the distribution -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) -} - -// ValidateGenesis performs genesis state validation for the distribution module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, _ sdkclient.TxEncodingConfig, bz json.RawMessage) error { - var data types.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { - return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) - } - - return types.ValidateGenesis(&data) -} - // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the distribution module. -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx sdkclient.Context, mux *gwruntime.ServeMux) { +func (AppModule) RegisterGRPCGatewayRoutes(clientCtx sdkclient.Context, mux *gwruntime.ServeMux) { if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { panic(err) } } // GetTxCmd returns the root tx command for the distribution module. -func (ab AppModuleBasic) GetTxCmd() *cobra.Command { +func (AppModule) GetTxCmd() *cobra.Command { return cli.NewTxCmd() } // RegisterInterfaces implements InterfaceModule -func (AppModuleBasic) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { +func (AppModule) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { types.RegisterInterfaces(registry) } -// AppModule implements an application module for the distribution module. -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper - stakingKeeper types.StakingKeeper - poolKeeper types.PoolKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule( - cdc codec.Codec, keeper keeper.Keeper, accountKeeper types.AccountKeeper, - bankKeeper types.BankKeeper, stakingKeeper types.StakingKeeper, poolKeeper types.PoolKeeper, -) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc}, - keeper: keeper, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - stakingKeeper: stakingKeeper, - poolKeeper: poolKeeper, - } -} - -// IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() {} - // RegisterInvariants registers the distribution module invariants. func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { keeper.RegisterInvariants(ir, am.keeper) @@ -128,6 +109,7 @@ func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { return nil } +// RegisterMigrations registers the distribution module's migrations. func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { m := keeper.NewMigrator(am.keeper) if err := mr.Register(types.ModuleName, 1, m.Migrate1to2); err != nil { @@ -145,8 +127,22 @@ func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { return nil } -// InitGenesis performs genesis initialization for the distribution module. It returns -// no validator updates. +// 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()) +} + +// ValidateGenesis performs genesis state validation for the distribution module. +func (AppModule) ValidateGenesis(cdc codec.JSONCodec, _ sdkclient.TxEncodingConfig, bz json.RawMessage) error { + var data types.GenesisState + if err := cdc.UnmarshalJSON(bz, &data); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + + return types.ValidateGenesis(&data) +} + +// InitGenesis performs genesis initialization for the distribution module. func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { var genesisState types.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) @@ -160,7 +156,7 @@ func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json return cdc.MustMarshalJSON(gs) } -// ConsensusVersion implements AppModule/ConsensusVersion. +// ConsensusVersion implements HasConsensusVersion func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } // BeginBlock returns the begin blocker for the distribution module. diff --git a/x/distribution/simulation/decoder_test.go b/x/distribution/simulation/decoder_test.go index fdd35a28ef56..71eb414442cb 100644 --- a/x/distribution/simulation/decoder_test.go +++ b/x/distribution/simulation/decoder_test.go @@ -24,7 +24,7 @@ var ( ) func TestDecodeDistributionStore(t *testing.T) { - encodingConfig := moduletestutil.MakeTestEncodingConfig(distribution.AppModuleBasic{}) + encodingConfig := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) cdc := encodingConfig.Codec dec := simulation.NewDecodeStore(cdc) diff --git a/x/evidence/depinject.go b/x/evidence/depinject.go index 880b23fb3107..49af8a23639c 100644 --- a/x/evidence/depinject.go +++ b/x/evidence/depinject.go @@ -6,6 +6,7 @@ import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/depinject" "cosmossdk.io/depinject/appconfig" + eviclient "cosmossdk.io/x/evidence/client" "cosmossdk.io/x/evidence/keeper" "cosmossdk.io/x/evidence/types" @@ -26,8 +27,9 @@ func init() { type ModuleInputs struct { depinject.In - Environment appmodule.Environment - Cdc codec.Codec + Environment appmodule.Environment + Cdc codec.Codec + EvidenceHandlers []eviclient.EvidenceHandler `optional:"true"` StakingKeeper types.StakingKeeper SlashingKeeper types.SlashingKeeper @@ -43,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) + m := NewAppModule(*k, in.EvidenceHandlers...) return ModuleOutputs{EvidenceKeeper: *k, Module: m} } diff --git a/x/evidence/doc.go b/x/evidence/doc.go index 3c8e5fc20352..94c4c1596276 100644 --- a/x/evidence/doc.go +++ b/x/evidence/doc.go @@ -15,11 +15,6 @@ flexibility in designing evidence handling. A full setup of the evidence module may look something as follows: - ModuleBasics = module.NewBasicManager( - // ..., - evidence.AppModuleBasic{}, - ) - // First, create the keeper evidenceKeeper := evidence.NewKeeper( appCodec, runtime.NewKVStoreService(keys[evidencetypes.StoreKey]), diff --git a/x/evidence/keeper/keeper_test.go b/x/evidence/keeper/keeper_test.go index 1fd7b3996399..6513aa581a11 100644 --- a/x/evidence/keeper/keeper_test.go +++ b/x/evidence/keeper/keeper_test.go @@ -84,7 +84,7 @@ type KeeperTestSuite struct { } func (suite *KeeperTestSuite) SetupTest() { - encCfg := moduletestutil.MakeTestEncodingConfig(evidence.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(evidence.AppModule{}) key := storetypes.NewKVStoreKey(types.StoreKey) env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) tkey := storetypes.NewTransientStoreKey("evidence_transient_store") @@ -115,7 +115,7 @@ func (suite *KeeperTestSuite) SetupTest() { evidenceKeeper.SetRouter(router) suite.ctx = testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1}) - suite.encCfg = moduletestutil.MakeTestEncodingConfig(evidence.AppModuleBasic{}) + suite.encCfg = moduletestutil.MakeTestEncodingConfig(evidence.AppModule{}) suite.accountKeeper = accountKeeper diff --git a/x/evidence/module.go b/x/evidence/module.go index fdd897b16483..b09183dbb50b 100644 --- a/x/evidence/module.go +++ b/x/evidence/module.go @@ -24,67 +24,57 @@ import ( ) var ( - _ module.AppModuleBasic = AppModule{} - _ module.AppModuleSimulation = AppModule{} - _ module.HasGenesis = AppModule{} + _ module.HasName = AppModule{} + _ module.HasAminoCodec = AppModule{} + _ module.HasGRPCGateway = AppModule{} + _ module.HasRegisterInterfaces = AppModule{} + _ module.AppModuleSimulation = AppModule{} + _ module.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasBeginBlocker = AppModule{} ) -// ---------------------------------------------------------------------------- -// AppModuleBasic -// ---------------------------------------------------------------------------- +const ConsensusVersion = 1 -// AppModuleBasic implements the AppModuleBasic interface for the evidence module. -type AppModuleBasic struct { - evidenceHandlers []eviclient.EvidenceHandler // eviclient evidence submission handlers +// AppModule implements the AppModule interface for the evidence module. +type AppModule struct { + evidenceHandlers []eviclient.EvidenceHandler + keeper keeper.Keeper } -// NewAppModuleBasic creates a AppModuleBasic without the codec. -func NewAppModuleBasic(evidenceHandlers ...eviclient.EvidenceHandler) AppModuleBasic { - return AppModuleBasic{ +// NewAppModule creates a new AppModule object. +func NewAppModule(keeper keeper.Keeper, evidenceHandlers ...eviclient.EvidenceHandler) AppModule { + return AppModule{ + keeper: keeper, evidenceHandlers: evidenceHandlers, } } +// IsAppModule implements the appmodule.AppModule interface. +func (am AppModule) IsAppModule() {} + // Name returns the evidence module's name. -func (AppModuleBasic) Name() string { +func (AppModule) Name() string { return types.ModuleName } // RegisterLegacyAminoCodec registers the evidence module's types to the LegacyAmino codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { +func (AppModule) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { types.RegisterLegacyAminoCodec(cdc) } -// DefaultGenesis returns the evidence module's default genesis state. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) -} - -// ValidateGenesis performs genesis state validation for the evidence module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var gs types.GenesisState - if err := cdc.UnmarshalJSON(bz, &gs); err != nil { - return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) - } - - return gs.Validate() -} - // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the evidence module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { +func (AppModule) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { panic(err) } } // GetTxCmd returns the evidence module's root tx command. -func (a AppModuleBasic) GetTxCmd() *cobra.Command { - evidenceCLIHandlers := make([]*cobra.Command, len(a.evidenceHandlers)) - - for i, evidenceHandler := range a.evidenceHandlers { +func (am AppModule) GetTxCmd() *cobra.Command { + evidenceCLIHandlers := make([]*cobra.Command, len(am.evidenceHandlers)) + for i, evidenceHandler := range am.evidenceHandlers { evidenceCLIHandlers[i] = evidenceHandler.CLIHandler() } @@ -92,32 +82,10 @@ func (a AppModuleBasic) GetTxCmd() *cobra.Command { } // RegisterInterfaces registers the evidence module's interface types -func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { +func (AppModule) RegisterInterfaces(registry codectypes.InterfaceRegistry) { types.RegisterInterfaces(registry) } -// ---------------------------------------------------------------------------- -// AppModule -// ---------------------------------------------------------------------------- - -// AppModule implements the AppModule interface for the evidence module. -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper -} - -// NewAppModule creates a new AppModule object. -func NewAppModule(keeper keeper.Keeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - } -} - -// IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() {} - // RegisterServices registers module services. func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { types.RegisterMsgServer(registrar, keeper.NewMsgServerImpl(am.keeper)) @@ -125,8 +93,22 @@ func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { return nil } -// InitGenesis performs the evidence module's genesis initialization It returns -// no validator updates. +// DefaultGenesis returns the evidence module's default genesis state. +func (AppModule) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { + return 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 { + var gs types.GenesisState + if err := cdc.UnmarshalJSON(bz, &gs); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + + return gs.Validate() +} + +// InitGenesis performs the evidence module's genesis initialization func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, bz json.RawMessage) { var gs types.GenesisState err := cdc.UnmarshalJSON(bz, &gs) @@ -142,8 +124,8 @@ func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json return cdc.MustMarshalJSON(ExportGenesis(ctx, am.keeper)) } -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { return 1 } +// ConsensusVersion implements HasConsensusVersion +func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } // BeginBlock executes all ABCI BeginBlock logic respective to the evidence module. func (am AppModule) BeginBlock(ctx context.Context) error { diff --git a/x/feegrant/client/cli/tx_test.go b/x/feegrant/client/cli/tx_test.go index 6f881b074342..d691821f26ec 100644 --- a/x/feegrant/client/cli/tx_test.go +++ b/x/feegrant/client/cli/tx_test.go @@ -61,7 +61,7 @@ func TestCLITestSuite(t *testing.T) { func (s *CLITestSuite) SetupSuite() { s.T().Log("setting up integration test suite") - s.encCfg = testutilmod.MakeTestEncodingConfig(module.AppModuleBasic{}, gov.AppModule{}) + s.encCfg = testutilmod.MakeTestEncodingConfig(module.AppModule{}, gov.AppModule{}) s.kr = keyring.NewInMemory(s.encCfg.Codec) s.baseCtx = client.Context{}. WithKeyring(s.kr). @@ -85,15 +85,10 @@ func (s *CLITestSuite) SetupSuite() { } s.clientCtx = ctxGen() - if testing.Short() { - s.T().Skip("skipping test in unit-tests mode.") - } - accounts := testutil.CreateKeyringAccounts(s.T(), s.kr, 2) granter := accounts[0].Address grantee := accounts[1].Address - s.createGrant(granter, grantee) granteeStr, err := s.baseCtx.AddressCodec.BytesToString(grantee) diff --git a/x/feegrant/filtered_fee_test.go b/x/feegrant/filtered_fee_test.go index 1ad87c313088..f5deee9e3d96 100644 --- a/x/feegrant/filtered_fee_test.go +++ b/x/feegrant/filtered_fee_test.go @@ -22,7 +22,7 @@ import ( func TestFilteredFeeValidAllow(t *testing.T) { key := storetypes.NewKVStoreKey(feegrant.StoreKey) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) diff --git a/x/feegrant/grant_test.go b/x/feegrant/grant_test.go index a6be9ff267af..0dcad40a7379 100644 --- a/x/feegrant/grant_test.go +++ b/x/feegrant/grant_test.go @@ -21,7 +21,7 @@ func TestGrant(t *testing.T) { addressCodec := codecaddress.NewBech32Codec("cosmos") key := storetypes.NewKVStoreKey(feegrant.StoreKey) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) diff --git a/x/feegrant/keeper/genesis_test.go b/x/feegrant/keeper/genesis_test.go index f3790ffb8fa5..eb2eff20d467 100644 --- a/x/feegrant/keeper/genesis_test.go +++ b/x/feegrant/keeper/genesis_test.go @@ -43,7 +43,7 @@ func initFixture(t *testing.T) *genesisFixture { t.Helper() key := storetypes.NewKVStoreKey(feegrant.StoreKey) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModule{}) ctrl := gomock.NewController(t) accountKeeper := feegranttestutil.NewMockAccountKeeper(ctrl) diff --git a/x/feegrant/keeper/keeper_test.go b/x/feegrant/keeper/keeper_test.go index eaa92c60f528..e68f798d94d2 100644 --- a/x/feegrant/keeper/keeper_test.go +++ b/x/feegrant/keeper/keeper_test.go @@ -44,7 +44,7 @@ func (suite *KeeperTestSuite) SetupTest() { suite.addrs = simtestutil.CreateIncrementalAccounts(20) key := storetypes.NewKVStoreKey(feegrant.StoreKey) testCtx := testutil.DefaultContextWithDB(suite.T(), key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModule{}) // setup gomock and initialize some globally expected executions ctrl := gomock.NewController(suite.T()) diff --git a/x/feegrant/key.go b/x/feegrant/key.go index 837435128c73..d44d7932f615 100644 --- a/x/feegrant/key.go +++ b/x/feegrant/key.go @@ -10,12 +10,6 @@ const ( // StoreKey is the store key string for supply StoreKey = ModuleName - - // RouterKey is the message route for supply - RouterKey = ModuleName - - // QuerierRoute is the querier route for supply - QuerierRoute = ModuleName ) var ( diff --git a/x/feegrant/migrations/v2/store_test.go b/x/feegrant/migrations/v2/store_test.go index be908e48252f..747e6f74fb6f 100644 --- a/x/feegrant/migrations/v2/store_test.go +++ b/x/feegrant/migrations/v2/store_test.go @@ -23,7 +23,7 @@ import ( ) func TestMigration(t *testing.T) { - encodingConfig := moduletestutil.MakeTestEncodingConfig(module.AppModuleBasic{}) + encodingConfig := moduletestutil.MakeTestEncodingConfig(module.AppModule{}) cdc := encodingConfig.Codec ac := addresscodec.NewBech32Codec("cosmos") diff --git a/x/feegrant/module/abci_test.go b/x/feegrant/module/abci_test.go index 0664726921ea..1fb1685aa3c9 100644 --- a/x/feegrant/module/abci_test.go +++ b/x/feegrant/module/abci_test.go @@ -28,7 +28,7 @@ import ( func TestFeegrantPruning(t *testing.T) { key := storetypes.NewKVStoreKey(feegrant.StoreKey) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModule{}) addrs := simtestutil.CreateIncrementalAccounts(4) granter1 := addrs[0] diff --git a/x/feegrant/module/module.go b/x/feegrant/module/module.go index b67d1e17f5b9..73ca979403fc 100644 --- a/x/feegrant/module/module.go +++ b/x/feegrant/module/module.go @@ -22,9 +22,12 @@ import ( ) var ( - _ module.AppModuleBasic = AppModule{} - _ module.AppModuleSimulation = AppModule{} - _ module.HasGenesis = AppModule{} + _ module.HasName = AppModule{} + _ module.HasAminoCodec = AppModule{} + _ module.HasGRPCGateway = AppModule{} + _ module.HasRegisterInterfaces = AppModule{} + _ module.AppModuleSimulation = AppModule{} + _ module.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasEndBlocker = AppModule{} @@ -32,20 +35,57 @@ var ( _ appmodule.HasMigrations = AppModule{} ) -// ---------------------------------------------------------------------------- -// AppModuleBasic -// ---------------------------------------------------------------------------- +// AppModule implements an application module for the feegrant module. +type AppModule struct { + cdc codec.Codec + registry cdctypes.InterfaceRegistry -// AppModuleBasic defines the basic application module used by the feegrant module. -type AppModuleBasic struct { - cdc codec.Codec + keeper keeper.Keeper + accountKeeper feegrant.AccountKeeper + bankKeeper feegrant.BankKeeper } +// NewAppModule creates a new AppModule object +func NewAppModule(cdc codec.Codec, ak feegrant.AccountKeeper, bk feegrant.BankKeeper, keeper keeper.Keeper, registry cdctypes.InterfaceRegistry) AppModule { + return AppModule{ + cdc: cdc, + keeper: keeper, + accountKeeper: ak, + bankKeeper: bk, + registry: registry, + } +} + +// IsAppModule implements the appmodule.AppModule interface. +func (AppModule) IsAppModule() {} + // Name returns the feegrant module's name. -func (ab AppModuleBasic) Name() string { +func (AppModule) Name() string { return feegrant.ModuleName } +// RegisterLegacyAminoCodec registers the feegrant module's types for the given codec. +func (AppModule) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + feegrant.RegisterLegacyAminoCodec(cdc) +} + +// RegisterInterfaces registers the feegrant module's interface types +func (AppModule) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { + feegrant.RegisterInterfaces(registry) +} + +// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the feegrant module. +func (AppModule) RegisterGRPCGatewayRoutes(clientCtx sdkclient.Context, mux *gwruntime.ServeMux) { + if err := feegrant.RegisterQueryHandlerClient(context.Background(), mux, feegrant.NewQueryClient(clientCtx)); err != nil { + panic(err) + } +} + +// GetTxCmd returns the root tx command for the feegrant module. +func (AppModule) GetTxCmd() *cobra.Command { + return cli.GetTxCmd() +} + // RegisterServices registers module services. func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { feegrant.RegisterMsgServer(registrar, keeper.NewMsgServerImpl(am.keeper)) @@ -54,6 +94,7 @@ func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { return nil } +// RegisterMigrations registers module migrations. func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { m := keeper.NewMigrator(am.keeper) @@ -64,24 +105,13 @@ func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { return nil } -// RegisterLegacyAminoCodec registers the feegrant module's types for the given codec. -func (ab AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - feegrant.RegisterLegacyAminoCodec(cdc) -} - -// RegisterInterfaces registers the feegrant module's interface types -func (ab AppModuleBasic) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { - feegrant.RegisterInterfaces(registry) -} - -// DefaultGenesis returns default genesis state as raw bytes for the feegrant -// module. -func (ab AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { +// 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()) } // ValidateGenesis performs genesis state validation for the feegrant module. -func (ab AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { +func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { var data feegrant.GenesisState if err := cdc.UnmarshalJSON(bz, &data); err != nil { return errors.Wrapf(err, "failed to unmarshal %s genesis state", feegrant.ModuleName) @@ -90,48 +120,7 @@ func (ab AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.T return feegrant.ValidateGenesis(data) } -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the feegrant module. -func (ab AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx sdkclient.Context, mux *gwruntime.ServeMux) { - if err := feegrant.RegisterQueryHandlerClient(context.Background(), mux, feegrant.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - -// GetTxCmd returns the root tx command for the feegrant module. -func (ab AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// ---------------------------------------------------------------------------- -// AppModule -// ---------------------------------------------------------------------------- - -// AppModule implements an application module for the feegrant module. -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper feegrant.AccountKeeper - bankKeeper feegrant.BankKeeper - registry cdctypes.InterfaceRegistry -} - -// NewAppModule creates a new AppModule object -func NewAppModule(cdc codec.Codec, ak feegrant.AccountKeeper, bk feegrant.BankKeeper, keeper keeper.Keeper, registry cdctypes.InterfaceRegistry) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc}, - keeper: keeper, - accountKeeper: ak, - bankKeeper: bk, - registry: registry, - } -} - -// IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() {} - -// InitGenesis performs genesis initialization for the feegrant module. It returns -// no validator updates. +// InitGenesis performs genesis initialization for the feegrant module. func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, bz json.RawMessage) { var gs feegrant.GenesisState cdc.MustUnmarshalJSON(bz, &gs) @@ -142,8 +131,7 @@ func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, bz jso } } -// ExportGenesis returns the exported genesis state as raw bytes for the feegrant -// module. +// 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 { gs, err := am.keeper.ExportGenesis(ctx) if err != nil { @@ -153,11 +141,10 @@ func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json return cdc.MustMarshalJSON(gs) } -// ConsensusVersion implements AppModule/ConsensusVersion. +// ConsensusVersion implements HasConsensusVersion func (AppModule) ConsensusVersion() uint64 { return 2 } -// EndBlock returns the end blocker for the feegrant module. It returns no validator -// updates. +// EndBlock returns the end blocker for the feegrant module. func (am AppModule) EndBlock(ctx context.Context) error { return EndBlocker(ctx, am.keeper) } diff --git a/x/feegrant/simulation/decoder_test.go b/x/feegrant/simulation/decoder_test.go index 6033f9e75143..37526f596526 100644 --- a/x/feegrant/simulation/decoder_test.go +++ b/x/feegrant/simulation/decoder_test.go @@ -25,7 +25,7 @@ var ( ) func TestDecodeStore(t *testing.T) { - encodingConfig := moduletestutil.MakeTestEncodingConfig(module.AppModuleBasic{}) + encodingConfig := moduletestutil.MakeTestEncodingConfig(module.AppModule{}) cdc := encodingConfig.Codec dec := simulation.NewDecodeStore(cdc) ac := addresscodec.NewBech32Codec("cosmos") diff --git a/x/feegrant/simulation/genesis_test.go b/x/feegrant/simulation/genesis_test.go index af9ffd667e7e..1271cd5bb001 100644 --- a/x/feegrant/simulation/genesis_test.go +++ b/x/feegrant/simulation/genesis_test.go @@ -18,7 +18,7 @@ import ( ) func TestRandomizedGenState(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModule{}) s := rand.NewSource(1) r := rand.New(s) diff --git a/x/genutil/client/cli/commands.go b/x/genutil/client/cli/commands.go index 267eecf408dc..9bb9800d7224 100644 --- a/x/genutil/client/cli/commands.go +++ b/x/genutil/client/cli/commands.go @@ -13,13 +13,13 @@ import ( ) // Commands adds core sdk's sub-commands into genesis command. -func Commands(txConfig client.TxConfig, moduleBasics module.BasicManager, appExport servertypes.AppExporter) *cobra.Command { - return CommandsWithCustomMigrationMap(txConfig, moduleBasics, appExport, MigrationMap) +func Commands(txConfig client.TxConfig, mm *module.Manager, appExport servertypes.AppExporter) *cobra.Command { + return CommandsWithCustomMigrationMap(txConfig, mm, appExport, MigrationMap) } // CommandsWithCustomMigrationMap adds core sdk's sub-commands into genesis command with custom migration map. // This custom migration map can be used by the application to add its own migration map. -func CommandsWithCustomMigrationMap(txConfig client.TxConfig, moduleBasics module.BasicManager, appExport servertypes.AppExporter, migrationMap genutiltypes.MigrationMap) *cobra.Command { +func CommandsWithCustomMigrationMap(txConfig client.TxConfig, mm *module.Manager, appExport servertypes.AppExporter, migrationMap genutiltypes.MigrationMap) *cobra.Command { cmd := &cobra.Command{ Use: "genesis", Short: "Application's genesis-related subcommands", @@ -27,13 +27,13 @@ func CommandsWithCustomMigrationMap(txConfig client.TxConfig, moduleBasics modul SuggestionsMinimumDistance: 2, RunE: client.ValidateCmd, } - gentxModule := moduleBasics[genutiltypes.ModuleName].(genutil.AppModuleBasic) + gentxModule := mm.Modules[genutiltypes.ModuleName].(genutil.AppModule) cmd.AddCommand( - GenTxCmd(moduleBasics, txConfig, banktypes.GenesisBalancesIterator{}, txConfig.SigningContext().ValidatorAddressCodec()), + GenTxCmd(mm, txConfig, banktypes.GenesisBalancesIterator{}, txConfig.SigningContext().ValidatorAddressCodec()), MigrateGenesisCmd(migrationMap), - CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, gentxModule.GenTxValidator, txConfig.SigningContext().ValidatorAddressCodec()), - ValidateGenesisCmd(moduleBasics), + CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, gentxModule.GenTxValidator(), txConfig.SigningContext().ValidatorAddressCodec()), + ValidateGenesisCmd(mm), AddGenesisAccountCmd(txConfig.SigningContext().AddressCodec()), ExportCmd(appExport), ) diff --git a/x/genutil/client/cli/export_test.go b/x/genutil/client/cli/export_test.go index 6c7878ce20f3..02be4bf5d82d 100644 --- a/x/genutil/client/cli/export_test.go +++ b/x/genutil/client/cli/export_test.go @@ -59,7 +59,7 @@ func NewExportSystem(t *testing.T, exporter types.AppExporter) *ExportSystem { sys := cmdtest.NewSystem() sys.AddCommands( cli.ExportCmd(exporter), - cli.InitCmd(module.NewBasicManager()), + cli.InitCmd(module.NewManager()), ) tw := zerolog.NewTestWriter(t) diff --git a/x/genutil/client/cli/genaccount_test.go b/x/genutil/client/cli/genaccount_test.go index fd533d2fcaa3..2c5b8a923b33 100644 --- a/x/genutil/client/cli/genaccount_test.go +++ b/x/genutil/client/cli/genaccount_test.go @@ -69,7 +69,7 @@ func TestAddGenesisAccountCmd(t *testing.T) { cfg, err := genutiltest.CreateDefaultCometConfig(home) require.NoError(t, err) - appCodec := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}).Codec + appCodec := moduletestutil.MakeTestEncodingConfig(auth.AppModule{}).Codec err = genutiltest.ExecInitCmd(testMbm, home, appCodec) require.NoError(t, err) diff --git a/x/genutil/client/cli/gentx.go b/x/genutil/client/cli/gentx.go index 2e2924a6fb96..d82b0476b81a 100644 --- a/x/genutil/client/cli/gentx.go +++ b/x/genutil/client/cli/gentx.go @@ -29,7 +29,7 @@ import ( ) // GenTxCmd builds the application's gentx command. -func GenTxCmd(mbm module.BasicManager, txEncCfg client.TxEncodingConfig, genBalIterator types.GenesisBalancesIterator, valAdddressCodec address.Codec) *cobra.Command { +func GenTxCmd(mm *module.Manager, txEncCfg client.TxEncodingConfig, genBalIterator types.GenesisBalancesIterator, valAdddressCodec address.Codec) *cobra.Command { ipDefault, _ := server.ExternalIP() fsCreateValidator, defaultsDesc := cli.CreateValidatorMsgFlagSet(ipDefault) @@ -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 = mbm.ValidateGenesis(cdc, txEncCfg, genesisState); err != nil { + if err = mm.ValidateGenesis(cdc, txEncCfg, genesisState); err != nil { return errors.Wrap(err, "failed to validate genesis state") } diff --git a/x/genutil/client/cli/gentx_test.go b/x/genutil/client/cli/gentx_test.go index 9b5fc19f6bc8..76ea4856d592 100644 --- a/x/genutil/client/cli/gentx_test.go +++ b/x/genutil/client/cli/gentx_test.go @@ -42,7 +42,7 @@ func TestCLITestSuite(t *testing.T) { } func (s *CLITestSuite) SetupSuite() { - s.encCfg = testutilmod.MakeTestEncodingConfig(genutil.AppModuleBasic{}) + s.encCfg = testutilmod.MakeTestEncodingConfig(genutil.AppModule{}) s.kr = keyring.NewInMemory(s.encCfg.Codec) s.baseCtx = client.Context{}. WithKeyring(s.kr). @@ -123,7 +123,7 @@ func (s *CLITestSuite) TestGenTxCmd() { clientCtx := s.clientCtx ctx := svrcmd.CreateExecuteContext(context.Background()) - cmd := cli.GenTxCmd(module.NewBasicManager(), clientCtx.TxConfig, banktypes.GenesisBalancesIterator{}, address.NewBech32Codec("cosmosvaloper")) + cmd := cli.GenTxCmd(module.NewManager(), clientCtx.TxConfig, banktypes.GenesisBalancesIterator{}, address.NewBech32Codec("cosmosvaloper")) cmd.SetContext(ctx) cmd.SetArgs(tc.args) diff --git a/x/genutil/client/cli/init.go b/x/genutil/client/cli/init.go index 999a3dbb0e8a..227acbe25f50 100644 --- a/x/genutil/client/cli/init.go +++ b/x/genutil/client/cli/init.go @@ -68,7 +68,7 @@ func displayInfo(info printInfo) error { // InitCmd returns a command that initializes all files needed for Tendermint // and the respective application. -func InitCmd(mbm module.BasicManager) *cobra.Command { +func InitCmd(mm *module.Manager) *cobra.Command { cmd := &cobra.Command{ Use: "init [moniker]", Short: "Initialize private validator, p2p, genesis, and application configuration files", @@ -133,7 +133,7 @@ func InitCmd(mbm module.BasicManager) *cobra.Command { if defaultDenom != "" { sdk.DefaultBondDenom = defaultDenom } - appGenState := mbm.DefaultGenesis(cdc) + appGenState := mm.DefaultGenesis(cdc) 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 6f086f47a2e7..82ad4ad64c7a 100644 --- a/x/genutil/client/cli/init_test.go +++ b/x/genutil/client/cli/init_test.go @@ -34,9 +34,9 @@ import ( genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" ) -var testMbm = module.NewBasicManager( - staking.AppModuleBasic{}, - genutil.AppModuleBasic{}, +var testMbm = module.NewManager( + staking.AppModule{}, + genutil.AppModule{}, ) func TestInitCmd(t *testing.T) { diff --git a/x/genutil/client/cli/validate_genesis.go b/x/genutil/client/cli/validate_genesis.go index 290542fe974f..71011f1f0989 100644 --- a/x/genutil/client/cli/validate_genesis.go +++ b/x/genutil/client/cli/validate_genesis.go @@ -15,7 +15,7 @@ import ( const chainUpgradeGuide = "https://github.com/cosmos/cosmos-sdk/blob/main/UPGRADING.md" // ValidateGenesisCmd takes a genesis file, and makes sure that it is valid. -func ValidateGenesisCmd(mbm module.BasicManager) *cobra.Command { +func ValidateGenesisCmd(mm *module.Manager) *cobra.Command { return &cobra.Command{ Use: "validate [file]", Aliases: []string{"validate-genesis"}, @@ -49,8 +49,10 @@ func ValidateGenesisCmd(mbm module.BasicManager) *cobra.Command { return fmt.Errorf("error unmarshalling genesis doc %s: %w", genesis, err) } - if err = mbm.ValidateGenesis(cdc, clientCtx.TxConfig, genState); err != nil { - return fmt.Errorf("error validating genesis file %s: %w", genesis, err) + if mm != nil { + if err = mm.ValidateGenesis(cdc, clientCtx.TxConfig, genState); err != nil { + return fmt.Errorf("error validating genesis file %s: %w", genesis, err) + } } fmt.Fprintf(cmd.OutOrStdout(), "File at %s is a valid genesis file\n", genesis) diff --git a/x/genutil/client/testutil/helpers.go b/x/genutil/client/testutil/helpers.go index 3d5e37f99db4..e4fc09e9acff 100644 --- a/x/genutil/client/testutil/helpers.go +++ b/x/genutil/client/testutil/helpers.go @@ -17,14 +17,14 @@ import ( genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" ) -func ExecInitCmd(testMbm module.BasicManager, home string, cdc codec.Codec) error { +func ExecInitCmd(mm *module.Manager, home string, cdc codec.Codec) error { logger := log.NewNopLogger() cfg, err := CreateDefaultCometConfig(home) if err != nil { return err } - cmd := genutilcli.InitCmd(testMbm) + cmd := genutilcli.InitCmd(mm) serverCtx := server.NewContext(viper.New(), cfg, logger) serverCtx.Config.SetRoot(home) clientCtx := client.Context{}.WithCodec(cdc).WithHomeDir(home) diff --git a/x/genutil/depinject.go b/x/genutil/depinject.go index 77320ca6b0c4..d8fb7ee6ed79 100644 --- a/x/genutil/depinject.go +++ b/x/genutil/depinject.go @@ -26,13 +26,18 @@ func init() { type ModuleInputs struct { depinject.In - AccountKeeper types.AccountKeeper - StakingKeeper types.StakingKeeper - DeliverTx genesis.TxHandler - Config client.TxConfig + AccountKeeper types.AccountKeeper + StakingKeeper types.StakingKeeper + DeliverTx genesis.TxHandler + Config client.TxConfig + GenTxValidator types.MessageValidator `optional:"true"` } func ProvideModule(in ModuleInputs) appmodule.AppModule { - m := NewAppModule(in.AccountKeeper, in.StakingKeeper, in.DeliverTx, in.Config) + if in.GenTxValidator == nil { + in.GenTxValidator = types.DefaultMessageValidator + } + + m := NewAppModule(in.AccountKeeper, in.StakingKeeper, in.DeliverTx, in.Config, in.GenTxValidator) return m } diff --git a/x/genutil/gentx_test.go b/x/genutil/gentx_test.go index 878841e55424..4ce47e3a3dfd 100644 --- a/x/genutil/gentx_test.go +++ b/x/genutil/gentx_test.go @@ -52,7 +52,7 @@ type GenTxTestSuite struct { } func (suite *GenTxTestSuite) SetupTest() { - suite.encodingConfig = moduletestutil.MakeTestEncodingConfig(genutil.AppModuleBasic{}) + suite.encodingConfig = moduletestutil.MakeTestEncodingConfig(genutil.AppModule{}) key := storetypes.NewKVStoreKey("a_Store_Key") tkey := storetypes.NewTransientStoreKey("a_transient_store") suite.ctx = testutil.DefaultContext(key, tkey) diff --git a/x/genutil/module.go b/x/genutil/module.go index 6029f5b45acc..bc0472da4d97 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -6,94 +6,73 @@ import ( "fmt" abci "github.com/cometbft/cometbft/abci/types" - gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" "cosmossdk.io/core/appmodule" "cosmossdk.io/core/genesis" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" - cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/genutil/types" ) var ( - _ module.AppModuleBasic = AppModule{} + _ module.HasName = AppModule{} _ module.HasABCIGenesis = AppModule{} _ appmodule.AppModule = AppModule{} ) -// AppModuleBasic defines the basic application module used by the genutil module. -type AppModuleBasic struct { - GenTxValidator types.MessageValidator -} - -// NewAppModuleBasic creates AppModuleBasic, validator is a function used to validate genesis -// transactions. -func NewAppModuleBasic(validator types.MessageValidator) AppModuleBasic { - return AppModuleBasic{validator} -} - -// Name returns the genutil module's name. -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec registers the genutil module's types on the given LegacyAmino codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {} - -// RegisterInterfaces registers the module's interface types -func (b AppModuleBasic) RegisterInterfaces(cdctypes.InterfaceRegistry) {} - -// DefaultGenesis returns default genesis state as raw bytes for the genutil -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) -} - -// ValidateGenesis performs genesis state validation for the genutil module. -func (b AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, txEncodingConfig client.TxEncodingConfig, bz json.RawMessage) error { - var data types.GenesisState - if err := 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) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the genutil module. -func (AppModuleBasic) RegisterGRPCGatewayRoutes(_ client.Context, _ *gwruntime.ServeMux) { -} - // AppModule implements an application module for the genutil module. type AppModule struct { - AppModuleBasic - accountKeeper types.AccountKeeper stakingKeeper types.StakingKeeper deliverTx genesis.TxHandler txEncodingConfig client.TxEncodingConfig + genTxValidator types.MessageValidator } // NewAppModule creates a new AppModule object -func NewAppModule(accountKeeper types.AccountKeeper, - stakingKeeper types.StakingKeeper, deliverTx genesis.TxHandler, +func NewAppModule( + accountKeeper types.AccountKeeper, + stakingKeeper types.StakingKeeper, + deliverTx genesis.TxHandler, txEncodingConfig client.TxEncodingConfig, -) module.GenesisOnlyAppModule { - return module.NewGenesisOnlyAppModule(AppModule{ - AppModuleBasic: AppModuleBasic{}, + genTxValidator types.MessageValidator, +) module.AppModule { + return AppModule{ accountKeeper: accountKeeper, stakingKeeper: stakingKeeper, deliverTx: deliverTx, txEncodingConfig: txEncodingConfig, - }) + genTxValidator: genTxValidator, + } } // IsAppModule implements the appmodule.AppModule interface. func (AppModule) IsAppModule() {} +// Name returns the genutil module's name. +func (AppModule) Name() string { + return types.ModuleName +} + +// 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()) +} + +// ValidateGenesis performs genesis state validation for the genutil module. +func (b AppModule) ValidateGenesis(cdc codec.JSONCodec, txEncodingConfig client.TxEncodingConfig, bz json.RawMessage) error { + var data types.GenesisState + if err := 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) +} + // InitGenesis performs genesis initialization for the genutil module. func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { var genesisState types.GenesisState @@ -105,11 +84,18 @@ func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data j return validators } -// ExportGenesis returns the exported genesis state as raw bytes for the genutil -// module. +// 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) } -// ConsensusVersion implements AppModule/ConsensusVersion. +// GenTxValidator returns the genutil module's genesis transaction validator. +func (am AppModule) GenTxValidator() types.MessageValidator { + return am.genTxValidator +} + +// ConsensusVersion implements HasConsensusVersion func (AppModule) ConsensusVersion() uint64 { return 1 } + +// RegisterInterfaces implements module.AppModule. +func (AppModule) RegisterInterfaces(codectypes.InterfaceRegistry) {} diff --git a/x/genutil/testutil/expected_keepers_mocks.go b/x/genutil/testutil/expected_keepers_mocks.go index 12002eb63d1c..c1d03bc51731 100644 --- a/x/genutil/testutil/expected_keepers_mocks.go +++ b/x/genutil/testutil/expected_keepers_mocks.go @@ -77,18 +77,6 @@ func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder { return m.recorder } -// IterateAccounts mocks base method. -func (m *MockAccountKeeper) IterateAccounts(ctx context.Context, process func(types0.AccountI) bool) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "IterateAccounts", ctx, process) -} - -// IterateAccounts indicates an expected call of IterateAccounts. -func (mr *MockAccountKeeperMockRecorder) IterateAccounts(ctx, process interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IterateAccounts", reflect.TypeOf((*MockAccountKeeper)(nil).IterateAccounts), ctx, process) -} - // NewAccount mocks base method. func (m *MockAccountKeeper) NewAccount(arg0 context.Context, arg1 types0.AccountI) types0.AccountI { m.ctrl.T.Helper() diff --git a/x/genutil/types/genesis_state_test.go b/x/genutil/types/genesis_state_test.go index 988cb4f41f17..95a6aef6d2d4 100644 --- a/x/genutil/types/genesis_state_test.go +++ b/x/genutil/types/genesis_state_test.go @@ -48,7 +48,7 @@ func TestValidateGenesisMultipleMessages(t *testing.T) { sdk.NewInt64Coin(sdk.DefaultBondDenom, 50), desc, comm, math.OneInt()) require.NoError(t, err) - txConfig := moduletestutil.MakeTestEncodingConfig(staking.AppModuleBasic{}, genutil.AppModuleBasic{}).TxConfig + txConfig := moduletestutil.MakeTestEncodingConfig(staking.AppModule{}, genutil.AppModule{}).TxConfig txBuilder := txConfig.NewTxBuilder() require.NoError(t, txBuilder.SetMsgs(msg1, msg2)) @@ -64,7 +64,7 @@ func TestValidateGenesisBadMessage(t *testing.T) { msg1 := stakingtypes.NewMsgEditValidator(sdk.ValAddress(pk1.Address()).String(), desc, nil, nil) - txConfig := moduletestutil.MakeTestEncodingConfig(staking.AppModuleBasic{}, genutil.AppModuleBasic{}).TxConfig + txConfig := moduletestutil.MakeTestEncodingConfig(staking.AppModule{}, genutil.AppModule{}).TxConfig txBuilder := txConfig.NewTxBuilder() err := txBuilder.SetMsgs(msg1) require.NoError(t, err) diff --git a/x/gov/client/cli/tx_test.go b/x/gov/client/cli/tx_test.go index b9cadf373651..05ffcb92d806 100644 --- a/x/gov/client/cli/tx_test.go +++ b/x/gov/client/cli/tx_test.go @@ -43,7 +43,7 @@ func TestCLITestSuite(t *testing.T) { } func (s *CLITestSuite) SetupSuite() { - s.encCfg = testutilmod.MakeTestEncodingConfig(gov.AppModuleBasic{}) + s.encCfg = testutilmod.MakeTestEncodingConfig(gov.AppModule{}) s.kr = keyring.NewInMemory(s.encCfg.Codec) s.baseCtx = client.Context{}. WithKeyring(s.kr). diff --git a/x/gov/client/utils/query_test.go b/x/gov/client/utils/query_test.go index 2b0f92aeccd5..3e539f71b4c5 100644 --- a/x/gov/client/utils/query_test.go +++ b/x/gov/client/utils/query_test.go @@ -54,7 +54,7 @@ func (mock TxSearchMock) Block(ctx context.Context, height *int64) (*coretypes.R } func TestGetPaginatedVotes(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig(gov.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(gov.AppModule{}) type testCase struct { description string diff --git a/x/gov/depinject.go b/x/gov/depinject.go index 40f2c9f30be5..99bf5e3bf75e 100644 --- a/x/gov/depinject.go +++ b/x/gov/depinject.go @@ -14,6 +14,7 @@ import ( "cosmossdk.io/depinject" "cosmossdk.io/depinject/appconfig" authtypes "cosmossdk.io/x/auth/types" + govclient "cosmossdk.io/x/gov/client" "cosmossdk.io/x/gov/keeper" govtypes "cosmossdk.io/x/gov/types" "cosmossdk.io/x/gov/types/v1beta1" @@ -37,11 +38,12 @@ func init() { type ModuleInputs struct { depinject.In - Config *modulev1.Module - Cdc codec.Codec - StoreService store.KVStoreService - ModuleKey depinject.OwnModuleKey - MsgServiceRouter baseapp.MessageRouter + Config *modulev1.Module + Cdc codec.Codec + StoreService store.KVStoreService + ModuleKey depinject.OwnModuleKey + MsgServiceRouter baseapp.MessageRouter + LegacyProposalHandler []govclient.ProposalHandler `optional:"true"` AccountKeeper govtypes.AccountKeeper BankKeeper govtypes.BankKeeper @@ -68,6 +70,9 @@ func ProvideModule(in ModuleInputs) ModuleOutputs { if in.Config.MaxSummaryLen != 0 { defaultConfig.MaxSummaryLen = in.Config.MaxSummaryLen } + if in.LegacyProposalHandler == nil { + in.LegacyProposalHandler = []govclient.ProposalHandler{} + } // default to governance authority if not provided authority := authtypes.NewModuleAddress(govtypes.ModuleName) @@ -86,7 +91,7 @@ func ProvideModule(in ModuleInputs) ModuleOutputs { defaultConfig, authority.String(), ) - m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper, in.PoolKeeper) + m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper, in.PoolKeeper, in.LegacyProposalHandler...) hr := v1beta1.HandlerRoute{Handler: v1beta1.ProposalHandler, RouteKey: govtypes.RouterKey} return ModuleOutputs{Module: m, Keeper: k, HandlerRoute: hr} diff --git a/x/gov/migrations/v5/store_test.go b/x/gov/migrations/v5/store_test.go index fbdd415591f8..c84ee38e0a34 100644 --- a/x/gov/migrations/v5/store_test.go +++ b/x/gov/migrations/v5/store_test.go @@ -19,7 +19,7 @@ import ( ) func TestMigrateStore(t *testing.T) { - cdc := moduletestutil.MakeTestEncodingConfig(gov.AppModuleBasic{}, bank.AppModuleBasic{}).Codec + cdc := moduletestutil.MakeTestEncodingConfig(gov.AppModule{}, bank.AppModule{}).Codec govKey := storetypes.NewKVStoreKey("gov") ctx := testutil.DefaultContext(govKey, storetypes.NewTransientStoreKey("transient_test")) store := ctx.KVStore(govKey) diff --git a/x/gov/migrations/v6/store_test.go b/x/gov/migrations/v6/store_test.go index e4a784f7fb7d..f356f59cca43 100644 --- a/x/gov/migrations/v6/store_test.go +++ b/x/gov/migrations/v6/store_test.go @@ -19,7 +19,7 @@ import ( ) func TestMigrateStore(t *testing.T) { - cdc := moduletestutil.MakeTestEncodingConfig(gov.AppModuleBasic{}).Codec + cdc := moduletestutil.MakeTestEncodingConfig(gov.AppModule{}).Codec govKey := storetypes.NewKVStoreKey("gov") ctx := testutil.DefaultContext(govKey, storetypes.NewTransientStoreKey("transient_test")) storeService := runtime.NewKVStoreService(govKey) diff --git a/x/gov/module.go b/x/gov/module.go index 8f42af98a43b..85c95353513a 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -9,7 +9,6 @@ import ( "github.com/spf13/cobra" "google.golang.org/grpc" - "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" govclient "cosmossdk.io/x/gov/client" "cosmossdk.io/x/gov/client/cli" @@ -30,10 +29,13 @@ import ( const ConsensusVersion = 6 var ( - _ module.AppModuleBasic = AppModuleBasic{} - _ module.AppModuleSimulation = AppModule{} - _ module.HasGenesis = AppModule{} - _ module.HasInvariants = AppModule{} + _ module.HasName = AppModule{} + _ module.HasAminoCodec = AppModule{} + _ module.HasGRPCGateway = AppModule{} + _ module.HasRegisterInterfaces = AppModule{} + _ module.AppModuleSimulation = AppModule{} + _ module.HasGenesis = AppModule{} + _ module.HasInvariants = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasEndBlocker = AppModule{} @@ -41,49 +43,49 @@ var ( _ appmodule.HasMigrations = AppModule{} ) -// AppModuleBasic defines the basic application module used by the gov module. -type AppModuleBasic struct { +// AppModule implements an application module for the gov module. +type AppModule struct { cdc codec.Codec - legacyProposalHandlers []govclient.ProposalHandler // legacy proposal handlers which live in governance cli and rest - ac address.Codec + legacyProposalHandlers []govclient.ProposalHandler + + keeper *keeper.Keeper + accountKeeper govtypes.AccountKeeper + bankKeeper govtypes.BankKeeper + poolKeeper govtypes.PoolKeeper } -// NewAppModuleBasic creates a new AppModuleBasic object -func NewAppModuleBasic(legacyProposalHandlers []govclient.ProposalHandler) AppModuleBasic { - return AppModuleBasic{ +// NewAppModule creates a new AppModule object +func NewAppModule( + cdc codec.Codec, keeper *keeper.Keeper, + ak govtypes.AccountKeeper, bk govtypes.BankKeeper, + pk govtypes.PoolKeeper, legacyProposalHandlers ...govclient.ProposalHandler, +) AppModule { + return AppModule{ + cdc: cdc, legacyProposalHandlers: legacyProposalHandlers, + keeper: keeper, + accountKeeper: ak, + bankKeeper: bk, + poolKeeper: pk, } } +// IsAppModule implements the appmodule.AppModule interface. +func (am AppModule) IsAppModule() {} + // Name returns the gov module's name. -func (AppModuleBasic) Name() string { +func (AppModule) Name() string { return govtypes.ModuleName } // RegisterLegacyAminoCodec registers the gov module's types for the given codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { +func (AppModule) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { v1beta1.RegisterLegacyAminoCodec(cdc) v1.RegisterLegacyAminoCodec(cdc) } -// DefaultGenesis returns default genesis state as raw bytes for the gov -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(v1.DefaultGenesisState()) -} - -// ValidateGenesis performs genesis state validation for the gov module. -func (am AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var data v1.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { - return fmt.Errorf("failed to unmarshal %s genesis state: %w", govtypes.ModuleName, err) - } - - return v1.ValidateGenesis(am.ac, &data) -} - // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the gov module. -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { +func (AppModule) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { if err := v1.RegisterQueryHandlerClient(context.Background(), mux, v1.NewQueryClient(clientCtx)); err != nil { panic(err) } @@ -93,8 +95,8 @@ func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *g } // GetTxCmd returns the root tx command for the gov module. -func (ab AppModuleBasic) GetTxCmd() *cobra.Command { - legacyProposalCLIHandlers := getProposalCLIHandlers(ab.legacyProposalHandlers) +func (am AppModule) GetTxCmd() *cobra.Command { + legacyProposalCLIHandlers := getProposalCLIHandlers(am.legacyProposalHandlers) return cli.NewTxCmd(legacyProposalCLIHandlers) } @@ -108,38 +110,11 @@ func getProposalCLIHandlers(handlers []govclient.ProposalHandler) []*cobra.Comma } // RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { +func (AppModule) RegisterInterfaces(registry codectypes.InterfaceRegistry) { v1.RegisterInterfaces(registry) v1beta1.RegisterInterfaces(registry) } -// AppModule implements an application module for the gov module. -type AppModule struct { - AppModuleBasic - - keeper *keeper.Keeper - accountKeeper govtypes.AccountKeeper - bankKeeper govtypes.BankKeeper - poolKeeper govtypes.PoolKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule( - cdc codec.Codec, keeper *keeper.Keeper, - ak govtypes.AccountKeeper, bk govtypes.BankKeeper, pk govtypes.PoolKeeper, -) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc, ac: ak.AddressCodec()}, - keeper: keeper, - accountKeeper: ak, - bankKeeper: bk, - poolKeeper: pk, - } -} - -// IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() {} - // RegisterInvariants registers module invariants func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { keeper.RegisterInvariants(ir, am.keeper, am.bankKeeper) @@ -157,6 +132,7 @@ func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { return nil } +// RegisterMigrations registers module migrations func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { m := keeper.NewMigrator(am.keeper) if err := mr.Register(govtypes.ModuleName, 1, m.Migrate1to2); err != nil { @@ -182,16 +158,29 @@ func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { return nil } -// InitGenesis performs genesis initialization for the gov module. It returns -// no validator updates. +// 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()) +} + +// ValidateGenesis performs genesis state validation for the gov module. +func (am AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { + var data v1.GenesisState + if err := cdc.UnmarshalJSON(bz, &data); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", govtypes.ModuleName, err) + } + + return v1.ValidateGenesis(am.accountKeeper.AddressCodec(), &data) +} + +// InitGenesis performs genesis initialization for the gov module. func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { var genesisState v1.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) InitGenesis(ctx, am.accountKeeper, am.bankKeeper, am.keeper, &genesisState) } -// ExportGenesis returns the exported genesis state as raw bytes for the gov -// module. +// 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 { gs, err := ExportGenesis(ctx, am.keeper) if err != nil { @@ -200,11 +189,10 @@ func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json return cdc.MustMarshalJSON(gs) } -// ConsensusVersion implements AppModule/ConsensusVersion. +// ConsensusVersion implements HasConsensusVersion func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } -// EndBlock returns the end blocker for the gov module. It returns no validator -// updates. +// EndBlock returns the end blocker for the gov module. func (am AppModule) EndBlock(ctx context.Context) error { c := sdk.UnwrapSDKContext(ctx) return EndBlocker(c, am.keeper) diff --git a/x/group/client/cli/tx.go b/x/group/client/cli/tx.go index 4a63623b4ddb..09b62061aa9b 100644 --- a/x/group/client/cli/tx.go +++ b/x/group/client/cli/tx.go @@ -7,7 +7,6 @@ import ( "github.com/spf13/cobra" - "cosmossdk.io/core/address" "cosmossdk.io/x/group" "cosmossdk.io/x/group/internal/math" @@ -26,7 +25,7 @@ const ( var errZeroGroupID = errors.New("group id cannot be 0") // TxCmd returns a root CLI command handler for all x/group transaction commands. -func TxCmd(name string, ac address.Codec) *cobra.Command { +func TxCmd(name string) *cobra.Command { txCmd := &cobra.Command{ Use: name, Short: "Group transaction subcommands", @@ -40,7 +39,7 @@ func TxCmd(name string, ac address.Codec) *cobra.Command { MsgUpdateGroupMembersCmd(), MsgCreateGroupWithPolicyCmd(), MsgCreateGroupPolicyCmd(), - MsgUpdateGroupPolicyDecisionPolicyCmd(ac), + MsgUpdateGroupPolicyDecisionPolicyCmd(), MsgSubmitProposalCmd(), NewCmdDraftProposal(), ) @@ -373,7 +372,7 @@ Here, we can use percentage decision policy when needed, where 0 < percentage <= // MsgUpdateGroupPolicyDecisionPolicyCmd creates a CLI command for Msg/UpdateGroupPolicyDecisionPolicy. // // This command is being handled better here, not converting to autocli -func MsgUpdateGroupPolicyDecisionPolicyCmd(ac address.Codec) *cobra.Command { +func MsgUpdateGroupPolicyDecisionPolicyCmd() *cobra.Command { cmd := &cobra.Command{ Use: "update-group-policy-decision-policy [admin] [group-policy-account] [decision-policy-json-file]", Short: "Update a group policy's decision policy", @@ -394,7 +393,7 @@ func MsgUpdateGroupPolicyDecisionPolicyCmd(ac address.Codec) *cobra.Command { return err } - accountAddress, err := ac.StringToBytes(args[1]) + accountAddress, err := clientCtx.AddressCodec.StringToBytes(args[1]) if err != nil { return err } diff --git a/x/group/client/cli/tx_test.go b/x/group/client/cli/tx_test.go index b3518e366837..d46599c17634 100644 --- a/x/group/client/cli/tx_test.go +++ b/x/group/client/cli/tx_test.go @@ -49,7 +49,7 @@ func TestCLITestSuite(t *testing.T) { } func (s *CLITestSuite) SetupSuite() { - s.encCfg = testutilmod.MakeTestEncodingConfig(groupmodule.AppModuleBasic{}) + s.encCfg = testutilmod.MakeTestEncodingConfig(groupmodule.AppModule{}) s.kr = keyring.NewInMemory(s.encCfg.Codec) s.baseCtx = client.Context{}. WithKeyring(s.kr). @@ -623,7 +623,7 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyDecisionPolicy() { thresholdDecisionPolicy := testutil.WriteToNewTempFile(s.T(), `{"@type":"/cosmos.group.v1.ThresholdDecisionPolicy", "threshold":"1", "windows":{"voting_period":"40000s"}}`) percentageDecisionPolicy := testutil.WriteToNewTempFile(s.T(), `{"@type":"/cosmos.group.v1.PercentageDecisionPolicy", "percentage":"0.5", "windows":{"voting_period":"40000s"}}`) - cmd := groupcli.MsgUpdateGroupPolicyDecisionPolicyCmd(addresscodec.NewBech32Codec("cosmos")) + cmd := groupcli.MsgUpdateGroupPolicyDecisionPolicyCmd() cmd.SetOutput(io.Discard) testCases := []struct { diff --git a/x/group/keeper/genesis_test.go b/x/group/keeper/genesis_test.go index 88488eccd3dc..412f5db64cb3 100644 --- a/x/group/keeper/genesis_test.go +++ b/x/group/keeper/genesis_test.go @@ -52,7 +52,7 @@ func (s *GenesisTestSuite) SetupTest() { key := storetypes.NewKVStoreKey(group.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModule{}) env := runtime.NewEnvironment(storeService, log.NewNopLogger()) ctrl := gomock.NewController(s.T()) diff --git a/x/group/keeper/grpc_query_test.go b/x/group/keeper/grpc_query_test.go index 545301177dba..4754d73e5703 100644 --- a/x/group/keeper/grpc_query_test.go +++ b/x/group/keeper/grpc_query_test.go @@ -45,7 +45,7 @@ func initKeeper(t *testing.T) *fixture { key := storetypes.NewKVStoreKey(group.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModule{}) ctx := testCtx.Ctx diff --git a/x/group/keeper/keeper_test.go b/x/group/keeper/keeper_test.go index 860c80738662..7fde6bd60109 100644 --- a/x/group/keeper/keeper_test.go +++ b/x/group/keeper/keeper_test.go @@ -55,7 +55,7 @@ func (s *TestSuite) SetupTest() { storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModuleBasic{}, bank.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModule{}, bank.AppModule{}) s.addrs = simtestutil.CreateIncrementalAccounts(6) env := runtime.NewEnvironment(storeService, log.NewNopLogger()) diff --git a/x/group/migrations/v2/migrate_test.go b/x/group/migrations/v2/migrate_test.go index b83c014cd9ee..098586580620 100644 --- a/x/group/migrations/v2/migrate_test.go +++ b/x/group/migrations/v2/migrate_test.go @@ -34,7 +34,7 @@ var ( ) func TestMigrate(t *testing.T) { - cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}, groupmodule.AppModuleBasic{}).Codec + cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModule{}, groupmodule.AppModule{}).Codec storeKey := storetypes.NewKVStoreKey(v2.ModuleName) storeService := runtime.NewKVStoreService(storeKey) tKey := storetypes.NewTransientStoreKey("transient_test") diff --git a/x/group/module/module.go b/x/group/module/module.go index c756aa3b0938..176ef28cf00a 100644 --- a/x/group/module/module.go +++ b/x/group/module/module.go @@ -9,7 +9,6 @@ import ( "github.com/spf13/cobra" "google.golang.org/grpc" - "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" "cosmossdk.io/x/group" "cosmossdk.io/x/group/client/cli" @@ -28,10 +27,13 @@ import ( const ConsensusVersion = 2 var ( - _ module.AppModuleBasic = AppModule{} - _ module.AppModuleSimulation = AppModule{} - _ module.HasGenesis = AppModule{} - _ module.HasInvariants = AppModule{} + _ module.HasName = AppModule{} + _ module.HasAminoCodec = AppModule{} + _ module.HasGRPCGateway = AppModule{} + _ module.HasRegisterInterfaces = AppModule{} + _ module.AppModuleSimulation = AppModule{} + _ module.HasGenesis = AppModule{} + _ module.HasInvariants = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasEndBlocker = AppModule{} @@ -40,71 +42,52 @@ var ( ) type AppModule struct { - AppModuleBasic + cdc codec.Codec + registry cdctypes.InterfaceRegistry + keeper keeper.Keeper bankKeeper group.BankKeeper accKeeper group.AccountKeeper - registry cdctypes.InterfaceRegistry } // NewAppModule creates a new AppModule object func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, ak group.AccountKeeper, bk group.BankKeeper, registry cdctypes.InterfaceRegistry) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc, ac: ak.AddressCodec()}, - keeper: keeper, - bankKeeper: bk, - accKeeper: ak, - registry: registry, + cdc: cdc, + keeper: keeper, + bankKeeper: bk, + accKeeper: ak, + registry: registry, } } // IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() {} - -type AppModuleBasic struct { - cdc codec.Codec - ac address.Codec -} +func (AppModule) IsAppModule() {} // Name returns the group module's name. -func (AppModuleBasic) Name() string { +func (am AppModule) Name() string { return group.ModuleName } -// DefaultGenesis returns default genesis state as raw bytes for the group -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(group.NewGenesisState()) -} - -// ValidateGenesis performs genesis state validation for the group module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { - var data group.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { - return fmt.Errorf("failed to unmarshal %s genesis state: %w", group.ModuleName, err) - } - return data.Validate() -} - // GetTxCmd returns the transaction commands for the group module -func (a AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.TxCmd(a.Name(), a.ac) +func (am AppModule) GetTxCmd() *cobra.Command { + return cli.TxCmd(am.Name()) } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the group module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx sdkclient.Context, mux *gwruntime.ServeMux) { +func (am AppModule) RegisterGRPCGatewayRoutes(clientCtx sdkclient.Context, mux *gwruntime.ServeMux) { if err := group.RegisterQueryHandlerClient(context.Background(), mux, group.NewQueryClient(clientCtx)); err != nil { panic(err) } } // RegisterInterfaces registers the group module's interface types -func (AppModuleBasic) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { +func (AppModule) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { group.RegisterInterfaces(registry) } // RegisterLegacyAminoCodec registers the group module's types for the given codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { +func (AppModule) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { group.RegisterLegacyAminoCodec(cdc) } @@ -113,19 +96,6 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { keeper.RegisterInvariants(ir, am.keeper) } -// InitGenesis performs genesis initialization for the group module. It returns -// no validator updates. -func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { - am.keeper.InitGenesis(ctx, 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) -} - // RegisterServices registers module services. func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { group.RegisterMsgServer(registrar, am.keeper) @@ -134,6 +104,7 @@ func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { return nil } +// RegisterMigrations registers module migrations func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { m := keeper.NewMigrator(am.keeper) if err := mr.Register(group.ModuleName, 1, m.Migrate1to2); err != nil { @@ -143,7 +114,7 @@ func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { return nil } -// ConsensusVersion implements AppModule/ConsensusVersion. +// ConsensusVersion implements HasConsensusVersion func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } // EndBlock implements the group module's EndBlock. @@ -151,6 +122,31 @@ func (am AppModule) EndBlock(ctx context.Context) error { return am.keeper.EndBlocker(ctx) } +// 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()) +} + +// ValidateGenesis performs genesis state validation for the group module. +func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { + var data group.GenesisState + if err := 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) +} + +// 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) +} + // GenerateGenesisState creates a randomized GenState of the group module. func (AppModule) GenerateGenesisState(simState *module.SimulationState) { simulation.RandomizedGenState(simState) diff --git a/x/group/proposal_test.go b/x/group/proposal_test.go index 3f2fa73a6f81..d7a5748d5f53 100644 --- a/x/group/proposal_test.go +++ b/x/group/proposal_test.go @@ -16,7 +16,7 @@ import ( // This test serves as a showcase that we need to be careful when unmarshalling // multiple times into the same reference. func TestGogoUnmarshalProposal(t *testing.T) { - encodingConfig := moduletestutil.MakeTestEncodingConfig(module.AppModuleBasic{}) + encodingConfig := moduletestutil.MakeTestEncodingConfig(module.AppModule{}) cdc := encodingConfig.Codec p1 := group.Proposal{Proposers: []string{"foo"}} diff --git a/x/group/simulation/decoder_test.go b/x/group/simulation/decoder_test.go index b2f57fb4f3b3..303490e02b8a 100644 --- a/x/group/simulation/decoder_test.go +++ b/x/group/simulation/decoder_test.go @@ -18,7 +18,7 @@ import ( ) func TestDecodeStore(t *testing.T) { - encodingConfig := moduletestutil.MakeTestEncodingConfig(module.AppModuleBasic{}) + encodingConfig := moduletestutil.MakeTestEncodingConfig(module.AppModule{}) cdc := encodingConfig.Codec dec := simulation.NewDecodeStore(cdc) diff --git a/x/group/simulation/genesis_test.go b/x/group/simulation/genesis_test.go index 5a5c7afa145f..7bc06aa2ccc7 100644 --- a/x/group/simulation/genesis_test.go +++ b/x/group/simulation/genesis_test.go @@ -19,7 +19,7 @@ import ( ) func TestRandomizedGenState(t *testing.T) { - encodingConfig := moduletestutil.MakeTestEncodingConfig(groupmodule.AppModuleBasic{}, bank.AppModuleBasic{}) + encodingConfig := moduletestutil.MakeTestEncodingConfig(groupmodule.AppModule{}, bank.AppModule{}) cdc := encodingConfig.Codec s := rand.NewSource(1) diff --git a/x/mint/keeper/genesis_test.go b/x/mint/keeper/genesis_test.go index c46260c73590..c21dbc4fc421 100644 --- a/x/mint/keeper/genesis_test.go +++ b/x/mint/keeper/genesis_test.go @@ -42,7 +42,7 @@ func TestGenesisTestSuite(t *testing.T) { func (s *GenesisTestSuite) SetupTest() { key := storetypes.NewKVStoreKey(types.StoreKey) testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) - encCfg := moduletestutil.MakeTestEncodingConfig(mint.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(mint.AppModule{}) // gomock initializations ctrl := gomock.NewController(s.T()) diff --git a/x/mint/keeper/grpc_query_test.go b/x/mint/keeper/grpc_query_test.go index 7b06a894de36..5b190ae5d444 100644 --- a/x/mint/keeper/grpc_query_test.go +++ b/x/mint/keeper/grpc_query_test.go @@ -31,7 +31,7 @@ type MintTestSuite struct { } func (suite *MintTestSuite) SetupTest() { - encCfg := moduletestutil.MakeTestEncodingConfig(mint.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(mint.AppModule{}) key := storetypes.NewKVStoreKey(types.StoreKey) storeService := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) testCtx := testutil.DefaultContextWithDB(suite.T(), key, storetypes.NewTransientStoreKey("transient_test")) diff --git a/x/mint/keeper/keeper_test.go b/x/mint/keeper/keeper_test.go index 02b96a285659..0f22cb763ae1 100644 --- a/x/mint/keeper/keeper_test.go +++ b/x/mint/keeper/keeper_test.go @@ -38,7 +38,7 @@ func TestKeeperTestSuite(t *testing.T) { } func (s *IntegrationTestSuite) SetupTest() { - encCfg := moduletestutil.MakeTestEncodingConfig(mint.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(mint.AppModule{}) key := storetypes.NewKVStoreKey(types.StoreKey) storeService := runtime.NewKVStoreService(key) env := runtime.NewEnvironment(storeService, log.NewNopLogger()) diff --git a/x/mint/module.go b/x/mint/module.go index 64fcb9356085..3f8e9fbabfb8 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -24,9 +24,12 @@ import ( const ConsensusVersion = 2 var ( - _ module.AppModuleBasic = AppModule{} - _ module.AppModuleSimulation = AppModule{} - _ module.HasGenesis = AppModule{} + _ module.HasName = AppModule{} + _ module.HasAminoCodec = AppModule{} + _ module.HasGRPCGateway = AppModule{} + _ module.HasRegisterInterfaces = AppModule{} + _ module.AppModuleSimulation = AppModule{} + _ module.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasBeginBlocker = AppModule{} @@ -34,53 +37,9 @@ var ( _ appmodule.HasMigrations = AppModule{} ) -// AppModuleBasic defines the basic application module used by the mint module. -type AppModuleBasic struct { - cdc codec.Codec -} - -// Name returns the mint module's name. -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec registers the mint module's types on the given LegacyAmino codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// RegisterInterfaces registers the module's interface types -func (b AppModuleBasic) RegisterInterfaces(r cdctypes.InterfaceRegistry) { - types.RegisterInterfaces(r) -} - -// DefaultGenesis returns default genesis state as raw bytes for the mint -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) -} - -// ValidateGenesis performs genesis state validation for the mint module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var data types.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { - return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) - } - - return types.ValidateGenesis(data) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the mint module. -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { - if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - // AppModule implements an application module for the mint module. type AppModule struct { - AppModuleBasic - + cdc codec.Codec keeper keeper.Keeper authKeeper types.AccountKeeper @@ -89,8 +48,8 @@ type AppModule struct { inflationCalculator types.InflationCalculationFn } -// NewAppModule creates a new AppModule object. If the InflationCalculationFn -// argument is nil, then the SDK's default inflation function will be used. +// NewAppModule creates a new AppModule object. +// If the InflationCalculationFn argument is nil, then the SDK's default inflation function will be used. func NewAppModule( cdc codec.Codec, keeper keeper.Keeper, @@ -102,7 +61,7 @@ func NewAppModule( } return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc}, + cdc: cdc, keeper: keeper, authKeeper: ak, inflationCalculator: ic, @@ -110,7 +69,29 @@ func NewAppModule( } // IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() {} +func (AppModule) IsAppModule() {} + +// Name returns the mint module's name. +func (AppModule) Name() string { + return types.ModuleName +} + +// RegisterLegacyAminoCodec registers the mint module's types on the given LegacyAmino codec. +func (AppModule) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + types.RegisterLegacyAminoCodec(cdc) +} + +// RegisterInterfaces registers the module's interface types +func (AppModule) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { + types.RegisterInterfaces(registry) +} + +// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the mint module. +func (AppModule) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { + if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { + panic(err) + } +} // RegisterServices registers module services. func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { @@ -131,8 +112,22 @@ func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { return nil } -// InitGenesis performs genesis initialization for the mint module. It returns -// no validator updates. +// 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()) +} + +// ValidateGenesis performs genesis state validation for the mint module. +func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { + var data types.GenesisState + if err := cdc.UnmarshalJSON(bz, &data); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + + return types.ValidateGenesis(data) +} + +// InitGenesis performs genesis initialization for the mint module. func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { var genesisState types.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) @@ -147,7 +142,7 @@ func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json return cdc.MustMarshalJSON(gs) } -// ConsensusVersion implements AppModule/ConsensusVersion. +// ConsensusVersion implements HasConsensusVersion func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } // BeginBlock returns the begin blocker for the mint module. diff --git a/x/mint/simulation/genesis_test.go b/x/mint/simulation/genesis_test.go index 7360319165ac..a4a79ef3f31b 100644 --- a/x/mint/simulation/genesis_test.go +++ b/x/mint/simulation/genesis_test.go @@ -21,7 +21,7 @@ import ( // TestRandomizedGenState tests the normal scenario of applying RandomizedGenState. // Abonormal scenarios are not tested here. func TestRandomizedGenState(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig(mint.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(mint.AppModule{}) s := rand.NewSource(1) r := rand.New(s) @@ -60,7 +60,7 @@ func TestRandomizedGenState(t *testing.T) { // TestRandomizedGenState tests abnormal scenarios of applying RandomizedGenState. func TestRandomizedGenState1(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig(mint.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(mint.AppModule{}) s := rand.NewSource(1) r := rand.New(s) diff --git a/x/nft/keeper/class.go b/x/nft/keeper/class.go index 1e73a27beec6..fc4145897df8 100644 --- a/x/nft/keeper/class.go +++ b/x/nft/keeper/class.go @@ -19,7 +19,7 @@ func (k Keeper) SaveClass(ctx context.Context, class nft.Class) error { if err != nil { return errors.Wrap(err, "Marshal nft.Class failed") } - store := k.storeService.OpenKVStore(ctx) + store := k.env.KVStoreService.OpenKVStore(ctx) return store.Set(classStoreKey(class.Id), bz) } @@ -32,13 +32,13 @@ func (k Keeper) UpdateClass(ctx context.Context, class nft.Class) error { if err != nil { return errors.Wrap(err, "Marshal nft.Class failed") } - store := k.storeService.OpenKVStore(ctx) + store := k.env.KVStoreService.OpenKVStore(ctx) return store.Set(classStoreKey(class.Id), bz) } // GetClass defines a method for returning the class information of the specified id func (k Keeper) GetClass(ctx context.Context, classID string) (nft.Class, bool) { - store := k.storeService.OpenKVStore(ctx) + store := k.env.KVStoreService.OpenKVStore(ctx) var class nft.Class bz, err := store.Get(classStoreKey(classID)) @@ -55,7 +55,7 @@ func (k Keeper) GetClass(ctx context.Context, classID string) (nft.Class, bool) // GetClasses defines a method for returning all classes information func (k Keeper) GetClasses(ctx context.Context) (classes []*nft.Class) { - store := k.storeService.OpenKVStore(ctx) + store := k.env.KVStoreService.OpenKVStore(ctx) iterator := storetypes.KVStorePrefixIterator(runtime.KVStoreAdapter(store), ClassKey) defer iterator.Close() for ; iterator.Valid(); iterator.Next() { @@ -68,7 +68,7 @@ func (k Keeper) GetClasses(ctx context.Context) (classes []*nft.Class) { // HasClass determines whether the specified classID exist func (k Keeper) HasClass(ctx context.Context, classID string) bool { - store := k.storeService.OpenKVStore(ctx) + store := k.env.KVStoreService.OpenKVStore(ctx) has, err := store.Has(classStoreKey(classID)) if err != nil { panic(err) diff --git a/x/nft/keeper/grpc_query.go b/x/nft/keeper/grpc_query.go index 5da5116a4c5f..9e3cfc71281c 100644 --- a/x/nft/keeper/grpc_query.go +++ b/x/nft/keeper/grpc_query.go @@ -239,7 +239,7 @@ func (k Keeper) Classes(ctx context.Context, r *nft.QueryClassesRequest) (*nft.Q return nil, sdkerrors.ErrInvalidRequest.Wrap("empty request") } - store := k.storeService.OpenKVStore(ctx) + store := k.env.KVStoreService.OpenKVStore(ctx) classStore := prefix.NewStore(runtime.KVStoreAdapter(store), ClassKey) var classes []*nft.Class diff --git a/x/nft/keeper/keeper.go b/x/nft/keeper/keeper.go index 54c587415101..a6a03974b80f 100644 --- a/x/nft/keeper/keeper.go +++ b/x/nft/keeper/keeper.go @@ -3,8 +3,6 @@ package keeper import ( "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" - "cosmossdk.io/core/event" - store "cosmossdk.io/core/store" "cosmossdk.io/x/nft" "github.com/cosmos/cosmos-sdk/codec" @@ -12,29 +10,25 @@ import ( // Keeper of the nft store type Keeper struct { - cdc codec.BinaryCodec - storeService store.KVStoreService - bk nft.BankKeeper - ac address.Codec - eventService event.Service + cdc codec.BinaryCodec + bk nft.BankKeeper + ac address.Codec + env appmodule.Environment } // NewKeeper creates a new nft Keeper instance func NewKeeper(env appmodule.Environment, cdc codec.BinaryCodec, ak nft.AccountKeeper, bk nft.BankKeeper, ) Keeper { - storeService := env.KVStoreService - // ensure nft module account is set if addr := ak.GetModuleAddress(nft.ModuleName); addr == nil { panic("the nft module account has not been set") } return Keeper{ - cdc: cdc, - storeService: storeService, - eventService: env.EventService, - bk: bk, - ac: ak.AddressCodec(), + cdc: cdc, + env: env, + bk: bk, + ac: ak.AddressCodec(), } } diff --git a/x/nft/keeper/keeper_test.go b/x/nft/keeper/keeper_test.go index b685cdbc73f7..2332a68b38e1 100644 --- a/x/nft/keeper/keeper_test.go +++ b/x/nft/keeper/keeper_test.go @@ -52,7 +52,7 @@ type TestSuite struct { func (s *TestSuite) SetupTest() { // suite setup s.addrs = simtestutil.CreateIncrementalAccounts(3) - s.encCfg = moduletestutil.MakeTestEncodingConfig(module.AppModuleBasic{}) + s.encCfg = moduletestutil.MakeTestEncodingConfig(module.AppModule{}) key := storetypes.NewKVStoreKey(nft.StoreKey) testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) diff --git a/x/nft/keeper/msg_server.go b/x/nft/keeper/msg_server.go index 98ba89018023..1f6f3cd3ff73 100644 --- a/x/nft/keeper/msg_server.go +++ b/x/nft/keeper/msg_server.go @@ -41,14 +41,12 @@ func (k Keeper) Send(ctx context.Context, msg *nft.MsgSend) (*nft.MsgSendRespons return nil, err } - err = k.eventService.EventManager(ctx).Emit(&nft.EventSend{ + if err = k.env.EventService.EventManager(ctx).Emit(&nft.EventSend{ ClassId: msg.ClassId, Id: msg.Id, Sender: msg.Sender, Receiver: msg.Receiver, - }) - - if err != nil { + }); err != nil { return nil, err } diff --git a/x/nft/keeper/nft.go b/x/nft/keeper/nft.go index cad95dde72b6..1381ad7e82dd 100644 --- a/x/nft/keeper/nft.go +++ b/x/nft/keeper/nft.go @@ -37,17 +37,11 @@ func (k Keeper) mintWithNoCheck(ctx context.Context, token nft.NFT, receiver sdk return err } - err = k.eventService.EventManager(ctx).Emit(&nft.EventMint{ + return k.env.EventService.EventManager(ctx).Emit(&nft.EventMint{ ClassId: token.ClassId, Id: token.Id, Owner: recStr, }) - - if err != nil { - return err - } - - return nil } // Burn defines a method for burning a nft from a specific account. @@ -84,17 +78,11 @@ func (k Keeper) burnWithNoCheck(ctx context.Context, classID, nftID string) erro return err } - err = k.eventService.EventManager(ctx).Emit(&nft.EventBurn{ + return k.env.EventService.EventManager(ctx).Emit(&nft.EventBurn{ ClassId: classID, Id: nftID, Owner: ownerStr, }) - - if err != nil { - return err - } - - return nil } // Update defines a method for updating an exist nft @@ -195,7 +183,7 @@ func (k Keeper) GetNFTsOfClass(ctx context.Context, classID string) (nfts []nft. // GetOwner returns the owner information of the specified nft func (k Keeper) GetOwner(ctx context.Context, classID, nftID string) sdk.AccAddress { - store := k.storeService.OpenKVStore(ctx) + store := k.env.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(ownerStoreKey(classID, nftID)) if err != nil { panic(err) @@ -211,7 +199,7 @@ func (k Keeper) GetBalance(ctx context.Context, classID string, owner sdk.AccAdd // GetTotalSupply returns the number of all nfts under the specified classID func (k Keeper) GetTotalSupply(ctx context.Context, classID string) uint64 { - store := k.storeService.OpenKVStore(ctx) + store := k.env.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(classTotalSupply(classID)) if err != nil { panic(err) @@ -232,7 +220,7 @@ func (k Keeper) setNFT(ctx context.Context, token nft.NFT) { } func (k Keeper) setOwner(ctx context.Context, classID, nftID string, owner sdk.AccAddress) { - store := k.storeService.OpenKVStore(ctx) + store := k.env.KVStoreService.OpenKVStore(ctx) err := store.Set(ownerStoreKey(classID, nftID), owner.Bytes()) if err != nil { panic(err) @@ -243,7 +231,7 @@ func (k Keeper) setOwner(ctx context.Context, classID, nftID string, owner sdk.A } func (k Keeper) deleteOwner(ctx context.Context, classID, nftID string, owner sdk.AccAddress) { - store := k.storeService.OpenKVStore(ctx) + store := k.env.KVStoreService.OpenKVStore(ctx) err := store.Delete(ownerStoreKey(classID, nftID)) if err != nil { panic(err) @@ -253,18 +241,18 @@ func (k Keeper) deleteOwner(ctx context.Context, classID, nftID string, owner sd } func (k Keeper) getNFTStore(ctx context.Context, classID string) prefix.Store { - store := k.storeService.OpenKVStore(ctx) + store := k.env.KVStoreService.OpenKVStore(ctx) return prefix.NewStore(runtime.KVStoreAdapter(store), nftStoreKey(classID)) } func (k Keeper) getClassStoreByOwner(ctx context.Context, owner sdk.AccAddress, classID string) prefix.Store { - store := k.storeService.OpenKVStore(ctx) + store := k.env.KVStoreService.OpenKVStore(ctx) key := nftOfClassByOwnerStoreKey(owner, classID) return prefix.NewStore(runtime.KVStoreAdapter(store), key) } func (k Keeper) prefixStoreNftOfClassByOwner(ctx context.Context, owner sdk.AccAddress) prefix.Store { - store := k.storeService.OpenKVStore(ctx) + store := k.env.KVStoreService.OpenKVStore(ctx) key := prefixNftOfClassByOwnerStoreKey(owner) return prefix.NewStore(runtime.KVStoreAdapter(store), key) } @@ -280,7 +268,7 @@ func (k Keeper) decrTotalSupply(ctx context.Context, classID string) { } func (k Keeper) updateTotalSupply(ctx context.Context, classID string, supply uint64) { - store := k.storeService.OpenKVStore(ctx) + store := k.env.KVStoreService.OpenKVStore(ctx) supplyKey := classTotalSupply(classID) err := store.Set(supplyKey, sdk.Uint64ToBigEndian(supply)) if err != nil { diff --git a/x/nft/module/module.go b/x/nft/module/module.go index 3173ede06b56..8f213b1305c9 100644 --- a/x/nft/module/module.go +++ b/x/nft/module/module.go @@ -7,7 +7,6 @@ import ( gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" "google.golang.org/grpc" - "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" "cosmossdk.io/errors" "cosmossdk.io/x/nft" @@ -22,21 +21,43 @@ import ( ) var ( - _ module.AppModuleBasic = AppModule{} - _ module.AppModuleSimulation = AppModule{} - _ module.HasGenesis = AppModule{} + _ module.HasName = AppModule{} + _ module.HasGRPCGateway = AppModule{} + _ module.HasRegisterInterfaces = AppModule{} + _ module.AppModuleSimulation = AppModule{} + _ module.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} ) -// AppModuleBasic defines the basic application module used by the nft module. -type AppModuleBasic struct { - cdc codec.Codec - ac address.Codec +const ConsensusVersion = 1 + +// AppModule implements the sdk.AppModule interface +type AppModule struct { + cdc codec.Codec + registry cdctypes.InterfaceRegistry + + keeper keeper.Keeper + accountKeeper nft.AccountKeeper + bankKeeper nft.BankKeeper } +// NewAppModule creates a new AppModule object +func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, ak nft.AccountKeeper, bk nft.BankKeeper, registry cdctypes.InterfaceRegistry) AppModule { + return AppModule{ + cdc: cdc, + keeper: keeper, + accountKeeper: ak, + bankKeeper: bk, + registry: registry, + } +} + +// IsAppModule implements the appmodule.AppModule interface. +func (AppModule) IsAppModule() {} + // Name returns the nft module's name. -func (AppModuleBasic) Name() string { +func (AppModule) Name() string { return nft.ModuleName } @@ -48,80 +69,48 @@ func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { return nil } -// RegisterLegacyAminoCodec registers the nft module's types for the given codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {} - // RegisterInterfaces registers the nft module's interface types -func (AppModuleBasic) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { +func (AppModule) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { nft.RegisterInterfaces(registry) } -// DefaultGenesis returns default genesis state as raw bytes for the nft -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(nft.DefaultGenesisState()) -} - -// ValidateGenesis performs genesis state validation for the nft module. -func (ab AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { - var data nft.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { - return errors.Wrapf(err, "failed to unmarshal %s genesis state", nft.ModuleName) - } - - return nft.ValidateGenesis(data, ab.ac) -} - // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the nft module. -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx sdkclient.Context, mux *gwruntime.ServeMux) { +func (AppModule) RegisterGRPCGatewayRoutes(clientCtx sdkclient.Context, mux *gwruntime.ServeMux) { if err := nft.RegisterQueryHandlerClient(context.Background(), mux, nft.NewQueryClient(clientCtx)); err != nil { panic(err) } } -// AppModule implements the sdk.AppModule interface -type AppModule struct { - AppModuleBasic - keeper keeper.Keeper - // TODO accountKeeper,bankKeeper will be replaced by query service - accountKeeper nft.AccountKeeper - bankKeeper nft.BankKeeper - registry cdctypes.InterfaceRegistry +// 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()) } -// NewAppModule creates a new AppModule object -func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, ak nft.AccountKeeper, bk nft.BankKeeper, registry cdctypes.InterfaceRegistry) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc, ac: ak.AddressCodec()}, - keeper: keeper, - accountKeeper: ak, - bankKeeper: bk, - registry: registry, +// ValidateGenesis performs genesis state validation for the nft module. +func (am AppModule) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { + var data nft.GenesisState + if err := cdc.UnmarshalJSON(bz, &data); err != nil { + return errors.Wrapf(err, "failed to unmarshal %s genesis state", nft.ModuleName) } -} -// IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() {} + return nft.ValidateGenesis(data, am.accountKeeper.AddressCodec()) +} -// InitGenesis performs genesis initialization for the nft module. It returns -// no validator updates. +// InitGenesis performs genesis initialization for the nft module. func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { var genesisState nft.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) am.keeper.InitGenesis(ctx, &genesisState) } -// ExportGenesis returns the exported genesis state as raw bytes for the nft -// module. +// 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 { gs := am.keeper.ExportGenesis(ctx) return cdc.MustMarshalJSON(gs) } -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { return 1 } - -// ____________________________________________________________________________ +// ConsensusVersion implements HasConsensusVersion +func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } // AppModuleSimulation functions diff --git a/x/nft/simulation/decoder_test.go b/x/nft/simulation/decoder_test.go index d3fff88a87a2..4c4b4a9941ec 100644 --- a/x/nft/simulation/decoder_test.go +++ b/x/nft/simulation/decoder_test.go @@ -23,7 +23,7 @@ var ( ) func TestDecodeStore(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModule{}) dec := simulation.NewDecodeStore(encCfg.Codec) class := nft.Class{ diff --git a/x/nft/simulation/genesis_test.go b/x/nft/simulation/genesis_test.go index a04511ed154a..cd82052df323 100644 --- a/x/nft/simulation/genesis_test.go +++ b/x/nft/simulation/genesis_test.go @@ -19,7 +19,7 @@ import ( ) func TestRandomizedGenState(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig(nftmodule.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(nftmodule.AppModule{}) s := rand.NewSource(1) r := rand.New(s) diff --git a/x/params/keeper/common_test.go b/x/params/keeper/common_test.go index 50115e50822e..2511b1e77eb3 100644 --- a/x/params/keeper/common_test.go +++ b/x/params/keeper/common_test.go @@ -12,7 +12,7 @@ import ( ) func testComponents() (*codec.LegacyAmino, sdk.Context, storetypes.StoreKey, storetypes.StoreKey, paramskeeper.Keeper) { - encodingConfig := moduletestutil.MakeTestEncodingConfig(params.AppModuleBasic{}) + encodingConfig := moduletestutil.MakeTestEncodingConfig(params.AppModule{}) cdc := encodingConfig.Codec legacyAmino := createTestCodec() diff --git a/x/params/keeper/keeper_test.go b/x/params/keeper/keeper_test.go index 52f8058bc8b0..382b5ed9e8f0 100644 --- a/x/params/keeper/keeper_test.go +++ b/x/params/keeper/keeper_test.go @@ -30,7 +30,7 @@ type KeeperTestSuite struct { } func (suite *KeeperTestSuite) SetupTest() { - encodingCfg := moduletestutil.MakeTestEncodingConfig(params.AppModuleBasic{}) + encodingCfg := moduletestutil.MakeTestEncodingConfig(params.AppModule{}) key := storetypes.NewKVStoreKey(types.StoreKey) tkey := storetypes.NewTransientStoreKey("params_transient_test") diff --git a/x/params/module.go b/x/params/module.go index 9ec3095c56a4..f919fc1ec16c 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -18,8 +18,11 @@ import ( ) var ( - _ module.AppModuleBasic = AppModule{} - _ module.AppModuleSimulation = AppModule{} + _ module.HasName = AppModule{} + _ module.HasAminoCodec = AppModule{} + _ module.HasGRPCGateway = AppModule{} + _ module.HasRegisterInterfaces = AppModule{} + _ module.AppModuleSimulation = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasServices = AppModule{} @@ -28,48 +31,43 @@ var ( // ConsensusVersion defines the current x/params module consensus version. const ConsensusVersion = 1 -// AppModuleBasic defines the basic application module used by the params module. -type AppModuleBasic struct{} +// AppModule implements an application module for the distribution module. +type AppModule struct { + keeper keeper.Keeper +} + +// NewAppModule creates a new AppModule object +func NewAppModule(k keeper.Keeper) AppModule { + return AppModule{ + keeper: k, + } +} + +// IsAppModule implements the appmodule.AppModule interface. +func (am AppModule) IsAppModule() {} // Name returns the params module's name. -func (AppModuleBasic) Name() string { +func (AppModule) Name() string { return proposal.ModuleName } // RegisterLegacyAminoCodec registers the params module's types on the given LegacyAmino codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { +func (AppModule) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { proposal.RegisterLegacyAminoCodec(cdc) } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the params module. -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { +func (AppModule) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { if err := proposal.RegisterQueryHandlerClient(context.Background(), mux, proposal.NewQueryClient(clientCtx)); err != nil { panic(err) } } -func (am AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { +// RegisterInterfaces registers the module's interface types +func (AppModule) RegisterInterfaces(registry codectypes.InterfaceRegistry) { proposal.RegisterInterfaces(registry) } -// AppModule implements an application module for the distribution module. -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(k keeper.Keeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: k, - } -} - -// IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() {} - // GenerateGenesisState performs a no-op. func (AppModule) GenerateGenesisState(simState *module.SimulationState) {} @@ -88,5 +86,5 @@ func (am AppModule) WeightedOperations(_ module.SimulationState) []simtypes.Weig return nil } -// ConsensusVersion implements AppModule/ConsensusVersion. +// ConsensusVersion implements HasConsensusVersion func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } diff --git a/x/params/types/subspace_test.go b/x/params/types/subspace_test.go index 81f8fb0c3555..f7aeeca28ca6 100644 --- a/x/params/types/subspace_test.go +++ b/x/params/types/subspace_test.go @@ -38,7 +38,7 @@ func (suite *SubspaceTestSuite) SetupTest() { ms.MountStoreWithDB(tkey, storetypes.StoreTypeTransient, db) suite.NoError(ms.LoadLatestVersion()) - encodingConfig := moduletestutil.MakeTestEncodingConfig(paramsmodule.AppModuleBasic{}) + encodingConfig := moduletestutil.MakeTestEncodingConfig(paramsmodule.AppModule{}) suite.cdc = encodingConfig.Codec suite.amino = encodingConfig.Amino diff --git a/x/protocolpool/module.go b/x/protocolpool/module.go index 35d36b027fe2..0257e69960eb 100644 --- a/x/protocolpool/module.go +++ b/x/protocolpool/module.go @@ -22,46 +22,74 @@ import ( const ConsensusVersion = 1 var ( - _ module.AppModuleBasic = 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{} + _ module.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasServices = AppModule{} ) -// AppModuleBasic defines the basic application module used by the pool module. -type AppModuleBasic struct { - cdc codec.Codec +// AppModule implements an application module for the pool module +type AppModule struct { + cdc codec.Codec + keeper keeper.Keeper + accountKeeper types.AccountKeeper + bankKeeper types.BankKeeper +} + +// NewAppModule creates a new AppModule object +func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, + accountKeeper types.AccountKeeper, bankKeeper types.BankKeeper, +) AppModule { + return AppModule{ + cdc: cdc, + keeper: keeper, + accountKeeper: accountKeeper, + bankKeeper: bankKeeper, + } } +// IsAppModule implements the appmodule.AppModule interface. +func (AppModule) IsAppModule() {} + // Name returns the pool module's name. -func (AppModuleBasic) Name() string { return types.ModuleName } +func (AppModule) Name() string { return types.ModuleName } // RegisterLegacyAminoCodec registers the pool module's types on the LegacyAmino codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {} +func (AppModule) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {} // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { +func (AppModule) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { panic(err) } } // RegisterInterfaces registers interfaces and implementations of the bank module. -func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { +func (AppModule) RegisterInterfaces(registry codectypes.InterfaceRegistry) { types.RegisterInterfaces(registry) } -// DefaultGenesis returns default genesis state as raw bytes for the protocolpool -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { +// RegisterServices registers module services. +func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { + types.RegisterMsgServer(registrar, keeper.NewMsgServerImpl(am.keeper)) + types.RegisterQueryServer(registrar, keeper.NewQuerier(am.keeper)) + + return nil +} + +// 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()) } // ValidateGenesis performs genesis state validation for the protocolpool module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { +func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { var data types.GenesisState if err := cdc.UnmarshalJSON(bz, &data); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) @@ -70,38 +98,6 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncod return types.ValidateGenesis(&data) } -// AppModule implements an application module for the pool module -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper -} - -// IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() {} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { - types.RegisterMsgServer(registrar, keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(registrar, keeper.NewQuerier(am.keeper)) - - return nil -} - -// NewAppModule creates a new AppModule object -func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, - accountKeeper types.AccountKeeper, bankKeeper types.BankKeeper, -) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc}, - keeper: keeper, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - } -} - // InitGenesis performs genesis initialization for the protocolpool module. func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { var genesisState types.GenesisState @@ -111,8 +107,7 @@ func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data j } } -// ExportGenesis returns the exported genesis state as raw bytes for the protocolpool -// module. +// 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 { gs, err := am.keeper.ExportGenesis(ctx) if err != nil { @@ -121,5 +116,5 @@ func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json return cdc.MustMarshalJSON(gs) } -// ConsensusVersion implements AppModule/ConsensusVersion. +// ConsensusVersion implements HasConsensusVersion func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } diff --git a/x/slashing/migrations/v4/migrate_test.go b/x/slashing/migrations/v4/migrate_test.go index 11e0e6b43893..de31d92e3e5e 100644 --- a/x/slashing/migrations/v4/migrate_test.go +++ b/x/slashing/migrations/v4/migrate_test.go @@ -20,7 +20,7 @@ import ( var consAddr = sdk.ConsAddress(sdk.AccAddress([]byte("addr1_______________"))) func TestMigrate(t *testing.T) { - cdc := moduletestutil.MakeTestEncodingConfig(slashing.AppModuleBasic{}).Codec + cdc := moduletestutil.MakeTestEncodingConfig(slashing.AppModule{}).Codec storeKey := storetypes.NewKVStoreKey(slashingtypes.ModuleName) tKey := storetypes.NewTransientStoreKey("transient_test") ctx := testutil.DefaultContext(storeKey, tKey) diff --git a/x/slashing/module.go b/x/slashing/module.go index e2e7bf4af777..cdadc1b03202 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -24,9 +24,12 @@ import ( const ConsensusVersion = 4 var ( - _ module.AppModuleBasic = AppModule{} - _ module.AppModuleSimulation = AppModule{} - _ module.HasGenesis = AppModule{} + _ module.HasName = AppModule{} + _ module.HasAminoCodec = AppModule{} + _ module.HasGRPCGateway = AppModule{} + _ module.HasRegisterInterfaces = AppModule{} + _ module.AppModuleSimulation = AppModule{} + _ module.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasBeginBlocker = AppModule{} @@ -34,53 +37,9 @@ var ( _ appmodule.HasMigrations = AppModule{} ) -// AppModuleBasic defines the basic application module used by the slashing module. -type AppModuleBasic struct { - cdc codec.Codec -} - -// Name returns the slashing module's name. -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec registers the slashing module's types for the given codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// RegisterInterfaces registers the module's interface types -func (b AppModuleBasic) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// DefaultGenesis returns default genesis state as raw bytes for the slashing -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) -} - -// ValidateGenesis performs genesis state validation for the slashing module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var data types.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { - return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) - } - - return types.ValidateGenesis(data) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the slashig module. -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { - if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - // AppModule implements an application module for the slashing module. type AppModule struct { - AppModuleBasic - + cdc codec.Codec registry cdctypes.InterfaceRegistry keeper keeper.Keeper @@ -99,16 +58,39 @@ func NewAppModule( registry cdctypes.InterfaceRegistry, ) AppModule { return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc}, - keeper: keeper, - accountKeeper: ak, - bankKeeper: bk, - stakingKeeper: sk, + cdc: cdc, + registry: registry, + keeper: keeper, + accountKeeper: ak, + bankKeeper: bk, + stakingKeeper: sk, } } // IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() {} +func (AppModule) IsAppModule() {} + +// Name returns the slashing module's name. +func (AppModule) Name() string { + return types.ModuleName +} + +// RegisterLegacyAminoCodec registers the slashing module's types for the given codec. +func (AppModule) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + types.RegisterLegacyAminoCodec(cdc) +} + +// RegisterInterfaces registers the module's interface types +func (AppModule) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { + types.RegisterInterfaces(registry) +} + +// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the slashig module. +func (AppModule) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { + if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { + panic(err) + } +} // RegisterServices registers module services. func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { @@ -118,6 +100,7 @@ func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { return nil } +// RegisterMigrations registers module migrations. func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { m := keeper.NewMigrator(am.keeper) @@ -136,22 +119,35 @@ func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { return nil } -// InitGenesis performs genesis initialization for the slashing module. It returns -// no validator updates. +// 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()) +} + +// ValidateGenesis performs genesis state validation for the slashing module. +func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { + var data types.GenesisState + if err := cdc.UnmarshalJSON(bz, &data); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + + return types.ValidateGenesis(data) +} + +// InitGenesis performs genesis initialization for the slashing module. func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) { var genesisState types.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) am.keeper.InitGenesis(ctx, am.stakingKeeper, &genesisState) } -// ExportGenesis returns the exported genesis state as raw bytes for the slashing -// module. +// 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 { gs := am.keeper.ExportGenesis(ctx) return cdc.MustMarshalJSON(gs) } -// ConsensusVersion implements AppModule/ConsensusVersion. +// ConsensusVersion implements HasConsensusVersion func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } // BeginBlock returns the begin blocker for the slashing module. diff --git a/x/slashing/simulation/decoder_test.go b/x/slashing/simulation/decoder_test.go index 8d62e18fa36b..d786b64de306 100644 --- a/x/slashing/simulation/decoder_test.go +++ b/x/slashing/simulation/decoder_test.go @@ -24,7 +24,7 @@ var ( ) func TestDecodeStore(t *testing.T) { - encodingConfig := moduletestutil.MakeTestEncodingConfig(slashing.AppModuleBasic{}) + encodingConfig := moduletestutil.MakeTestEncodingConfig(slashing.AppModule{}) cdc := encodingConfig.Codec dec := simulation.NewDecodeStore(cdc) diff --git a/x/slashing/testutil/expected_keepers_mocks.go b/x/slashing/testutil/expected_keepers_mocks.go index ee9fdfebbe94..8c9accc757aa 100644 --- a/x/slashing/testutil/expected_keepers_mocks.go +++ b/x/slashing/testutil/expected_keepers_mocks.go @@ -67,18 +67,6 @@ func (mr *MockAccountKeeperMockRecorder) GetAccount(ctx, addr interface{}) *gomo return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccount", reflect.TypeOf((*MockAccountKeeper)(nil).GetAccount), ctx, addr) } -// IterateAccounts mocks base method. -func (m *MockAccountKeeper) IterateAccounts(ctx context.Context, process func(types0.AccountI) bool) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "IterateAccounts", ctx, process) -} - -// IterateAccounts indicates an expected call of IterateAccounts. -func (mr *MockAccountKeeperMockRecorder) IterateAccounts(ctx, process interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IterateAccounts", reflect.TypeOf((*MockAccountKeeper)(nil).IterateAccounts), ctx, process) -} - // MockBankKeeper is a mock of BankKeeper interface. type MockBankKeeper struct { ctrl *gomock.Controller diff --git a/x/staking/client/cli/tx_test.go b/x/staking/client/cli/tx_test.go index 272ec636527b..10edb4c1344c 100644 --- a/x/staking/client/cli/tx_test.go +++ b/x/staking/client/cli/tx_test.go @@ -44,7 +44,7 @@ func TestCLITestSuite(t *testing.T) { } func (s *CLITestSuite) SetupSuite() { - s.encCfg = testutilmod.MakeTestEncodingConfig(staking.AppModuleBasic{}) + s.encCfg = testutilmod.MakeTestEncodingConfig(staking.AppModule{}) s.kr = keyring.NewInMemory(s.encCfg.Codec) s.baseCtx = client.Context{}. WithKeyring(s.kr). diff --git a/x/staking/migrations/v5/migrations_test.go b/x/staking/migrations/v5/migrations_test.go index c21f1c53dd8a..1f731415f342 100644 --- a/x/staking/migrations/v5/migrations_test.go +++ b/x/staking/migrations/v5/migrations_test.go @@ -80,7 +80,7 @@ func createHistoricalInfo(height int64, chainID string) *stakingtypes.Historical } func TestDelegationsByValidatorMigrations(t *testing.T) { - cdc := moduletestutil.MakeTestEncodingConfig(staking.AppModuleBasic{}).Codec + cdc := moduletestutil.MakeTestEncodingConfig(staking.AppModule{}).Codec storeKey := storetypes.NewKVStoreKey(v5.ModuleName) tKey := storetypes.NewTransientStoreKey("transient_test") ctx := testutil.DefaultContext(storeKey, tKey) diff --git a/x/staking/module.go b/x/staking/module.go index 0883ca5ad842..2e4254133d17 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -28,94 +28,76 @@ const ( ) var ( - _ module.AppModuleBasic = AppModuleBasic{} - _ module.AppModuleSimulation = AppModule{} - _ module.HasInvariants = AppModule{} - _ module.HasABCIGenesis = AppModule{} - _ module.HasABCIEndBlock = AppModule{} - _ depinject.OnePerModuleType = AppModule{} + _ module.AppModuleSimulation = AppModule{} + _ module.HasName = AppModule{} + _ module.HasAminoCodec = AppModule{} + _ module.HasGRPCGateway = AppModule{} + _ module.HasRegisterInterfaces = AppModule{} + _ module.HasInvariants = AppModule{} + _ module.HasABCIGenesis = AppModule{} + _ module.HasABCIEndBlock = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasBeginBlocker = AppModule{} _ appmodule.HasServices = AppModule{} _ appmodule.HasMigrations = AppModule{} + + _ depinject.OnePerModuleType = AppModule{} ) -// AppModuleBasic defines the basic application module used by the staking module. -type AppModuleBasic struct { - cdc codec.Codec +// AppModule implements an application module for the staking module. +type AppModule struct { + cdc codec.Codec + keeper *keeper.Keeper + accountKeeper types.AccountKeeper + bankKeeper types.BankKeeper } +// NewAppModule creates a new AppModule object +func NewAppModule( + cdc codec.Codec, + keeper *keeper.Keeper, + ak types.AccountKeeper, + bk types.BankKeeper, +) AppModule { + return AppModule{ + cdc: cdc, + keeper: keeper, + accountKeeper: ak, + bankKeeper: bk, + } +} + +// IsAppModule implements the appmodule.AppModule interface. +func (am AppModule) IsAppModule() {} + // Name returns the staking module's name. -func (AppModuleBasic) Name() string { +func (AppModule) Name() string { return types.ModuleName } // RegisterLegacyAminoCodec registers the staking module's types on the given LegacyAmino codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { +func (AppModule) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { types.RegisterLegacyAminoCodec(cdc) } // RegisterInterfaces registers the module's interface types -func (AppModuleBasic) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { +func (AppModule) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { types.RegisterInterfaces(registry) } -// DefaultGenesis returns default genesis state as raw bytes for the staking -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) -} - -// ValidateGenesis performs genesis state validation for the staking module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var data types.GenesisState - if err := cdc.UnmarshalJSON(bz, &data); err != nil { - return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) - } - - return ValidateGenesis(&data) -} - // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the staking module. -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { +func (AppModule) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { panic(err) } } // GetTxCmd returns the root tx command for the staking module. -func (amb AppModuleBasic) GetTxCmd() *cobra.Command { +func (AppModule) GetTxCmd() *cobra.Command { return cli.NewTxCmd() } -// AppModule implements an application module for the staking module. -type AppModule struct { - AppModuleBasic - - keeper *keeper.Keeper - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule( - cdc codec.Codec, - keeper *keeper.Keeper, - ak types.AccountKeeper, - bk types.BankKeeper, -) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{cdc: cdc}, - keeper: keeper, - accountKeeper: ak, - bankKeeper: bk, - } -} - -// IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() {} - // RegisterInvariants registers the staking module invariants. func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { keeper.RegisterInvariants(ir, am.keeper) @@ -129,6 +111,7 @@ func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { return nil } +// RegisterMigrations registers module migrations func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { m := keeper.NewMigrator(am.keeper) if err := mr.Register(types.ModuleName, 1, m.Migrate1to2); err != nil { @@ -147,6 +130,21 @@ func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { return nil } +// 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()) +} + +// ValidateGenesis performs genesis state validation for the staking module. +func (AppModule) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { + var data types.GenesisState + if err := cdc.UnmarshalJSON(bz, &data); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + + return ValidateGenesis(&data) +} + // InitGenesis performs genesis initialization for the staking module. func (am AppModule) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { var genesisState types.GenesisState @@ -162,7 +160,7 @@ func (am AppModule) ExportGenesis(ctx context.Context, cdc codec.JSONCodec) json return cdc.MustMarshalJSON(am.keeper.ExportGenesis(ctx)) } -// ConsensusVersion implements AppModule/ConsensusVersion. +// ConsensusVersion implements HasConsensusVersion func (AppModule) ConsensusVersion() uint64 { return consensusVersion } // BeginBlock returns the begin blocker for the staking module. diff --git a/x/staking/testutil/expected_keepers_mocks.go b/x/staking/testutil/expected_keepers_mocks.go index fdf54c9085b2..f1f4cd652f1f 100644 --- a/x/staking/testutil/expected_keepers_mocks.go +++ b/x/staking/testutil/expected_keepers_mocks.go @@ -97,18 +97,6 @@ func (mr *MockAccountKeeperMockRecorder) GetModuleAddress(name interface{}) *gom return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetModuleAddress", reflect.TypeOf((*MockAccountKeeper)(nil).GetModuleAddress), name) } -// IterateAccounts mocks base method. -func (m *MockAccountKeeper) IterateAccounts(ctx context.Context, process func(types1.AccountI) bool) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "IterateAccounts", ctx, process) -} - -// IterateAccounts indicates an expected call of IterateAccounts. -func (mr *MockAccountKeeperMockRecorder) IterateAccounts(ctx, process interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IterateAccounts", reflect.TypeOf((*MockAccountKeeper)(nil).IterateAccounts), ctx, process) -} - // SetModuleAccount mocks base method. func (m *MockAccountKeeper) SetModuleAccount(arg0 context.Context, arg1 types1.ModuleAccountI) { m.ctrl.T.Helper() diff --git a/x/upgrade/depinject.go b/x/upgrade/depinject.go index 0cf46765fcdf..29fbce81ad16 100644 --- a/x/upgrade/depinject.go +++ b/x/upgrade/depinject.go @@ -71,14 +71,14 @@ func ProvideModule(in ModuleInputs) ModuleOutputs { authority = authtypes.NewModuleAddressOrBech32Address(in.Config.Authority) } - auth, err := in.AddressCodec.BytesToString(authority) + authorityStr, err := in.AddressCodec.BytesToString(authority) if err != nil { panic(err) } // set the governance module account as the authority for conducting upgrades - k := keeper.NewKeeper(in.Environment, skipUpgradeHeights, in.Cdc, homePath, in.AppVersionModifier, auth) - m := NewAppModule(k, in.AddressCodec) + k := keeper.NewKeeper(in.Environment, skipUpgradeHeights, in.Cdc, homePath, in.AppVersionModifier, authorityStr) + m := NewAppModule(k) return ModuleOutputs{UpgradeKeeper: k, Module: m} } diff --git a/x/upgrade/keeper/abci_test.go b/x/upgrade/keeper/abci_test.go index 84a53991b429..e74005dd8949 100644 --- a/x/upgrade/keeper/abci_test.go +++ b/x/upgrade/keeper/abci_test.go @@ -111,7 +111,7 @@ func (s *TestSuite) VerifySet(t *testing.T, skipUpgradeHeights map[int64]bool) { func setupTest(t *testing.T, height int64, skip map[int64]bool) *TestSuite { t.Helper() s := TestSuite{} - s.encCfg = moduletestutil.MakeTestEncodingConfig(upgrade.AppModuleBasic{}) + s.encCfg = moduletestutil.MakeTestEncodingConfig(upgrade.AppModule{}) key := storetypes.NewKVStoreKey(types.StoreKey) storeService := runtime.NewKVStoreService(key) env := runtime.NewEnvironment(storeService, log.NewNopLogger()) @@ -133,7 +133,7 @@ func setupTest(t *testing.T, height int64, skip map[int64]bool) *TestSuite { s.ctx = testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now(), Height: height}) - s.preModule = upgrade.NewAppModule(s.keeper, addresscodec.NewBech32Codec("cosmos")) + s.preModule = upgrade.NewAppModule(s.keeper) return &s } @@ -458,7 +458,7 @@ func TestBinaryVersion(t *testing.T) { func TestDowngradeVerification(t *testing.T) { // could not use setupTest() here, because we have to use the same key // for the two keepers. - encCfg := moduletestutil.MakeTestEncodingConfig(upgrade.AppModuleBasic{}) + encCfg := moduletestutil.MakeTestEncodingConfig(upgrade.AppModule{}) key := storetypes.NewKVStoreKey(types.StoreKey) storeService := runtime.NewKVStoreService(key) env := runtime.NewEnvironment(storeService, log.NewNopLogger()) @@ -471,7 +471,7 @@ func TestDowngradeVerification(t *testing.T) { require.NoError(t, err) k := keeper.NewKeeper(env, skip, encCfg.Codec, t.TempDir(), nil, authority) - m := upgrade.NewAppModule(k, addresscodec.NewBech32Codec("cosmos")) + m := upgrade.NewAppModule(k) // submit a plan. planName := "downgrade" @@ -520,7 +520,7 @@ func TestDowngradeVerification(t *testing.T) { // downgrade. now keeper does not have the handler. k := keeper.NewKeeper(env, skip, encCfg.Codec, t.TempDir(), nil, authority) - m := upgrade.NewAppModule(k, addresscodec.NewBech32Codec("cosmos")) + m := upgrade.NewAppModule(k) // assertions lastAppliedPlan, _, err := k.GetLastCompletedUpgrade(ctx) diff --git a/x/upgrade/keeper/grpc_query_test.go b/x/upgrade/keeper/grpc_query_test.go index 7390bb324e30..2911f11380c7 100644 --- a/x/upgrade/keeper/grpc_query_test.go +++ b/x/upgrade/keeper/grpc_query_test.go @@ -35,7 +35,7 @@ type UpgradeTestSuite struct { } func (suite *UpgradeTestSuite) SetupTest() { - suite.encCfg = moduletestutil.MakeTestEncodingConfig(upgrade.AppModuleBasic{}) + suite.encCfg = moduletestutil.MakeTestEncodingConfig(upgrade.AppModule{}) key := storetypes.NewKVStoreKey(types.StoreKey) storeService := runtime.NewKVStoreService(key) env := runtime.NewEnvironment(storeService, log.NewNopLogger()) diff --git a/x/upgrade/keeper/keeper_test.go b/x/upgrade/keeper/keeper_test.go index 6c0313505b00..798c93d9ce99 100644 --- a/x/upgrade/keeper/keeper_test.go +++ b/x/upgrade/keeper/keeper_test.go @@ -43,7 +43,7 @@ type KeeperTestSuite struct { } func (s *KeeperTestSuite) SetupTest() { - s.encCfg = moduletestutil.MakeTestEncodingConfig(upgrade.AppModuleBasic{}) + s.encCfg = moduletestutil.MakeTestEncodingConfig(upgrade.AppModule{}) key := storetypes.NewKVStoreKey(types.StoreKey) storeService := runtime.NewKVStoreService(key) env := runtime.NewEnvironment(storeService, log.NewNopLogger()) diff --git a/x/upgrade/module.go b/x/upgrade/module.go index 905e36abb481..7a609ae4b25a 100644 --- a/x/upgrade/module.go +++ b/x/upgrade/module.go @@ -9,7 +9,6 @@ import ( "github.com/spf13/cobra" "google.golang.org/grpc" - "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" "cosmossdk.io/x/upgrade/client/cli" "cosmossdk.io/x/upgrade/keeper" @@ -29,8 +28,11 @@ func init() { const ConsensusVersion uint64 = 3 var ( - _ module.AppModuleBasic = AppModule{} - _ module.HasGenesis = AppModule{} + _ module.HasName = AppModule{} + _ module.HasAminoCodec = AppModule{} + _ module.HasGRPCGateway = AppModule{} + _ module.HasRegisterInterfaces = AppModule{} + _ module.HasGenesis = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasPreBlocker = AppModule{} @@ -38,53 +40,48 @@ var ( _ appmodule.HasMigrations = AppModule{} ) -// AppModuleBasic implements the sdk.AppModuleBasic interface -type AppModuleBasic struct{} +// AppModule implements the sdk.AppModule interface +type AppModule struct { + keeper *keeper.Keeper +} + +// NewAppModule creates a new AppModule object +func NewAppModule(keeper *keeper.Keeper) AppModule { + return AppModule{ + keeper: keeper, + } +} + +// IsAppModule implements the appmodule.AppModule interface. +func (AppModule) IsAppModule() {} // Name returns the ModuleName -func (AppModuleBasic) Name() string { +func (AppModule) Name() string { return types.ModuleName } // RegisterLegacyAminoCodec registers the upgrade types on the LegacyAmino codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { +func (AppModule) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { types.RegisterLegacyAminoCodec(cdc) } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the upgrade module. -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { +func (AppModule) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) { if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { panic(err) } } // GetTxCmd returns the CLI transaction commands for this module -func (ab AppModuleBasic) GetTxCmd() *cobra.Command { +func (AppModule) GetTxCmd() *cobra.Command { return cli.GetTxCmd() } // RegisterInterfaces registers interfaces and implementations of the upgrade module. -func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { +func (AppModule) RegisterInterfaces(registry codectypes.InterfaceRegistry) { types.RegisterInterfaces(registry) } -// AppModule implements the sdk.AppModule interface -type AppModule struct { - AppModuleBasic - keeper *keeper.Keeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper *keeper.Keeper, ac address.Codec) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - } -} - -// IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() {} - // RegisterServices registers module services. func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { types.RegisterMsgServer(registrar, keeper.NewMsgServerImpl(am.keeper)) @@ -93,6 +90,7 @@ func (am AppModule) RegisterServices(registrar grpc.ServiceRegistrar) error { return nil } +// RegisterMigrations registers module migrations func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { m := keeper.NewMigrator(am.keeper) if err := mr.Register(types.ModuleName, 1, m.Migrate1to2); err != nil { @@ -106,6 +104,16 @@ func (am AppModule) RegisterMigrations(mr appmodule.MigrationRegistrar) error { return nil } +// DefaultGenesis is an empty object +func (AppModule) DefaultGenesis(_ codec.JSONCodec) json.RawMessage { + return []byte("{}") +} + +// ValidateGenesis is always successful, as we ignore the value +func (AppModule) ValidateGenesis(_ codec.JSONCodec, _ client.TxEncodingConfig, _ 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) { // set version map automatically if available @@ -130,22 +138,12 @@ func (am AppModule) InitGenesis(ctx context.Context, _ codec.JSONCodec, _ json.R } } -// DefaultGenesis is an empty object -func (AppModuleBasic) DefaultGenesis(_ codec.JSONCodec) json.RawMessage { - return []byte("{}") -} - -// ValidateGenesis is always successful, as we ignore the value -func (AppModuleBasic) ValidateGenesis(_ codec.JSONCodec, _ client.TxEncodingConfig, _ json.RawMessage) error { - 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) } -// ConsensusVersion implements AppModule/ConsensusVersion. +// ConsensusVersion implements HasConsensusVersion func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } // PreBlock calls the upgrade module hooks