diff --git a/depinject/README.md b/depinject/README.md new file mode 100644 index 000000000000..ae682717851c --- /dev/null +++ b/depinject/README.md @@ -0,0 +1,205 @@ +--- +sidebar_position: 1 +--- + +# Depinject + +> **DISCLAIMER**: This is a **beta** package. The SDK team is actively working on this feature and we are looking for feedback from the community. Please try it out and let us know what you think. + +## Overview + +`depinject` is a dependency injection (DI) framework for the Cosmos SDK, designed to streamline the process of building and configuring blockchain applications. It works in conjunction with the `core/appconfig` module to replace the majority of boilerplate code in `app.go` with a configuration file in Go, YAML, or JSON format. + +`depinject` is particularly useful for developing blockchain applications: + +* With multiple interdependent components, modules, or services. Helping manage their dependencies effectively. +* That require decoupling of these components, making it easier to test, modify, or replace individual parts without affecting the entire system. +* That are wanting to simplify the setup and initialisation of modules and their dependencies by reducing boilerplate code and automating dependency management. + +By using `depinject`, developers can achieve: + +* Cleaner and more organised code. +* Improved modularity and maintainability. +* A more maintainable and modular structure for their blockchain applications, ultimately enhancing development velocity and code quality. + +* [Go Doc](https://pkg.go.dev/cosmossdk.io/depinject) + +## Usage + +The `depinject` framework, based on dependency injection concepts, streamlines the management of dependencies within your blockchain application using its Configuration API. This API offers a set of functions and methods to create easy to use configurations, making it simple to define, modify, and access dependencies and their relationships. + +A core component of the [Configuration API](https://pkg.go.dev/github.com/cosmos/cosmos-sdk/depinject#Config) is the `Provide` function, which allows you to register provider functions that supply dependencies. Inspired by constructor injection, these provider functions form the basis of the dependency tree, enabling the management and resolution of dependencies in a structured and maintainable manner. Additionally, `depinject` supports interface types as inputs to provider functions, offering flexibility and decoupling between components, similar to interface injection concepts. + +By leveraging `depinject` and its Configuration API, you can efficiently handle dependencies in your blockchain application, ensuring a clean, modular, and well-organised codebase. + +Example: + +```go +package main + +import ( + "fmt" + + "cosmossdk.io/depinject" +) + +type AnotherInt int + +func GetInt() int { return 1 } +func GetAnotherInt() AnotherInt { return 2 } + +func main() { + var ( + x int + y AnotherInt + ) + + fmt.Printf("Before (%v, %v)\n", x, y) + depinject.Inject( + depinject.Provide( + GetInt, + GetAnotherInt, + ), + &x, + &y, + ) + fmt.Printf("After (%v, %v)\n", x, y) +} +``` + +In this example, `depinject.Provide` registers two provider functions that return `int` and `AnotherInt` values. The `depinject.Inject` function is then used to inject these values into the variables `x` and `y`. + +Provider functions serve as the basis for the dependency tree. They are analysed to identify their inputs as dependencies and their outputs as dependents. These dependents can either be used by another provider function or be stored outside the DI container (e.g., `&x` and `&y` in the example above). Provider functions must be exported. + +### Interface type resolution + +`depinject` supports the use of interface types as inputs to provider functions, which helps decouple dependencies between modules. This approach is particularly useful for managing complex systems with multiple modules, such as the Cosmos SDK, where dependencies need to be flexible and maintainable. + +For example, `x/bank` expects an [AccountKeeper](https://pkg.go.dev/cosmossdk.io/x/bank/types#AccountKeeper) interface as [input to ProvideModule](https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/bank/module.go#L208-L260). `SimApp` uses the implementation in `x/auth`, but the modular design allows for easy changes to the implementation if needed. + +Consider the following example: + +```go +package duck + +type Duck interface { + quack() +} + +type AlsoDuck interface { + quack() +} + +type Mallard struct{} +type Canvasback struct{} + +func (duck Mallard) quack() {} +func (duck Canvasback) quack() {} + +type Pond struct { + Duck AlsoDuck +} +``` + +And the following provider functions: + +```go +func GetMallard() duck.Mallard { + return Mallard{} +} + +func GetPond(duck Duck) Pond { + return Pond{Duck: duck} +} + +func GetCanvasback() Canvasback { + return Canvasback{} +} +``` + +In this example, there's a `Pond` struct that has a `Duck` field of type `AlsoDuck`. The `depinject` framework can automatically resolve the appropriate implementation when there's only one available, as shown below: + +```go +var pond Pond + +depinject.Inject( + depinject.Provide( + GetMallard, + GetPond, + ), + &pond) +``` + +This code snippet results in the `Duck` field of `Pond` being implicitly bound to the `Mallard` implementation because it's the only implementation of the `Duck` interface in the container. + +However, if there are multiple implementations of the `Duck` interface, as in the following example, you'll encounter an error: + +```go +var pond Pond + +depinject.Inject( + depinject.Provide( + GetMallard, + GetCanvasback, + GetPond, + ), + &pond) +``` + +A specific binding preference for `Duck` is required. + +#### `BindInterface` API + +In the above situation registering a binding for a given interface binding may look like: + +```go +depinject.Inject( + depinject.Configs( + depinject.BindInterface( + "duck/duck.Duck", + "duck/duck.Mallard", + ), + depinject.Provide( + GetMallard, + GetCanvasback, + GetPond, + ), + ), + &pond) +``` + +Now `depinject` has enough information to provide `Mallard` as an input to `APond`. + +### Full example in real app + +:::warning +When using `depinject.Inject`, the injected types must be pointers. +::: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/v0.52.0-beta.2/simapp/app_di.go#L187-L206 +``` + +## Debugging + +Issues with resolving dependencies in the container can be done with logs and [Graphviz](https://graphviz.org) renderings of the container tree. +By default, whenever there is an error, logs will be printed to stderr and a rendering of the dependency graph in Graphviz DOT format will be saved to `debug_container.dot`. + +Here is an example Graphviz rendering of a successful build of a dependency graph: +![Graphviz Example](https://raw.githubusercontent.com/cosmos/cosmos-sdk/ff39d243d421442b400befcd959ec3ccd2525154/depinject/testdata/example.svg) + +Rectangles represent functions, ovals represent types, rounded rectangles represent modules and the single hexagon +represents the function which called `Build`. Black-colored shapes mark functions and types that were called/resolved +without an error. Gray-colored nodes mark functions and types that could have been called/resolved in the container but +were left unused. + +Here is an example Graphviz rendering of a dependency graph build which failed: +![Graphviz Error Example](https://raw.githubusercontent.com/cosmos/cosmos-sdk/ff39d243d421442b400befcd959ec3ccd2525154/depinject/testdata/example_error.svg) + +Graphviz DOT files can be converted into SVG's for viewing in a web browser using the `dot` command-line tool, ex: + +```txt +dot -Tsvg debug_container.dot > debug_container.svg +``` + +Many other tools including some IDEs support working with DOT files. diff --git a/runtime/v2/app.go b/runtime/v2/app.go new file mode 100644 index 000000000000..5c5c78532f33 --- /dev/null +++ b/runtime/v2/app.go @@ -0,0 +1,108 @@ +package runtime + +import ( + "encoding/json" + + runtimev2 "cosmossdk.io/api/cosmos/app/runtime/v2" + appmodulev2 "cosmossdk.io/core/appmodule/v2" + "cosmossdk.io/core/registry" + "cosmossdk.io/core/transaction" + "cosmossdk.io/log" + "cosmossdk.io/schema/decoding" + "cosmossdk.io/server/v2/appmanager" + "cosmossdk.io/server/v2/stf" +) + +// App is a wrapper around AppManager and ModuleManager that can be used in hybrid +// app.go/app config scenarios or directly as a servertypes.Application instance. +// To get an instance of *App, *AppBuilder must be requested as a dependency +// in a container which declares the runtime module and the AppBuilder.Build() +// method must be called. +// +// App can be used to create a hybrid app.go setup where some configuration is +// done declaratively with an app config and the rest of it is done the old way. +// See simapp/v2/app.go for an example of this setup. +type App[T transaction.Tx] struct { + appmanager.AppManager[T] + + // app configuration + logger log.Logger + config *runtimev2.Module + + // state + stf *stf.STF[T] + msgRouterBuilder *stf.MsgRouterBuilder + queryRouterBuilder *stf.MsgRouterBuilder + db Store + storeLoader StoreLoader + + // modules + interfaceRegistrar registry.InterfaceRegistrar + amino registry.AminoRegistrar + moduleManager *MM[T] + queryHandlers map[string]appmodulev2.Handler // queryHandlers defines the query handlers +} + +// Name returns the app name. +func (a *App[T]) Name() string { + return a.config.AppName +} + +// Logger returns the app logger. +func (a *App[T]) Logger() log.Logger { + return a.logger +} + +// ModuleManager returns the module manager. +func (a *App[T]) ModuleManager() *MM[T] { + return a.moduleManager +} + +// DefaultGenesis returns a default genesis from the registered modules. +func (a *App[T]) DefaultGenesis() map[string]json.RawMessage { + return a.moduleManager.DefaultGenesis() +} + +// SetStoreLoader sets the store loader. +func (a *App[T]) SetStoreLoader(loader StoreLoader) { + a.storeLoader = loader +} + +// LoadLatest loads the latest version. +func (a *App[T]) LoadLatest() error { + return a.storeLoader(a.db) +} + +// LoadHeight loads a particular height +func (a *App[T]) LoadHeight(height uint64) error { + return a.db.LoadVersion(height) +} + +// LoadLatestHeight loads the latest height. +func (a *App[T]) LoadLatestHeight() (uint64, error) { + return a.db.GetLatestVersion() +} + +// QueryHandlers returns the query handlers. +func (a *App[T]) QueryHandlers() map[string]appmodulev2.Handler { + return a.queryHandlers +} + +// SchemaDecoderResolver returns the module schema resolver. +func (a *App[T]) SchemaDecoderResolver() decoding.DecoderResolver { + moduleSet := map[string]any{} + for moduleName, module := range a.moduleManager.Modules() { + moduleSet[moduleName] = module + } + + for _, overrideKey := range a.config.OverrideStoreKeys { + moduleSet[overrideKey.KvStoreKey] = moduleSet[overrideKey.ModuleName] + } + + return decoding.ModuleSetDecoderResolver(moduleSet) +} + +// Close is called in start cmd to gracefully cleanup resources. +func (a *App[T]) Close() error { + return nil +} diff --git a/simapp/app.go b/simapp/app.go index a681849f509e..aeb8ff102758 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -1,8 +1,13 @@ +<<<<<<< HEAD //go:build app_v1 +======= +//go:build !app_v1 +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) package simapp import ( +<<<<<<< HEAD "encoding/json" "fmt" "io" @@ -93,10 +98,48 @@ import ( "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/runtime" runtimeservices "github.com/cosmos/cosmos-sdk/runtime/services" +======= + _ "embed" + "fmt" + "io" + + _ "github.com/jackc/pgx/v5/stdlib" // Import and register pgx driver + + clienthelpers "cosmossdk.io/client/v2/helpers" + "cosmossdk.io/core/address" + "cosmossdk.io/core/appmodule" + "cosmossdk.io/core/registry" + corestore "cosmossdk.io/core/store" + "cosmossdk.io/depinject" + _ "cosmossdk.io/indexer/postgres" // register the postgres indexer + "cosmossdk.io/log" + "cosmossdk.io/x/accounts" + basedepinject "cosmossdk.io/x/accounts/defaults/base/depinject" + lockupdepinject "cosmossdk.io/x/accounts/defaults/lockup/depinject" + multisigdepinject "cosmossdk.io/x/accounts/defaults/multisig/depinject" + "cosmossdk.io/x/accounts/testing/account_abstraction" + "cosmossdk.io/x/accounts/testing/counter" + bankkeeper "cosmossdk.io/x/bank/keeper" + circuitkeeper "cosmossdk.io/x/circuit/keeper" + consensuskeeper "cosmossdk.io/x/consensus/keeper" + distrkeeper "cosmossdk.io/x/distribution/keeper" + feegrantkeeper "cosmossdk.io/x/feegrant/keeper" + _ "cosmossdk.io/x/protocolpool" + slashingkeeper "cosmossdk.io/x/slashing/keeper" + stakingkeeper "cosmossdk.io/x/staking/keeper" + upgradekeeper "cosmossdk.io/x/upgrade/keeper" + + "github.com/cosmos/cosmos-sdk/baseapp" + "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/runtime" +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server/api" "github.com/cosmos/cosmos-sdk/server/config" servertypes "github.com/cosmos/cosmos-sdk/server/types" +<<<<<<< HEAD "github.com/cosmos/cosmos-sdk/std" testdata_pulsar "github.com/cosmos/cosmos-sdk/testutil/testdata/testpb" sdk "github.com/cosmos/cosmos-sdk/types" @@ -140,6 +183,20 @@ var ( nft.ModuleName: nil, } ) +======= + testdata_pulsar "github.com/cosmos/cosmos-sdk/testutil/testdata/testpb" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/ante" + "github.com/cosmos/cosmos-sdk/x/auth/ante/unorderedtx" + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +// DefaultNodeHome default home directories for the application daemon +var DefaultNodeHome string +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) var ( _ runtime.AppI = (*SimApp)(nil) @@ -150,6 +207,7 @@ var ( // They are exported for convenience in creating helper functions, as object // capabilities aren't needed for testing. type SimApp struct { +<<<<<<< HEAD *baseapp.BaseApp logger log.Logger legacyAmino *codec.LegacyAmino @@ -187,6 +245,29 @@ type SimApp struct { // module configurator configurator module.Configurator //nolint:staticcheck // SA1019: Configurator is deprecated but still used in runtime v1. +======= + *runtime.App + legacyAmino registry.AminoRegistrar + appCodec codec.Codec + txConfig client.TxConfig + interfaceRegistry codectypes.InterfaceRegistry + + // required keepers during wiring + // others keepers are all in the app + AccountsKeeper accounts.Keeper + AuthKeeper authkeeper.AccountKeeper + BankKeeper bankkeeper.Keeper + StakingKeeper *stakingkeeper.Keeper + SlashingKeeper slashingkeeper.Keeper + DistrKeeper distrkeeper.Keeper + UpgradeKeeper *upgradekeeper.Keeper + FeeGrantKeeper feegrantkeeper.Keeper + ConsensusParamsKeeper consensuskeeper.Keeper + CircuitBreakerKeeper circuitkeeper.Keeper + + // simulation manager + sm *module.SimulationManager +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) } func init() { @@ -197,6 +278,19 @@ func init() { } } +<<<<<<< HEAD +======= +// AppConfig returns the default app config. +func AppConfig() depinject.Config { + return depinject.Configs( + appConfig, // Alternatively use appconfig.LoadYAML(AppConfigYAML) + depinject.Provide( + ProvideExampleMintFn, // optional: override the mint module's mint function with epoched minting + ), + ) +} + +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) // NewSimApp returns a reference to an initialized SimApp. func NewSimApp( logger log.Logger, @@ -206,6 +300,7 @@ func NewSimApp( appOpts servertypes.AppOptions, baseAppOptions ...func(*baseapp.BaseApp), ) *SimApp { +<<<<<<< HEAD interfaceRegistry, _ := types.NewInterfaceRegistryWithOptions(types.InterfaceRegistryOptions{ ProtoFiles: proto.HybridResolver, SigningOptions: signing.Options{ @@ -236,6 +331,109 @@ func NewSimApp( std.RegisterLegacyAminoCodec(legacyAmino) std.RegisterInterfaces(interfaceRegistry) +======= + var ( + app = &SimApp{} + appBuilder *runtime.AppBuilder + + // merge the AppConfig and other configuration in one config + appConfig = depinject.Configs( + AppConfig(), + depinject.Supply( + // supply the application options + appOpts, + // supply the logger + logger, + + // ADVANCED CONFIGURATION + + // + // AUTH + // + // For providing a custom function required in auth to generate custom account types + // add it below. By default the auth module uses simulation.RandomGenesisAccounts. + // + // authtypes.RandomGenesisAccountsFn(simulation.RandomGenesisAccounts), + // + // For providing a custom a base account type add it below. + // By default the auth module uses authtypes.ProtoBaseAccount(). + // + // func() sdk.AccountI { return authtypes.ProtoBaseAccount() }, + // + // For providing a different address codec, add it below. + // By default the auth module uses a Bech32 address codec, + // with the prefix defined in the auth module configuration. + // + // func() address.Codec { return <- custom address codec type -> } + + // + // STAKING + // + // For provinding a different validator and consensus address codec, add it below. + // By default the staking module uses the bech32 prefix provided in the auth config, + // and appends "valoper" and "valcons" for validator and consensus addresses respectively. + // When providing a custom address codec in auth, custom address codecs must be provided here as well. + // + // func() runtime.ValidatorAddressCodec { return <- custom validator address codec type -> } + // func() runtime.ConsensusAddressCodec { return <- custom consensus address codec type -> } + + // + // MINT + // + + // For providing a custom inflation function for x/mint add here your + // custom function that implements the minttypes.MintFn interface. + ), + depinject.Provide( + // inject desired account types: + multisigdepinject.ProvideAccount, + basedepinject.ProvideAccount, + lockupdepinject.ProvideAllLockupAccounts, + + // provide base account options + basedepinject.ProvideSecp256K1PubKey, + // if you want to provide a custom public key you + // can do it from here. + // Example: + // basedepinject.ProvideCustomPubkey[Ed25519PublicKey]() + // + // You can also provide a custom public key with a custom validation function: + // + // basedepinject.ProvideCustomPubKeyAndValidationFunc(func(pub Ed25519PublicKey) error { + // if len(pub.Key) != 64 { + // return fmt.Errorf("invalid pub key size") + // } + // }) + + // TESTING: do not add below account types + counter.ProvideAccount, + account_abstraction.ProvideAccount, + ), + ) + ) + + var appModules map[string]appmodule.AppModule + if err := depinject.Inject(appConfig, + &appBuilder, + &appModules, + &app.appCodec, + &app.legacyAmino, + &app.txConfig, + &app.interfaceRegistry, + &app.AuthKeeper, + &app.AccountsKeeper, + &app.BankKeeper, + &app.StakingKeeper, + &app.SlashingKeeper, + &app.DistrKeeper, + &app.UpgradeKeeper, + &app.FeeGrantKeeper, + &app.ConsensusParamsKeeper, + &app.CircuitBreakerKeeper, + ); err != nil { + panic(err) + } +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) // Below we could construct and set an application specific mempool and // ABCI 1.0 PrepareProposal and ProcessProposal handlers. These defaults are @@ -244,6 +442,7 @@ func NewSimApp( // // Example: // +<<<<<<< HEAD // bApp := baseapp.NewBaseApp(...) // nonceMempool := mempool.NewSenderNonceMempool() // abciPropHandler := NewDefaultProposalHandler(nonceMempool, bApp) @@ -254,6 +453,18 @@ func NewSimApp( // // Alternatively, you can construct BaseApp options, append those to // baseAppOptions and pass them to NewBaseApp. +======= + // app.App = appBuilder.Build(...) + // nonceMempool := mempool.NewSenderNonceMempool() + // abciPropHandler := NewDefaultProposalHandler(nonceMempool, app.App.BaseApp) + // + // app.App.BaseApp.SetMempool(nonceMempool) + // app.App.BaseApp.SetPrepareProposal(abciPropHandler.PrepareProposalHandler()) + // app.App.BaseApp.SetProcessProposal(abciPropHandler.ProcessProposalHandler()) + // + // Alternatively, you can construct BaseApp options, append those to + // baseAppOptions and pass them to the appBuilder. +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) // // Example: // @@ -270,6 +481,7 @@ func NewSimApp( } baseAppOptions = append(baseAppOptions, voteExtOp, baseapp.SetOptimisticExecution()) +<<<<<<< HEAD bApp := baseapp.NewBaseApp(appName, logger, db, txConfig.TxDecoder(), baseAppOptions...) bApp.SetCommitMultiStoreTracer(traceStore) bApp.SetVersion(version.Version) @@ -571,6 +783,15 @@ func NewSimApp( } reflectionv1.RegisterReflectionServiceServer(app.GRPCQueryRouter(), reflectionSvc) +======= + app.App = appBuilder.Build(db, traceStore, baseAppOptions...) + + /**** Module Options ****/ + + // RegisterUpgradeHandlers is used for registering any on-chain upgrades. + app.RegisterUpgradeHandlers() + +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) // add test gRPC service for testing gRPC queries in isolation testdata_pulsar.RegisterQueryServer(app.GRPCQueryRouter(), testdata_pulsar.QueryImpl{}) @@ -579,6 +800,7 @@ func NewSimApp( // NOTE: this is not required apps that don't use the simulator for fuzz testing // transactions overrideModules := map[string]module.AppModuleSimulation{ +<<<<<<< HEAD authtypes.ModuleName: auth.NewAppModule(app.appCodec, app.AuthKeeper, app.AccountsKeeper, authsims.RandomGenesisAccounts, nil), } app.sm = module.NewSimulationManagerFromAppModules(app.ModuleManager.Modules, overrideModules) @@ -598,10 +820,35 @@ func NewSimApp( unorderedtx.NewSnapshotter(app.UnorderedTxManager), ) if err != nil { +======= + authtypes.ModuleName: auth.NewAppModule(app.appCodec, app.AuthKeeper, &app.AccountsKeeper, authsims.RandomGenesisAccounts, nil), + } + app.sm = module.NewSimulationManagerFromAppModules(app.ModuleManager.Modules, overrideModules) + + app.sm.RegisterStoreDecoders() + + // A custom InitChainer can be set if extra pre-init-genesis logic is required. + // By default, when using app wiring enabled module, this is not required. + // For instance, the upgrade module will set automatically the module version map in its init genesis thanks to app wiring. + // However, when registering a module manually (i.e. that does not support app wiring), the module version map + // must be set manually as follow. The upgrade module will de-duplicate the module version map. + // + // app.SetInitChainer(func(ctx sdk.Context, req *abci.InitChainRequest) (*abci.InitChainResponse, error) { + // app.UpgradeKeeper.SetModuleVersionMap(ctx, app.ModuleManager.GetVersionMap()) + // return app.App.InitChainer(ctx, req) + // }) + + // register custom snapshot extensions (if any) + if manager := app.SnapshotManager(); manager != nil { + if err := manager.RegisterExtensions( + unorderedtx.NewSnapshotter(app.UnorderedTxManager), + ); err != nil { +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) panic(fmt.Errorf("failed to register snapshot extension: %w", err)) } } +<<<<<<< HEAD app.sm.RegisterStoreDecoders() // initialize stores @@ -647,10 +894,19 @@ func NewSimApp( panic(fmt.Errorf("error loading last version: %w", err)) } } +======= + // set custom ante handlers + app.setCustomAnteHandler() + + if err := app.Load(loadLatest); err != nil { + panic(err) + } +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) return app } +<<<<<<< HEAD func (app *SimApp) setAnteHandler(txConfig client.TxConfig) { anteHandler, err := NewAnteHandler( HandlerOptions{ @@ -666,6 +922,25 @@ func (app *SimApp) setAnteHandler(txConfig client.TxConfig) { UnorderedTxManager: app.UnorderedTxManager, }, &app.CircuitKeeper, +======= +// setCustomAnteHandler overwrites default ante handlers with custom ante handlers +// set SkipAnteHandler to true in app config and set custom ante handler on baseapp +func (app *SimApp) setCustomAnteHandler() { + anteHandler, err := NewAnteHandler( + HandlerOptions{ + ante.HandlerOptions{ + AccountKeeper: app.AuthKeeper, + BankKeeper: app.BankKeeper, + ConsensusKeeper: app.ConsensusParamsKeeper, + SignModeHandler: app.txConfig.SignModeHandler(), + FeegrantKeeper: app.FeeGrantKeeper, + SigGasConsumer: ante.DefaultSigVerificationGasConsumer, + UnorderedTxManager: app.UnorderedTxManager, + Environment: app.AuthKeeper.Environment, + AccountAbstractionKeeper: app.AccountsKeeper, + }, + &app.CircuitBreakerKeeper, +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) }, ) if err != nil { @@ -676,6 +951,7 @@ func (app *SimApp) setAnteHandler(txConfig client.TxConfig) { app.SetAnteHandler(anteHandler) } +<<<<<<< HEAD func (app *SimApp) setPostHandler() { postHandler, err := posthandler.NewPostHandler( posthandler.HandlerOptions{}, @@ -739,12 +1015,23 @@ func (app *SimApp) LoadHeight(height int64) error { return app.LoadVersion(height) } +======= +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) // LegacyAmino returns SimApp's amino codec. // // NOTE: This is solely to be used for testing purposes as it may be desirable // for modules to register their own custom testing types. func (app *SimApp) LegacyAmino() *codec.LegacyAmino { +<<<<<<< HEAD return app.legacyAmino +======= + switch cdc := app.legacyAmino.(type) { + case *codec.LegacyAmino: + return cdc + default: + panic("unexpected codec type") + } +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) } // AppCodec returns SimApp's app codec. @@ -755,8 +1042,13 @@ func (app *SimApp) AppCodec() codec.Codec { return app.appCodec } +<<<<<<< HEAD // InterfaceRegistry returns SimApp's InterfaceRegistry func (app *SimApp) InterfaceRegistry() types.InterfaceRegistry { +======= +// InterfaceRegistry returns SimApp's InterfaceRegistry. +func (app *SimApp) InterfaceRegistry() codectypes.InterfaceRegistry { +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) return app.interfaceRegistry } @@ -765,6 +1057,7 @@ func (app *SimApp) TxConfig() client.TxConfig { return app.txConfig } +<<<<<<< HEAD // AutoCliOpts returns the autocli options for the app. func (app *SimApp) AutoCliOpts() autocli.AppOptions { return autocli.AppOptions{ @@ -795,6 +1088,8 @@ func (app *SimApp) GetStoreKeys() []storetypes.StoreKey { return keys } +======= +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) // SimulationManager implements the SimulationApp interface func (app *SimApp) SimulationManager() *module.SimulationManager { return app.sm @@ -803,6 +1098,7 @@ func (app *SimApp) SimulationManager() *module.SimulationManager { // RegisterAPIRoutes registers all application module routes with the provided // API server. func (app *SimApp) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig) { +<<<<<<< HEAD clientCtx := apiSvr.ClientCtx // Register new tx routes from grpc-gateway. authtx.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) @@ -817,11 +1113,16 @@ func (app *SimApp) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APICon app.ModuleManager.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) // register swagger API from root so that other applications can override easily +======= + app.App.RegisterAPIRoutes(apiSvr, apiConfig) + // register swagger API in app.go so that other applications can override easily +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) if err := server.RegisterSwaggerAPI(apiSvr.ClientCtx, apiSvr.Router, apiConfig.Swagger); err != nil { panic(err) } } +<<<<<<< HEAD // RegisterTxService implements the Application.RegisterTxService method. func (app *SimApp) RegisterTxService(clientCtx client.Context) { authtx.RegisterTxService(app.BaseApp.GRPCQueryRouter(), clientCtx, app.BaseApp.Simulate, app.interfaceRegistry) @@ -850,10 +1151,13 @@ func (app *SimApp) ValidatorKeyProvider() runtime.KeyGenF { } } +======= +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) // GetMaccPerms returns a copy of the module account permissions // // NOTE: This is solely to be used for testing purposes. func GetMaccPerms() map[string][]string { +<<<<<<< HEAD return maps.Clone(maccPerms) } @@ -876,4 +1180,31 @@ func BlockedAddresses(ac coreaddress.Codec) (map[string]bool, error) { delete(modAccAddrs, addr) return modAccAddrs, nil +======= + dup := make(map[string][]string) + for _, perms := range moduleAccPerms { + dup[perms.Account] = perms.Permissions + } + + return dup +} + +// BlockedAddresses returns all the app's blocked account addresses. +// This function takes an address.Codec parameter to maintain compatibility +// with the signature of the same function in appV1. +func BlockedAddresses(_ address.Codec) (map[string]bool, error) { + result := make(map[string]bool) + + if len(blockAccAddrs) > 0 { + for _, addr := range blockAccAddrs { + result[addr] = true + } + } else { + for addr := range GetMaccPerms() { + result[addr] = true + } + } + + return result, nil +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) } diff --git a/simapp/app_di.go b/simapp/app_di.go deleted file mode 100644 index 4597ff8be733..000000000000 --- a/simapp/app_di.go +++ /dev/null @@ -1,405 +0,0 @@ -//go:build !app_v1 - -package simapp - -import ( - _ "embed" - "fmt" - "io" - - _ "github.com/jackc/pgx/v5/stdlib" // Import and register pgx driver - - clienthelpers "cosmossdk.io/client/v2/helpers" - "cosmossdk.io/core/address" - "cosmossdk.io/core/appmodule" - "cosmossdk.io/core/registry" - corestore "cosmossdk.io/core/store" - "cosmossdk.io/depinject" - _ "cosmossdk.io/indexer/postgres" // register the postgres indexer - "cosmossdk.io/log" - "cosmossdk.io/x/accounts" - basedepinject "cosmossdk.io/x/accounts/defaults/base/depinject" - lockupdepinject "cosmossdk.io/x/accounts/defaults/lockup/depinject" - multisigdepinject "cosmossdk.io/x/accounts/defaults/multisig/depinject" - "cosmossdk.io/x/accounts/testing/account_abstraction" - "cosmossdk.io/x/accounts/testing/counter" - bankkeeper "cosmossdk.io/x/bank/keeper" - circuitkeeper "cosmossdk.io/x/circuit/keeper" - consensuskeeper "cosmossdk.io/x/consensus/keeper" - distrkeeper "cosmossdk.io/x/distribution/keeper" - feegrantkeeper "cosmossdk.io/x/feegrant/keeper" - _ "cosmossdk.io/x/protocolpool" - slashingkeeper "cosmossdk.io/x/slashing/keeper" - stakingkeeper "cosmossdk.io/x/staking/keeper" - upgradekeeper "cosmossdk.io/x/upgrade/keeper" - - "github.com/cosmos/cosmos-sdk/baseapp" - "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/runtime" - "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/server/api" - "github.com/cosmos/cosmos-sdk/server/config" - servertypes "github.com/cosmos/cosmos-sdk/server/types" - testdata_pulsar "github.com/cosmos/cosmos-sdk/testutil/testdata/testpb" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/auth/ante" - "github.com/cosmos/cosmos-sdk/x/auth/ante/unorderedtx" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// DefaultNodeHome default home directories for the application daemon -var DefaultNodeHome string - -var ( - _ runtime.AppI = (*SimApp)(nil) - _ servertypes.Application = (*SimApp)(nil) -) - -// SimApp extends an ABCI application, but with most of its parameters exported. -// They are exported for convenience in creating helper functions, as object -// capabilities aren't needed for testing. -type SimApp struct { - *runtime.App - legacyAmino registry.AminoRegistrar - appCodec codec.Codec - txConfig client.TxConfig - interfaceRegistry codectypes.InterfaceRegistry - - // required keepers during wiring - // others keepers are all in the app - AccountsKeeper accounts.Keeper - AuthKeeper authkeeper.AccountKeeper - BankKeeper bankkeeper.Keeper - StakingKeeper *stakingkeeper.Keeper - SlashingKeeper slashingkeeper.Keeper - DistrKeeper distrkeeper.Keeper - UpgradeKeeper *upgradekeeper.Keeper - FeeGrantKeeper feegrantkeeper.Keeper - ConsensusParamsKeeper consensuskeeper.Keeper - CircuitBreakerKeeper circuitkeeper.Keeper - - // simulation manager - sm *module.SimulationManager -} - -func init() { - var err error - DefaultNodeHome, err = clienthelpers.GetNodeHomeDirectory(".simapp") - if err != nil { - panic(err) - } -} - -// AppConfig returns the default app config. -func AppConfig() depinject.Config { - return depinject.Configs( - appConfig, // Alternatively use appconfig.LoadYAML(AppConfigYAML) - depinject.Provide( - ProvideExampleMintFn, // optional: override the mint module's mint function with epoched minting - ), - ) -} - -// NewSimApp returns a reference to an initialized SimApp. -func NewSimApp( - logger log.Logger, - db corestore.KVStoreWithBatch, - traceStore io.Writer, - loadLatest bool, - appOpts servertypes.AppOptions, - baseAppOptions ...func(*baseapp.BaseApp), -) *SimApp { - var ( - app = &SimApp{} - appBuilder *runtime.AppBuilder - - // merge the AppConfig and other configuration in one config - appConfig = depinject.Configs( - AppConfig(), - depinject.Supply( - // supply the application options - appOpts, - // supply the logger - logger, - - // ADVANCED CONFIGURATION - - // - // AUTH - // - // For providing a custom function required in auth to generate custom account types - // add it below. By default the auth module uses simulation.RandomGenesisAccounts. - // - // authtypes.RandomGenesisAccountsFn(simulation.RandomGenesisAccounts), - // - // For providing a custom a base account type add it below. - // By default the auth module uses authtypes.ProtoBaseAccount(). - // - // func() sdk.AccountI { return authtypes.ProtoBaseAccount() }, - // - // For providing a different address codec, add it below. - // By default the auth module uses a Bech32 address codec, - // with the prefix defined in the auth module configuration. - // - // func() address.Codec { return <- custom address codec type -> } - - // - // STAKING - // - // For provinding a different validator and consensus address codec, add it below. - // By default the staking module uses the bech32 prefix provided in the auth config, - // and appends "valoper" and "valcons" for validator and consensus addresses respectively. - // When providing a custom address codec in auth, custom address codecs must be provided here as well. - // - // func() runtime.ValidatorAddressCodec { return <- custom validator address codec type -> } - // func() runtime.ConsensusAddressCodec { return <- custom consensus address codec type -> } - - // - // MINT - // - - // For providing a custom inflation function for x/mint add here your - // custom function that implements the minttypes.MintFn interface. - ), - depinject.Provide( - // inject desired account types: - multisigdepinject.ProvideAccount, - basedepinject.ProvideAccount, - lockupdepinject.ProvideAllLockupAccounts, - - // provide base account options - basedepinject.ProvideSecp256K1PubKey, - // if you want to provide a custom public key you - // can do it from here. - // Example: - // basedepinject.ProvideCustomPubkey[Ed25519PublicKey]() - // - // You can also provide a custom public key with a custom validation function: - // - // basedepinject.ProvideCustomPubKeyAndValidationFunc(func(pub Ed25519PublicKey) error { - // if len(pub.Key) != 64 { - // return fmt.Errorf("invalid pub key size") - // } - // }) - - // TESTING: do not add below account types - counter.ProvideAccount, - account_abstraction.ProvideAccount, - ), - ) - ) - - var appModules map[string]appmodule.AppModule - if err := depinject.Inject(appConfig, - &appBuilder, - &appModules, - &app.appCodec, - &app.legacyAmino, - &app.txConfig, - &app.interfaceRegistry, - &app.AuthKeeper, - &app.AccountsKeeper, - &app.BankKeeper, - &app.StakingKeeper, - &app.SlashingKeeper, - &app.DistrKeeper, - &app.UpgradeKeeper, - &app.FeeGrantKeeper, - &app.ConsensusParamsKeeper, - &app.CircuitBreakerKeeper, - ); err != nil { - panic(err) - } - - // Below we could construct and set an application specific mempool and - // ABCI 1.0 PrepareProposal and ProcessProposal handlers. These defaults are - // already set in the SDK's BaseApp, this shows an example of how to override - // them. - // - // Example: - // - // app.App = appBuilder.Build(...) - // nonceMempool := mempool.NewSenderNonceMempool() - // abciPropHandler := NewDefaultProposalHandler(nonceMempool, app.App.BaseApp) - // - // app.App.BaseApp.SetMempool(nonceMempool) - // app.App.BaseApp.SetPrepareProposal(abciPropHandler.PrepareProposalHandler()) - // app.App.BaseApp.SetProcessProposal(abciPropHandler.ProcessProposalHandler()) - // - // Alternatively, you can construct BaseApp options, append those to - // baseAppOptions and pass them to the appBuilder. - // - // Example: - // - // prepareOpt = func(app *baseapp.BaseApp) { - // abciPropHandler := baseapp.NewDefaultProposalHandler(nonceMempool, app) - // app.SetPrepareProposal(abciPropHandler.PrepareProposalHandler()) - // } - // baseAppOptions = append(baseAppOptions, prepareOpt) - - // create and set dummy vote extension handler - voteExtOp := func(bApp *baseapp.BaseApp) { - voteExtHandler := NewVoteExtensionHandler() - voteExtHandler.SetHandlers(bApp) - } - baseAppOptions = append(baseAppOptions, voteExtOp, baseapp.SetOptimisticExecution()) - - app.App = appBuilder.Build(db, traceStore, baseAppOptions...) - - /**** Module Options ****/ - - // RegisterUpgradeHandlers is used for registering any on-chain upgrades. - app.RegisterUpgradeHandlers() - - // add test gRPC service for testing gRPC queries in isolation - testdata_pulsar.RegisterQueryServer(app.GRPCQueryRouter(), testdata_pulsar.QueryImpl{}) - - // create the simulation manager and define the order of the modules for deterministic simulations - // - // NOTE: this is not required apps that don't use the simulator for fuzz testing - // transactions - overrideModules := map[string]module.AppModuleSimulation{ - authtypes.ModuleName: auth.NewAppModule(app.appCodec, app.AuthKeeper, &app.AccountsKeeper, authsims.RandomGenesisAccounts, nil), - } - app.sm = module.NewSimulationManagerFromAppModules(app.ModuleManager.Modules, overrideModules) - - app.sm.RegisterStoreDecoders() - - // A custom InitChainer can be set if extra pre-init-genesis logic is required. - // By default, when using app wiring enabled module, this is not required. - // For instance, the upgrade module will set automatically the module version map in its init genesis thanks to app wiring. - // However, when registering a module manually (i.e. that does not support app wiring), the module version map - // must be set manually as follow. The upgrade module will de-duplicate the module version map. - // - // app.SetInitChainer(func(ctx sdk.Context, req *abci.InitChainRequest) (*abci.InitChainResponse, error) { - // app.UpgradeKeeper.SetModuleVersionMap(ctx, app.ModuleManager.GetVersionMap()) - // return app.App.InitChainer(ctx, req) - // }) - - // register custom snapshot extensions (if any) - if manager := app.SnapshotManager(); manager != nil { - if err := manager.RegisterExtensions( - unorderedtx.NewSnapshotter(app.UnorderedTxManager), - ); err != nil { - panic(fmt.Errorf("failed to register snapshot extension: %w", err)) - } - } - - // set custom ante handlers - app.setCustomAnteHandler() - - if err := app.Load(loadLatest); err != nil { - panic(err) - } - - return app -} - -// setCustomAnteHandler overwrites default ante handlers with custom ante handlers -// set SkipAnteHandler to true in app config and set custom ante handler on baseapp -func (app *SimApp) setCustomAnteHandler() { - anteHandler, err := NewAnteHandler( - HandlerOptions{ - ante.HandlerOptions{ - AccountKeeper: app.AuthKeeper, - BankKeeper: app.BankKeeper, - ConsensusKeeper: app.ConsensusParamsKeeper, - SignModeHandler: app.txConfig.SignModeHandler(), - FeegrantKeeper: app.FeeGrantKeeper, - SigGasConsumer: ante.DefaultSigVerificationGasConsumer, - UnorderedTxManager: app.UnorderedTxManager, - Environment: app.AuthKeeper.Environment, - AccountAbstractionKeeper: app.AccountsKeeper, - }, - &app.CircuitBreakerKeeper, - }, - ) - if err != nil { - panic(err) - } - - // Set the AnteHandler for the app - app.SetAnteHandler(anteHandler) -} - -// LegacyAmino returns SimApp's amino codec. -// -// NOTE: This is solely to be used for testing purposes as it may be desirable -// for modules to register their own custom testing types. -func (app *SimApp) LegacyAmino() *codec.LegacyAmino { - switch cdc := app.legacyAmino.(type) { - case *codec.LegacyAmino: - return cdc - default: - panic("unexpected codec type") - } -} - -// AppCodec returns SimApp's app codec. -// -// NOTE: This is solely to be used for testing purposes as it may be desirable -// for modules to register their own custom testing types. -func (app *SimApp) AppCodec() codec.Codec { - return app.appCodec -} - -// InterfaceRegistry returns SimApp's InterfaceRegistry. -func (app *SimApp) InterfaceRegistry() codectypes.InterfaceRegistry { - return app.interfaceRegistry -} - -// TxConfig returns SimApp's TxConfig -func (app *SimApp) TxConfig() client.TxConfig { - return app.txConfig -} - -// SimulationManager implements the SimulationApp interface -func (app *SimApp) SimulationManager() *module.SimulationManager { - return app.sm -} - -// RegisterAPIRoutes registers all application module routes with the provided -// API server. -func (app *SimApp) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig) { - app.App.RegisterAPIRoutes(apiSvr, apiConfig) - // register swagger API in app.go so that other applications can override easily - if err := server.RegisterSwaggerAPI(apiSvr.ClientCtx, apiSvr.Router, apiConfig.Swagger); err != nil { - panic(err) - } -} - -// GetMaccPerms returns a copy of the module account permissions -// -// NOTE: This is solely to be used for testing purposes. -func GetMaccPerms() map[string][]string { - dup := make(map[string][]string) - for _, perms := range moduleAccPerms { - dup[perms.Account] = perms.Permissions - } - - return dup -} - -// BlockedAddresses returns all the app's blocked account addresses. -// This function takes an address.Codec parameter to maintain compatibility -// with the signature of the same function in appV1. -func BlockedAddresses(_ address.Codec) (map[string]bool, error) { - result := make(map[string]bool) - - if len(blockAccAddrs) > 0 { - for _, addr := range blockAccAddrs { - result[addr] = true - } - } else { - for addr := range GetMaccPerms() { - result[addr] = true - } - } - - return result, nil -} diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 7851629e7716..31e4ccae0660 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -1,4 +1,8 @@ +<<<<<<< HEAD //go:build app_v1 +======= +//go:build !app_v1 +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) package cmd @@ -7,25 +11,48 @@ import ( "github.com/spf13/cobra" +<<<<<<< HEAD coretesting "cosmossdk.io/core/testing" "cosmossdk.io/log" "cosmossdk.io/simapp" "cosmossdk.io/simapp/params" txsigning "cosmossdk.io/x/tx/signing" +======= + authv1 "cosmossdk.io/api/cosmos/auth/module/v1" + autocliv1 "cosmossdk.io/api/cosmos/autocli/v1" + stakingv1 "cosmossdk.io/api/cosmos/staking/module/v1" + "cosmossdk.io/client/v2/autocli" + "cosmossdk.io/core/address" + "cosmossdk.io/core/registry" + "cosmossdk.io/depinject" + "cosmossdk.io/log" + "cosmossdk.io/simapp" + basedepinject "cosmossdk.io/x/accounts/defaults/base/depinject" + lockupdepinject "cosmossdk.io/x/accounts/defaults/lockup/depinject" + multisigdepinject "cosmossdk.io/x/accounts/defaults/multisig/depinject" +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/config" nodeservice "github.com/cosmos/cosmos-sdk/client/grpc/node" +<<<<<<< HEAD addresscodec "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/server" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/tx/signing" +======= + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/server" + "github.com/cosmos/cosmos-sdk/types/module" +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) "github.com/cosmos/cosmos-sdk/x/auth/tx" authtxconfig "github.com/cosmos/cosmos-sdk/x/auth/tx/config" "github.com/cosmos/cosmos-sdk/x/auth/types" ) +<<<<<<< HEAD // NewRootCmd creates a new root command for simd. It is called once in the // main function. func NewRootCmd() *cobra.Command { @@ -53,6 +80,35 @@ func NewRootCmd() *cobra.Command { WithViper(""). // uses by default the binary name as prefix WithAddressPrefix(sdk.GetConfig().GetBech32AccountAddrPrefix()). WithValidatorPrefix(sdk.GetConfig().GetBech32ValidatorAddrPrefix()) +======= +// NewRootCmd creates a new root command for simd. It is called once in the main function. +func NewRootCmd() *cobra.Command { + var ( + autoCliOpts autocli.AppOptions + moduleManager *module.Manager + clientCtx client.Context + ) + + if err := depinject.Inject( + depinject.Configs(simapp.AppConfig(), + depinject.Supply(log.NewNopLogger()), + depinject.Provide( + ProvideClientContext, + multisigdepinject.ProvideAccount, + basedepinject.ProvideAccount, + lockupdepinject.ProvideAllLockupAccounts, + + // provide base account options + basedepinject.ProvideSecp256K1PubKey, + ), + ), + &autoCliOpts, + &moduleManager, + &clientCtx, + ); err != nil { + panic(err) + } +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) rootCmd := &cobra.Command{ Use: "simd", @@ -63,18 +119,28 @@ func NewRootCmd() *cobra.Command { cmd.SetOut(cmd.OutOrStdout()) cmd.SetErr(cmd.ErrOrStderr()) +<<<<<<< HEAD initClientCtx = initClientCtx.WithCmdContext(cmd.Context()) initClientCtx, err := client.ReadPersistentCommandFlags(initClientCtx, cmd.Flags()) +======= + clientCtx = clientCtx.WithCmdContext(cmd.Context()).WithViper("") + clientCtx, err := client.ReadPersistentCommandFlags(clientCtx, cmd.Flags()) +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) if err != nil { return err } customClientTemplate, customClientConfig := initClientConfig() +<<<<<<< HEAD initClientCtx, err = config.CreateClientConfig(initClientCtx, customClientTemplate, customClientConfig) +======= + clientCtx, err = config.CreateClientConfig(clientCtx, customClientTemplate, customClientConfig) +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) if err != nil { return err } +<<<<<<< HEAD // This needs to go after CreateClientConfig, as that function // sets the RPC client needed for SIGN_MODE_TEXTUAL. This sign mode // is only available if the client is online. @@ -100,6 +166,9 @@ func NewRootCmd() *cobra.Command { } if err := client.SetCmdClientContextHandler(initClientCtx, cmd); err != nil { +======= + if err := client.SetCmdClientContextHandler(clientCtx, cmd); err != nil { +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) return err } @@ -110,6 +179,7 @@ func NewRootCmd() *cobra.Command { }, } +<<<<<<< HEAD initRootCmd(rootCmd, tempApp.ModuleManager) // autocli opts @@ -127,6 +197,12 @@ func NewRootCmd() *cobra.Command { autoCliOpts.Cdc = initClientCtx.Codec nodeCmds := nodeservice.NewNodeCommands() +======= + initRootCmd(rootCmd, moduleManager) + + nodeCmds := nodeservice.NewNodeCommands() + autoCliOpts.ModuleOptions = make(map[string]*autocliv1.ModuleOptions) +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) autoCliOpts.ModuleOptions[nodeCmds.Name()] = nodeCmds.AutoCLIOptions() if err := autoCliOpts.EnhanceRootCommand(rootCmd); err != nil { @@ -135,3 +211,56 @@ func NewRootCmd() *cobra.Command { return rootCmd } +<<<<<<< HEAD +======= + +func ProvideClientContext( + appCodec codec.Codec, + interfaceRegistry codectypes.InterfaceRegistry, + txConfigOpts tx.ConfigOptions, + legacyAmino registry.AminoRegistrar, + addressCodec address.Codec, + validatorAddressCodec address.ValidatorAddressCodec, + consensusAddressCodec address.ConsensusAddressCodec, + authConfig *authv1.Module, + stakingConfig *stakingv1.Module, +) client.Context { + var err error + + amino, ok := legacyAmino.(*codec.LegacyAmino) + if !ok { + panic("ProvideClientContext requires a *codec.LegacyAmino instance") + } + + clientCtx := client.Context{}. + WithCodec(appCodec). + WithInterfaceRegistry(interfaceRegistry). + WithLegacyAmino(amino). + WithInput(os.Stdin). + WithAccountRetriever(types.AccountRetriever{}). + WithAddressCodec(addressCodec). + WithValidatorAddressCodec(validatorAddressCodec). + WithConsensusAddressCodec(consensusAddressCodec). + WithHomeDir(simapp.DefaultNodeHome). + WithViper(""). // uses by default the binary name as prefix + WithAddressPrefix(authConfig.Bech32Prefix). + WithValidatorPrefix(stakingConfig.Bech32PrefixValidator) + + // Read the config to overwrite the default values with the values from the config file + customClientTemplate, customClientConfig := initClientConfig() + clientCtx, err = config.CreateClientConfig(clientCtx, customClientTemplate, customClientConfig) + if err != nil { + panic(err) + } + + // textual is enabled by default, we need to re-create the tx config grpc instead of bank keeper. + txConfigOpts.TextualCoinMetadataQueryFn = authtxconfig.NewGRPCCoinMetadataQueryFn(clientCtx) + txConfig, err := tx.NewTxConfigWithOptions(clientCtx.Codec, txConfigOpts) + if err != nil { + panic(err) + } + clientCtx = clientCtx.WithTxConfig(txConfig) + + return clientCtx +} +>>>>>>> aa8266e70 (docs: runtime docs (#22816)) diff --git a/simapp/simd/cmd/root_di.go b/simapp/simd/cmd/root_di.go deleted file mode 100644 index ea6e70f37a99..000000000000 --- a/simapp/simd/cmd/root_di.go +++ /dev/null @@ -1,156 +0,0 @@ -//go:build !app_v1 - -package cmd - -import ( - "os" - - "github.com/spf13/cobra" - - authv1 "cosmossdk.io/api/cosmos/auth/module/v1" - autocliv1 "cosmossdk.io/api/cosmos/autocli/v1" - stakingv1 "cosmossdk.io/api/cosmos/staking/module/v1" - "cosmossdk.io/client/v2/autocli" - "cosmossdk.io/core/address" - "cosmossdk.io/core/registry" - "cosmossdk.io/depinject" - "cosmossdk.io/log" - "cosmossdk.io/simapp" - basedepinject "cosmossdk.io/x/accounts/defaults/base/depinject" - lockupdepinject "cosmossdk.io/x/accounts/defaults/lockup/depinject" - multisigdepinject "cosmossdk.io/x/accounts/defaults/multisig/depinject" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/config" - nodeservice "github.com/cosmos/cosmos-sdk/client/grpc/node" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/auth/tx" - authtxconfig "github.com/cosmos/cosmos-sdk/x/auth/tx/config" - "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// NewRootCmd creates a new root command for simd. It is called once in the main function. -func NewRootCmd() *cobra.Command { - var ( - autoCliOpts autocli.AppOptions - moduleManager *module.Manager - clientCtx client.Context - ) - - if err := depinject.Inject( - depinject.Configs(simapp.AppConfig(), - depinject.Supply(log.NewNopLogger()), - depinject.Provide( - ProvideClientContext, - multisigdepinject.ProvideAccount, - basedepinject.ProvideAccount, - lockupdepinject.ProvideAllLockupAccounts, - - // provide base account options - basedepinject.ProvideSecp256K1PubKey, - ), - ), - &autoCliOpts, - &moduleManager, - &clientCtx, - ); err != nil { - panic(err) - } - - rootCmd := &cobra.Command{ - Use: "simd", - Short: "simulation app", - SilenceErrors: true, - PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { - // set the default command outputs - cmd.SetOut(cmd.OutOrStdout()) - cmd.SetErr(cmd.ErrOrStderr()) - - clientCtx = clientCtx.WithCmdContext(cmd.Context()).WithViper("") - clientCtx, err := client.ReadPersistentCommandFlags(clientCtx, cmd.Flags()) - if err != nil { - return err - } - - customClientTemplate, customClientConfig := initClientConfig() - clientCtx, err = config.CreateClientConfig(clientCtx, customClientTemplate, customClientConfig) - if err != nil { - return err - } - - if err := client.SetCmdClientContextHandler(clientCtx, cmd); err != nil { - return err - } - - customAppTemplate, customAppConfig := initAppConfig() - customCMTConfig := initCometBFTConfig() - - return server.InterceptConfigsPreRunHandler(cmd, customAppTemplate, customAppConfig, customCMTConfig) - }, - } - - initRootCmd(rootCmd, moduleManager) - - nodeCmds := nodeservice.NewNodeCommands() - autoCliOpts.ModuleOptions = make(map[string]*autocliv1.ModuleOptions) - autoCliOpts.ModuleOptions[nodeCmds.Name()] = nodeCmds.AutoCLIOptions() - - if err := autoCliOpts.EnhanceRootCommand(rootCmd); err != nil { - panic(err) - } - - return rootCmd -} - -func ProvideClientContext( - appCodec codec.Codec, - interfaceRegistry codectypes.InterfaceRegistry, - txConfigOpts tx.ConfigOptions, - legacyAmino registry.AminoRegistrar, - addressCodec address.Codec, - validatorAddressCodec address.ValidatorAddressCodec, - consensusAddressCodec address.ConsensusAddressCodec, - authConfig *authv1.Module, - stakingConfig *stakingv1.Module, -) client.Context { - var err error - - amino, ok := legacyAmino.(*codec.LegacyAmino) - if !ok { - panic("ProvideClientContext requires a *codec.LegacyAmino instance") - } - - clientCtx := client.Context{}. - WithCodec(appCodec). - WithInterfaceRegistry(interfaceRegistry). - WithLegacyAmino(amino). - WithInput(os.Stdin). - WithAccountRetriever(types.AccountRetriever{}). - WithAddressCodec(addressCodec). - WithValidatorAddressCodec(validatorAddressCodec). - WithConsensusAddressCodec(consensusAddressCodec). - WithHomeDir(simapp.DefaultNodeHome). - WithViper(""). // uses by default the binary name as prefix - WithAddressPrefix(authConfig.Bech32Prefix). - WithValidatorPrefix(stakingConfig.Bech32PrefixValidator) - - // Read the config to overwrite the default values with the values from the config file - customClientTemplate, customClientConfig := initClientConfig() - clientCtx, err = config.CreateClientConfig(clientCtx, customClientTemplate, customClientConfig) - if err != nil { - panic(err) - } - - // textual is enabled by default, we need to re-create the tx config grpc instead of bank keeper. - txConfigOpts.TextualCoinMetadataQueryFn = authtxconfig.NewGRPCCoinMetadataQueryFn(clientCtx) - txConfig, err := tx.NewTxConfigWithOptions(clientCtx.Codec, txConfigOpts) - if err != nil { - panic(err) - } - clientCtx = clientCtx.WithTxConfig(txConfig) - - return clientCtx -} diff --git a/simapp/v2/app_di.go b/simapp/v2/app.go similarity index 100% rename from simapp/v2/app_di.go rename to simapp/v2/app.go diff --git a/simapp/v2/simdv2/cmd/root_di.go b/simapp/v2/simdv2/cmd/root.go similarity index 100% rename from simapp/v2/simdv2/cmd/root_di.go rename to simapp/v2/simdv2/cmd/root.go