diff --git a/UPGRADING.md b/UPGRADING.md index 6126ce607b9c..95e6bafe43f9 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -154,35 +154,25 @@ The `codectypes.Any` has moved to `github.com/cosmos/gogoproto/types/any`. Modul #### `**all**` -##### Simulation - -`MsgSimulatorFn` has been updated to return an error. Its context argument has been removed, and an address.Codec has -been added to avoid the use of the Accounts.String() method. - -```diff --type MsgSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []Account) sdk.Msg -+type MsgSimulatorFn func(r *rand.Rand, accs []Account, cdc address.Codec) (sdk.Msg, error) -``` - ##### Core API 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. -Additionally, the `appmodule.Environment` interface is introduced to fetch different services from the application. +Additionally, the `appmodule.Environment` struct 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. +It needs to be passed into a module at instantiation (or depinject will inject the correct environment). `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()) +app.CircuitKeeper = circuitkeeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[circuittypes.StoreKey]), logger.With(log.ModuleKey, "x/circuit")), appCodec, authtypes.NewModuleAddress(govtypes.ModuleName).String(), app.AuthKeeper.AddressCodec()) ``` If your module requires a message server or query server, it should be passed in the environment as well. ```diff -govKeeper := govkeeper.NewKeeper(appCodec, runtime.NewKVStoreService(keys[govtypes.StoreKey]), app.AuthKeeper, app.BankKeeper,app.StakingKeeper, app.PoolKeeper, app.MsgServiceRouter(), govConfig, authtypes.NewModuleAddress(govtypes.ModuleName).String()) -+govKeeper := govkeeper.NewKeeper(appCodec, runtime.NewEnvironment(runtime.NewKVStoreService(keys[govtypes.StoreKey]), logger, runtime.EnvWithRouterService(app.GRPCQueryRouter(), app.MsgServiceRouter())), app.AuthKeeper, app.BankKeeper, app.StakingKeeper, app.PoolKeeper, govConfig, authtypes.NewModuleAddress(govtypes.ModuleName).String()) ++govKeeper := govkeeper.NewKeeper(appCodec, runtime.NewEnvironment(runtime.NewKVStoreService(keys[govtypes.StoreKey]), logger.With(log.ModuleKey, "x/circuit"), runtime.EnvWithRouterService(app.GRPCQueryRouter(), app.MsgServiceRouter())), app.AuthKeeper, app.BankKeeper, app.StakingKeeper, app.PoolKeeper, govConfig, authtypes.NewModuleAddress(govtypes.ModuleName).String()) ``` The signature of the extension interface `HasRegisterInterfaces` has been changed to accept a `cosmossdk.io/core/registry.InterfaceRegistrar` instead of a `codec.InterfaceRegistry`. `HasRegisterInterfaces` is now a part of `cosmossdk.io/core/appmodule`. Modules should update their `HasRegisterInterfaces` implementation to accept a `cosmossdk.io/core/registry.InterfaceRegistrar` interface. @@ -192,6 +182,16 @@ The signature of the extension interface `HasRegisterInterfaces` has been change +func (AppModule) RegisterInterfaces(registry registry.InterfaceRegistrar) { ``` +##### Simulation + +`MsgSimulatorFn` has been updated to return an error. Its context argument has been removed, and an address.Codec has +been added to avoid the use of the Accounts.String() method. + +```diff +-type MsgSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []Account) sdk.Msg ++type MsgSimulatorFn func(r *rand.Rand, accs []Account, cdc address.Codec) (sdk.Msg, error) +``` + ##### Dependency Injection Previously `cosmossdk.io/core` held functions `Invoke`, `Provide` and `Register` were moved to `cosmossdk.io/depinject/appconfig`. diff --git a/core/comet/service.go b/core/comet/service.go index bc99e820f11f..772ceec325a6 100644 --- a/core/comet/service.go +++ b/core/comet/service.go @@ -5,9 +5,9 @@ import ( "time" ) -// CometInfoService is an interface that can be used to get information specific to Comet -type CometInfoService interface { - GetCometInfo(context.Context) Info +// Service is an interface that can be used to get information specific to Comet +type Service interface { + CometInfo(context.Context) Info } // Info is the information comet provides apps in ABCI diff --git a/core/gas/service.go b/core/gas/service.go index 40d212e943f1..2fb587d0d961 100644 --- a/core/gas/service.go +++ b/core/gas/service.go @@ -24,23 +24,24 @@ const NoGasLimit Gas = math.MaxUint64 // gas.Service is a core API type that should be provided by the runtime module being used to // build an app via depinject. type Service interface { - // GetGasMeter returns the current transaction-level gas meter. A non-nil meter + // GasMeter returns the current transaction-level gas meter. A non-nil meter // is always returned. When one is unavailable in the context an infinite gas meter // will be returned. - GetGasMeter(context.Context) Meter - - // GetBlockGasMeter returns the current block-level gas meter. A non-nil meter - // is always returned. When one is unavailable in the context an infinite gas meter - // will be returned. - GetBlockGasMeter(context.Context) Meter + GasMeter(context.Context) Meter // WithGasMeter returns a new context with the provided transaction-level gas meter. WithGasMeter(ctx context.Context, meter Meter) context.Context + // BlockGasMeter returns the current block-level gas meter. A non-nil meter + // is always returned. When one is unavailable in the context an infinite gas meter + // will be returned. + BlockGasMeter(context.Context) Meter + // WithBlockGasMeter returns a new context with the provided block-level gas meter. WithBlockGasMeter(ctx context.Context, meter Meter) context.Context - GetGasConfig(ctx context.Context) GasConfig + // GasConfig returns the gas costs. + GasConfig(ctx context.Context) GasConfig } // Meter represents a gas meter for modules consumption diff --git a/core/header/service.go b/core/header/service.go index cce7e6de30c5..2dcebc4f151c 100644 --- a/core/header/service.go +++ b/core/header/service.go @@ -7,7 +7,7 @@ import ( // Service defines the interface in which you can get header information type Service interface { - GetHeaderInfo(context.Context) Info + HeaderInfo(context.Context) Info } // Info defines a struct that contains information about the header diff --git a/core/store/database.go b/core/store/database.go index 45283ee62184..ef36b8967980 100644 --- a/core/store/database.go +++ b/core/store/database.go @@ -3,7 +3,7 @@ package store // DatabaseService provides access to the underlying database for CRUD operations of non-consensus data. // WARNING: using this api will make your module unprovable for fraud and validity proofs type DatabaseService interface { - GetDatabase() NonConsensusStore + Database() NonConsensusStore } // NonConsensusStore is a simple key-value store that is used to store non-consensus data. diff --git a/docs/architecture/adr-063-core-module-api.md b/docs/architecture/adr-063-core-module-api.md index 1615a590eb21..22dfaf849456 100644 --- a/docs/architecture/adr-063-core-module-api.md +++ b/docs/architecture/adr-063-core-module-api.md @@ -330,7 +330,7 @@ Header Service defines a way to get header information about a block. This infor ```go type Service interface { - GetHeaderInfo(context.Context) Info + HeaderInfo(context.Context) Info } type Info struct { @@ -463,6 +463,7 @@ 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` diff --git a/runtime/gas.go b/runtime/gas.go index f6e28c9f2f56..ec7f5014047c 100644 --- a/runtime/gas.go +++ b/runtime/gas.go @@ -14,30 +14,26 @@ var _ gas.Service = GasService{} type GasService struct{} -func (g GasService) GetGasMeter(ctx context.Context) gas.Meter { +func (g GasService) GasMeter(ctx context.Context) gas.Meter { return CoreGasmeter{gm: sdk.UnwrapSDKContext(ctx).GasMeter()} } -func (g GasService) GetBlockGasMeter(ctx context.Context) gas.Meter { - return CoreGasmeter{gm: sdk.UnwrapSDKContext(ctx).BlockGasMeter()} -} - func (g GasService) WithGasMeter(ctx context.Context, meter gas.Meter) context.Context { return sdk.UnwrapSDKContext(ctx).WithGasMeter(SDKGasMeter{gm: meter}) } +func (g GasService) BlockGasMeter(ctx context.Context) gas.Meter { + return CoreGasmeter{gm: sdk.UnwrapSDKContext(ctx).BlockGasMeter()} +} + func (g GasService) WithBlockGasMeter(ctx context.Context, meter gas.Meter) context.Context { return sdk.UnwrapSDKContext(ctx).WithGasMeter(SDKGasMeter{gm: meter}) } -func (g GasService) GetGasConfig(ctx context.Context) gas.GasConfig { +func (g GasService) GasConfig(ctx context.Context) gas.GasConfig { return gas.GasConfig(sdk.UnwrapSDKContext(ctx).KVGasConfig()) } -// ______________________________________________________________________________________________ -// Gas Meter Wrappers -// ______________________________________________________________________________________________ - // SDKGasMeter is a wrapper around the SDK's GasMeter that implements the GasMeter interface. type SDKGasMeter struct { gm gas.Meter diff --git a/runtime/header.go b/runtime/header.go index 5016912d9a71..c27df04f1fd2 100644 --- a/runtime/header.go +++ b/runtime/header.go @@ -12,6 +12,6 @@ var _ header.Service = (*HeaderService)(nil) type HeaderService struct{} -func (h HeaderService) GetHeaderInfo(ctx context.Context) header.Info { +func (h HeaderService) HeaderInfo(ctx context.Context) header.Info { return sdk.UnwrapSDKContext(ctx).HeaderInfo() } diff --git a/runtime/module.go b/runtime/module.go index 65a3ddcf4ec2..aff84e730862 100644 --- a/runtime/module.go +++ b/runtime/module.go @@ -260,7 +260,7 @@ func ProvideEnvironment( return kvService, memStoreService, NewEnvironment( kvService, - logger, + logger.With(log.ModuleKey, fmt.Sprintf("x/%s", key.Name())), EnvWithRouterService(queryServiceRouter, msgServiceRouter), EnvWithMemStoreService(memStoreService), ) diff --git a/simapp/ante.go b/simapp/ante.go index 713c342b8bcf..939d14362477 100644 --- a/simapp/ante.go +++ b/simapp/ante.go @@ -37,9 +37,9 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) { ante.NewSetUpContextDecorator(), // outermost AnteDecorator. SetUpContext must be called first circuitante.NewCircuitBreakerDecorator(options.CircuitKeeper), ante.NewExtensionOptionsDecorator(options.ExtensionOptionChecker), - ante.NewValidateBasicDecorator(options.AccountKeeper.Environment()), + ante.NewValidateBasicDecorator(options.AccountKeeper.GetEnvironment()), ante.NewTxTimeoutHeightDecorator(), - ante.NewUnorderedTxDecorator(unorderedtx.DefaultMaxUnOrderedTTL, options.TxManager, options.AccountKeeper.Environment()), + ante.NewUnorderedTxDecorator(unorderedtx.DefaultMaxUnOrderedTTL, options.TxManager, options.AccountKeeper.GetEnvironment()), ante.NewValidateMemoDecorator(options.AccountKeeper), ante.NewConsumeGasForTxSizeDecorator(options.AccountKeeper), ante.NewDeductFeeDecorator(options.AccountKeeper, options.BankKeeper, options.FeegrantKeeper, options.TxFeeChecker), diff --git a/simapp/app.go b/simapp/app.go index 27b7add32317..9bf64c813bd9 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -281,13 +281,13 @@ func NewSimApp( } // set the BaseApp's parameter store - app.ConsensusParamsKeeper = consensusparamkeeper.NewKeeper(appCodec, runtime.NewEnvironment(runtime.NewKVStoreService(keys[consensusparamtypes.StoreKey]), logger), authtypes.NewModuleAddress(govtypes.ModuleName).String()) + app.ConsensusParamsKeeper = consensusparamkeeper.NewKeeper(appCodec, runtime.NewEnvironment(runtime.NewKVStoreService(keys[consensusparamtypes.StoreKey]), logger.With(log.ModuleKey, "x/consensus")), authtypes.NewModuleAddress(govtypes.ModuleName).String()) bApp.SetParamStore(app.ConsensusParamsKeeper.ParamsStore) // add keepers accountsKeeper, err := accounts.NewKeeper( appCodec, - runtime.NewEnvironment(runtime.NewKVStoreService(keys[accounts.StoreKey]), logger, runtime.EnvWithRouterService(app.GRPCQueryRouter(), app.MsgServiceRouter())), + runtime.NewEnvironment(runtime.NewKVStoreService(keys[accounts.StoreKey]), logger.With(log.ModuleKey, "x/accounts"), runtime.EnvWithRouterService(app.GRPCQueryRouter(), app.MsgServiceRouter())), signingCtx.AddressCodec(), appCodec.InterfaceRegistry(), // TESTING: do not add @@ -306,10 +306,10 @@ func NewSimApp( } app.AccountsKeeper = accountsKeeper - app.AuthKeeper = authkeeper.NewAccountKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[authtypes.StoreKey]), logger), appCodec, authtypes.ProtoBaseAccount, accountsKeeper, maccPerms, signingCtx.AddressCodec(), sdk.Bech32MainPrefix, authtypes.NewModuleAddress(govtypes.ModuleName).String()) + app.AuthKeeper = authkeeper.NewAccountKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[authtypes.StoreKey]), logger.With(log.ModuleKey, "x/auth")), appCodec, authtypes.ProtoBaseAccount, accountsKeeper, maccPerms, signingCtx.AddressCodec(), sdk.Bech32MainPrefix, authtypes.NewModuleAddress(govtypes.ModuleName).String()) app.BankKeeper = bankkeeper.NewBaseKeeper( - runtime.NewEnvironment(runtime.NewKVStoreService(keys[banktypes.StoreKey]), logger), + runtime.NewEnvironment(runtime.NewKVStoreService(keys[banktypes.StoreKey]), logger.With(log.ModuleKey, "x/bank")), appCodec, app.AuthKeeper, BlockedAddresses(), @@ -336,19 +336,19 @@ func NewSimApp( app.txConfig = txConfig app.StakingKeeper = stakingkeeper.NewKeeper( - appCodec, runtime.NewEnvironment(runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), logger), app.AuthKeeper, app.BankKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), signingCtx.ValidatorAddressCodec(), authcodec.NewBech32Codec(sdk.Bech32PrefixConsAddr), + appCodec, runtime.NewEnvironment(runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), logger.With(log.ModuleKey, "x/staking")), app.AuthKeeper, app.BankKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), signingCtx.ValidatorAddressCodec(), authcodec.NewBech32Codec(sdk.Bech32PrefixConsAddr), ) - app.MintKeeper = mintkeeper.NewKeeper(appCodec, runtime.NewEnvironment(runtime.NewKVStoreService(keys[minttypes.StoreKey]), logger), app.StakingKeeper, app.AuthKeeper, app.BankKeeper, authtypes.FeeCollectorName, authtypes.NewModuleAddress(govtypes.ModuleName).String()) + app.MintKeeper = mintkeeper.NewKeeper(appCodec, runtime.NewEnvironment(runtime.NewKVStoreService(keys[minttypes.StoreKey]), logger.With(log.ModuleKey, "x/mint")), app.StakingKeeper, app.AuthKeeper, app.BankKeeper, authtypes.FeeCollectorName, authtypes.NewModuleAddress(govtypes.ModuleName).String()) - app.PoolKeeper = poolkeeper.NewKeeper(appCodec, runtime.NewEnvironment(runtime.NewKVStoreService(keys[pooltypes.StoreKey]), logger), app.AuthKeeper, app.BankKeeper, app.StakingKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String()) + app.PoolKeeper = poolkeeper.NewKeeper(appCodec, runtime.NewEnvironment(runtime.NewKVStoreService(keys[pooltypes.StoreKey]), logger.With(log.ModuleKey, "x/protocolpool")), app.AuthKeeper, app.BankKeeper, app.StakingKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String()) - app.DistrKeeper = distrkeeper.NewKeeper(appCodec, runtime.NewEnvironment(runtime.NewKVStoreService(keys[distrtypes.StoreKey]), logger), app.AuthKeeper, app.BankKeeper, app.StakingKeeper, app.PoolKeeper, authtypes.FeeCollectorName, authtypes.NewModuleAddress(govtypes.ModuleName).String()) + app.DistrKeeper = distrkeeper.NewKeeper(appCodec, runtime.NewEnvironment(runtime.NewKVStoreService(keys[distrtypes.StoreKey]), logger.With(log.ModuleKey, "x/distribution")), app.AuthKeeper, app.BankKeeper, app.StakingKeeper, app.PoolKeeper, authtypes.FeeCollectorName, authtypes.NewModuleAddress(govtypes.ModuleName).String()) - app.SlashingKeeper = slashingkeeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[slashingtypes.StoreKey]), logger), + app.SlashingKeeper = slashingkeeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[slashingtypes.StoreKey]), logger.With(log.ModuleKey, "x/slashing")), appCodec, legacyAmino, app.StakingKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) - app.FeeGrantKeeper = feegrantkeeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[feegrant.StoreKey]), logger), appCodec, app.AuthKeeper) + app.FeeGrantKeeper = feegrantkeeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[feegrant.StoreKey]), logger.With(log.ModuleKey, "x/feegrant")), appCodec, app.AuthKeeper) // register the staking hooks // NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks @@ -356,10 +356,10 @@ func NewSimApp( stakingtypes.NewMultiStakingHooks(app.DistrKeeper.Hooks(), app.SlashingKeeper.Hooks()), ) - app.CircuitKeeper = circuitkeeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[circuittypes.StoreKey]), logger), appCodec, authtypes.NewModuleAddress(govtypes.ModuleName).String(), app.AuthKeeper.AddressCodec()) + app.CircuitKeeper = circuitkeeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[circuittypes.StoreKey]), logger.With(log.ModuleKey, "x/circuit")), appCodec, authtypes.NewModuleAddress(govtypes.ModuleName).String(), app.AuthKeeper.AddressCodec()) app.BaseApp.SetCircuitBreaker(&app.CircuitKeeper) - app.AuthzKeeper = authzkeeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[authzkeeper.StoreKey]), logger, runtime.EnvWithRouterService(app.GRPCQueryRouter(), app.MsgServiceRouter())), appCodec, app.AuthKeeper) + app.AuthzKeeper = authzkeeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[authzkeeper.StoreKey]), logger.With(log.ModuleKey, "x/authz"), runtime.EnvWithRouterService(app.GRPCQueryRouter(), app.MsgServiceRouter())), appCodec, app.AuthKeeper) groupConfig := group.DefaultConfig() /* @@ -369,7 +369,7 @@ func NewSimApp( config.MaxProposalTitleLen = 255 // example max title length in characters config.MaxProposalSummaryLen = 10200 // example max summary length in characters */ - app.GroupKeeper = groupkeeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[group.StoreKey]), logger, runtime.EnvWithRouterService(app.GRPCQueryRouter(), app.MsgServiceRouter())), appCodec, app.AuthKeeper, groupConfig) + app.GroupKeeper = groupkeeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[group.StoreKey]), logger.With(log.ModuleKey, "x/group"), runtime.EnvWithRouterService(app.GRPCQueryRouter(), app.MsgServiceRouter())), appCodec, app.AuthKeeper, groupConfig) // get skipUpgradeHeights from the app options skipUpgradeHeights := map[int64]bool{} @@ -378,7 +378,7 @@ func NewSimApp( } homePath := cast.ToString(appOpts.Get(flags.FlagHome)) // set the governance module account as the authority for conducting upgrades - app.UpgradeKeeper = upgradekeeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[upgradetypes.StoreKey]), logger), skipUpgradeHeights, appCodec, homePath, app.BaseApp, authtypes.NewModuleAddress(govtypes.ModuleName).String()) + app.UpgradeKeeper = upgradekeeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[upgradetypes.StoreKey]), logger.With(log.ModuleKey, "x/upgrade")), skipUpgradeHeights, appCodec, homePath, app.BaseApp, authtypes.NewModuleAddress(govtypes.ModuleName).String()) // Register the proposal types // Deprecated: Avoid adding new handlers, instead use the new proposal flow @@ -390,7 +390,7 @@ func NewSimApp( Example of setting gov params: govConfig.MaxMetadataLen = 10000 */ - govKeeper := govkeeper.NewKeeper(appCodec, runtime.NewEnvironment(runtime.NewKVStoreService(keys[govtypes.StoreKey]), logger, runtime.EnvWithRouterService(app.GRPCQueryRouter(), app.MsgServiceRouter())), app.AuthKeeper, app.BankKeeper, app.StakingKeeper, app.PoolKeeper, govConfig, authtypes.NewModuleAddress(govtypes.ModuleName).String()) + govKeeper := govkeeper.NewKeeper(appCodec, runtime.NewEnvironment(runtime.NewKVStoreService(keys[govtypes.StoreKey]), logger.With(log.ModuleKey, "x/gov"), runtime.EnvWithRouterService(app.GRPCQueryRouter(), app.MsgServiceRouter())), app.AuthKeeper, app.BankKeeper, app.StakingKeeper, app.PoolKeeper, govConfig, authtypes.NewModuleAddress(govtypes.ModuleName).String()) // Set legacy router for backwards compatibility with gov v1beta1 govKeeper.SetLegacyRouter(govRouter) @@ -401,17 +401,17 @@ func NewSimApp( ), ) - app.NFTKeeper = nftkeeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[nftkeeper.StoreKey]), logger), appCodec, app.AuthKeeper, app.BankKeeper) + app.NFTKeeper = nftkeeper.NewKeeper(runtime.NewEnvironment(runtime.NewKVStoreService(keys[nftkeeper.StoreKey]), logger.With(log.ModuleKey, "x/nft")), appCodec, app.AuthKeeper, app.BankKeeper) // create evidence keeper with router evidenceKeeper := evidencekeeper.NewKeeper( - appCodec, runtime.NewEnvironment(runtime.NewKVStoreService(keys[evidencetypes.StoreKey]), logger), app.StakingKeeper, app.SlashingKeeper, app.AuthKeeper.AddressCodec(), + appCodec, runtime.NewEnvironment(runtime.NewKVStoreService(keys[evidencetypes.StoreKey]), logger.With(log.ModuleKey, "x/evidence")), app.StakingKeeper, app.SlashingKeeper, app.AuthKeeper.AddressCodec(), ) // If evidence needs to be handled for the app, set routes in router here and seal app.EvidenceKeeper = *evidenceKeeper app.EpochsKeeper = epochskeeper.NewKeeper( - runtime.NewEnvironment(runtime.NewKVStoreService(keys[epochstypes.StoreKey]), logger), + runtime.NewEnvironment(runtime.NewKVStoreService(keys[epochstypes.StoreKey]), logger.With(log.ModuleKey, "x/epochs")), appCodec, ) diff --git a/x/accounts/defaults/base/account.go b/x/accounts/defaults/base/account.go index 76f76124996f..7b29b2f10faf 100644 --- a/x/accounts/defaults/base/account.go +++ b/x/accounts/defaults/base/account.go @@ -127,7 +127,7 @@ func (a Account) computeSignerData(ctx context.Context) (secp256k1.PubKey, signi if err != nil { return secp256k1.PubKey{}, signing.SignerData{}, err } - chainID := a.hs.GetHeaderInfo(ctx).ChainID + chainID := a.hs.HeaderInfo(ctx).ChainID wantSequence, err := a.Sequence.Next(ctx) if err != nil { diff --git a/x/accounts/defaults/lockup/continuous_locking_account.go b/x/accounts/defaults/lockup/continuous_locking_account.go index c38a48d4ee08..d01acdbbf7ff 100644 --- a/x/accounts/defaults/lockup/continuous_locking_account.go +++ b/x/accounts/defaults/lockup/continuous_locking_account.go @@ -45,7 +45,7 @@ func (cva ContinuousLockingAccount) Init(ctx context.Context, msg *lockuptypes.M return nil, sdkerrors.ErrInvalidRequest.Wrap("invalid start and end time (must be start before end)") } - hs := cva.headerService.GetHeaderInfo(ctx) + hs := cva.headerService.HeaderInfo(ctx) start := msg.StartTime if msg.StartTime.IsZero() { @@ -197,7 +197,7 @@ func (cva ContinuousLockingAccount) QueryLockupAccountInfo(ctx context.Context, if err != nil { return nil, err } - hs := cva.headerService.GetHeaderInfo(ctx) + hs := cva.headerService.HeaderInfo(ctx) unlockedCoins, lockedCoins, err := cva.GetLockCoinsInfo(ctx, hs.Time) if err != nil { return nil, err diff --git a/x/accounts/defaults/lockup/delayed_locking_account.go b/x/accounts/defaults/lockup/delayed_locking_account.go index dbc19d960081..deb8361d5dcc 100644 --- a/x/accounts/defaults/lockup/delayed_locking_account.go +++ b/x/accounts/defaults/lockup/delayed_locking_account.go @@ -131,7 +131,7 @@ func (dva DelayedLockingAccount) QueryVestingAccountInfo(ctx context.Context, re if err != nil { return nil, err } - hs := dva.headerService.GetHeaderInfo(ctx) + hs := dva.headerService.HeaderInfo(ctx) unlockedCoins, lockedCoins, err := dva.GetLockCoinsInfo(ctx, hs.Time) if err != nil { return nil, err diff --git a/x/accounts/defaults/lockup/lockup.go b/x/accounts/defaults/lockup/lockup.go index 71e7687c8428..bceea5b71e36 100644 --- a/x/accounts/defaults/lockup/lockup.go +++ b/x/accounts/defaults/lockup/lockup.go @@ -135,7 +135,7 @@ func (bva *BaseLockup) Delegate( return nil, err } - hs := bva.headerService.GetHeaderInfo(ctx) + hs := bva.headerService.HeaderInfo(ctx) balance, err := bva.getBalance(ctx, delegatorAddress, msg.Amount.Denom) if err != nil { @@ -209,7 +209,7 @@ func (bva *BaseLockup) SendCoins( return nil, err } - hs := bva.headerService.GetHeaderInfo(ctx) + hs := bva.headerService.HeaderInfo(ctx) lockedCoins, err := getLockedCoinsFunc(ctx, hs.Time, msg.Amount.Denoms()...) if err != nil { @@ -247,7 +247,7 @@ func (bva *BaseLockup) WithdrawUnlockedCoins( return nil, err } - hs := bva.headerService.GetHeaderInfo(ctx) + hs := bva.headerService.HeaderInfo(ctx) lockedCoins, err := getLockedCoinsFunc(ctx, hs.Time, msg.Denoms...) if err != nil { return nil, err diff --git a/x/accounts/defaults/lockup/periodic_locking_account.go b/x/accounts/defaults/lockup/periodic_locking_account.go index be3ce30c1539..6d07afacba84 100644 --- a/x/accounts/defaults/lockup/periodic_locking_account.go +++ b/x/accounts/defaults/lockup/periodic_locking_account.go @@ -44,7 +44,7 @@ func (pva PeriodicLockingAccount) Init(ctx context.Context, msg *lockuptypes.Msg return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid 'owner' address: %s", err) } - hs := pva.headerService.GetHeaderInfo(ctx) + hs := pva.headerService.HeaderInfo(ctx) if msg.StartTime.Before(hs.Time) { return nil, sdkerrors.ErrInvalidRequest.Wrap("start time %s should be after block time") @@ -290,7 +290,7 @@ func (pva PeriodicLockingAccount) QueryLockupAccountInfo(ctx context.Context, re if err != nil { return nil, err } - hs := pva.headerService.GetHeaderInfo(ctx) + hs := pva.headerService.HeaderInfo(ctx) unlockedCoins, lockedCoins, err := pva.GetLockCoinsInfo(ctx, hs.Time) if err != nil { return nil, err diff --git a/x/accounts/keeper.go b/x/accounts/keeper.go index 45cb44422483..d61faecf5098 100644 --- a/x/accounts/keeper.go +++ b/x/accounts/keeper.go @@ -49,7 +49,7 @@ func NewKeeper( ) (Keeper, error) { sb := collections.NewSchemaBuilder(env.KVStoreService) keeper := Keeper{ - environment: env, + Environment: env, codec: cdc, addressCodec: addressCodec, makeSendCoinsMsg: defaultCoinsTransferMsgFunc(addressCodec), @@ -74,8 +74,8 @@ func NewKeeper( } type Keeper struct { - // deps coming from the runtime - environment appmodule.Environment + appmodule.Environment + addressCodec address.Codec codec codec.Codec makeSendCoinsMsg coinsTransferMsgFunc @@ -268,7 +268,7 @@ func (k Keeper) makeAccountContext(ctx context.Context, accountNumber uint64, ac if !isQuery { return implementation.MakeAccountContext( ctx, - k.environment.KVStoreService, + k.KVStoreService, accountNumber, accountAddr, sender, @@ -283,7 +283,7 @@ func (k Keeper) makeAccountContext(ctx context.Context, accountNumber uint64, ac // and does not allow to get the sender. return implementation.MakeAccountContext( ctx, - k.environment.KVStoreService, + k.KVStoreService, accountNumber, accountAddr, nil, @@ -324,7 +324,7 @@ func (k Keeper) sendAnyMessages(ctx context.Context, sender []byte, anyMessages // SendModuleMessageUntyped can be used to send a message towards a module. // It should be used when the response type is not known by the caller. func (k Keeper) SendModuleMessageUntyped(ctx context.Context, sender []byte, msg implementation.ProtoMsg) (implementation.ProtoMsg, error) { - resp, err := k.environment.RouterService.MessageRouterService().InvokeUntyped(ctx, msg) + resp, err := k.RouterService.MessageRouterService().InvokeUntyped(ctx, msg) if err != nil { return nil, err } @@ -347,14 +347,14 @@ func (k Keeper) sendModuleMessage(ctx context.Context, sender []byte, msg, msgRe if !bytes.Equal(sender, wantSenders[0]) { return fmt.Errorf("%w: sender does not match expected sender", ErrUnauthorized) } - return k.environment.RouterService.MessageRouterService().InvokeTyped(ctx, msg, msgResp) + return k.RouterService.MessageRouterService().InvokeTyped(ctx, msg, msgResp) } // queryModule is the entrypoint for an account to query a module. // It will try to find the query handler for the given query and execute it. // If multiple query handlers are found, it will return an error. func (k Keeper) queryModule(ctx context.Context, queryReq, queryResp implementation.ProtoMsg) error { - return k.environment.RouterService.QueryRouterService().InvokeTyped(ctx, queryReq, queryResp) + return k.RouterService.QueryRouterService().InvokeTyped(ctx, queryReq, queryResp) } // maybeSendFunds will send the provided coins between the provided addresses, if amt diff --git a/x/accounts/msg_server.go b/x/accounts/msg_server.go index 62c0776e1982..182d7025d119 100644 --- a/x/accounts/msg_server.go +++ b/x/accounts/msg_server.go @@ -42,7 +42,7 @@ func (m msgServer) Init(ctx context.Context, request *v1.MsgInit) (*v1.MsgInitRe return nil, err } - eventManager := m.k.environment.EventService.EventManager(ctx) + eventManager := m.k.EventService.EventManager(ctx) err = eventManager.EmitKV( "account_creation", event.NewAttribute("address", accAddrString), diff --git a/x/accounts/testing/counter/counter.go b/x/accounts/testing/counter/counter.go index 0e1ab9d78334..ec96c0884fb6 100644 --- a/x/accounts/testing/counter/counter.go +++ b/x/accounts/testing/counter/counter.go @@ -110,10 +110,10 @@ func (a Account) TestDependencies(ctx context.Context, _ *counterv1.MsgTestDepen } // test header service - chainID := a.hs.GetHeaderInfo(ctx).ChainID + chainID := a.hs.HeaderInfo(ctx).ChainID // test gas meter - gm := a.gs.GetGasMeter(ctx) + gm := a.gs.GasMeter(ctx) gasBefore := gm.Limit() - gm.Remaining() gm.Consume(10, "test") gasAfter := gm.Limit() - gm.Remaining() diff --git a/x/auth/ante/ante.go b/x/auth/ante/ante.go index c3e68b92af59..7f823eef343d 100644 --- a/x/auth/ante/ante.go +++ b/x/auth/ante/ante.go @@ -42,7 +42,7 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) { anteDecorators := []sdk.AnteDecorator{ NewSetUpContextDecorator(), // outermost AnteDecorator. SetUpContext must be called first NewExtensionOptionsDecorator(options.ExtensionOptionChecker), - NewValidateBasicDecorator(options.AccountKeeper.Environment()), + NewValidateBasicDecorator(options.AccountKeeper.GetEnvironment()), NewTxTimeoutHeightDecorator(), NewValidateMemoDecorator(options.AccountKeeper), NewConsumeGasForTxSizeDecorator(options.AccountKeeper), diff --git a/x/auth/ante/basic.go b/x/auth/ante/basic.go index 37994cad1ec7..de5d8b7f5227 100644 --- a/x/auth/ante/basic.go +++ b/x/auth/ante/basic.go @@ -108,7 +108,7 @@ func (cgts ConsumeTxSizeGasDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, _ b ctx.GasMeter().ConsumeGas(params.TxSizeCostPerByte*storetypes.Gas(len(ctx.TxBytes())), "txSize") // simulate gas cost for signatures in simulate mode - txService := cgts.ak.Environment().TransactionService + txService := cgts.ak.GetEnvironment().TransactionService if txService.ExecMode(ctx) == transaction.ExecModeSimulate { // in simulate mode, each element should be a nil signature sigs, err := sigTx.GetSignaturesV2() diff --git a/x/auth/ante/basic_test.go b/x/auth/ante/basic_test.go index 7546d59e7d62..5186f9b79fc1 100644 --- a/x/auth/ante/basic_test.go +++ b/x/auth/ante/basic_test.go @@ -36,7 +36,7 @@ func TestValidateBasic(t *testing.T) { invalidTx, err := suite.CreateTestTx(suite.ctx, privs, accNums, accSeqs, suite.ctx.ChainID(), signing.SignMode_SIGN_MODE_DIRECT) require.NoError(t, err) - vbd := ante.NewValidateBasicDecorator(suite.accountKeeper.Environment()) + vbd := ante.NewValidateBasicDecorator(suite.accountKeeper.GetEnvironment()) antehandler := sdk.ChainAnteDecorators(vbd) _, err = antehandler(suite.ctx, invalidTx, false) diff --git a/x/auth/ante/expected_keepers.go b/x/auth/ante/expected_keepers.go index 52bf0acc31f3..f65dfb6d2d9a 100644 --- a/x/auth/ante/expected_keepers.go +++ b/x/auth/ante/expected_keepers.go @@ -10,10 +10,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -type HasEnvironment interface { - Environment() appmodule.Environment -} - // AccountKeeper defines the contract needed for AccountKeeper related APIs. // Interface provides support to use non-sdk AccountKeeper for AnteHandler's decorators. type AccountKeeper interface { @@ -23,7 +19,7 @@ type AccountKeeper interface { GetModuleAddress(moduleName string) sdk.AccAddress NewAccountWithAddress(ctx context.Context, addr sdk.AccAddress) sdk.AccountI AddressCodec() address.Codec - Environment() appmodule.Environment + GetEnvironment() appmodule.Environment } // FeegrantKeeper defines the expected feegrant keeper. diff --git a/x/auth/ante/fee.go b/x/auth/ante/fee.go index cf3e54a5b272..c057d5a7fa73 100644 --- a/x/auth/ante/fee.go +++ b/x/auth/ante/fee.go @@ -46,7 +46,7 @@ func (dfd DeductFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, _ bool, nex return ctx, errorsmod.Wrap(sdkerrors.ErrTxDecode, "Tx must be a FeeTx") } - txService := dfd.accountKeeper.Environment().TransactionService + txService := dfd.accountKeeper.GetEnvironment().TransactionService execMode := txService.ExecMode(ctx) if execMode != transaction.ExecModeSimulate && ctx.BlockHeight() > 0 && feeTx.GetGas() == 0 { return ctx, errorsmod.Wrap(sdkerrors.ErrInvalidGasLimit, "must provide positive gas") diff --git a/x/auth/ante/sigverify.go b/x/auth/ante/sigverify.go index 9db1433c0d02..b09bcff5c2c7 100644 --- a/x/auth/ante/sigverify.go +++ b/x/auth/ante/sigverify.go @@ -281,7 +281,7 @@ func (svd SigVerificationDecorator) consumeSignatureGas( pubKey cryptotypes.PubKey, signature signing.SignatureV2, ) error { - if svd.ak.Environment().TransactionService.ExecMode(ctx) == transaction.ExecModeSimulate && pubKey == nil { + if svd.ak.GetEnvironment().TransactionService.ExecMode(ctx) == transaction.ExecModeSimulate && pubKey == nil { pubKey = simSecp256k1Pubkey } @@ -311,7 +311,7 @@ func (svd SigVerificationDecorator) verifySig(ctx sdk.Context, tx sdk.Tx, acc sd // we're in simulation mode, or in ReCheckTx, or context is not // on sig verify tx, then we do not need to verify the signatures // in the tx. - if svd.ak.Environment().TransactionService.ExecMode(ctx) == transaction.ExecModeSimulate || ctx.IsReCheckTx() || !ctx.IsSigverifyTx() { + if svd.ak.GetEnvironment().TransactionService.ExecMode(ctx) == transaction.ExecModeSimulate || ctx.IsReCheckTx() || !ctx.IsSigverifyTx() { return nil } @@ -385,7 +385,7 @@ func (svd SigVerificationDecorator) setPubKey(ctx sdk.Context, acc sdk.AccountI, if txPubKey == nil { // if we're not in simulation mode, and we do not have a valid pubkey // for this signer, then we simply error. - if svd.ak.Environment().TransactionService.ExecMode(ctx) != transaction.ExecModeSimulate { + if svd.ak.GetEnvironment().TransactionService.ExecMode(ctx) != transaction.ExecModeSimulate { return fmt.Errorf("the account %s is without a pubkey and did not provide a pubkey in the tx to set it", acc.GetAddress().String()) } // if we're in simulation mode, then we can populate the pubkey with the diff --git a/x/auth/ante/sigverify_internal_test.go b/x/auth/ante/sigverify_internal_test.go index 47be009d798a..40fbe6746fc7 100644 --- a/x/auth/ante/sigverify_internal_test.go +++ b/x/auth/ante/sigverify_internal_test.go @@ -20,7 +20,7 @@ type mockAccount struct { ante.AccountKeeper } -func (*mockAccount) Environment() appmodule.Environment { +func (*mockAccount) GetEnvironment() appmodule.Environment { return appmodule.Environment{ TransactionService: &mockTransactionService{}, } diff --git a/x/auth/ante/unordered_test.go b/x/auth/ante/unordered_test.go index 5e4ec4a5ead3..c64a267f4afa 100644 --- a/x/auth/ante/unordered_test.go +++ b/x/auth/ante/unordered_test.go @@ -25,7 +25,7 @@ func TestUnorderedTxDecorator_OrderedTx(t *testing.T) { suite := SetupTestSuite(t, false) - chain := sdk.ChainAnteDecorators(ante.NewUnorderedTxDecorator(unorderedtx.DefaultMaxUnOrderedTTL, txm, suite.accountKeeper.Environment())) + chain := sdk.ChainAnteDecorators(ante.NewUnorderedTxDecorator(unorderedtx.DefaultMaxUnOrderedTTL, txm, suite.accountKeeper.GetEnvironment())) tx, txBz := genUnorderedTx(t, false, 0) ctx := sdk.Context{}.WithTxBytes(txBz).WithBlockHeight(100) @@ -44,7 +44,7 @@ func TestUnorderedTxDecorator_UnorderedTx_NoTTL(t *testing.T) { suite := SetupTestSuite(t, false) - chain := sdk.ChainAnteDecorators(ante.NewUnorderedTxDecorator(unorderedtx.DefaultMaxUnOrderedTTL, txm, suite.accountKeeper.Environment())) + chain := sdk.ChainAnteDecorators(ante.NewUnorderedTxDecorator(unorderedtx.DefaultMaxUnOrderedTTL, txm, suite.accountKeeper.GetEnvironment())) tx, txBz := genUnorderedTx(t, true, 0) ctx := sdk.Context{}.WithTxBytes(txBz).WithBlockHeight(100) @@ -63,7 +63,7 @@ func TestUnorderedTxDecorator_UnorderedTx_InvalidTTL(t *testing.T) { suite := SetupTestSuite(t, false) - chain := sdk.ChainAnteDecorators(ante.NewUnorderedTxDecorator(unorderedtx.DefaultMaxUnOrderedTTL, txm, suite.accountKeeper.Environment())) + chain := sdk.ChainAnteDecorators(ante.NewUnorderedTxDecorator(unorderedtx.DefaultMaxUnOrderedTTL, txm, suite.accountKeeper.GetEnvironment())) tx, txBz := genUnorderedTx(t, true, 100+unorderedtx.DefaultMaxUnOrderedTTL+1) ctx := sdk.Context{}.WithTxBytes(txBz).WithBlockHeight(100) @@ -82,7 +82,7 @@ func TestUnorderedTxDecorator_UnorderedTx_AlreadyExists(t *testing.T) { suite := SetupTestSuite(t, false) - chain := sdk.ChainAnteDecorators(ante.NewUnorderedTxDecorator(unorderedtx.DefaultMaxUnOrderedTTL, txm, suite.accountKeeper.Environment())) + chain := sdk.ChainAnteDecorators(ante.NewUnorderedTxDecorator(unorderedtx.DefaultMaxUnOrderedTTL, txm, suite.accountKeeper.GetEnvironment())) tx, txBz := genUnorderedTx(t, true, 150) ctx := sdk.Context{}.WithTxBytes(txBz).WithBlockHeight(100) @@ -104,7 +104,7 @@ func TestUnorderedTxDecorator_UnorderedTx_ValidCheckTx(t *testing.T) { suite := SetupTestSuite(t, false) - chain := sdk.ChainAnteDecorators(ante.NewUnorderedTxDecorator(unorderedtx.DefaultMaxUnOrderedTTL, txm, suite.accountKeeper.Environment())) + chain := sdk.ChainAnteDecorators(ante.NewUnorderedTxDecorator(unorderedtx.DefaultMaxUnOrderedTTL, txm, suite.accountKeeper.GetEnvironment())) tx, txBz := genUnorderedTx(t, true, 150) ctx := sdk.Context{}.WithTxBytes(txBz).WithBlockHeight(100).WithExecMode(sdk.ExecModeCheck) @@ -123,7 +123,7 @@ func TestUnorderedTxDecorator_UnorderedTx_ValidDeliverTx(t *testing.T) { suite := SetupTestSuite(t, false) - chain := sdk.ChainAnteDecorators(ante.NewUnorderedTxDecorator(unorderedtx.DefaultMaxUnOrderedTTL, txm, suite.accountKeeper.Environment())) + chain := sdk.ChainAnteDecorators(ante.NewUnorderedTxDecorator(unorderedtx.DefaultMaxUnOrderedTTL, txm, suite.accountKeeper.GetEnvironment())) tx, txBz := genUnorderedTx(t, true, 150) ctx := sdk.Context{}.WithTxBytes(txBz).WithBlockHeight(100).WithExecMode(sdk.ExecModeFinalize) diff --git a/x/auth/keeper/keeper.go b/x/auth/keeper/keeper.go index 1474acbe9eb1..076509cdf35f 100644 --- a/x/auth/keeper/keeper.go +++ b/x/auth/keeper/keeper.go @@ -10,7 +10,6 @@ import ( "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" errorsmod "cosmossdk.io/errors" - "cosmossdk.io/log" "cosmossdk.io/x/auth/types" "github.com/cosmos/cosmos-sdk/codec" @@ -54,9 +53,6 @@ type AccountKeeperI interface { // AddressCodec returns the account address codec. AddressCodec() address.Codec - - // Environment returns the module's environment. - Environment() appmodule.Environment } func NewAccountIndexes(sb *collections.SchemaBuilder) AccountsIndexes { @@ -84,10 +80,11 @@ func (a AccountsIndexes) IndexesList() []collections.Index[sdk.AccAddress, sdk.A // AccountKeeper encodes/decodes accounts using the go-amino (binary) // encoding/decoding library. type AccountKeeper struct { + appmodule.Environment + addressCodec address.Codec AccountsModKeeper types.AccountsModKeeper - environment appmodule.Environment cdc codec.BinaryCodec permAddrs map[string]types.PermissionsForAddress bech32Prefix string @@ -127,9 +124,9 @@ func NewAccountKeeper( sb := collections.NewSchemaBuilder(env.KVStoreService) ak := AccountKeeper{ + Environment: env, addressCodec: ac, bech32Prefix: bech32Prefix, - environment: env, proto: proto, cdc: cdc, AccountsModKeeper: accountsModKeeper, @@ -152,17 +149,16 @@ func (ak AccountKeeper) GetAuthority() string { return ak.authority } +func (ak AccountKeeper) GetEnvironment() appmodule.Environment { + return ak.Environment +} + // AddressCodec returns the x/auth account address codec. // x/auth is tied to bech32 encoded user accounts func (ak AccountKeeper) AddressCodec() address.Codec { return ak.addressCodec } -// Logger returns a module-specific logger. -func (ak AccountKeeper) Logger(ctx context.Context) log.Logger { - return ak.environment.Logger.With("module", "x/"+types.ModuleName) -} - // GetPubKey Returns the PubKey of the account at address func (ak AccountKeeper) GetPubKey(ctx context.Context, addr sdk.AccAddress) (cryptotypes.PubKey, error) { acc := ak.GetAccount(ctx, addr) @@ -294,7 +290,7 @@ func (ak AccountKeeper) NonAtomicMsgsExec(ctx context.Context, signer sdk.AccAdd } } - if err := ak.environment.BranchService.Execute(ctx, func(ctx context.Context) error { + if err := ak.BranchService.Execute(ctx, func(ctx context.Context) error { result, err := ak.AccountsModKeeper.SendModuleMessageUntyped(ctx, signer, msg) if err != nil { // If an error occurs during message execution, append error response @@ -318,8 +314,3 @@ func (ak AccountKeeper) NonAtomicMsgsExec(ctx context.Context, signer sdk.AccAdd return msgResponses, nil } - -// Environment returns the module's environment. -func (ak AccountKeeper) Environment() appmodule.Environment { - return ak.environment -} diff --git a/x/auth/keeper/migrations.go b/x/auth/keeper/migrations.go index 998fdbe87b98..797583c31a99 100644 --- a/x/auth/keeper/migrations.go +++ b/x/auth/keeper/migrations.go @@ -42,7 +42,7 @@ func (m Migrator) Migrate3to4(ctx context.Context) error { // It migrates the GlobalAccountNumber from being a protobuf defined value to a // big-endian encoded uint64, it also migrates it to use a more canonical prefix. func (m Migrator) Migrate4To5(ctx context.Context) error { - return v5.Migrate(ctx, m.keeper.environment.KVStoreService, m.keeper.AccountNumber) + return v5.Migrate(ctx, m.keeper.KVStoreService, m.keeper.AccountNumber) } // V45_SetAccount implements V45_SetAccount @@ -51,7 +51,7 @@ func (m Migrator) Migrate4To5(ctx context.Context) error { // NOTE: This is used for testing purposes only. func (m Migrator) V45SetAccount(ctx context.Context, acc sdk.AccountI) error { addr := acc.GetAddress() - store := m.keeper.environment.KVStoreService.OpenKVStore(ctx) + store := m.keeper.KVStoreService.OpenKVStore(ctx) bz, err := m.keeper.Accounts.ValueCodec().Encode(acc) if err != nil { diff --git a/x/authz/keeper/genesis.go b/x/authz/keeper/genesis.go index 909c54dc1421..c669f2aa2622 100644 --- a/x/authz/keeper/genesis.go +++ b/x/authz/keeper/genesis.go @@ -11,7 +11,7 @@ import ( // InitGenesis initializes new authz genesis func (k Keeper) InitGenesis(ctx context.Context, data *authz.GenesisState) error { - now := k.environment.HeaderService.GetHeaderInfo(ctx).Time + now := k.HeaderService.HeaderInfo(ctx).Time for _, entry := range data.Authorization { // ignore expired authorizations if entry.Expiration != nil && entry.Expiration.Before(now) { diff --git a/x/authz/keeper/grpc_query.go b/x/authz/keeper/grpc_query.go index 4b7c45a19af9..4d73afac4e6c 100644 --- a/x/authz/keeper/grpc_query.go +++ b/x/authz/keeper/grpc_query.go @@ -58,7 +58,7 @@ func (k Keeper) Grants(ctx context.Context, req *authz.QueryGrantsRequest) (*aut }, nil } - store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) key := grantStoreKey(grantee, granter, "") grantsStore := prefix.NewStore(store, key) @@ -100,7 +100,7 @@ func (k Keeper) GranterGrants(ctx context.Context, req *authz.QueryGranterGrants return nil, err } - store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) authzStore := prefix.NewStore(store, grantStoreKey(nil, granter, "")) grants, pageRes, err := query.GenericFilteredPaginate(k.cdc, authzStore, req.Pagination, func(key []byte, auth *authz.Grant) (*authz.GrantAuthorization, error) { @@ -151,7 +151,7 @@ func (k Keeper) GranteeGrants(ctx context.Context, req *authz.QueryGranteeGrants return nil, err } - store := prefix.NewStore(runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx)), GrantKey) + store := prefix.NewStore(runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)), GrantKey) authorizations, pageRes, err := query.GenericFilteredPaginate(k.cdc, store, req.Pagination, func(key []byte, auth *authz.Grant) (*authz.GrantAuthorization, error) { auth1, err := auth.GetAuthorization() diff --git a/x/authz/keeper/keeper.go b/x/authz/keeper/keeper.go index 8d580f5e1f8b..0be13bd6d1e5 100644 --- a/x/authz/keeper/keeper.go +++ b/x/authz/keeper/keeper.go @@ -10,7 +10,6 @@ import ( "cosmossdk.io/core/appmodule" errorsmod "cosmossdk.io/errors" - "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/authz" @@ -27,28 +26,24 @@ import ( const gasCostPerIteration = uint64(20) type Keeper struct { - environment appmodule.Environment - cdc codec.Codec - authKeeper authz.AccountKeeper + appmodule.Environment + + cdc codec.Codec + authKeeper authz.AccountKeeper } // NewKeeper constructs a message authorization Keeper func NewKeeper(env appmodule.Environment, cdc codec.Codec, ak authz.AccountKeeper) Keeper { return Keeper{ - environment: env, + Environment: env, cdc: cdc, authKeeper: ak, } } -// Logger returns a module-specific logger. -func (k Keeper) Logger() log.Logger { - return k.environment.Logger.With("module", fmt.Sprintf("x/%s", authz.ModuleName)) -} - // getGrant returns grant stored at skey. func (k Keeper) getGrant(ctx context.Context, skey []byte) (grant authz.Grant, found bool) { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(skey) if err != nil { @@ -80,7 +75,7 @@ func (k Keeper) update(ctx context.Context, grantee, granter sdk.AccAddress, upd } grant.Authorization = any - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) return store.Set(skey, k.cdc.MustMarshal(&grant)) } @@ -147,7 +142,7 @@ func (k Keeper) DispatchActions(ctx context.Context, grantee sdk.AccAddress, msg } // no need to use the branch service here, as if the transaction fails, the transaction will be reverted - _, err = k.environment.RouterService.MessageRouterService().InvokeUntyped(ctx, msg) + _, err = k.RouterService.MessageRouterService().InvokeUntyped(ctx, msg) if err != nil { return nil, fmt.Errorf("failed to execute message %d; message %v: %w", i, msg, err) } @@ -161,10 +156,10 @@ func (k Keeper) DispatchActions(ctx context.Context, grantee sdk.AccAddress, msg // same `sdk.Msg` type, this grant overwrites that. func (k Keeper) SaveGrant(ctx context.Context, grantee, granter sdk.AccAddress, authorization authz.Authorization, expiration *time.Time) error { msgType := authorization.MsgTypeURL() - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) skey := grantStoreKey(grantee, granter, msgType) - grant, err := authz.NewGrant(k.environment.HeaderService.GetHeaderInfo(ctx).Time, authorization, expiration) + grant, err := authz.NewGrant(k.HeaderService.HeaderInfo(ctx).Time, authorization, expiration) if err != nil { return err } @@ -206,7 +201,7 @@ func (k Keeper) SaveGrant(ctx context.Context, grantee, granter sdk.AccAddress, return err } - return k.environment.EventService.EventManager(ctx).Emit(&authz.EventGrant{ + return k.EventService.EventManager(ctx).Emit(&authz.EventGrant{ MsgTypeUrl: authorization.MsgTypeURL(), Granter: granterAddr, Grantee: granteeAddr, @@ -216,7 +211,7 @@ func (k Keeper) SaveGrant(ctx context.Context, grantee, granter sdk.AccAddress, // DeleteGrant revokes any authorization for the provided message type granted to the grantee // by the granter. func (k Keeper) DeleteGrant(ctx context.Context, grantee, granter sdk.AccAddress, msgType string) error { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) skey := grantStoreKey(grantee, granter, msgType) grant, found := k.getGrant(ctx, skey) if !found { @@ -254,7 +249,7 @@ func (k Keeper) DeleteGrant(ctx context.Context, grantee, granter sdk.AccAddress if err != nil { return err } - return k.environment.EventService.EventManager(ctx).Emit(&authz.EventRevoke{ + return k.EventService.EventManager(ctx).Emit(&authz.EventRevoke{ MsgTypeUrl: msgType, Granter: granterAddr, Grantee: granteeAddr, @@ -263,7 +258,7 @@ func (k Keeper) DeleteGrant(ctx context.Context, grantee, granter sdk.AccAddress // GetAuthorizations Returns list of `Authorizations` granted to the grantee by the granter. func (k Keeper) GetAuthorizations(ctx context.Context, grantee, granter sdk.AccAddress) ([]authz.Authorization, error) { - store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) key := grantStoreKey(grantee, granter, "") iter := storetypes.KVStorePrefixIterator(store, key) defer iter.Close() @@ -293,7 +288,7 @@ func (k Keeper) GetAuthorizations(ctx context.Context, grantee, granter sdk.AccA // - There was an error getting the authorization from the grant. func (k Keeper) GetAuthorization(ctx context.Context, grantee, granter sdk.AccAddress, msgType string) (authz.Authorization, *time.Time) { grant, found := k.getGrant(ctx, grantStoreKey(grantee, granter, msgType)) - if !found || (grant.Expiration != nil && grant.Expiration.Before(k.environment.HeaderService.GetHeaderInfo(ctx).Time)) { + if !found || (grant.Expiration != nil && grant.Expiration.Before(k.HeaderService.HeaderInfo(ctx).Time)) { return nil, nil } @@ -312,7 +307,7 @@ func (k Keeper) GetAuthorization(ctx context.Context, grantee, granter sdk.AccAd func (k Keeper) IterateGrants(ctx context.Context, handler func(granterAddr, granteeAddr sdk.AccAddress, grant authz.Grant) (bool, error), ) error { - store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) iter := storetypes.KVStorePrefixIterator(store, GrantKey) defer iter.Close() for ; iter.Valid(); iter.Next() { @@ -331,7 +326,7 @@ func (k Keeper) IterateGrants(ctx context.Context, } func (k Keeper) getGrantQueueItem(ctx context.Context, expiration time.Time, granter, grantee sdk.AccAddress) (*authz.GrantQueueItem, error) { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(GrantQueueKey(expiration, granter, grantee)) if err != nil { return nil, err @@ -351,7 +346,7 @@ func (k Keeper) getGrantQueueItem(ctx context.Context, expiration time.Time, gra func (k Keeper) setGrantQueueItem(ctx context.Context, expiration time.Time, granter, grantee sdk.AccAddress, queueItems *authz.GrantQueueItem, ) error { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := k.cdc.Marshal(queueItems) if err != nil { return err @@ -372,7 +367,7 @@ func (k Keeper) insertIntoGrantQueue(ctx context.Context, granter, grantee sdk.A // removeFromGrantQueue removes a grant key from the grant queue func (k Keeper) removeFromGrantQueue(ctx context.Context, grantKey []byte, granter, grantee sdk.AccAddress, expiration time.Time) error { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) key := GrantQueueKey(expiration, granter, grantee) bz, err := store.Get(key) if err != nil { @@ -392,7 +387,7 @@ func (k Keeper) removeFromGrantQueue(ctx context.Context, grantKey []byte, grant queueItems := queueItem.MsgTypeUrls for index, typeURL := range queueItems { - k.environment.GasService.GetGasMeter(ctx).Consume(gasCostPerIteration, "grant queue") + k.GasService.GasMeter(ctx).Consume(gasCostPerIteration, "grant queue") if typeURL == msgType { end := len(queueItem.MsgTypeUrls) - 1 @@ -413,9 +408,9 @@ func (k Keeper) removeFromGrantQueue(ctx context.Context, grantKey []byte, grant // DequeueAndDeleteExpiredGrants deletes expired grants from the state and grant queue. func (k Keeper) DequeueAndDeleteExpiredGrants(ctx context.Context, limit int) error { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) - iterator, err := store.Iterator(GrantQueuePrefix, storetypes.InclusiveEndBytes(GrantQueueTimePrefix(k.environment.HeaderService.GetHeaderInfo(ctx).Time))) + iterator, err := store.Iterator(GrantQueuePrefix, storetypes.InclusiveEndBytes(GrantQueueTimePrefix(k.HeaderService.HeaderInfo(ctx).Time))) if err != nil { return err } diff --git a/x/authz/keeper/migrations.go b/x/authz/keeper/migrations.go index 34cf0bdd45e0..426b4151da20 100644 --- a/x/authz/keeper/migrations.go +++ b/x/authz/keeper/migrations.go @@ -18,5 +18,5 @@ func NewMigrator(keeper Keeper) Migrator { // Migrate1to2 migrates from version 1 to 2. func (m Migrator) Migrate1to2(ctx context.Context) error { - return v2.MigrateStore(ctx, m.keeper.environment, m.keeper.cdc) + return v2.MigrateStore(ctx, m.keeper.Environment, m.keeper.cdc) } diff --git a/x/authz/keeper/msg_server.go b/x/authz/keeper/msg_server.go index fe14037cd328..05f73a097d2a 100644 --- a/x/authz/keeper/msg_server.go +++ b/x/authz/keeper/msg_server.go @@ -40,7 +40,7 @@ func (k Keeper) Grant(ctx context.Context, msg *authz.MsgGrant) (*authz.MsgGrant } t := authorization.MsgTypeURL() - if err := k.environment.RouterService.MessageRouterService().CanInvoke(ctx, t); err != nil { + if err := k.RouterService.MessageRouterService().CanInvoke(ctx, t); err != nil { return nil, sdkerrors.ErrInvalidType.Wrapf("%s doesn't exist", t) } @@ -117,7 +117,7 @@ func (k Keeper) PruneExpiredGrants(ctx context.Context, msg *authz.MsgPruneExpir return nil, err } - if err := k.environment.EventService.EventManager(ctx).Emit(&authz.EventPruneExpiredGrants{Pruner: msg.Pruner}); err != nil { + if err := k.EventService.EventManager(ctx).Emit(&authz.EventPruneExpiredGrants{Pruner: msg.Pruner}); err != nil { return nil, err } diff --git a/x/authz/migrations/v2/store.go b/x/authz/migrations/v2/store.go index b32cf92fcb4d..65d3be4140dc 100644 --- a/x/authz/migrations/v2/store.go +++ b/x/authz/migrations/v2/store.go @@ -34,7 +34,7 @@ func addExpiredGrantsIndex(ctx context.Context, env appmodule.Environment, cdc c defer grantsIter.Close() queueItems := make(map[string][]string) - now := env.HeaderService.GetHeaderInfo(ctx).Time + now := env.HeaderService.HeaderInfo(ctx).Time for ; grantsIter.Valid(); grantsIter.Next() { var grant authz.Grant bz := grantsIter.Value() diff --git a/x/bank/keeper/grpc_query.go b/x/bank/keeper/grpc_query.go index b24fc91434c9..df7c5f312178 100644 --- a/x/bank/keeper/grpc_query.go +++ b/x/bank/keeper/grpc_query.go @@ -172,7 +172,7 @@ func (k BaseKeeper) DenomsMetadata(c context.Context, req *types.QueryDenomsMeta if req == nil { return nil, status.Errorf(codes.InvalidArgument, "empty request") } - kvStore := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(c)) + kvStore := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(c)) store := prefix.NewStore(kvStore, types.DenomMetadataPrefix) metadatas := []types.Metadata{} diff --git a/x/bank/keeper/keeper.go b/x/bank/keeper/keeper.go index 749c81ace578..c8f9e5ba7bca 100644 --- a/x/bank/keeper/keeper.go +++ b/x/bank/keeper/keeper.go @@ -55,11 +55,11 @@ type Keeper interface { // BaseKeeper manages transfers between accounts. It implements the Keeper interface. type BaseKeeper struct { + appmodule.Environment BaseSendKeeper ak types.AccountKeeper cdc codec.BinaryCodec - environment appmodule.Environment mintCoinsRestrictionFn types.MintingRestrictionFn } @@ -96,10 +96,10 @@ func NewBaseKeeper( env.Logger = env.Logger.With(log.ModuleKey, "x/"+types.ModuleName) return BaseKeeper{ + Environment: env, BaseSendKeeper: NewBaseSendKeeper(env, cdc, ak, blockedAddrs, authority), ak: ak, cdc: cdc, - environment: env, mintCoinsRestrictionFn: types.NoOpMintingRestrictionFn, } } @@ -154,7 +154,7 @@ func (k BaseKeeper) DelegateCoins(ctx context.Context, delegatorAddr, moduleAccA if err != nil { return err } - if err := k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( types.EventTypeCoinSpent, event.NewAttribute(types.AttributeKeySpender, delAddrStr), event.NewAttribute(sdk.AttributeKeyAmount, amt.String()), @@ -348,7 +348,7 @@ func (k BaseKeeper) UndelegateCoinsFromModuleToAccount( func (k BaseKeeper) MintCoins(ctx context.Context, moduleName string, amounts sdk.Coins) error { err := k.mintCoinsRestrictionFn(ctx, amounts) if err != nil { - k.Logger().Error(fmt.Sprintf("Module %q attempted to mint coins %s it doesn't have permission for, error %v", moduleName, amounts, err)) + k.Logger.Error(fmt.Sprintf("Module %q attempted to mint coins %s it doesn't have permission for, error %v", moduleName, amounts, err)) return err } acc := k.ak.GetModuleAccount(ctx, moduleName) @@ -371,7 +371,7 @@ func (k BaseKeeper) MintCoins(ctx context.Context, moduleName string, amounts sd k.setSupply(ctx, supply) } - k.Logger().Debug("minted coins from module account", "amount", amounts.String(), "from", moduleName) + k.Logger.Debug("minted coins from module account", "amount", amounts.String(), "from", moduleName) addrStr, err := k.ak.AddressCodec().BytesToString(acc.GetAddress()) if err != nil { @@ -379,7 +379,7 @@ func (k BaseKeeper) MintCoins(ctx context.Context, moduleName string, amounts sd } // emit mint event - return k.environment.EventService.EventManager(ctx).EmitKV( + return k.EventService.EventManager(ctx).EmitKV( types.EventTypeCoinMint, event.NewAttribute(types.AttributeKeyMinter, addrStr), event.NewAttribute(sdk.AttributeKeyAmount, amounts.String()), @@ -411,14 +411,14 @@ func (k BaseKeeper) BurnCoins(ctx context.Context, address []byte, amounts sdk.C k.setSupply(ctx, supply) } - k.Logger().Debug("burned tokens from account", "amount", amounts.String(), "from", address) + k.Logger.Debug("burned tokens from account", "amount", amounts.String(), "from", address) addrStr, err := k.ak.AddressCodec().BytesToString(acc.GetAddress()) if err != nil { return err } // emit burn event - return k.environment.EventService.EventManager(ctx).EmitKV( + return k.EventService.EventManager(ctx).EmitKV( types.EventTypeCoinBurn, event.NewAttribute(types.AttributeKeyBurner, addrStr), event.NewAttribute(sdk.AttributeKeyAmount, amounts.String()), @@ -449,7 +449,7 @@ func (k BaseKeeper) trackDelegation(ctx context.Context, addr sdk.AccAddress, ba vacc, ok := acc.(types.VestingAccount) if ok { // TODO: return error on account.TrackDelegation - vacc.TrackDelegation(k.environment.HeaderService.GetHeaderInfo(ctx).Time, balance, amt) + vacc.TrackDelegation(k.HeaderService.HeaderInfo(ctx).Time, balance, amt) k.ak.SetAccount(ctx, acc) } diff --git a/x/bank/keeper/send.go b/x/bank/keeper/send.go index 86c88f68d2d2..8055542754ea 100644 --- a/x/bank/keeper/send.go +++ b/x/bank/keeper/send.go @@ -53,11 +53,11 @@ var _ SendKeeper = (*BaseSendKeeper)(nil) // BaseSendKeeper only allows transfers between accounts without the possibility of // creating coins. It implements the SendKeeper interface. type BaseSendKeeper struct { + appmodule.Environment BaseViewKeeper - cdc codec.BinaryCodec - ak types.AccountKeeper - environment appmodule.Environment + cdc codec.BinaryCodec + ak types.AccountKeeper // list of addresses that are restricted from receiving transactions blockedAddrs map[string]bool @@ -81,10 +81,10 @@ func NewBaseSendKeeper( } return BaseSendKeeper{ + Environment: env, BaseViewKeeper: NewBaseViewKeeper(env, cdc, ak), cdc: cdc, ak: ak, - environment: env, blockedAddrs: blockedAddrs, authority: authority, sendRestriction: newSendRestriction(), @@ -169,7 +169,7 @@ func (k BaseSendKeeper) InputOutputCoins(ctx context.Context, input types.Input, return err } - if err := k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( types.EventTypeTransfer, event.NewAttribute(types.AttributeKeyRecipient, out.Address), event.NewAttribute(sdk.AttributeKeyAmount, out.Coins.String()), @@ -209,7 +209,7 @@ func (k BaseSendKeeper) SendCoins(ctx context.Context, fromAddr, toAddr sdk.AccA return err } - return k.environment.EventService.EventManager(ctx).EmitKV( + return k.EventService.EventManager(ctx).EmitKV( types.EventTypeTransfer, event.NewAttribute(types.AttributeKeyRecipient, toAddrString), event.NewAttribute(types.AttributeKeySender, fromAddrString), @@ -260,7 +260,7 @@ func (k BaseSendKeeper) subUnlockedCoins(ctx context.Context, addr sdk.AccAddres return err } - return k.environment.EventService.EventManager(ctx).EmitKV( + return k.EventService.EventManager(ctx).EmitKV( types.EventTypeCoinSpent, event.NewAttribute(types.AttributeKeySpender, addrStr), event.NewAttribute(sdk.AttributeKeyAmount, amt.String()), @@ -289,7 +289,7 @@ func (k BaseSendKeeper) addCoins(ctx context.Context, addr sdk.AccAddress, amt s return err } - return k.environment.EventService.EventManager(ctx).EmitKV( + return k.EventService.EventManager(ctx).EmitKV( types.EventTypeCoinReceived, event.NewAttribute(types.AttributeKeyReceiver, addrStr), event.NewAttribute(sdk.AttributeKeyAmount, amt.String()), diff --git a/x/bank/keeper/view.go b/x/bank/keeper/view.go index d8eaa737fa14..48a725989b3b 100644 --- a/x/bank/keeper/view.go +++ b/x/bank/keeper/view.go @@ -8,7 +8,6 @@ import ( "cosmossdk.io/collections/indexes" "cosmossdk.io/core/appmodule" errorsmod "cosmossdk.io/errors" - "cosmossdk.io/log" "cosmossdk.io/math" "cosmossdk.io/x/bank/types" @@ -56,9 +55,10 @@ func (b BalancesIndexes) IndexesList() []collections.Index[collections.Pair[sdk. // BaseViewKeeper implements a read only keeper implementation of ViewKeeper. type BaseViewKeeper struct { - cdc codec.BinaryCodec - environment appmodule.Environment - ak types.AccountKeeper + appmodule.Environment + + cdc codec.BinaryCodec + ak types.AccountKeeper Schema collections.Schema Supply collections.Map[string, math.Int] @@ -72,8 +72,8 @@ type BaseViewKeeper struct { func NewBaseViewKeeper(env appmodule.Environment, cdc codec.BinaryCodec, ak types.AccountKeeper) BaseViewKeeper { sb := collections.NewSchemaBuilder(env.KVStoreService) k := BaseViewKeeper{ + Environment: env, cdc: cdc, - environment: env, ak: ak, Supply: collections.NewMap(sb, types.SupplyKey, "supply", collections.StringKey, sdk.IntValue), DenomMetadata: collections.NewMap(sb, types.DenomMetadataPrefix, "denom_metadata", collections.StringKey, codec.CollValue[types.Metadata](cdc)), @@ -95,11 +95,6 @@ func (k BaseViewKeeper) HasBalance(ctx context.Context, addr sdk.AccAddress, amt return k.GetBalance(ctx, addr, amt.Denom).IsGTE(amt) } -// Logger returns a module-specific logger. -func (k BaseViewKeeper) Logger() log.Logger { - return k.environment.Logger -} - // GetAllBalances returns all the account balances for the given account address. func (k BaseViewKeeper) GetAllBalances(ctx context.Context, addr sdk.AccAddress) sdk.Coins { balances := sdk.NewCoins() @@ -184,7 +179,7 @@ func (k BaseViewKeeper) LockedCoins(ctx context.Context, addr sdk.AccAddress) sd if acc != nil { vacc, ok := acc.(types.VestingAccount) if ok { - return vacc.LockedCoins(k.environment.HeaderService.GetHeaderInfo(ctx).Time) + return vacc.LockedCoins(k.HeaderService.HeaderInfo(ctx).Time) } } diff --git a/x/circuit/keeper/keeper.go b/x/circuit/keeper/keeper.go index ed18593c526e..6902720170f6 100644 --- a/x/circuit/keeper/keeper.go +++ b/x/circuit/keeper/keeper.go @@ -13,12 +13,11 @@ import ( // Keeper defines the circuit module's keeper. type Keeper struct { - cdc codec.BinaryCodec - env appmodule.Environment - - authority []byte + appmodule.Environment + cdc codec.BinaryCodec addressCodec address.Codec + authority []byte Schema collections.Schema // Permissions contains the permissions for each account @@ -37,9 +36,9 @@ func NewKeeper(env appmodule.Environment, cdc codec.BinaryCodec, authority strin sb := collections.NewSchemaBuilder(env.KVStoreService) k := Keeper{ + Environment: env, cdc: cdc, authority: auth, - env: env, addressCodec: addressCodec, Permissions: collections.NewMap( sb, diff --git a/x/circuit/keeper/msg_server.go b/x/circuit/keeper/msg_server.go index 8a1efd3dabf1..fbb46e35d167 100644 --- a/x/circuit/keeper/msg_server.go +++ b/x/circuit/keeper/msg_server.go @@ -63,7 +63,7 @@ func (srv msgServer) AuthorizeCircuitBreaker(ctx context.Context, msg *types.Msg return nil, err } - if err = srv.Keeper.env.EventService.EventManager(ctx).EmitKV( + if err = srv.Keeper.EventService.EventManager(ctx).EmitKV( "authorize_circuit_breaker", event.NewAttribute("granter", msg.Granter), event.NewAttribute("grantee", msg.Grantee), @@ -120,7 +120,7 @@ func (srv msgServer) TripCircuitBreaker(ctx context.Context, msg *types.MsgTripC urls := strings.Join(msg.GetMsgTypeUrls(), ",") - if err = srv.Keeper.env.EventService.EventManager(ctx).EmitKV( + if err = srv.Keeper.EventService.EventManager(ctx).EmitKV( "trip_circuit_breaker", event.NewAttribute("authority", msg.Authority), event.NewAttribute("msg_url", urls), @@ -178,7 +178,7 @@ func (srv msgServer) ResetCircuitBreaker(ctx context.Context, msg *types.MsgRese urls := strings.Join(msg.GetMsgTypeUrls(), ",") - if err = srv.Keeper.env.EventService.EventManager(ctx).EmitKV( + if err = srv.Keeper.EventService.EventManager(ctx).EmitKV( "reset_circuit_breaker", event.NewAttribute("authority", msg.Authority), event.NewAttribute("msg_url", urls), diff --git a/x/consensus/keeper/keeper.go b/x/consensus/keeper/keeper.go index d9e4baf3dcc8..8dee839f9931 100644 --- a/x/consensus/keeper/keeper.go +++ b/x/consensus/keeper/keeper.go @@ -21,7 +21,7 @@ import ( var StoreKey = "Consensus" type Keeper struct { - environment appmodule.Environment + appmodule.Environment authority string ParamsStore collections.Item[cmtproto.ConsensusParams] @@ -32,7 +32,7 @@ var _ exported.ConsensusParamSetter = Keeper{}.ParamsStore func NewKeeper(cdc codec.BinaryCodec, env appmodule.Environment, authority string) Keeper { sb := collections.NewSchemaBuilder(env.KVStoreService) return Keeper{ - environment: env, + Environment: env, authority: authority, ParamsStore: collections.NewItem(sb, collections.NewPrefix("Consensus"), "params", codec.CollValue[cmtproto.ConsensusParams](cdc)), } @@ -77,7 +77,7 @@ func (k Keeper) UpdateParams(ctx context.Context, msg *types.MsgUpdateParams) (* return nil, err } - if err := k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( "update_consensus_params", event.NewAttribute("authority", msg.Authority), event.NewAttribute("parameters", consensusParams.String())); err != nil { diff --git a/x/counter/keeper/keeper.go b/x/counter/keeper/keeper.go index f03b978ad1e4..f8d5c01cc2a0 100644 --- a/x/counter/keeper/keeper.go +++ b/x/counter/keeper/keeper.go @@ -18,7 +18,7 @@ import ( var StoreKey = "Counter" type Keeper struct { - env appmodule.Environment + appmodule.Environment CountStore collections.Item[int64] } @@ -26,8 +26,8 @@ type Keeper struct { func NewKeeper(env appmodule.Environment) Keeper { sb := collections.NewSchemaBuilder(env.KVStoreService) return Keeper{ - env: env, - CountStore: collections.NewItem(sb, collections.NewPrefix(0), "count", collections.Int64Value), + Environment: env, + CountStore: collections.NewItem(sb, collections.NewPrefix(0), "count", collections.Int64Value), } } @@ -67,7 +67,7 @@ func (k Keeper) IncreaseCount(ctx context.Context, msg *types.MsgIncreaseCounter return nil, err } - if err := k.env.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( "increase_counter", event.NewAttribute("signer", msg.Signer), event.NewAttribute("new count", fmt.Sprint(num+msg.Count))); err != nil { diff --git a/x/crisis/keeper/keeper.go b/x/crisis/keeper/keeper.go index 64cfc3b8d013..12571b0082ba 100644 --- a/x/crisis/keeper/keeper.go +++ b/x/crisis/keeper/keeper.go @@ -21,6 +21,7 @@ type Keeper struct { invCheckPeriod uint storeService storetypes.KVStoreService cdc codec.BinaryCodec + addressCodec address.Codec // the address capable of executing a MsgUpdateParams message. Typically, this // should be the x/gov module account. @@ -30,8 +31,6 @@ type Keeper struct { feeCollectorName string // name of the FeeCollector ModuleAccount - addressCodec address.Codec - Schema collections.Schema ConstantFee collections.Item[sdk.Coin] } @@ -51,8 +50,7 @@ func NewKeeper( feeCollectorName: feeCollectorName, authority: authority, addressCodec: ac, - - ConstantFee: collections.NewItem(sb, types.ConstantFeeKey, "constant_fee", codec.CollValue[sdk.Coin](cdc)), + ConstantFee: collections.NewItem(sb, types.ConstantFeeKey, "constant_fee", codec.CollValue[sdk.Coin](cdc)), } schema, err := sb.Build() if err != nil { diff --git a/x/distribution/keeper/allocation.go b/x/distribution/keeper/allocation.go index 667a05c58377..67008af6f6ee 100644 --- a/x/distribution/keeper/allocation.go +++ b/x/distribution/keeper/allocation.go @@ -104,7 +104,7 @@ func (k Keeper) AllocateTokensToValidator(ctx context.Context, val sdk.Validator } // update current commission - if err = k.environment.EventService.EventManager(ctx).EmitKV( + if err = k.EventService.EventManager(ctx).EmitKV( types.EventTypeCommission, event.NewAttribute(sdk.AttributeKeyAmount, commission.String()), event.NewAttribute(types.AttributeKeyValidator, val.GetOperator()), @@ -136,7 +136,7 @@ func (k Keeper) AllocateTokensToValidator(ctx context.Context, val sdk.Validator } // update outstanding rewards - if err = k.environment.EventService.EventManager(ctx).EmitKV( + if err = k.EventService.EventManager(ctx).EmitKV( types.EventTypeRewards, event.NewAttribute(sdk.AttributeKeyAmount, tokens.String()), event.NewAttribute(types.AttributeKeyValidator, val.GetOperator()), diff --git a/x/distribution/keeper/delegation.go b/x/distribution/keeper/delegation.go index 50c4e6e8799f..e175d48795b6 100644 --- a/x/distribution/keeper/delegation.go +++ b/x/distribution/keeper/delegation.go @@ -42,7 +42,7 @@ func (k Keeper) initializeDelegation(ctx context.Context, val sdk.ValAddress, de // we don't store directly, so multiply delegation shares * (tokens per share) // note: necessary to truncate so we don't allow withdrawing more rewards than owed stake := validator.TokensFromSharesTruncated(delegation.GetShares()) - headerinfo := k.environment.HeaderService.GetHeaderInfo(ctx) + headerinfo := k.HeaderService.HeaderInfo(ctx) return k.DelegatorStartingInfo.Set(ctx, collections.Join(val, del), types.NewDelegatorStartingInfo(previousPeriod, stake, uint64(headerinfo.Height))) } @@ -104,7 +104,7 @@ func (k Keeper) CalculateDelegationRewards(ctx context.Context, val sdk.Validato return sdk.DecCoins{}, err } - headerinfo := k.environment.HeaderService.GetHeaderInfo(ctx) + headerinfo := k.HeaderService.HeaderInfo(ctx) if startingInfo.Height == uint64(headerinfo.Height) { // started this height, no rewards yet return sdk.DecCoins{}, nil } @@ -242,8 +242,7 @@ func (k Keeper) withdrawDelegationRewards(ctx context.Context, val sdk.Validator // of the decCoins due to operation order of the distribution mechanism. rewards := rewardsRaw.Intersect(outstanding) if !rewards.Equal(rewardsRaw) { - logger := k.Logger(ctx) - logger.Info( + k.Logger.Info( "rounding error withdrawing rewards from validator", "delegator", del.GetDelegatorAddr(), "validator", val.GetOperator(), @@ -313,7 +312,7 @@ func (k Keeper) withdrawDelegationRewards(ctx context.Context, val sdk.Validator finalRewards = sdk.Coins{sdk.NewCoin(baseDenom, math.ZeroInt())} } - err = k.environment.EventService.EventManager(ctx).EmitKV( + err = k.EventService.EventManager(ctx).EmitKV( types.EventTypeWithdrawRewards, event.NewAttribute(sdk.AttributeKeyAmount, finalRewards.String()), event.NewAttribute(types.AttributeKeyValidator, val.GetOperator()), diff --git a/x/distribution/keeper/keeper.go b/x/distribution/keeper/keeper.go index 845666de3d21..dfc90cdc4eef 100644 --- a/x/distribution/keeper/keeper.go +++ b/x/distribution/keeper/keeper.go @@ -11,7 +11,6 @@ import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/core/event" errorsmod "cosmossdk.io/errors" - "cosmossdk.io/log" "cosmossdk.io/x/distribution/types" "github.com/cosmos/cosmos-sdk/codec" @@ -21,7 +20,8 @@ import ( // Keeper of the distribution store type Keeper struct { - environment appmodule.Environment + appmodule.Environment + cdc codec.BinaryCodec authKeeper types.AccountKeeper bankKeeper types.BankKeeper @@ -69,7 +69,7 @@ func NewKeeper( sb := collections.NewSchemaBuilder(env.KVStoreService) k := Keeper{ - environment: env, + Environment: env, cdc: cdc, authKeeper: ak, bankKeeper: bk, @@ -145,11 +145,6 @@ func (k Keeper) GetAuthority() string { return k.authority } -// Logger returns a module-specific logger. -func (k Keeper) Logger(ctx context.Context) log.Logger { - return k.environment.Logger.With(log.ModuleKey, "x/"+types.ModuleName) -} - // SetWithdrawAddr sets a new address that will receive the rewards upon withdrawal func (k Keeper) SetWithdrawAddr(ctx context.Context, delegatorAddr, withdrawAddr sdk.AccAddress) error { if k.bankKeeper.BlockedAddr(withdrawAddr) { @@ -170,7 +165,7 @@ func (k Keeper) SetWithdrawAddr(ctx context.Context, delegatorAddr, withdrawAddr return err } - if err = k.environment.EventService.EventManager(ctx).EmitKV( + if err = k.EventService.EventManager(ctx).EmitKV( types.EventTypeSetWithdrawAddress, event.NewAttribute(types.AttributeKeyWithdrawAddress, addr), ); err != nil { @@ -255,7 +250,7 @@ func (k Keeper) WithdrawValidatorCommission(ctx context.Context, valAddr sdk.Val } } - err = k.environment.EventService.EventManager(ctx).EmitKV( + err = k.EventService.EventManager(ctx).EmitKV( types.EventTypeWithdrawCommission, event.NewAttribute(sdk.AttributeKeyAmount, commission.String()), ) diff --git a/x/distribution/keeper/migrations.go b/x/distribution/keeper/migrations.go index 28b014c4ea7c..cb6be65cb6b2 100644 --- a/x/distribution/keeper/migrations.go +++ b/x/distribution/keeper/migrations.go @@ -33,7 +33,7 @@ func (m Migrator) Migrate2to3(ctx context.Context) error { // Migrate3to4 migrates the x/distribution module state to use collections // Additionally it migrates distribution fee pool to use protocol pool module account func (m Migrator) Migrate3to4(ctx context.Context) error { - if err := v4.MigrateStore(ctx, m.keeper.environment, m.keeper.cdc); err != nil { + if err := v4.MigrateStore(ctx, m.keeper.Environment, m.keeper.cdc); err != nil { return err } diff --git a/x/distribution/keeper/msg_server.go b/x/distribution/keeper/msg_server.go index 48282e0f9ed8..c20995f57bb4 100644 --- a/x/distribution/keeper/msg_server.go +++ b/x/distribution/keeper/msg_server.go @@ -162,8 +162,7 @@ func (k msgServer) CommunityPoolSpend(ctx context.Context, msg *types.MsgCommuni return nil, err } - logger := k.Logger(ctx) - logger.Info("transferred from the community pool to recipient", "amount", msg.Amount.String(), "recipient", msg.Recipient) + k.Logger.Info("transferred from the community pool to recipient", "amount", msg.Amount.String(), "recipient", msg.Recipient) return &types.MsgCommunityPoolSpendResponse{}, nil } @@ -200,8 +199,7 @@ func (k msgServer) DepositValidatorRewardsPool(ctx context.Context, msg *types.M return nil, err } - logger := k.Logger(ctx) - logger.Info( + k.Logger.Info( "transferred from rewards to validator rewards pool", "depositor", msg.Depositor, "amount", msg.Amount.String(), diff --git a/x/distribution/keeper/validator.go b/x/distribution/keeper/validator.go index fe39d44f4337..812fbbe5086b 100644 --- a/x/distribution/keeper/validator.go +++ b/x/distribution/keeper/validator.go @@ -155,7 +155,7 @@ func (k Keeper) updateValidatorSlashFraction(ctx context.Context, valAddr sdk.Va panic(fmt.Sprintf("fraction must be >=0 and <=1, current fraction: %v", fraction)) } - headerinfo := k.environment.HeaderService.GetHeaderInfo(ctx) + headerinfo := k.HeaderService.HeaderInfo(ctx) val, err := k.stakingKeeper.Validator(ctx, valAddr) if err != nil { return err diff --git a/x/epochs/keeper/abci.go b/x/epochs/keeper/abci.go index e05399e9b02e..33821e7fd92c 100644 --- a/x/epochs/keeper/abci.go +++ b/x/epochs/keeper/abci.go @@ -13,8 +13,7 @@ import ( func (k Keeper) BeginBlocker(ctx context.Context) error { defer telemetry.ModuleMeasureSince(types.ModuleName, telemetry.Now(), telemetry.MetricKeyBeginBlocker) - logger := k.Logger() - headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + headerInfo := k.HeaderService.HeaderInfo(ctx) err := k.EpochInfo.Walk( ctx, nil, @@ -38,29 +37,29 @@ func (k Keeper) BeginBlocker(ctx context.Context) error { epochInfo.EpochCountingStarted = true epochInfo.CurrentEpoch = 1 epochInfo.CurrentEpochStartTime = epochInfo.StartTime - logger.Debug(fmt.Sprintf("Starting new epoch with identifier %s epoch number %d", epochInfo.Identifier, epochInfo.CurrentEpoch)) + k.Logger.Debug(fmt.Sprintf("Starting new epoch with identifier %s epoch number %d", epochInfo.Identifier, epochInfo.CurrentEpoch)) } else { - err := k.environment.EventService.EventManager(ctx).Emit(&types.EventEpochEnd{ + err := k.EventService.EventManager(ctx).Emit(&types.EventEpochEnd{ EpochNumber: epochInfo.CurrentEpoch, }) if err != nil { return false, nil } - if err := k.environment.BranchService.Execute(ctx, func(ctx context.Context) error { + if err := k.BranchService.Execute(ctx, func(ctx context.Context) error { return k.AfterEpochEnd(ctx, epochInfo.Identifier, epochInfo.CurrentEpoch) }); err != nil { // purposely ignoring the error here not to halt the chain if the hook fails - logger.Error(fmt.Sprintf("Error after epoch end with identifier %s epoch number %d", epochInfo.Identifier, epochInfo.CurrentEpoch)) + k.Logger.Error(fmt.Sprintf("Error after epoch end with identifier %s epoch number %d", epochInfo.Identifier, epochInfo.CurrentEpoch)) } epochInfo.CurrentEpoch += 1 epochInfo.CurrentEpochStartTime = epochInfo.CurrentEpochStartTime.Add(epochInfo.Duration) - logger.Debug(fmt.Sprintf("Starting epoch with identifier %s epoch number %d", epochInfo.Identifier, epochInfo.CurrentEpoch)) + k.Logger.Debug(fmt.Sprintf("Starting epoch with identifier %s epoch number %d", epochInfo.Identifier, epochInfo.CurrentEpoch)) } // emit new epoch start event, set epoch info, and run BeforeEpochStart hook - err = k.environment.EventService.EventManager(ctx).Emit(&types.EventEpochStart{ + err = k.EventService.EventManager(ctx).Emit(&types.EventEpochStart{ EpochNumber: epochInfo.CurrentEpoch, EpochStartTime: epochInfo.CurrentEpochStartTime.Unix(), }) @@ -69,14 +68,14 @@ func (k Keeper) BeginBlocker(ctx context.Context) error { } err = k.EpochInfo.Set(ctx, epochInfo.Identifier, epochInfo) if err != nil { - logger.Error(fmt.Sprintf("Error set epoch info with identifier %s epoch number %d", epochInfo.Identifier, epochInfo.CurrentEpoch)) + k.Logger.Error(fmt.Sprintf("Error set epoch info with identifier %s epoch number %d", epochInfo.Identifier, epochInfo.CurrentEpoch)) return false, nil } - if err := k.environment.BranchService.Execute(ctx, func(ctx context.Context) error { + if err := k.BranchService.Execute(ctx, func(ctx context.Context) error { return k.BeforeEpochStart(ctx, epochInfo.Identifier, epochInfo.CurrentEpoch) }); err != nil { // purposely ignoring the error here not to halt the chain if the hook fails - logger.Error(fmt.Sprintf("Error before epoch start with identifier %s epoch number %d", epochInfo.Identifier, epochInfo.CurrentEpoch)) + k.Logger.Error(fmt.Sprintf("Error before epoch start with identifier %s epoch number %d", epochInfo.Identifier, epochInfo.CurrentEpoch)) } return false, nil }, diff --git a/x/epochs/keeper/epoch.go b/x/epochs/keeper/epoch.go index de5f0f51f9e0..3943cf4c61c5 100644 --- a/x/epochs/keeper/epoch.go +++ b/x/epochs/keeper/epoch.go @@ -26,10 +26,10 @@ func (k Keeper) AddEpochInfo(ctx context.Context, epoch types.EpochInfo) error { // Initialize empty and default epoch values if epoch.StartTime.IsZero() { - epoch.StartTime = k.environment.HeaderService.GetHeaderInfo(ctx).Time + epoch.StartTime = k.HeaderService.HeaderInfo(ctx).Time } if epoch.CurrentEpochStartHeight == 0 { - epoch.CurrentEpochStartHeight = k.environment.HeaderService.GetHeaderInfo(ctx).Height + epoch.CurrentEpochStartHeight = k.HeaderService.HeaderInfo(ctx).Height } return k.EpochInfo.Set(ctx, epoch.Identifier, epoch) } @@ -57,5 +57,5 @@ func (k Keeper) NumBlocksSinceEpochStart(ctx context.Context, identifier string) if err != nil { return 0, fmt.Errorf("epoch with identifier %s not found", identifier) } - return k.environment.HeaderService.GetHeaderInfo(ctx).Height - epoch.CurrentEpochStartHeight, nil + return k.HeaderService.HeaderInfo(ctx).Height - epoch.CurrentEpochStartHeight, nil } diff --git a/x/epochs/keeper/keeper.go b/x/epochs/keeper/keeper.go index a389b183a52e..2b47d40be2b9 100644 --- a/x/epochs/keeper/keeper.go +++ b/x/epochs/keeper/keeper.go @@ -3,29 +3,27 @@ package keeper import ( "cosmossdk.io/collections" "cosmossdk.io/core/appmodule" - "cosmossdk.io/log" "cosmossdk.io/x/epochs/types" "github.com/cosmos/cosmos-sdk/codec" ) -type ( - Keeper struct { - cdc codec.BinaryCodec - environment appmodule.Environment - hooks types.EpochHooks +type Keeper struct { + appmodule.Environment - Schema collections.Schema - EpochInfo collections.Map[string, types.EpochInfo] - } -) + cdc codec.BinaryCodec + hooks types.EpochHooks + + Schema collections.Schema + EpochInfo collections.Map[string, types.EpochInfo] +} // NewKeeper returns a new keeper by codec and storeKey inputs. func NewKeeper(env appmodule.Environment, cdc codec.BinaryCodec) Keeper { sb := collections.NewSchemaBuilder(env.KVStoreService) k := Keeper{ + Environment: env, cdc: cdc, - environment: env, EpochInfo: collections.NewMap(sb, types.KeyPrefixEpoch, "epoch_info", collections.StringKey, codec.CollValue[types.EpochInfo](cdc)), } @@ -47,7 +45,3 @@ func (k Keeper) SetHooks(eh types.EpochHooks) Keeper { return k } - -func (k Keeper) Logger() log.Logger { - return k.environment.Logger -} diff --git a/x/evidence/keeper/abci.go b/x/evidence/keeper/abci.go index 5e5321e40f3e..a759e13ace05 100644 --- a/x/evidence/keeper/abci.go +++ b/x/evidence/keeper/abci.go @@ -30,7 +30,7 @@ func (k Keeper) BeginBlocker(ctx context.Context) error { return err } default: - k.Logger().Error(fmt.Sprintf("ignored unknown evidence type: %x", evidence.Type)) + k.Logger.Error(fmt.Sprintf("ignored unknown evidence type: %x", evidence.Type)) } } return nil diff --git a/x/evidence/keeper/infraction.go b/x/evidence/keeper/infraction.go index d0adc0e9f9c8..4c0fe688a044 100644 --- a/x/evidence/keeper/infraction.go +++ b/x/evidence/keeper/infraction.go @@ -25,7 +25,6 @@ import ( // TODO: Some of the invalid constraints listed above may need to be reconsidered // in the case of a lunatic attack. func (k Keeper) handleEquivocationEvidence(ctx context.Context, evidence *types.Equivocation) error { - logger := k.Logger() consAddr := evidence.GetConsensusAddress(k.stakingKeeper.ConsensusAddressCodec()) validator, err := k.stakingKeeper.ValidatorByConsAddr(ctx, consAddr) @@ -58,12 +57,12 @@ func (k Keeper) handleEquivocationEvidence(ctx context.Context, evidence *types. // allowable but none of the disallowed evidence types. Instead of // getting this coordination right, it is easier to relax the // constraints and ignore evidence that cannot be handled. - logger.Error(fmt.Sprintf("ignore evidence; expected public key for validator %s not found", consAddr)) + k.Logger.Error(fmt.Sprintf("ignore evidence; expected public key for validator %s not found", consAddr)) return nil } } - headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + headerInfo := k.HeaderService.HeaderInfo(ctx) // calculate the age of the evidence infractionHeight := evidence.GetHeight() infractionTime := evidence.GetTime() @@ -77,7 +76,7 @@ func (k Keeper) handleEquivocationEvidence(ctx context.Context, evidence *types. cp := sdkCtx.ConsensusParams() // TODO: remove in favor of querying consensus module if cp.Evidence != nil { if ageDuration > cp.Evidence.MaxAgeDuration && ageBlocks > cp.Evidence.MaxAgeNumBlocks { - logger.Info( + k.Logger.Info( "ignored equivocation; evidence too old", "validator", consAddr, "infraction_height", infractionHeight, @@ -95,7 +94,7 @@ func (k Keeper) handleEquivocationEvidence(ctx context.Context, evidence *types. // ignore if the validator is already tombstoned if k.slashingKeeper.IsTombstoned(ctx, consAddr) { - logger.Info( + k.Logger.Info( "ignored equivocation; validator already tombstoned", "validator", consAddr, "infraction_height", infractionHeight, @@ -104,7 +103,7 @@ func (k Keeper) handleEquivocationEvidence(ctx context.Context, evidence *types. return nil } - logger.Info( + k.Logger.Info( "confirmed equivocation", "validator", consAddr, "infraction_height", infractionHeight, diff --git a/x/evidence/keeper/keeper.go b/x/evidence/keeper/keeper.go index e5c54104aab4..1a3356f420ae 100644 --- a/x/evidence/keeper/keeper.go +++ b/x/evidence/keeper/keeper.go @@ -11,7 +11,6 @@ import ( "cosmossdk.io/core/appmodule" "cosmossdk.io/core/event" "cosmossdk.io/errors" - "cosmossdk.io/log" "cosmossdk.io/x/evidence/exported" "cosmossdk.io/x/evidence/types" @@ -22,8 +21,9 @@ import ( // managing persistence, state transitions and query handling for the evidence // module. type Keeper struct { + appmodule.Environment + cdc codec.BinaryCodec - environment appmodule.Environment router types.Router stakingKeeper types.StakingKeeper slashingKeeper types.SlashingKeeper @@ -41,8 +41,8 @@ func NewKeeper( ) *Keeper { sb := collections.NewSchemaBuilder(env.KVStoreService) k := &Keeper{ + Environment: env, cdc: cdc, - environment: env, stakingKeeper: stakingKeeper, slashingKeeper: slashingKeeper, addressCodec: ac, @@ -56,11 +56,6 @@ func NewKeeper( return k } -// Logger returns a module-specific logger. -func (k Keeper) Logger() log.Logger { - return k.environment.Logger.With("module", "x/"+types.ModuleName) -} - // SetRouter sets the Evidence Handler router for the x/evidence module. Note, // we allow the ability to set the router after the Keeper is constructed as a // given Handler may need access the Keeper before being constructed. The router @@ -106,7 +101,7 @@ func (k Keeper) SubmitEvidence(ctx context.Context, evidence exported.Evidence) return errors.Wrap(types.ErrInvalidEvidence, err.Error()) } - if err := k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( types.EventTypeSubmitEvidence, event.NewAttribute(types.AttributeKeyEvidenceHash, strings.ToUpper(hex.EncodeToString(evidence.Hash()))), ); err != nil { diff --git a/x/evidence/keeper/keeper_test.go b/x/evidence/keeper/keeper_test.go index 1784b003b945..a21edc60d7c9 100644 --- a/x/evidence/keeper/keeper_test.go +++ b/x/evidence/keeper/keeper_test.go @@ -132,7 +132,7 @@ func (suite *KeeperTestSuite) SetupTest() { suite.evidenceKeeper = *evidenceKeeper suite.Require().Equal(testCtx.Ctx.Logger().With("module", "x/"+types.ModuleName), - suite.evidenceKeeper.Logger()) + suite.evidenceKeeper.Logger) suite.msgServer = keeper.NewMsgServerImpl(suite.evidenceKeeper) } diff --git a/x/feegrant/keeper/keeper.go b/x/feegrant/keeper/keeper.go index d3a6e8a57e70..903794ab5850 100644 --- a/x/feegrant/keeper/keeper.go +++ b/x/feegrant/keeper/keeper.go @@ -21,10 +21,11 @@ import ( // Keeper manages state of all fee grants, as well as calculating approval. // It must have a codec with all available allowances registered. type Keeper struct { - cdc codec.BinaryCodec - environment appmodule.Environment - authKeeper feegrant.AccountKeeper - Schema collections.Schema + appmodule.Environment + + cdc codec.BinaryCodec + authKeeper feegrant.AccountKeeper + Schema collections.Schema // FeeAllowance key: grantee+granter | value: Grant FeeAllowance collections.Map[collections.Pair[sdk.AccAddress, sdk.AccAddress], feegrant.Grant] // FeeAllowanceQueue key: expiration time+grantee+granter | value: bool @@ -38,8 +39,8 @@ func NewKeeper(env appmodule.Environment, cdc codec.BinaryCodec, ak feegrant.Acc sb := collections.NewSchemaBuilder(env.KVStoreService) return Keeper{ + Environment: env, cdc: cdc, - environment: env, authKeeper: ak, FeeAllowance: collections.NewMap( sb, @@ -77,7 +78,7 @@ func (k Keeper) GrantAllowance(ctx context.Context, granter, grantee sdk.AccAddr // expiration shouldn't be in the past. - now := k.environment.HeaderService.GetHeaderInfo(ctx).Time + now := k.HeaderService.HeaderInfo(ctx).Time if exp != nil && exp.Before(now) { return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "expiration is before current block time") } @@ -117,7 +118,7 @@ func (k Keeper) GrantAllowance(ctx context.Context, granter, grantee sdk.AccAddr return err } - return k.environment.EventService.EventManager(ctx).EmitKV( + return k.EventService.EventManager(ctx).EmitKV( feegrant.EventTypeSetFeeGrant, event.NewAttribute(feegrant.AttributeKeyGranter, grant.Granter), event.NewAttribute(feegrant.AttributeKeyGrantee, grant.Grantee), @@ -149,7 +150,7 @@ func (k Keeper) UpdateAllowance(ctx context.Context, granter, grantee sdk.AccAdd return err } - return k.environment.EventService.EventManager(ctx).EmitKV( + return k.EventService.EventManager(ctx).EmitKV( feegrant.EventTypeUpdateFeeGrant, event.NewAttribute(feegrant.AttributeKeyGranter, grant.Granter), event.NewAttribute(feegrant.AttributeKeyGrantee, grant.Grantee), @@ -187,7 +188,7 @@ func (k Keeper) revokeAllowance(ctx context.Context, granter, grantee sdk.AccAdd return err } - return k.environment.EventService.EventManager(ctx).EmitKV( + return k.EventService.EventManager(ctx).EmitKV( feegrant.EventTypeRevokeFeeGrant, event.NewAttribute(feegrant.AttributeKeyGranter, granterStr), event.NewAttribute(feegrant.AttributeKeyGrantee, granteeStr), @@ -250,7 +251,7 @@ func (k Keeper) UseGrantedFees(ctx context.Context, granter, grantee sdk.AccAddr } func (k *Keeper) emitUseGrantEvent(ctx context.Context, granter, grantee string) error { - return k.environment.EventService.EventManager(ctx).EmitKV( + return k.EventService.EventManager(ctx).EmitKV( feegrant.EventTypeUseFeeGrant, event.NewAttribute(feegrant.AttributeKeyGranter, granter), event.NewAttribute(feegrant.AttributeKeyGrantee, grantee), @@ -298,7 +299,7 @@ func (k Keeper) ExportGenesis(ctx context.Context) (*feegrant.GenesisState, erro // RemoveExpiredAllowances iterates grantsByExpiryQueue and deletes the expired grants. func (k Keeper) RemoveExpiredAllowances(ctx context.Context, limit int) error { - exp := k.environment.HeaderService.GetHeaderInfo(ctx).Time + exp := k.HeaderService.HeaderInfo(ctx).Time rng := collections.NewPrefixUntilTripleRange[time.Time, sdk.AccAddress, sdk.AccAddress](exp) count := 0 diff --git a/x/feegrant/keeper/migrations.go b/x/feegrant/keeper/migrations.go index 8e94535fd93a..d4721d9654c1 100644 --- a/x/feegrant/keeper/migrations.go +++ b/x/feegrant/keeper/migrations.go @@ -18,5 +18,5 @@ func NewMigrator(keeper Keeper) Migrator { // Migrate1to2 migrates from version 1 to 2. func (m Migrator) Migrate1to2(ctx context.Context) error { - return v2.MigrateStore(ctx, m.keeper.environment, m.keeper.cdc) + return v2.MigrateStore(ctx, m.keeper.Environment, m.keeper.cdc) } diff --git a/x/feegrant/keeper/msg_server.go b/x/feegrant/keeper/msg_server.go index b4ce56b01783..79e4405ccfb9 100644 --- a/x/feegrant/keeper/msg_server.go +++ b/x/feegrant/keeper/msg_server.go @@ -94,7 +94,7 @@ func (k msgServer) PruneAllowances(ctx context.Context, req *feegrant.MsgPruneAl return nil, err } - if err := k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( feegrant.EventTypePruneFeeGrant, event.NewAttribute(feegrant.AttributeKeyPruner, req.Pruner), ); err != nil { diff --git a/x/feegrant/migrations/v2/store.go b/x/feegrant/migrations/v2/store.go index cc8ea48d2b53..82a76eacfe53 100644 --- a/x/feegrant/migrations/v2/store.go +++ b/x/feegrant/migrations/v2/store.go @@ -37,7 +37,7 @@ func addAllowancesByExpTimeQueue(ctx context.Context, env appmodule.Environment, if exp != nil { // store key is not changed in 0.46 key := iterator.Key() - if exp.Before(env.HeaderService.GetHeaderInfo(ctx).Time) { + if exp.Before(env.HeaderService.HeaderInfo(ctx).Time) { prefixStore.Delete(key) } else { grantByExpTimeQueueKey := FeeAllowancePrefixQueue(exp, key) diff --git a/x/gov/keeper/abci.go b/x/gov/keeper/abci.go index 4969d4abfbda..1a9fc760cf06 100644 --- a/x/gov/keeper/abci.go +++ b/x/gov/keeper/abci.go @@ -11,7 +11,6 @@ import ( "cosmossdk.io/collections" "cosmossdk.io/core/event" "cosmossdk.io/core/router" - "cosmossdk.io/log" "cosmossdk.io/x/gov/types" v1 "cosmossdk.io/x/gov/types/v1" @@ -23,10 +22,9 @@ import ( func (k Keeper) EndBlocker(ctx context.Context) error { defer telemetry.ModuleMeasureSince(types.ModuleName, telemetry.Now(), telemetry.MetricKeyEndBlocker) - logger := k.Logger() // delete dead proposals from store and returns theirs deposits. // A proposal is dead when it's inactive and didn't get enough deposit on time to get into voting phase. - rng := collections.NewPrefixUntilPairRange[time.Time, uint64](k.environment.HeaderService.GetHeaderInfo(ctx).Time) + rng := collections.NewPrefixUntilPairRange[time.Time, uint64](k.HeaderService.HeaderInfo(ctx).Time) iter, err := k.InactiveProposalsQueue.Iterate(ctx, rng) if err != nil { return err @@ -45,7 +43,7 @@ func (k Keeper) EndBlocker(ctx context.Context) error { // instead of returning an error (i.e, halting the chain), we fail the proposal if errors.Is(err, collections.ErrEncoding) { proposal.Id = prop.Key.K2() - if err := failUnsupportedProposal(logger, ctx, k, proposal, err.Error(), false); err != nil { + if err := failUnsupportedProposal(ctx, k, proposal, err.Error(), false); err != nil { return err } @@ -79,21 +77,21 @@ func (k Keeper) EndBlocker(ctx context.Context) error { // called when proposal become inactive // call hook when proposal become inactive - if err := k.environment.BranchService.Execute(ctx, func(ctx context.Context) error { + if err := k.BranchService.Execute(ctx, func(ctx context.Context) error { return k.Hooks().AfterProposalFailedMinDeposit(ctx, proposal.Id) }); err != nil { // purposely ignoring the error here not to halt the chain if the hook fails - logger.Error("failed to execute AfterProposalFailedMinDeposit hook", "error", err) + k.Logger.Error("failed to execute AfterProposalFailedMinDeposit hook", "error", err) } - if err := k.environment.EventService.EventManager(ctx).EmitKV(types.EventTypeInactiveProposal, + if err := k.EventService.EventManager(ctx).EmitKV(types.EventTypeInactiveProposal, event.NewAttribute(types.AttributeKeyProposalID, fmt.Sprintf("%d", proposal.Id)), event.NewAttribute(types.AttributeKeyProposalResult, types.AttributeValueProposalDropped), ); err != nil { - logger.Error("failed to emit event", "error", err) + k.Logger.Error("failed to emit event", "error", err) } - logger.Info( + k.Logger.Info( "proposal did not meet minimum deposit; deleted", "proposal", proposal.Id, "proposal_type", proposal.ProposalType, @@ -104,7 +102,7 @@ func (k Keeper) EndBlocker(ctx context.Context) error { } // fetch active proposals whose voting periods have ended (are passed the block time) - rng = collections.NewPrefixUntilPairRange[time.Time, uint64](k.environment.HeaderService.GetHeaderInfo(ctx).Time) + rng = collections.NewPrefixUntilPairRange[time.Time, uint64](k.HeaderService.HeaderInfo(ctx).Time) iter, err = k.ActiveProposalsQueue.Iterate(ctx, rng) if err != nil { @@ -125,7 +123,7 @@ func (k Keeper) EndBlocker(ctx context.Context) error { // instead of returning an error (i.e, halting the chain), we fail the proposal if errors.Is(err, collections.ErrEncoding) { proposal.Id = prop.Key.K2() - if err := failUnsupportedProposal(logger, ctx, k, proposal, err.Error(), true); err != nil { + if err := failUnsupportedProposal(ctx, k, proposal, err.Error(), true); err != nil { return err } @@ -159,14 +157,14 @@ func (k Keeper) EndBlocker(ctx context.Context) error { // in case of an error, log it and emit an event // we do not want to halt the chain if the refund/burn fails // as it could happen due to a governance mistake (governance has let a proposal pass that sends gov funds that were from proposal deposits) - k.Logger().Error("failed to refund or burn deposits", "error", err) + k.Logger.Error("failed to refund or burn deposits", "error", err) - if err := k.environment.EventService.EventManager(ctx).EmitKV(types.EventTypeProposalDeposit, + if err := k.EventService.EventManager(ctx).EmitKV(types.EventTypeProposalDeposit, event.NewAttribute(types.AttributeKeyProposalID, fmt.Sprintf("%d", proposal.Id)), event.NewAttribute(types.AttributeKeyProposalDepositError, "failed to refund or burn deposits"), event.NewAttribute("error", err.Error()), ); err != nil { - k.Logger().Error("failed to emit event", "error", err) + k.Logger.Error("failed to emit event", "error", err) } } @@ -195,10 +193,10 @@ func (k Keeper) EndBlocker(ctx context.Context) error { // Messages may mutate state thus we use a cached context. If one of // the handlers fails, no state mutation is written and the error // message is logged. - if err := k.environment.BranchService.Execute(ctx, func(ctx context.Context) error { + if err := k.BranchService.Execute(ctx, func(ctx context.Context) error { // execute all messages for idx, msg = range messages { - if _, err := safeExecuteHandler(ctx, msg, k.environment.RouterService.MessageRouterService()); err != nil { + if _, err := safeExecuteHandler(ctx, msg, k.RouterService.MessageRouterService()); err != nil { // `idx` and `err` are populated with the msg index and error. proposal.Status = v1.StatusFailed proposal.FailedReason = err.Error() @@ -258,14 +256,14 @@ func (k Keeper) EndBlocker(ctx context.Context) error { } // call hook when proposal become active - if err := k.environment.BranchService.Execute(ctx, func(ctx context.Context) error { + if err := k.BranchService.Execute(ctx, func(ctx context.Context) error { return k.Hooks().AfterProposalVotingPeriodEnded(ctx, proposal.Id) }); err != nil { // purposely ignoring the error here not to halt the chain if the hook fails - logger.Error("failed to execute AfterProposalVotingPeriodEnded hook", "error", err) + k.Logger.Error("failed to execute AfterProposalVotingPeriodEnded hook", "error", err) } - logger.Info( + k.Logger.Info( "proposal tallied", "proposal", proposal.Id, "proposal_type", proposal.ProposalType, @@ -274,12 +272,12 @@ func (k Keeper) EndBlocker(ctx context.Context) error { "results", logMsg, ) - if err := k.environment.EventService.EventManager(ctx).EmitKV(types.EventTypeActiveProposal, + if err := k.EventService.EventManager(ctx).EmitKV(types.EventTypeActiveProposal, event.NewAttribute(types.AttributeKeyProposalID, fmt.Sprintf("%d", proposal.Id)), event.NewAttribute(types.AttributeKeyProposalResult, tagValue), event.NewAttribute(types.AttributeKeyProposalLog, logMsg), ); err != nil { - logger.Error("failed to emit event", "error", err) + k.Logger.Error("failed to emit event", "error", err) } } return nil @@ -299,7 +297,6 @@ func safeExecuteHandler(ctx context.Context, msg sdk.Msg, router router.Router) // failUnsupportedProposal fails a proposal that cannot be processed by gov func failUnsupportedProposal( - logger log.Logger, ctx context.Context, k Keeper, proposal v1.Proposal, @@ -323,14 +320,14 @@ func failUnsupportedProposal( eventType = types.EventTypeActiveProposal } - if err := k.environment.EventService.EventManager(ctx).EmitKV(eventType, + if err := k.EventService.EventManager(ctx).EmitKV(eventType, event.NewAttribute(types.AttributeKeyProposalID, fmt.Sprintf("%d", proposal.Id)), event.NewAttribute(types.AttributeKeyProposalResult, types.AttributeValueProposalFailed), ); err != nil { - logger.Error("failed to emit event", "error", err) + k.Logger.Error("failed to emit event", "error", err) } - logger.Info( + k.Logger.Info( "proposal failed to decode; deleted", "proposal", proposal.Id, "proposal_type", proposal.ProposalType, diff --git a/x/gov/keeper/deposit.go b/x/gov/keeper/deposit.go index 51b2e728fff1..d2c13cea6ba8 100644 --- a/x/gov/keeper/deposit.go +++ b/x/gov/keeper/deposit.go @@ -186,7 +186,7 @@ func (k Keeper) AddDeposit(ctx context.Context, proposalID uint64, depositorAddr return false, err } - if err := k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( types.EventTypeProposalDeposit, event.NewAttribute(types.AttributeKeyDepositor, depositorStrAddr), event.NewAttribute(sdk.AttributeKeyAmount, depositAmount.String()), diff --git a/x/gov/keeper/keeper.go b/x/gov/keeper/keeper.go index 0610da71e1d5..57464eb01181 100644 --- a/x/gov/keeper/keeper.go +++ b/x/gov/keeper/keeper.go @@ -8,7 +8,6 @@ import ( "cosmossdk.io/collections" "cosmossdk.io/core/appmodule" - "cosmossdk.io/log" "cosmossdk.io/x/gov/types" v1 "cosmossdk.io/x/gov/types/v1" "cosmossdk.io/x/gov/types/v1beta1" @@ -19,6 +18,8 @@ import ( // Keeper defines the governance module Keeper type Keeper struct { + appmodule.Environment + authKeeper types.AccountKeeper bankKeeper types.BankKeeper poolKeeper types.PoolKeeper @@ -31,9 +32,6 @@ type Keeper struct { // The codec for binary encoding/decoding. cdc codec.Codec - // Module environment - environment appmodule.Environment - // Legacy Proposal router legacyRouter v1beta1.Router @@ -111,7 +109,7 @@ func NewKeeper( sb := collections.NewSchemaBuilder(env.KVStoreService) k := &Keeper{ - environment: env, + Environment: env, authKeeper: authKeeper, bankKeeper: bankKeeper, sk: sk, @@ -168,11 +166,6 @@ func (k *Keeper) SetLegacyRouter(router v1beta1.Router) { k.legacyRouter = router } -// Logger returns a module-specific logger. -func (k Keeper) Logger() log.Logger { - return k.environment.Logger.With("module", "x/"+types.ModuleName) -} - // LegacyRouter returns the gov keeper's legacy router func (k Keeper) LegacyRouter() v1beta1.Router { return k.legacyRouter diff --git a/x/gov/keeper/migrations.go b/x/gov/keeper/migrations.go index d6278326f7a0..5b366b9b7373 100644 --- a/x/gov/keeper/migrations.go +++ b/x/gov/keeper/migrations.go @@ -36,10 +36,10 @@ func (m Migrator) Migrate3to4(ctx context.Context) error { // Migrate4to5 migrates from version 4 to 5. func (m Migrator) Migrate4to5(ctx context.Context) error { - return v5.MigrateStore(ctx, m.keeper.environment.KVStoreService, m.keeper.cdc, m.keeper.Constitution) + return v5.MigrateStore(ctx, m.keeper.KVStoreService, m.keeper.cdc, m.keeper.Constitution) } // Migrate4to5 migrates from version 5 to 6. func (m Migrator) Migrate5to6(ctx context.Context) error { - return v6.MigrateStore(ctx, m.keeper.environment.KVStoreService, m.keeper.Params, m.keeper.Proposals) + return v6.MigrateStore(ctx, m.keeper.KVStoreService, m.keeper.Params, m.keeper.Proposals) } diff --git a/x/gov/keeper/msg_server.go b/x/gov/keeper/msg_server.go index 1799cbefcd87..02120624a57b 100644 --- a/x/gov/keeper/msg_server.go +++ b/x/gov/keeper/msg_server.go @@ -97,8 +97,8 @@ func (k msgServer) SubmitProposal(ctx context.Context, msg *v1.MsgSubmitProposal } // ref: https://github.com/cosmos/cosmos-sdk/issues/9683 - k.environment.GasService.GetGasMeter(ctx).Consume( - 3*k.environment.GasService.GetGasConfig(ctx).WriteCostPerByte*uint64(len(bytes)), + k.GasService.GasMeter(ctx).Consume( + 3*k.GasService.GasConfig(ctx).WriteCostPerByte*uint64(len(bytes)), "submit proposal", ) @@ -108,7 +108,7 @@ func (k msgServer) SubmitProposal(ctx context.Context, msg *v1.MsgSubmitProposal } if votingStarted { - if err := k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( govtypes.EventTypeSubmitProposal, event.NewAttribute(govtypes.AttributeKeyVotingPeriodStart, fmt.Sprintf("%d", proposal.Id)), ); err != nil { @@ -171,7 +171,7 @@ func (k msgServer) CancelProposal(ctx context.Context, msg *v1.MsgCancelProposal return nil, err } - if err := k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( govtypes.EventTypeCancelProposal, event.NewAttribute(sdk.AttributeKeySender, msg.Proposer), event.NewAttribute(govtypes.AttributeKeyProposalID, fmt.Sprint(msg.ProposalId)), @@ -181,8 +181,8 @@ func (k msgServer) CancelProposal(ctx context.Context, msg *v1.MsgCancelProposal return &v1.MsgCancelProposalResponse{ ProposalId: msg.ProposalId, - CanceledTime: k.environment.HeaderService.GetHeaderInfo(ctx).Time, - CanceledHeight: uint64(k.environment.HeaderService.GetHeaderInfo(ctx).Height), + CanceledTime: k.HeaderService.HeaderInfo(ctx).Time, + CanceledHeight: uint64(k.HeaderService.HeaderInfo(ctx).Height), }, nil } @@ -293,7 +293,7 @@ func (k msgServer) Deposit(ctx context.Context, msg *v1.MsgDeposit) (*v1.MsgDepo } if votingStarted { - if err := k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( govtypes.EventTypeProposalDeposit, event.NewAttribute(govtypes.AttributeKeyVotingPeriodStart, fmt.Sprintf("%d", msg.ProposalId)), ); err != nil { @@ -374,13 +374,13 @@ func (k msgServer) SudoExec(ctx context.Context, msg *v1.MsgSudoExec) (*v1.MsgSu } var msgResp protoiface.MessageV1 - if err := k.environment.BranchService.Execute(ctx, func(ctx context.Context) error { + if err := k.BranchService.Execute(ctx, func(ctx context.Context) error { // TODO add route check here - if err := k.environment.RouterService.MessageRouterService().CanInvoke(ctx, sdk.MsgTypeURL(sudoedMsg)); err != nil { + if err := k.RouterService.MessageRouterService().CanInvoke(ctx, sdk.MsgTypeURL(sudoedMsg)); err != nil { return errors.Wrapf(govtypes.ErrInvalidProposal, err.Error()) } - msgResp, err = k.environment.RouterService.MessageRouterService().InvokeUntyped(ctx, sudoedMsg) + msgResp, err = k.RouterService.MessageRouterService().InvokeUntyped(ctx, sudoedMsg) if err != nil { return errors.Wrapf(err, "failed to execute sudo-ed message; message %v", sudoedMsg) } diff --git a/x/gov/keeper/proposal.go b/x/gov/keeper/proposal.go index b3373f12ac2c..ff7a8ab1ebde 100644 --- a/x/gov/keeper/proposal.go +++ b/x/gov/keeper/proposal.go @@ -87,7 +87,7 @@ func (k Keeper) SubmitProposal(ctx context.Context, messages []sdk.Msg, metadata return v1.Proposal{}, errorsmod.Wrapf(types.ErrInvalidSigner, addr) } - if err := k.environment.RouterService.MessageRouterService().CanInvoke(ctx, sdk.MsgTypeURL(msg)); err != nil { + if err := k.RouterService.MessageRouterService().CanInvoke(ctx, sdk.MsgTypeURL(msg)); err != nil { return v1.Proposal{}, errorsmod.Wrap(types.ErrUnroutableProposalMsg, err.Error()) } @@ -111,7 +111,7 @@ func (k Keeper) SubmitProposal(ctx context.Context, messages []sdk.Msg, metadata return v1.Proposal{}, errorsmod.Wrap(types.ErrNoProposalHandlerExists, content.ProposalRoute()) } - if err = k.environment.BranchService.Execute(ctx, func(ctx context.Context) error { + if err = k.BranchService.Execute(ctx, func(ctx context.Context) error { handler := k.legacyRouter.GetRoute(content.ProposalRoute()) if err := handler(ctx, content); err != nil { return types.ErrInvalidProposalContent.Wrapf("failed to run legacy handler %s, %+v", content.ProposalRoute(), err) @@ -132,7 +132,7 @@ func (k Keeper) SubmitProposal(ctx context.Context, messages []sdk.Msg, metadata if err != nil { return v1.Proposal{}, err } - submitTime := k.environment.HeaderService.GetHeaderInfo(ctx).Time + submitTime := k.HeaderService.HeaderInfo(ctx).Time proposal, err := v1.NewProposal(messages, proposalID, submitTime, submitTime.Add(*params.MaxDepositPeriod), metadata, title, summary, proposerAddr, proposalType) if err != nil { return v1.Proposal{}, err @@ -152,7 +152,7 @@ func (k Keeper) SubmitProposal(ctx context.Context, messages []sdk.Msg, metadata return v1.Proposal{}, err } - if err := k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( types.EventTypeSubmitProposal, event.NewAttribute(types.AttributeKeyProposalType, proposalType.String()), event.NewAttribute(types.AttributeKeyProposalID, fmt.Sprintf("%d", proposalID)), @@ -198,7 +198,7 @@ func (k Keeper) CancelProposal(ctx context.Context, proposalID uint64, proposer // Check proposal is not too far in voting period to be canceled if proposal.VotingEndTime != nil { - currentTime := k.environment.HeaderService.GetHeaderInfo(ctx).Time + currentTime := k.HeaderService.HeaderInfo(ctx).Time maxCancelPeriodRate := sdkmath.LegacyMustNewDecFromStr(params.ProposalCancelMaxPeriod) maxCancelPeriod := time.Duration(float64(proposal.VotingEndTime.Sub(*proposal.VotingStartTime)) * maxCancelPeriodRate.MustFloat64()).Round(time.Second) @@ -229,7 +229,7 @@ func (k Keeper) CancelProposal(ctx context.Context, proposalID uint64, proposer return err } - k.Logger().Info( + k.Logger.Info( "proposal is canceled by proposer", "proposal", proposal.Id, "proposer", proposal.Proposer, @@ -263,7 +263,7 @@ func (k Keeper) DeleteProposal(ctx context.Context, proposalID uint64) error { // ActivateVotingPeriod activates the voting period of a proposal func (k Keeper) ActivateVotingPeriod(ctx context.Context, proposal v1.Proposal) error { - startTime := k.environment.HeaderService.GetHeaderInfo(ctx).Time + startTime := k.HeaderService.HeaderInfo(ctx).Time proposal.VotingStartTime = &startTime params, err := k.Params.Get(ctx) diff --git a/x/gov/keeper/vote.go b/x/gov/keeper/vote.go index 1e635c34c0a1..f1f13d7d71c8 100644 --- a/x/gov/keeper/vote.go +++ b/x/gov/keeper/vote.go @@ -83,7 +83,7 @@ func (k Keeper) AddVote(ctx context.Context, proposalID uint64, voterAddr sdk.Ac return err } - return k.environment.EventService.EventManager(ctx).EmitKV(types.EventTypeProposalVote, + return k.EventService.EventManager(ctx).EmitKV(types.EventTypeProposalVote, event.NewAttribute(types.AttributeKeyVoter, voterStrAddr), event.NewAttribute(types.AttributeKeyOption, options.String()), event.NewAttribute(types.AttributeKeyProposalID, fmt.Sprintf("%d", proposalID)), diff --git a/x/group/keeper/abci.go b/x/group/keeper/abci.go index 64a965a06e11..563490cbe856 100644 --- a/x/group/keeper/abci.go +++ b/x/group/keeper/abci.go @@ -7,9 +7,9 @@ import ( // EndBlocker called at every block, updates proposal's `FinalTallyResult` and // prunes expired proposals. func (k Keeper) EndBlocker(ctx context.Context) error { - if err := k.TallyProposalsAtVPEnd(ctx, k.environment); err != nil { + if err := k.TallyProposalsAtVPEnd(ctx); err != nil { return err } - return k.PruneProposals(ctx, k.environment) + return k.PruneProposals(ctx) } diff --git a/x/group/keeper/genesis.go b/x/group/keeper/genesis.go index a119a24bc32c..8c30ee85e71e 100644 --- a/x/group/keeper/genesis.go +++ b/x/group/keeper/genesis.go @@ -15,7 +15,7 @@ func (k Keeper) InitGenesis(ctx context.Context, cdc codec.JSONCodec, data json. var genesisState group.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := k.groupTable.Import(store, genesisState.Groups, genesisState.GroupSeq); err != nil { return errors.Wrap(err, "groups") @@ -50,7 +50,7 @@ func (k Keeper) ExportGenesis(ctx context.Context, _ codec.JSONCodec) (*group.Ge var groups []*group.GroupInfo - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) groupSeq, err := k.groupTable.Export(store, &groups) if err != nil { diff --git a/x/group/keeper/grpc_query.go b/x/group/keeper/grpc_query.go index 6884616d851f..5284f489a383 100644 --- a/x/group/keeper/grpc_query.go +++ b/x/group/keeper/grpc_query.go @@ -32,7 +32,7 @@ func (k Keeper) GroupInfo(ctx context.Context, request *group.QueryGroupInfoRequ // getGroupInfo gets the group info of the given group id. func (k Keeper) getGroupInfo(ctx context.Context, id uint64) (group.GroupInfo, error) { var obj group.GroupInfo - _, err := k.groupTable.GetOne(k.environment.KVStoreService.OpenKVStore(ctx), id, &obj) + _, err := k.groupTable.GetOne(k.KVStoreService.OpenKVStore(ctx), id, &obj) return obj, err } @@ -54,7 +54,7 @@ func (k Keeper) GroupPolicyInfo(ctx context.Context, request *group.QueryGroupPo // getGroupPolicyInfo gets the group policy info of the given account address. func (k Keeper) getGroupPolicyInfo(ctx context.Context, accountAddress string) (group.GroupPolicyInfo, error) { var obj group.GroupPolicyInfo - return obj, k.groupPolicyTable.GetOne(k.environment.KVStoreService.OpenKVStore(ctx), orm.PrimaryKey(&group.GroupPolicyInfo{Address: accountAddress}), &obj) + return obj, k.groupPolicyTable.GetOne(k.KVStoreService.OpenKVStore(ctx), orm.PrimaryKey(&group.GroupPolicyInfo{Address: accountAddress}), &obj) } // GroupMembers queries all members of a group. @@ -79,7 +79,7 @@ func (k Keeper) GroupMembers(ctx context.Context, request *group.QueryGroupMembe // getGroupMembers returns an iterator for the given group id and page request. func (k Keeper) getGroupMembers(ctx context.Context, id uint64, pageRequest *query.PageRequest) (orm.Iterator, error) { - return k.groupMemberByGroupIndex.GetPaginated(k.environment.KVStoreService.OpenKVStore(ctx), id, pageRequest) + return k.groupMemberByGroupIndex.GetPaginated(k.KVStoreService.OpenKVStore(ctx), id, pageRequest) } // GroupsByAdmin queries all groups where a given address is admin. @@ -107,7 +107,7 @@ func (k Keeper) GroupsByAdmin(ctx context.Context, request *group.QueryGroupsByA // getGroupsByAdmin returns an iterator for the given admin account address and page request. func (k Keeper) getGroupsByAdmin(ctx context.Context, admin sdk.AccAddress, pageRequest *query.PageRequest) (orm.Iterator, error) { - return k.groupByAdminIndex.GetPaginated(k.environment.KVStoreService.OpenKVStore(ctx), admin.Bytes(), pageRequest) + return k.groupByAdminIndex.GetPaginated(k.KVStoreService.OpenKVStore(ctx), admin.Bytes(), pageRequest) } // GroupPoliciesByGroup queries all groups policies of a given group. @@ -132,7 +132,7 @@ func (k Keeper) GroupPoliciesByGroup(ctx context.Context, request *group.QueryGr // getGroupPoliciesByGroup returns an iterator for the given group id and page request. func (k Keeper) getGroupPoliciesByGroup(ctx context.Context, id uint64, pageRequest *query.PageRequest) (orm.Iterator, error) { - return k.groupPolicyByGroupIndex.GetPaginated(k.environment.KVStoreService.OpenKVStore(ctx), id, pageRequest) + return k.groupPolicyByGroupIndex.GetPaginated(k.KVStoreService.OpenKVStore(ctx), id, pageRequest) } // GroupPoliciesByAdmin queries all groups policies where a given address is @@ -161,7 +161,7 @@ func (k Keeper) GroupPoliciesByAdmin(ctx context.Context, request *group.QueryGr // getGroupPoliciesByAdmin returns an iterator for the given admin account address and page request. func (k Keeper) getGroupPoliciesByAdmin(ctx context.Context, admin sdk.AccAddress, pageRequest *query.PageRequest) (orm.Iterator, error) { - return k.groupPolicyByAdminIndex.GetPaginated(k.environment.KVStoreService.OpenKVStore(ctx), admin.Bytes(), pageRequest) + return k.groupPolicyByAdminIndex.GetPaginated(k.KVStoreService.OpenKVStore(ctx), admin.Bytes(), pageRequest) } // Proposal queries a proposal. @@ -200,13 +200,13 @@ func (k Keeper) ProposalsByGroupPolicy(ctx context.Context, request *group.Query // getProposalsByGroupPolicy returns an iterator for the given account address and page request. func (k Keeper) getProposalsByGroupPolicy(ctx context.Context, account sdk.AccAddress, pageRequest *query.PageRequest) (orm.Iterator, error) { - return k.proposalByGroupPolicyIndex.GetPaginated(k.environment.KVStoreService.OpenKVStore(ctx), account.Bytes(), pageRequest) + return k.proposalByGroupPolicyIndex.GetPaginated(k.KVStoreService.OpenKVStore(ctx), account.Bytes(), pageRequest) } // getProposal gets the proposal info of the given proposal id. func (k Keeper) getProposal(ctx context.Context, proposalID uint64) (group.Proposal, error) { var p group.Proposal - if _, err := k.proposalTable.GetOne(k.environment.KVStoreService.OpenKVStore(ctx), proposalID, &p); err != nil { + if _, err := k.proposalTable.GetOne(k.KVStoreService.OpenKVStore(ctx), proposalID, &p); err != nil { return group.Proposal{}, errorsmod.Wrap(err, "load proposal") } return p, nil @@ -282,7 +282,7 @@ func (k Keeper) GroupsByMember(ctx context.Context, request *group.QueryGroupsBy return nil, err } - iter, err := k.groupMemberByMemberIndex.GetPaginated(k.environment.KVStoreService.OpenKVStore(ctx), member, request.Pagination) + iter, err := k.groupMemberByMemberIndex.GetPaginated(k.KVStoreService.OpenKVStore(ctx), member, request.Pagination) if err != nil { return nil, err } @@ -311,17 +311,17 @@ func (k Keeper) GroupsByMember(ctx context.Context, request *group.QueryGroupsBy // getVote gets the vote info for the given proposal id and voter address. func (k Keeper) getVote(ctx context.Context, proposalID uint64, voter string) (group.Vote, error) { var v group.Vote - return v, k.voteTable.GetOne(k.environment.KVStoreService.OpenKVStore(ctx), orm.PrimaryKey(&group.Vote{ProposalId: proposalID, Voter: voter}), &v) + return v, k.voteTable.GetOne(k.KVStoreService.OpenKVStore(ctx), orm.PrimaryKey(&group.Vote{ProposalId: proposalID, Voter: voter}), &v) } // getVotesByProposal returns an iterator for the given proposal id and page request. func (k Keeper) getVotesByProposal(ctx context.Context, proposalID uint64, pageRequest *query.PageRequest) (orm.Iterator, error) { - return k.voteByProposalIndex.GetPaginated(k.environment.KVStoreService.OpenKVStore(ctx), proposalID, pageRequest) + return k.voteByProposalIndex.GetPaginated(k.KVStoreService.OpenKVStore(ctx), proposalID, pageRequest) } // getVotesByVoter returns an iterator for the given voter address and page request. func (k Keeper) getVotesByVoter(ctx context.Context, voter sdk.AccAddress, pageRequest *query.PageRequest) (orm.Iterator, error) { - return k.voteByVoterIndex.GetPaginated(k.environment.KVStoreService.OpenKVStore(ctx), voter.Bytes(), pageRequest) + return k.voteByVoterIndex.GetPaginated(k.KVStoreService.OpenKVStore(ctx), voter.Bytes(), pageRequest) } // TallyResult computes the live tally result of a proposal. @@ -354,7 +354,7 @@ func (k Keeper) TallyResult(ctx context.Context, request *group.QueryTallyResult // Groups returns all the groups present in the state. func (k Keeper) Groups(ctx context.Context, request *group.QueryGroupsRequest) (*group.QueryGroupsResponse, error) { - it, err := k.groupTable.PrefixScan(k.environment.KVStoreService.OpenKVStore(ctx), 1, math.MaxUint64) + it, err := k.groupTable.PrefixScan(k.KVStoreService.OpenKVStore(ctx), 1, math.MaxUint64) if err != nil { return nil, err } diff --git a/x/group/keeper/invariants.go b/x/group/keeper/invariants.go index 98d9c0e796e2..a88f6d10699b 100644 --- a/x/group/keeper/invariants.go +++ b/x/group/keeper/invariants.go @@ -26,7 +26,7 @@ func RegisterInvariants(ir sdk.InvariantRegistry, keeper Keeper) { // GroupTotalWeightInvariant checks that group's TotalWeight must be equal to the sum of its members. func GroupTotalWeightInvariant(keeper Keeper) sdk.Invariant { return func(ctx sdk.Context) (string, bool) { - msg, broken := GroupTotalWeightInvariantHelper(ctx, keeper.environment.KVStoreService, keeper.groupTable, keeper.groupMemberByGroupIndex) + msg, broken := GroupTotalWeightInvariantHelper(ctx, keeper.KVStoreService, keeper.groupTable, keeper.groupMemberByGroupIndex) return sdk.FormatInvariant(group.ModuleName, weightInvariant, msg), broken } } diff --git a/x/group/keeper/keeper.go b/x/group/keeper/keeper.go index 622f5703ecda..f29468d987f0 100644 --- a/x/group/keeper/keeper.go +++ b/x/group/keeper/keeper.go @@ -7,7 +7,6 @@ import ( "cosmossdk.io/core/appmodule" errorsmod "cosmossdk.io/errors" - "cosmossdk.io/log" "cosmossdk.io/x/group" "cosmossdk.io/x/group/errors" "cosmossdk.io/x/group/internal/orm" @@ -46,8 +45,8 @@ const ( ) type Keeper struct { - environment appmodule.Environment - accKeeper group.AccountKeeper + appmodule.Environment + accKeeper group.AccountKeeper // Group Table groupTable orm.AutoUInt64Table @@ -82,7 +81,7 @@ type Keeper struct { // NewKeeper creates a new group keeper. func NewKeeper(env appmodule.Environment, cdc codec.Codec, accKeeper group.AccountKeeper, config group.Config) Keeper { k := Keeper{ - environment: env, + Environment: env, accKeeper: accKeeper, cdc: cdc, } @@ -231,25 +230,20 @@ func NewKeeper(env appmodule.Environment, cdc codec.Codec, accKeeper group.Accou return k } -// Logger returns a module-specific logger. -func (k Keeper) Logger() log.Logger { - return k.environment.Logger.With("module", fmt.Sprintf("x/%s", group.ModuleName)) -} - // GetGroupSequence returns the current value of the group table sequence func (k Keeper) GetGroupSequence(ctx sdk.Context) uint64 { - return k.groupTable.Sequence().CurVal(k.environment.KVStoreService.OpenKVStore(ctx)) + return k.groupTable.Sequence().CurVal(k.KVStoreService.OpenKVStore(ctx)) } // GetGroupPolicySeq returns the current value of the group policy table sequence func (k Keeper) GetGroupPolicySeq(ctx sdk.Context) uint64 { - return k.groupPolicySeq.CurVal(k.environment.KVStoreService.OpenKVStore(ctx)) + return k.groupPolicySeq.CurVal(k.KVStoreService.OpenKVStore(ctx)) } // proposalsByVPEnd returns all proposals whose voting_period_end is after the `endTime` time argument. func (k Keeper) proposalsByVPEnd(ctx context.Context, endTime time.Time) (proposals []group.Proposal, err error) { timeBytes := sdk.FormatTimeBytes(endTime) - it, err := k.proposalsByVotingPeriodEnd.PrefixScan(k.environment.KVStoreService.OpenKVStore(ctx), nil, timeBytes) + it, err := k.proposalsByVotingPeriodEnd.PrefixScan(k.KVStoreService.OpenKVStore(ctx), nil, timeBytes) if err != nil { return proposals, err } @@ -281,12 +275,12 @@ func (k Keeper) proposalsByVPEnd(ctx context.Context, endTime time.Time) (propos // pruneProposal deletes a proposal from state. func (k Keeper) pruneProposal(ctx context.Context, proposalID uint64) error { - err := k.proposalTable.Delete(k.environment.KVStoreService.OpenKVStore(ctx), proposalID) + err := k.proposalTable.Delete(k.KVStoreService.OpenKVStore(ctx), proposalID) if err != nil { return err } - k.Logger().Debug(fmt.Sprintf("Pruned proposal %d", proposalID)) + k.Logger.Debug(fmt.Sprintf("Pruned proposal %d", proposalID)) return nil } @@ -304,7 +298,7 @@ func (k Keeper) abortProposals(ctx context.Context, groupPolicyAddr sdk.AccAddre if proposalInfo.Status == group.PROPOSAL_STATUS_SUBMITTED { proposalInfo.Status = group.PROPOSAL_STATUS_ABORTED - if err := k.proposalTable.Update(k.environment.KVStoreService.OpenKVStore(ctx), proposalInfo.Id, &proposalInfo); err != nil { + if err := k.proposalTable.Update(k.KVStoreService.OpenKVStore(ctx), proposalInfo.Id, &proposalInfo); err != nil { return err } } @@ -314,7 +308,7 @@ func (k Keeper) abortProposals(ctx context.Context, groupPolicyAddr sdk.AccAddre // proposalsByGroupPolicy returns all proposals for a given group policy. func (k Keeper) proposalsByGroupPolicy(ctx context.Context, groupPolicyAddr sdk.AccAddress) ([]group.Proposal, error) { - proposalIt, err := k.proposalByGroupPolicyIndex.Get(k.environment.KVStoreService.OpenKVStore(ctx), groupPolicyAddr.Bytes()) + proposalIt, err := k.proposalByGroupPolicyIndex.Get(k.KVStoreService.OpenKVStore(ctx), groupPolicyAddr.Bytes()) if err != nil { return nil, err } @@ -345,7 +339,7 @@ func (k Keeper) pruneVotes(ctx context.Context, proposalID uint64) error { //nolint:gosec // "implicit memory aliasing in the for loop (because of the pointer on &v)" for _, v := range votes { - err = k.voteTable.Delete(k.environment.KVStoreService.OpenKVStore(ctx), &v) + err = k.voteTable.Delete(k.KVStoreService.OpenKVStore(ctx), &v) if err != nil { return err } @@ -356,7 +350,7 @@ func (k Keeper) pruneVotes(ctx context.Context, proposalID uint64) error { // votesByProposal returns all votes for a given proposal. func (k Keeper) votesByProposal(ctx context.Context, proposalID uint64) ([]group.Vote, error) { - it, err := k.voteByProposalIndex.Get(k.environment.KVStoreService.OpenKVStore(ctx), proposalID) + it, err := k.voteByProposalIndex.Get(k.KVStoreService.OpenKVStore(ctx), proposalID) if err != nil { return nil, err } @@ -380,8 +374,8 @@ func (k Keeper) votesByProposal(ctx context.Context, proposalID uint64) ([]group // PruneProposals prunes all proposals that are expired, i.e. whose // `voting_period + max_execution_period` is greater than the current block // time. -func (k Keeper) PruneProposals(ctx context.Context, env appmodule.Environment) error { - endTime := env.HeaderService.GetHeaderInfo(ctx).Time.Add(-k.config.MaxExecutionPeriod) +func (k Keeper) PruneProposals(ctx context.Context) error { + endTime := k.HeaderService.HeaderInfo(ctx).Time.Add(-k.config.MaxExecutionPeriod) proposals, err := k.proposalsByVPEnd(ctx, endTime) if err != nil { return nil @@ -394,7 +388,7 @@ func (k Keeper) PruneProposals(ctx context.Context, env appmodule.Environment) e return err } // Emit event for proposal finalized with its result - if err := k.environment.EventService.EventManager(ctx).Emit( + if err := k.EventService.EventManager(ctx).Emit( &group.EventProposalPruned{ ProposalId: proposal.Id, Status: proposal.Status, @@ -411,8 +405,8 @@ func (k Keeper) PruneProposals(ctx context.Context, env appmodule.Environment) e // TallyProposalsAtVPEnd iterates over all proposals whose voting period // has ended, tallies their votes, prunes them, and updates the proposal's // `FinalTallyResult` field. -func (k Keeper) TallyProposalsAtVPEnd(ctx context.Context, env appmodule.Environment) error { - proposals, err := k.proposalsByVPEnd(ctx, env.HeaderService.GetHeaderInfo(ctx).Time) +func (k Keeper) TallyProposalsAtVPEnd(ctx context.Context) error { + proposals, err := k.proposalsByVPEnd(ctx, k.HeaderService.HeaderInfo(ctx).Time) if err != nil { return nil } @@ -437,7 +431,7 @@ func (k Keeper) TallyProposalsAtVPEnd(ctx context.Context, env appmodule.Environ return err } // Emit event for proposal finalized with its result - if err := k.environment.EventService.EventManager(ctx).Emit( + if err := k.EventService.EventManager(ctx).Emit( &group.EventProposalPruned{ ProposalId: proposal.Id, Status: proposal.Status, @@ -450,7 +444,7 @@ func (k Keeper) TallyProposalsAtVPEnd(ctx context.Context, env appmodule.Environ return errorsmod.Wrap(err, "doTallyAndUpdate") } - if err := k.proposalTable.Update(k.environment.KVStoreService.OpenKVStore(ctx), proposal.Id, &proposal); err != nil { + if err := k.proposalTable.Update(k.KVStoreService.OpenKVStore(ctx), proposal.Id, &proposal); err != nil { return errorsmod.Wrap(err, "proposal update") } } diff --git a/x/group/keeper/keeper_test.go b/x/group/keeper/keeper_test.go index b6a61d186689..fa44f4f72915 100644 --- a/x/group/keeper/keeper_test.go +++ b/x/group/keeper/keeper_test.go @@ -9,7 +9,6 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/suite" - "cosmossdk.io/core/appmodule" "cosmossdk.io/core/header" "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" @@ -49,7 +48,6 @@ type TestSuite struct { blockTime time.Time bankKeeper *grouptestutil.MockBankKeeper accountKeeper *grouptestutil.MockAccountKeeper - environment appmodule.Environment } func (s *TestSuite) SetupTest() { @@ -90,8 +88,6 @@ func (s *TestSuite) SetupTest() { s.ctx = testCtx.Ctx.WithHeaderInfo(header.Info{Time: s.blockTime}) s.sdkCtx = sdk.UnwrapSDKContext(s.ctx) - s.environment = env - // Initial group, group policy and balance setup members := []group.MemberRequest{ {Address: s.addrsStr[4], Weight: "1"}, {Address: s.addrsStr[1], Weight: "2"}, @@ -341,7 +337,7 @@ func (s *TestSuite) TestPruneProposals() { s.sdkCtx = s.sdkCtx.WithHeaderInfo(header.Info{Time: s.sdkCtx.HeaderInfo().Time.Add(expirationTime)}) // Prune Expired Proposals - err = s.groupKeeper.PruneProposals(s.sdkCtx, s.environment) + err = s.groupKeeper.PruneProposals(s.sdkCtx) s.Require().NoError(err) postPrune, err := s.groupKeeper.Proposal(s.ctx, &queryProposal) s.Require().Nil(postPrune) @@ -464,7 +460,7 @@ func (s *TestSuite) TestTallyProposalsAtVPEnd() { s.Require().Equal("1", result.Tally.YesCount) s.Require().NoError(err) - s.Require().NoError(s.groupKeeper.TallyProposalsAtVPEnd(ctx, s.environment)) + s.Require().NoError(s.groupKeeper.TallyProposalsAtVPEnd(ctx)) s.NotPanics(func() { err := s.groupKeeper.EndBlocker(ctx) if err != nil { @@ -527,7 +523,7 @@ func (s *TestSuite) TestTallyProposalsAtVPEnd_GroupMemberLeaving() { ctx := s.sdkCtx.WithHeaderInfo(header.Info{Time: s.sdkCtx.HeaderInfo().Time.Add(votingPeriod + 1)}) // Tally the result. This saves the tally result to state. - s.Require().NoError(s.groupKeeper.TallyProposalsAtVPEnd(ctx, s.environment)) + s.Require().NoError(s.groupKeeper.TallyProposalsAtVPEnd(ctx)) s.NotPanics(func() { err := s.groupKeeper.EndBlocker(ctx) if err != nil { @@ -542,7 +538,7 @@ func (s *TestSuite) TestTallyProposalsAtVPEnd_GroupMemberLeaving() { }) s.Require().NoError(err) - s.Require().NoError(s.groupKeeper.TallyProposalsAtVPEnd(ctx, s.environment)) + s.Require().NoError(s.groupKeeper.TallyProposalsAtVPEnd(ctx)) s.NotPanics(func() { err := s.groupKeeper.EndBlocker(ctx) if err != nil { diff --git a/x/group/keeper/migrations.go b/x/group/keeper/migrations.go index 953888284e98..9653ff866d84 100644 --- a/x/group/keeper/migrations.go +++ b/x/group/keeper/migrations.go @@ -20,7 +20,7 @@ func NewMigrator(keeper Keeper) Migrator { func (m Migrator) Migrate1to2(ctx context.Context) error { return v2.Migrate( ctx, - m.keeper.environment.KVStoreService, + m.keeper.KVStoreService, m.keeper.accKeeper, m.keeper.groupPolicySeq, m.keeper.groupPolicyTable, diff --git a/x/group/keeper/msg_server.go b/x/group/keeper/msg_server.go index caf0a1a47b3d..975f0cf5c3df 100644 --- a/x/group/keeper/msg_server.go +++ b/x/group/keeper/msg_server.go @@ -61,14 +61,14 @@ func (k Keeper) CreateGroup(ctx context.Context, msg *group.MsgCreateGroup) (*gr } // Create a new group in the groupTable. - kvStore := k.environment.KVStoreService.OpenKVStore(ctx) + kvStore := k.KVStoreService.OpenKVStore(ctx) groupInfo := &group.GroupInfo{ Id: k.groupTable.Sequence().PeekNextVal(kvStore), Admin: msg.Admin, Metadata: msg.Metadata, Version: 1, TotalWeight: totalWeight.String(), - CreatedAt: k.environment.HeaderService.GetHeaderInfo(ctx).Time, + CreatedAt: k.HeaderService.HeaderInfo(ctx).Time, } groupID, err := k.groupTable.Create(kvStore, groupInfo) if err != nil { @@ -83,7 +83,7 @@ func (k Keeper) CreateGroup(ctx context.Context, msg *group.MsgCreateGroup) (*gr Address: m.Address, Weight: m.Weight, Metadata: m.Metadata, - AddedAt: k.environment.HeaderService.GetHeaderInfo(ctx).Time, + AddedAt: k.HeaderService.HeaderInfo(ctx).Time, }, }) if err != nil { @@ -91,7 +91,7 @@ func (k Keeper) CreateGroup(ctx context.Context, msg *group.MsgCreateGroup) (*gr } } - if err := k.environment.EventService.EventManager(ctx).Emit(&group.EventCreateGroup{GroupId: groupID}); err != nil { + if err := k.EventService.EventManager(ctx).Emit(&group.EventCreateGroup{GroupId: groupID}); err != nil { return nil, err } @@ -111,7 +111,7 @@ func (k Keeper) UpdateGroupMembers(ctx context.Context, msg *group.MsgUpdateGrou return nil, errorsmod.Wrap(err, "members") } - kvStore := k.environment.KVStoreService.OpenKVStore(ctx) + kvStore := k.KVStoreService.OpenKVStore(ctx) action := func(g *group.GroupInfo) error { totalWeight, err := math.NewNonNegativeDecFromString(g.TotalWeight) if err != nil { @@ -189,7 +189,7 @@ func (k Keeper) UpdateGroupMembers(ctx context.Context, msg *group.MsgUpdateGrou return errorsmod.Wrap(err, "add member") } } else { // else handle create. - groupMember.Member.AddedAt = k.environment.HeaderService.GetHeaderInfo(ctx).Time + groupMember.Member.AddedAt = k.HeaderService.HeaderInfo(ctx).Time if err := k.groupMemberTable.Create(kvStore, &groupMember); err != nil { return errorsmod.Wrap(err, "add member") } @@ -235,7 +235,7 @@ func (k Keeper) UpdateGroupAdmin(ctx context.Context, msg *group.MsgUpdateGroupA return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "new admin address") } - kvStore := k.environment.KVStoreService.OpenKVStore(ctx) + kvStore := k.KVStoreService.OpenKVStore(ctx) action := func(g *group.GroupInfo) error { g.Admin = msg.NewAdmin g.Version++ @@ -263,7 +263,7 @@ func (k Keeper) UpdateGroupMetadata(ctx context.Context, msg *group.MsgUpdateGro return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "admin address") } - kvStore := k.environment.KVStoreService.OpenKVStore(ctx) + kvStore := k.KVStoreService.OpenKVStore(ctx) action := func(g *group.GroupInfo) error { g.Metadata = msg.Metadata g.Version++ @@ -367,7 +367,7 @@ func (k Keeper) CreateGroupPolicy(ctx context.Context, msg *group.MsgCreateGroup return nil, err } - kvStore := k.environment.KVStoreService.OpenKVStore(ctx) + kvStore := k.KVStoreService.OpenKVStore(ctx) // Generate account address of group policy. var accountAddr sdk.AccAddress @@ -413,7 +413,7 @@ func (k Keeper) CreateGroupPolicy(ctx context.Context, msg *group.MsgCreateGroup msg.GetMetadata(), 1, policy, - k.environment.HeaderService.GetHeaderInfo(ctx).Time, + k.HeaderService.HeaderInfo(ctx).Time, ) if err != nil { return nil, err @@ -423,7 +423,7 @@ func (k Keeper) CreateGroupPolicy(ctx context.Context, msg *group.MsgCreateGroup return nil, errorsmod.Wrap(err, "could not create group policy") } - if err := k.environment.EventService.EventManager(ctx).Emit(&group.EventCreateGroupPolicy{Address: accountStrAddr}); err != nil { + if err := k.EventService.EventManager(ctx).Emit(&group.EventCreateGroupPolicy{Address: accountStrAddr}); err != nil { return nil, err } @@ -439,7 +439,7 @@ func (k Keeper) UpdateGroupPolicyAdmin(ctx context.Context, msg *group.MsgUpdate return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "new admin address") } - kvStore := k.environment.KVStoreService.OpenKVStore(ctx) + kvStore := k.KVStoreService.OpenKVStore(ctx) action := func(groupPolicy *group.GroupPolicyInfo) error { groupPolicy.Admin = msg.NewAdmin groupPolicy.Version++ @@ -463,7 +463,7 @@ func (k Keeper) UpdateGroupPolicyDecisionPolicy(ctx context.Context, msg *group. return nil, errorsmod.Wrap(err, "decision policy") } - kvStore := k.environment.KVStoreService.OpenKVStore(ctx) + kvStore := k.KVStoreService.OpenKVStore(ctx) action := func(groupPolicy *group.GroupPolicyInfo) error { groupInfo, err := k.getGroupInfo(ctx, groupPolicy.GroupId) if err != nil { @@ -493,7 +493,7 @@ func (k Keeper) UpdateGroupPolicyDecisionPolicy(ctx context.Context, msg *group. func (k Keeper) UpdateGroupPolicyMetadata(ctx context.Context, msg *group.MsgUpdateGroupPolicyMetadata) (*group.MsgUpdateGroupPolicyMetadataResponse, error) { metadata := msg.GetMetadata() - kvStore := k.environment.KVStoreService.OpenKVStore(ctx) + kvStore := k.KVStoreService.OpenKVStore(ctx) action := func(groupPolicy *group.GroupPolicyInfo) error { groupPolicy.Metadata = metadata @@ -565,7 +565,7 @@ func (k Keeper) SubmitProposal(ctx context.Context, msg *group.MsgSubmitProposal return nil, err } - kvStore := k.environment.KVStoreService.OpenKVStore(ctx) + kvStore := k.KVStoreService.OpenKVStore(ctx) policyAcc, err := k.getGroupPolicyInfo(ctx, msg.GroupPolicyAddress) if err != nil { return nil, errorsmod.Wrapf(err, "load group policy: %s", msg.GroupPolicyAddress) @@ -603,12 +603,12 @@ func (k Keeper) SubmitProposal(ctx context.Context, msg *group.MsgSubmitProposal GroupPolicyAddress: msg.GroupPolicyAddress, Metadata: msg.Metadata, Proposers: msg.Proposers, - SubmitTime: k.environment.HeaderService.GetHeaderInfo(ctx).Time, + SubmitTime: k.HeaderService.HeaderInfo(ctx).Time, GroupVersion: groupInfo.Version, GroupPolicyVersion: policyAcc.Version, Status: group.PROPOSAL_STATUS_SUBMITTED, ExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, - VotingPeriodEnd: k.environment.HeaderService.GetHeaderInfo(ctx).Time.Add(policy.GetVotingPeriod()), // The voting window begins as soon as the proposal is submitted. + VotingPeriodEnd: k.HeaderService.HeaderInfo(ctx).Time.Add(policy.GetVotingPeriod()), // The voting window begins as soon as the proposal is submitted. FinalTallyResult: group.DefaultTallyResult(), Title: msg.Title, Summary: msg.Summary, @@ -623,7 +623,7 @@ func (k Keeper) SubmitProposal(ctx context.Context, msg *group.MsgSubmitProposal return nil, errorsmod.Wrap(err, "create proposal") } - if err := k.environment.EventService.EventManager(ctx).Emit(&group.EventSubmitProposal{ProposalId: id}); err != nil { + if err := k.EventService.EventManager(ctx).Emit(&group.EventSubmitProposal{ProposalId: id}); err != nil { return nil, err } @@ -631,7 +631,7 @@ func (k Keeper) SubmitProposal(ctx context.Context, msg *group.MsgSubmitProposal if msg.Exec == group.Exec_EXEC_TRY { // Consider proposers as Yes votes for _, proposer := range msg.Proposers { - k.environment.GasService.GetGasMeter(ctx).Consume(gasCostPerIteration, "vote on proposal") + k.GasService.GasMeter(ctx).Consume(gasCostPerIteration, "vote on proposal") _, err = k.Vote(ctx, &group.MsgVote{ ProposalId: id, Voter: proposer, @@ -666,7 +666,7 @@ func (k Keeper) WithdrawProposal(ctx context.Context, msg *group.MsgWithdrawProp return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid group policy admin / proposer address: %s", msg.Address) } - kvStore := k.environment.KVStoreService.OpenKVStore(ctx) + kvStore := k.KVStoreService.OpenKVStore(ctx) proposal, err := k.getProposal(ctx, msg.ProposalId) if err != nil { return nil, err @@ -692,7 +692,7 @@ func (k Keeper) WithdrawProposal(ctx context.Context, msg *group.MsgWithdrawProp return nil, err } - if err := k.environment.EventService.EventManager(ctx).Emit(&group.EventWithdrawProposal{ProposalId: msg.ProposalId}); err != nil { + if err := k.EventService.EventManager(ctx).Emit(&group.EventWithdrawProposal{ProposalId: msg.ProposalId}); err != nil { return nil, err } @@ -721,7 +721,7 @@ func (k Keeper) Vote(ctx context.Context, msg *group.MsgVote) (*group.MsgVoteRes return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid voter address: %s", msg.Voter) } - kvStore := k.environment.KVStoreService.OpenKVStore(ctx) + kvStore := k.KVStoreService.OpenKVStore(ctx) proposal, err := k.getProposal(ctx, msg.ProposalId) if err != nil { return nil, err @@ -732,7 +732,7 @@ func (k Keeper) Vote(ctx context.Context, msg *group.MsgVote) (*group.MsgVoteRes return nil, errorsmod.Wrap(errors.ErrInvalid, "proposal not open for voting") } - if k.environment.HeaderService.GetHeaderInfo(ctx).Time.After(proposal.VotingPeriodEnd) { + if k.HeaderService.HeaderInfo(ctx).Time.After(proposal.VotingPeriodEnd) { return nil, errorsmod.Wrap(errors.ErrExpired, "voting period has ended already") } @@ -756,7 +756,7 @@ func (k Keeper) Vote(ctx context.Context, msg *group.MsgVote) (*group.MsgVoteRes Voter: msg.Voter, Option: msg.Option, Metadata: msg.Metadata, - SubmitTime: k.environment.HeaderService.GetHeaderInfo(ctx).Time, + SubmitTime: k.HeaderService.HeaderInfo(ctx).Time, } // The ORM will return an error if the vote already exists, @@ -765,7 +765,7 @@ func (k Keeper) Vote(ctx context.Context, msg *group.MsgVote) (*group.MsgVoteRes return nil, errorsmod.Wrap(err, "store vote") } - if err := k.environment.EventService.EventManager(ctx).Emit(&group.EventVote{ProposalId: msg.ProposalId}); err != nil { + if err := k.EventService.EventManager(ctx).Emit(&group.EventVote{ProposalId: msg.ProposalId}); err != nil { return nil, err } @@ -801,7 +801,7 @@ func (k Keeper) doTallyAndUpdate(ctx context.Context, p *group.Proposal, groupIn // If the result was final (i.e. enough votes to pass) or if the voting // period ended, then we consider the proposal as final. - if isFinal := result.Final || k.environment.HeaderService.GetHeaderInfo(ctx).Time.After(p.VotingPeriodEnd); isFinal { + if isFinal := result.Final || k.HeaderService.HeaderInfo(ctx).Time.After(p.VotingPeriodEnd); isFinal { if err := k.pruneVotes(ctx, p.Id); err != nil { return err } @@ -862,12 +862,12 @@ func (k Keeper) Exec(goCtx context.Context, msg *group.MsgExec) (*group.MsgExecR decisionPolicy := policyInfo.DecisionPolicy.GetCachedValue().(group.DecisionPolicy) - if err := k.environment.BranchService.Execute(ctx, func(ctx context.Context) error { + if err := k.BranchService.Execute(ctx, func(ctx context.Context) error { return k.doExecuteMsgs(ctx, proposal, addr, decisionPolicy) }); err != nil { proposal.ExecutorResult = group.PROPOSAL_EXECUTOR_RESULT_FAILURE logs = fmt.Sprintf("proposal execution failed on proposal %d, because of error %s", proposal.Id, err.Error()) - k.Logger().Info("proposal execution failed", "cause", err, "proposalID", proposal.Id) + k.Logger.Info("proposal execution failed", "cause", err, "proposalID", proposal.Id) } else { proposal.ExecutorResult = group.PROPOSAL_EXECUTOR_RESULT_SUCCESS } @@ -881,7 +881,7 @@ func (k Keeper) Exec(goCtx context.Context, msg *group.MsgExec) (*group.MsgExecR } // Emit event for proposal finalized with its result - if err := k.environment.EventService.EventManager(ctx).Emit( + if err := k.EventService.EventManager(ctx).Emit( &group.EventProposalPruned{ ProposalId: proposal.Id, Status: proposal.Status, @@ -890,13 +890,13 @@ func (k Keeper) Exec(goCtx context.Context, msg *group.MsgExec) (*group.MsgExecR return nil, err } } else { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err := k.proposalTable.Update(store, proposal.Id, &proposal); err != nil { return nil, err } } - if err := k.environment.EventService.EventManager(ctx).Emit(&group.EventExec{ + if err := k.EventService.EventManager(ctx).Emit(&group.EventExec{ ProposalId: proposal.Id, Logs: logs, Result: proposal.ExecutorResult, @@ -948,7 +948,7 @@ func (k Keeper) LeaveGroup(ctx context.Context, msg *group.MsgLeaveGroup) (*grou return nil, err } - kvStore := k.environment.KVStoreService.OpenKVStore(ctx) + kvStore := k.KVStoreService.OpenKVStore(ctx) // delete group member in the groupMemberTable. if err := k.groupMemberTable.Delete(kvStore, gm); err != nil { @@ -967,7 +967,7 @@ func (k Keeper) LeaveGroup(ctx context.Context, msg *group.MsgLeaveGroup) (*grou return nil, err } - if err := k.environment.EventService.EventManager(ctx).Emit(&group.EventLeaveGroup{ + if err := k.EventService.EventManager(ctx).Emit(&group.EventLeaveGroup{ GroupId: msg.GroupId, Address: msg.Address, }); err != nil { @@ -978,7 +978,7 @@ func (k Keeper) LeaveGroup(ctx context.Context, msg *group.MsgLeaveGroup) (*grou } func (k Keeper) getGroupMember(ctx context.Context, member *group.GroupMember) (*group.GroupMember, error) { - kvStore := k.environment.KVStoreService.OpenKVStore(ctx) + kvStore := k.KVStoreService.OpenKVStore(ctx) var groupMember group.GroupMember switch err := k.groupMemberTable.GetOne(kvStore, orm.PrimaryKey(member), &groupMember); { @@ -1029,7 +1029,7 @@ func (k Keeper) doUpdateGroupPolicy(ctx context.Context, reqGroupPolicy, reqAdmi return err } - if err = k.environment.EventService.EventManager(ctx).Emit(&group.EventUpdateGroupPolicy{Address: groupPolicyInfo.Address}); err != nil { + if err = k.EventService.EventManager(ctx).Emit(&group.EventUpdateGroupPolicy{Address: groupPolicyInfo.Address}); err != nil { return err } @@ -1052,7 +1052,7 @@ func (k Keeper) doUpdateGroup(ctx context.Context, groupID uint64, reqGroupAdmin return errorsmod.Wrap(err, errNote) } - if err := k.environment.EventService.EventManager(ctx).Emit(&group.EventUpdateGroup{GroupId: groupID}); err != nil { + if err := k.EventService.EventManager(ctx).Emit(&group.EventUpdateGroup{GroupId: groupID}); err != nil { return err } @@ -1062,7 +1062,7 @@ func (k Keeper) doUpdateGroup(ctx context.Context, groupID uint64, reqGroupAdmin // validateDecisionPolicies loops through all decision policies from the group, // and calls each of their Validate() method. func (k Keeper) validateDecisionPolicies(ctx context.Context, g group.GroupInfo) error { - kvStore := k.environment.KVStoreService.OpenKVStore(ctx) + kvStore := k.KVStoreService.OpenKVStore(ctx) it, err := k.groupPolicyByGroupIndex.Get(kvStore, g.Id) if err != nil { return err diff --git a/x/group/keeper/msg_server_test.go b/x/group/keeper/msg_server_test.go index a5f3e58de814..fed87820bf99 100644 --- a/x/group/keeper/msg_server_test.go +++ b/x/group/keeper/msg_server_test.go @@ -12,8 +12,6 @@ import ( "github.com/golang/mock/gomock" "cosmossdk.io/core/header" - "cosmossdk.io/log" - storetypes "cosmossdk.io/store/types" banktypes "cosmossdk.io/x/bank/types" "cosmossdk.io/x/group" "cosmossdk.io/x/group/internal/math" @@ -21,7 +19,6 @@ import ( minttypes "cosmossdk.io/x/mint/types" "github.com/cosmos/cosmos-sdk/codec/address" - "github.com/cosmos/cosmos-sdk/runtime" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" @@ -1995,12 +1992,10 @@ func (s *TestSuite) TestWithdrawProposal() { postRun: func(sdkCtx sdk.Context) { resp, err := s.groupKeeper.Proposal(s.ctx, &group.QueryProposalRequest{ProposalId: proposalID}) s.Require().NoError(err) - key := storetypes.NewKVStoreKey(group.StoreKey) - env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) vpe := resp.Proposal.VotingPeriodEnd timeDiff := vpe.Sub(s.sdkCtx.HeaderInfo().Time) ctxVPE := sdkCtx.WithHeaderInfo(header.Info{Time: s.sdkCtx.HeaderInfo().Time.Add(timeDiff).Add(time.Second * 1)}) - s.Require().NoError(s.groupKeeper.TallyProposalsAtVPEnd(ctxVPE, env)) + s.Require().NoError(s.groupKeeper.TallyProposalsAtVPEnd(ctxVPE)) events := ctxVPE.EventManager().ABCIEvents() s.Require().True(eventTypeFound(events, EventProposalPruned)) diff --git a/x/group/keeper/proposal_executor.go b/x/group/keeper/proposal_executor.go index 7a3a530e78d2..484807c50215 100644 --- a/x/group/keeper/proposal_executor.go +++ b/x/group/keeper/proposal_executor.go @@ -17,7 +17,7 @@ import ( // doExecuteMsgs routes the messages to the registered handlers. Messages are limited to those that require no authZ or // by the account of group policy only. Otherwise this gives access to other peoples accounts as the sdk middlewares are bypassed func (k Keeper) doExecuteMsgs(ctx context.Context, proposal group.Proposal, groupPolicyAcc sdk.AccAddress, decisionPolicy group.DecisionPolicy) error { - currentTime := k.environment.HeaderService.GetHeaderInfo(ctx).Time + currentTime := k.HeaderService.HeaderInfo(ctx).Time // Ensure it's not too early to execute the messages. minExecutionDate := proposal.SubmitTime.Add(decisionPolicy.GetMinExecutionPeriod()) @@ -45,7 +45,7 @@ func (k Keeper) doExecuteMsgs(ctx context.Context, proposal group.Proposal, grou } for i, msg := range msgs { - if _, err := k.environment.RouterService.MessageRouterService().InvokeUntyped(ctx, msg); err != nil { + if _, err := k.RouterService.MessageRouterService().InvokeUntyped(ctx, msg); err != nil { return errorsmod.Wrapf(err, "message %s at position %d", sdk.MsgTypeURL(msg), i) } } diff --git a/x/group/keeper/tally.go b/x/group/keeper/tally.go index 68a29acc5b6e..4c643fed7e97 100644 --- a/x/group/keeper/tally.go +++ b/x/group/keeper/tally.go @@ -23,7 +23,7 @@ func (k Keeper) Tally(ctx context.Context, p group.Proposal, groupID uint64) (gr return p.FinalTallyResult, nil } - kvStore := k.environment.KVStoreService.OpenKVStore(ctx) + kvStore := k.KVStoreService.OpenKVStore(ctx) it, err := k.voteByProposalIndex.Get(kvStore, p.Id) if err != nil { diff --git a/x/mint/keeper/abci.go b/x/mint/keeper/abci.go index 04677ad2f317..478393e26c34 100644 --- a/x/mint/keeper/abci.go +++ b/x/mint/keeper/abci.go @@ -61,7 +61,7 @@ func (k Keeper) BeginBlocker(ctx context.Context, ic types.InflationCalculationF defer telemetry.ModuleSetGauge(types.ModuleName, float32(mintedCoin.Amount.Int64()), "minted_tokens") } - return k.environment.EventService.EventManager(ctx).EmitKV( + return k.EventService.EventManager(ctx).EmitKV( types.EventTypeMint, event.NewAttribute(types.AttributeKeyBondedRatio, bondedRatio.String()), event.NewAttribute(types.AttributeKeyInflation, minter.Inflation.String()), diff --git a/x/mint/keeper/keeper.go b/x/mint/keeper/keeper.go index 9dbccd31faaf..f7306a131bea 100644 --- a/x/mint/keeper/keeper.go +++ b/x/mint/keeper/keeper.go @@ -16,8 +16,9 @@ import ( // Keeper of the mint store type Keeper struct { + appmodule.Environment + cdc codec.BinaryCodec - environment appmodule.Environment stakingKeeper types.StakingKeeper bankKeeper types.BankKeeper logger log.Logger @@ -48,8 +49,8 @@ func NewKeeper( sb := collections.NewSchemaBuilder(env.KVStoreService) k := Keeper{ + Environment: env, cdc: cdc, - environment: env, stakingKeeper: sk, bankKeeper: bk, logger: env.Logger, @@ -72,11 +73,6 @@ func (k Keeper) GetAuthority() string { return k.authority } -// Logger returns a module-specific logger. -func (k Keeper) Logger(ctx context.Context) log.Logger { - return k.environment.Logger.With("module", "x/"+types.ModuleName) -} - // StakingTokenSupply implements an alias call to the underlying staking keeper's // StakingTokenSupply to be used in BeginBlocker. func (k Keeper) StakingTokenSupply(ctx context.Context) (math.Int, error) { diff --git a/x/mint/keeper/keeper_test.go b/x/mint/keeper/keeper_test.go index fb4fa58c1827..e5ddd1b0d469 100644 --- a/x/mint/keeper/keeper_test.go +++ b/x/mint/keeper/keeper_test.go @@ -66,9 +66,6 @@ func (s *IntegrationTestSuite) SetupTest() { s.stakingKeeper = stakingKeeper s.bankKeeper = bankKeeper - s.Require().Equal(testCtx.Ctx.Logger().With("module", "x/"+types.ModuleName), - s.mintKeeper.Logger(testCtx.Ctx)) - err := s.mintKeeper.Params.Set(s.ctx, types.DefaultParams()) s.Require().NoError(err) diff --git a/x/nft/keeper/class.go b/x/nft/keeper/class.go index fc4145897df8..1619441145be 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.env.KVStoreService.OpenKVStore(ctx) + store := k.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.env.KVStoreService.OpenKVStore(ctx) + store := k.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.env.KVStoreService.OpenKVStore(ctx) + store := k.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.env.KVStoreService.OpenKVStore(ctx) + store := k.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.env.KVStoreService.OpenKVStore(ctx) + store := k.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 9e3cfc71281c..11589a0f80dc 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.env.KVStoreService.OpenKVStore(ctx) + store := k.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 a6a03974b80f..4dde7a7e41e5 100644 --- a/x/nft/keeper/keeper.go +++ b/x/nft/keeper/keeper.go @@ -10,10 +10,11 @@ import ( // Keeper of the nft store type Keeper struct { + appmodule.Environment + cdc codec.BinaryCodec bk nft.BankKeeper ac address.Codec - env appmodule.Environment } // NewKeeper creates a new nft Keeper instance @@ -26,9 +27,9 @@ func NewKeeper(env appmodule.Environment, } return Keeper{ - cdc: cdc, - env: env, - bk: bk, - ac: ak.AddressCodec(), + Environment: env, + cdc: cdc, + bk: bk, + ac: ak.AddressCodec(), } } diff --git a/x/nft/keeper/msg_server.go b/x/nft/keeper/msg_server.go index 1f6f3cd3ff73..ba6721b76468 100644 --- a/x/nft/keeper/msg_server.go +++ b/x/nft/keeper/msg_server.go @@ -41,7 +41,7 @@ func (k Keeper) Send(ctx context.Context, msg *nft.MsgSend) (*nft.MsgSendRespons return nil, err } - if err = k.env.EventService.EventManager(ctx).Emit(&nft.EventSend{ + if err = k.EventService.EventManager(ctx).Emit(&nft.EventSend{ ClassId: msg.ClassId, Id: msg.Id, Sender: msg.Sender, diff --git a/x/nft/keeper/nft.go b/x/nft/keeper/nft.go index 1381ad7e82dd..fae630198b11 100644 --- a/x/nft/keeper/nft.go +++ b/x/nft/keeper/nft.go @@ -37,7 +37,7 @@ func (k Keeper) mintWithNoCheck(ctx context.Context, token nft.NFT, receiver sdk return err } - return k.env.EventService.EventManager(ctx).Emit(&nft.EventMint{ + return k.EventService.EventManager(ctx).Emit(&nft.EventMint{ ClassId: token.ClassId, Id: token.Id, Owner: recStr, @@ -78,7 +78,7 @@ func (k Keeper) burnWithNoCheck(ctx context.Context, classID, nftID string) erro return err } - return k.env.EventService.EventManager(ctx).Emit(&nft.EventBurn{ + return k.EventService.EventManager(ctx).Emit(&nft.EventBurn{ ClassId: classID, Id: nftID, Owner: ownerStr, @@ -183,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.env.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(ownerStoreKey(classID, nftID)) if err != nil { panic(err) @@ -199,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.env.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(classTotalSupply(classID)) if err != nil { panic(err) @@ -220,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.env.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) err := store.Set(ownerStoreKey(classID, nftID), owner.Bytes()) if err != nil { panic(err) @@ -231,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.env.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) err := store.Delete(ownerStoreKey(classID, nftID)) if err != nil { panic(err) @@ -241,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.env.KVStoreService.OpenKVStore(ctx) + store := k.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.env.KVStoreService.OpenKVStore(ctx) + store := k.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.env.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) key := prefixNftOfClassByOwnerStoreKey(owner) return prefix.NewStore(runtime.KVStoreAdapter(store), key) } @@ -268,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.env.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) supplyKey := classTotalSupply(classID) err := store.Set(supplyKey, sdk.Uint64ToBigEndian(supply)) if err != nil { diff --git a/x/protocolpool/keeper/genesis.go b/x/protocolpool/keeper/genesis.go index c5211513d99d..2919777b500a 100644 --- a/x/protocolpool/keeper/genesis.go +++ b/x/protocolpool/keeper/genesis.go @@ -10,7 +10,7 @@ import ( ) func (k Keeper) InitGenesis(ctx context.Context, data *types.GenesisState) error { - currentTime := k.environment.HeaderService.GetHeaderInfo(ctx).Time + currentTime := k.HeaderService.HeaderInfo(ctx).Time for _, cf := range data.ContinuousFund { // ignore expired ContinuousFunds if cf.Expiry != nil && cf.Expiry.Before(currentTime) { diff --git a/x/protocolpool/keeper/grpc_query_test.go b/x/protocolpool/keeper/grpc_query_test.go index 2fc082b811e8..13ac6bc47b09 100644 --- a/x/protocolpool/keeper/grpc_query_test.go +++ b/x/protocolpool/keeper/grpc_query_test.go @@ -11,7 +11,7 @@ import ( ) func (suite *KeeperTestSuite) TestUnclaimedBudget() { - startTime := suite.environment.HeaderService.GetHeaderInfo(suite.ctx).Time.Add(-70 * time.Second) + startTime := suite.environment.HeaderService.HeaderInfo(suite.ctx).Time.Add(-70 * time.Second) period := time.Duration(60) * time.Second zeroCoin := sdk.NewCoin("foo", math.ZeroInt()) nextClaimFrom := startTime.Add(period) diff --git a/x/protocolpool/keeper/keeper.go b/x/protocolpool/keeper/keeper.go index cbfe25c1d23a..a3769fedf063 100644 --- a/x/protocolpool/keeper/keeper.go +++ b/x/protocolpool/keeper/keeper.go @@ -10,7 +10,6 @@ import ( "cosmossdk.io/collections" "cosmossdk.io/core/appmodule" errorsmod "cosmossdk.io/errors" - "cosmossdk.io/log" "cosmossdk.io/math" "cosmossdk.io/x/protocolpool/types" @@ -20,7 +19,8 @@ import ( ) type Keeper struct { - environment appmodule.Environment + appmodule.Environment + authKeeper types.AccountKeeper bankKeeper types.BankKeeper stakingKeeper types.StakingKeeper @@ -55,7 +55,7 @@ func NewKeeper(cdc codec.BinaryCodec, env appmodule.Environment, ak types.Accoun sb := collections.NewSchemaBuilder(env.KVStoreService) keeper := Keeper{ - environment: env, + Environment: env, authKeeper: ak, bankKeeper: bk, stakingKeeper: sk, @@ -82,11 +82,6 @@ func (k Keeper) GetAuthority() string { return k.authority } -// Logger returns a module-specific logger. -func (k Keeper) Logger(ctx context.Context) log.Logger { - return k.environment.Logger.With(log.ModuleKey, "x/"+types.ModuleName) -} - // FundCommunityPool allows an account to directly fund the community fund pool. func (k Keeper) FundCommunityPool(ctx context.Context, amount sdk.Coins, sender sdk.AccAddress) error { return k.bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleName, amount) @@ -126,7 +121,7 @@ func (k Keeper) withdrawContinuousFund(ctx context.Context, recipientAddr string } return sdk.Coin{}, fmt.Errorf("get continuous fund failed for recipient: %s", recipientAddr) } - if cf.Expiry != nil && cf.Expiry.Before(k.environment.HeaderService.GetHeaderInfo(ctx).Time) { + if cf.Expiry != nil && cf.Expiry.Before(k.HeaderService.HeaderInfo(ctx).Time) { return sdk.Coin{}, fmt.Errorf("cannot withdraw continuous funds: continuous fund expired for recipient: %s", recipientAddr) } @@ -193,7 +188,7 @@ func (k Keeper) SetToDistribute(ctx context.Context, amount sdk.Coins, addr stri if err != nil { return err } - hasPermission, err := k.hasPermission(ctx, authAddr) + hasPermission, err := k.hasPermission(authAddr) if err != nil { return err } @@ -249,7 +244,7 @@ func (k Keeper) sendFundsToStreamModule(ctx context.Context, denom string, perce return nil } -func (k Keeper) hasPermission(ctx context.Context, addr []byte) (bool, error) { +func (k Keeper) hasPermission(addr []byte) (bool, error) { authority := k.GetAuthority() authAcc, err := k.authKeeper.AddressCodec().StringToBytes(authority) if err != nil { @@ -368,7 +363,7 @@ func (k Keeper) getClaimableFunds(ctx context.Context, recipientAddr string) (am } } - currentTime := k.environment.HeaderService.GetHeaderInfo(ctx).Time + currentTime := k.HeaderService.HeaderInfo(ctx).Time startTime := budget.StartTime // Check if the start time is reached @@ -416,7 +411,7 @@ func (k Keeper) calculateClaimableFunds(ctx context.Context, recipient sdk.AccAd nextClaimFrom := budget.NextClaimFrom.Add(*budget.Period) budget.NextClaimFrom = &nextClaimFrom - k.Logger(ctx).Debug(fmt.Sprintf("Processing budget for recipient: %s. Amount: %s", budget.RecipientAddress, coinsToDistribute.String())) + k.Logger.Debug(fmt.Sprintf("Processing budget for recipient: %s. Amount: %s", budget.RecipientAddress, coinsToDistribute.String())) // Save the updated budget in the state if err := k.BudgetProposal.Set(ctx, recipient, budget); err != nil { @@ -435,7 +430,7 @@ func (k Keeper) validateAndUpdateBudgetProposal(ctx context.Context, bp types.Ms return nil, fmt.Errorf("invalid budget proposal: %w", err) } - currentTime := k.environment.HeaderService.GetHeaderInfo(ctx).Time + currentTime := k.HeaderService.HeaderInfo(ctx).Time if bp.StartTime.IsZero() || bp.StartTime == nil { bp.StartTime = ¤tTime } @@ -478,7 +473,7 @@ func (k Keeper) validateContinuousFund(ctx context.Context, msg types.MsgCreateC } // Validate expiry - currentTime := k.environment.HeaderService.GetHeaderInfo(ctx).Time + currentTime := k.HeaderService.HeaderInfo(ctx).Time if msg.Expiry != nil && msg.Expiry.Compare(currentTime) == -1 { return fmt.Errorf("expiry time cannot be less than the current block time") } diff --git a/x/protocolpool/keeper/msg_server.go b/x/protocolpool/keeper/msg_server.go index 4c03c08e85cf..42e5821e6e6b 100644 --- a/x/protocolpool/keeper/msg_server.go +++ b/x/protocolpool/keeper/msg_server.go @@ -95,7 +95,7 @@ func (k MsgServer) CommunityPoolSpend(ctx context.Context, msg *types.MsgCommuni return nil, err } - k.Logger(ctx).Info("transferred from the community pool to recipient", "amount", msg.Amount.String(), "recipient", msg.Recipient) + k.Logger.Info("transferred from the community pool to recipient", "amount", msg.Amount.String(), "recipient", msg.Recipient) return &types.MsgCommunityPoolSpendResponse{}, nil } @@ -164,7 +164,7 @@ func (k MsgServer) WithdrawContinuousFund(ctx context.Context, msg *types.MsgWit return nil, err } if amount.IsNil() { - k.Logger(ctx).Info(fmt.Sprintf("no distribution amount found for recipient %s", msg.RecipientAddress)) + k.Logger.Info(fmt.Sprintf("no distribution amount found for recipient %s", msg.RecipientAddress)) } return &types.MsgWithdrawContinuousFundResponse{Amount: amount}, nil @@ -180,8 +180,8 @@ func (k MsgServer) CancelContinuousFund(ctx context.Context, msg *types.MsgCance return nil, err } - canceledHeight := k.environment.HeaderService.GetHeaderInfo(ctx).Height - canceledTime := k.environment.HeaderService.GetHeaderInfo(ctx).Time + canceledHeight := k.HeaderService.HeaderInfo(ctx).Height + canceledTime := k.HeaderService.HeaderInfo(ctx).Time found, err := k.ContinuousFund.Has(ctx, recipient) if !found { diff --git a/x/protocolpool/keeper/msg_server_test.go b/x/protocolpool/keeper/msg_server_test.go index ed0343403153..55fc5de8b09b 100644 --- a/x/protocolpool/keeper/msg_server_test.go +++ b/x/protocolpool/keeper/msg_server_test.go @@ -21,8 +21,8 @@ var ( func (suite *KeeperTestSuite) TestMsgSubmitBudgetProposal() { invalidCoin := sdk.NewInt64Coin("foo", 0) - startTime := suite.environment.HeaderService.GetHeaderInfo(suite.ctx).Time.Add(10 * time.Second) - invalidStartTime := suite.environment.HeaderService.GetHeaderInfo(suite.ctx).Time.Add(-15 * time.Second) + startTime := suite.environment.HeaderService.HeaderInfo(suite.ctx).Time.Add(10 * time.Second) + invalidStartTime := suite.environment.HeaderService.HeaderInfo(suite.ctx).Time.Add(-15 * time.Second) period := time.Duration(60) * time.Second zeroPeriod := time.Duration(0) * time.Second recipientStrAddr, err := codectestutil.CodecOptions{}.GetAddressCodec().BytesToString(recipientAddr) @@ -145,7 +145,7 @@ func (suite *KeeperTestSuite) TestMsgSubmitBudgetProposal() { } func (suite *KeeperTestSuite) TestMsgClaimBudget() { - startTime := suite.environment.HeaderService.GetHeaderInfo(suite.ctx).Time.Add(-70 * time.Second) + startTime := suite.environment.HeaderService.HeaderInfo(suite.ctx).Time.Add(-70 * time.Second) period := time.Duration(60) * time.Second recipientStrAddr, err := codectestutil.CodecOptions{}.GetAddressCodec().BytesToString(recipientAddr) suite.Require().NoError(err) @@ -169,7 +169,7 @@ func (suite *KeeperTestSuite) TestMsgClaimBudget() { }, "claiming before start time": { preRun: func() { - startTime := suite.environment.HeaderService.GetHeaderInfo(suite.ctx).Time.Add(3600 * time.Second) + startTime := suite.environment.HeaderService.HeaderInfo(suite.ctx).Time.Add(3600 * time.Second) // Prepare the budget proposal with a future start time budget := types.Budget{ RecipientAddress: recipientStrAddr, @@ -187,7 +187,7 @@ func (suite *KeeperTestSuite) TestMsgClaimBudget() { }, "budget period has not passed": { preRun: func() { - startTime := suite.environment.HeaderService.GetHeaderInfo(suite.ctx).Time.Add(-50 * time.Second) + startTime := suite.environment.HeaderService.HeaderInfo(suite.ctx).Time.Add(-50 * time.Second) // Prepare the budget proposal with start time and a short period budget := types.Budget{ RecipientAddress: recipientStrAddr, @@ -248,7 +248,7 @@ func (suite *KeeperTestSuite) TestMsgClaimBudget() { "valid double claim attempt": { preRun: func() { oneMonthInSeconds := int64(30 * 24 * 60 * 60) // Approximate number of seconds in 1 month - startTimeBeforeMonth := suite.environment.HeaderService.GetHeaderInfo(suite.ctx).Time.Add(time.Duration(-oneMonthInSeconds) * time.Second) + startTimeBeforeMonth := suite.environment.HeaderService.HeaderInfo(suite.ctx).Time.Add(time.Duration(-oneMonthInSeconds) * time.Second) oneMonthPeriod := time.Duration(oneMonthInSeconds) * time.Second // Prepare the budget proposal with valid start time and period of 1 month (in seconds) budget := types.Budget{ @@ -270,7 +270,7 @@ func (suite *KeeperTestSuite) TestMsgClaimBudget() { suite.Require().NoError(err) // Create a new context with an updated block time to simulate a delay - newBlockTime := suite.environment.HeaderService.GetHeaderInfo(suite.ctx).Time.Add(time.Duration(oneMonthInSeconds) * time.Second) + newBlockTime := suite.environment.HeaderService.HeaderInfo(suite.ctx).Time.Add(time.Duration(oneMonthInSeconds) * time.Second) suite.ctx = suite.ctx.WithHeaderInfo(header.Info{ Time: newBlockTime, }) @@ -301,7 +301,7 @@ func (suite *KeeperTestSuite) TestMsgClaimBudget() { suite.Require().NoError(err) // Create a new context with an updated block time to simulate a delay - newBlockTime := suite.environment.HeaderService.GetHeaderInfo(suite.ctx).Time.Add(60 * time.Second) + newBlockTime := suite.environment.HeaderService.HeaderInfo(suite.ctx).Time.Add(60 * time.Second) suite.ctx = suite.ctx.WithHeaderInfo(header.Info{ Time: newBlockTime, }) @@ -378,7 +378,7 @@ func (suite *KeeperTestSuite) TestWithdrawContinuousFund() { percentage, err := math.LegacyNewDecFromStr("0.2") suite.Require().NoError(err) oneMonthInSeconds := int64(30 * 24 * 60 * 60) // Approximate number of seconds in 1 month - expiry := suite.environment.HeaderService.GetHeaderInfo(suite.ctx).Time.Add(time.Duration(oneMonthInSeconds) * time.Second) + expiry := suite.environment.HeaderService.HeaderInfo(suite.ctx).Time.Add(time.Duration(oneMonthInSeconds) * time.Second) cf := types.ContinuousFund{ Recipient: recipientStrAddr, Percentage: percentage, @@ -424,7 +424,7 @@ func (suite *KeeperTestSuite) TestWithdrawContinuousFund() { preRun: func() { percentage, err := math.LegacyNewDecFromStr("0.2") suite.Require().NoError(err) - expiry := suite.environment.HeaderService.GetHeaderInfo(suite.ctx).Time.Add(time.Duration(-1) * time.Second) + expiry := suite.environment.HeaderService.HeaderInfo(suite.ctx).Time.Add(time.Duration(-1) * time.Second) cf := types.ContinuousFund{ Recipient: recipientStrAddr, Percentage: percentage, @@ -443,7 +443,7 @@ func (suite *KeeperTestSuite) TestWithdrawContinuousFund() { percentage, err := math.LegacyNewDecFromStr("0.2") suite.Require().NoError(err) oneMonthInSeconds := int64(30 * 24 * 60 * 60) // Approximate number of seconds in 1 month - expiry := suite.environment.HeaderService.GetHeaderInfo(suite.ctx).Time.Add(time.Duration(oneMonthInSeconds) * time.Second) + expiry := suite.environment.HeaderService.HeaderInfo(suite.ctx).Time.Add(time.Duration(oneMonthInSeconds) * time.Second) cf := types.ContinuousFund{ Recipient: recipientStrAddr, Percentage: percentage, @@ -496,7 +496,7 @@ func (suite *KeeperTestSuite) TestWithdrawContinuousFund() { percentage, err := math.LegacyNewDecFromStr("0.2") suite.Require().NoError(err) oneMonthInSeconds := int64(30 * 24 * 60 * 60) // Approximate number of seconds in 1 month - expiry := suite.environment.HeaderService.GetHeaderInfo(suite.ctx).Time.Add(time.Duration(oneMonthInSeconds) * time.Second) + expiry := suite.environment.HeaderService.HeaderInfo(suite.ctx).Time.Add(time.Duration(oneMonthInSeconds) * time.Second) cf := types.ContinuousFund{ Recipient: recipientStrAddr, Percentage: percentage, @@ -526,7 +526,7 @@ func (suite *KeeperTestSuite) TestWithdrawContinuousFund() { percentage, err := math.LegacyNewDecFromStr("0.3") suite.Require().NoError(err) oneMonthInSeconds := int64(30 * 24 * 60 * 60) // Approximate number of seconds in 1 month - expiry := suite.environment.HeaderService.GetHeaderInfo(suite.ctx).Time.Add(time.Duration(oneMonthInSeconds) * time.Second) + expiry := suite.environment.HeaderService.HeaderInfo(suite.ctx).Time.Add(time.Duration(oneMonthInSeconds) * time.Second) cf := types.ContinuousFund{ Recipient: recipientStrAddr, Percentage: percentage, @@ -630,9 +630,9 @@ func (suite *KeeperTestSuite) TestCreateContinuousFund() { suite.Require().NoError(err) negativePercentage, err := math.LegacyNewDecFromStr("-0.2") suite.Require().NoError(err) - invalidExpirty := suite.environment.HeaderService.GetHeaderInfo(suite.ctx).Time.Add(-15 * time.Second) + invalidExpirty := suite.environment.HeaderService.HeaderInfo(suite.ctx).Time.Add(-15 * time.Second) oneMonthInSeconds := int64(30 * 24 * 60 * 60) // Approximate number of seconds in 1 month - expiry := suite.environment.HeaderService.GetHeaderInfo(suite.ctx).Time.Add(time.Duration(oneMonthInSeconds) * time.Second) + expiry := suite.environment.HeaderService.HeaderInfo(suite.ctx).Time.Add(time.Duration(oneMonthInSeconds) * time.Second) recipientStrAddr, err := codectestutil.CodecOptions{}.GetAddressCodec().BytesToString(recipientAddr) suite.Require().NoError(err) testCases := map[string]struct { @@ -790,7 +790,7 @@ func (suite *KeeperTestSuite) TestCancelContinuousFund() { percentage, err := math.LegacyNewDecFromStr("0.2") suite.Require().NoError(err) oneMonthInSeconds := int64(30 * 24 * 60 * 60) // Approximate number of seconds in 1 month - expiry := suite.environment.HeaderService.GetHeaderInfo(suite.ctx).Time.Add(time.Duration(oneMonthInSeconds) * time.Second) + expiry := suite.environment.HeaderService.HeaderInfo(suite.ctx).Time.Add(time.Duration(oneMonthInSeconds) * time.Second) cf := types.ContinuousFund{ Recipient: "", Percentage: percentage, @@ -813,7 +813,7 @@ func (suite *KeeperTestSuite) TestCancelContinuousFund() { percentage, err := math.LegacyNewDecFromStr("0.2") suite.Require().NoError(err) oneMonthInSeconds := int64(30 * 24 * 60 * 60) // Approximate number of seconds in 1 month - expiry := suite.environment.HeaderService.GetHeaderInfo(suite.ctx).Time.Add(time.Duration(oneMonthInSeconds) * time.Second) + expiry := suite.environment.HeaderService.HeaderInfo(suite.ctx).Time.Add(time.Duration(oneMonthInSeconds) * time.Second) cf := types.ContinuousFund{ Recipient: recipientStrAddr, Percentage: percentage, @@ -873,7 +873,7 @@ func (suite *KeeperTestSuite) TestCancelContinuousFund() { percentage, err := math.LegacyNewDecFromStr("0.2") suite.Require().NoError(err) oneMonthInSeconds := int64(30 * 24 * 60 * 60) // Approximate number of seconds in 1 month - expiry := suite.environment.HeaderService.GetHeaderInfo(suite.ctx).Time.Add(time.Duration(oneMonthInSeconds) * time.Second) + expiry := suite.environment.HeaderService.HeaderInfo(suite.ctx).Time.Add(time.Duration(oneMonthInSeconds) * time.Second) cf := types.ContinuousFund{ Recipient: recipientStrAddr, Percentage: percentage, diff --git a/x/slashing/keeper/grpc_query.go b/x/slashing/keeper/grpc_query.go index 0ea9c03e0731..fa3167168ab3 100644 --- a/x/slashing/keeper/grpc_query.go +++ b/x/slashing/keeper/grpc_query.go @@ -62,7 +62,7 @@ func (k Keeper) SigningInfos(ctx context.Context, req *types.QuerySigningInfosRe return nil, status.Errorf(codes.InvalidArgument, "empty request") } - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) var signInfos []types.ValidatorSigningInfo sigInfoStore := prefix.NewStore(runtime.KVStoreAdapter(store), types.ValidatorSigningInfoKeyPrefix) diff --git a/x/slashing/keeper/hooks.go b/x/slashing/keeper/hooks.go index 9d92dd0a8853..d9c63bf5ee11 100644 --- a/x/slashing/keeper/hooks.go +++ b/x/slashing/keeper/hooks.go @@ -28,7 +28,7 @@ func (k Keeper) Hooks() Hooks { // AfterValidatorBonded updates the signing info start height or create a new signing info func (h Hooks) AfterValidatorBonded(ctx context.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) error { signingInfo, err := h.k.ValidatorSigningInfo.Get(ctx, consAddr) - blockHeight := h.k.environment.HeaderService.GetHeaderInfo(ctx).Height + blockHeight := h.k.HeaderService.HeaderInfo(ctx).Height if err == nil { signingInfo.StartHeight = blockHeight } else { diff --git a/x/slashing/keeper/infractions.go b/x/slashing/keeper/infractions.go index 2b6b90cec626..f044210cb9cd 100644 --- a/x/slashing/keeper/infractions.go +++ b/x/slashing/keeper/infractions.go @@ -25,8 +25,7 @@ func (k Keeper) HandleValidatorSignature(ctx context.Context, addr cryptotypes.A } func (k Keeper) HandleValidatorSignatureWithParams(ctx context.Context, params types.Params, addr cryptotypes.Address, power int64, signed comet.BlockIDFlag) error { - logger := k.Logger(ctx) - height := k.environment.HeaderService.GetHeaderInfo(ctx).Height + height := k.HeaderService.HeaderInfo(ctx).Height // fetch the validator public key consAddr := sdk.ConsAddress(addr) @@ -115,7 +114,7 @@ func (k Keeper) HandleValidatorSignatureWithParams(ctx context.Context, params t } if missed { - if err := k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( types.EventTypeLiveness, event.NewAttribute(types.AttributeKeyAddress, consStr), event.NewAttribute(types.AttributeKeyMissedBlocks, fmt.Sprintf("%d", signInfo.MissedBlocksCounter)), @@ -124,7 +123,7 @@ func (k Keeper) HandleValidatorSignatureWithParams(ctx context.Context, params t return err } - logger.Debug( + k.Logger.Debug( "absent validator", "height", height, "validator", consStr, @@ -162,7 +161,7 @@ func (k Keeper) HandleValidatorSignatureWithParams(ctx context.Context, params t return err } - if err := k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( types.EventTypeSlash, event.NewAttribute(types.AttributeKeyAddress, consStr), event.NewAttribute(types.AttributeKeyPower, fmt.Sprintf("%d", power)), @@ -181,7 +180,7 @@ func (k Keeper) HandleValidatorSignatureWithParams(ctx context.Context, params t if err != nil { return err } - signInfo.JailedUntil = k.environment.HeaderService.GetHeaderInfo(ctx).Time.Add(downtimeJailDur) + signInfo.JailedUntil = k.HeaderService.HeaderInfo(ctx).Time.Add(downtimeJailDur) // We need to reset the counter & bitmap so that the validator won't be // immediately slashed for downtime upon re-bonding. @@ -193,7 +192,7 @@ func (k Keeper) HandleValidatorSignatureWithParams(ctx context.Context, params t return err } - logger.Info( + k.Logger.Info( "slashing and jailing validator due to liveness fault", "height", height, "validator", consStr, @@ -204,7 +203,7 @@ func (k Keeper) HandleValidatorSignatureWithParams(ctx context.Context, params t ) } else { // validator was (a) not found or (b) already jailed so we do not slash - logger.Info( + k.Logger.Info( "validator would have been slashed for downtime, but was either not found in store or already jailed", "validator", consStr, ) diff --git a/x/slashing/keeper/keeper.go b/x/slashing/keeper/keeper.go index fdfded853e7c..1a511626e5ab 100644 --- a/x/slashing/keeper/keeper.go +++ b/x/slashing/keeper/keeper.go @@ -8,7 +8,6 @@ import ( "cosmossdk.io/collections" "cosmossdk.io/core/appmodule" "cosmossdk.io/core/event" - "cosmossdk.io/log" sdkmath "cosmossdk.io/math" "cosmossdk.io/x/slashing/types" @@ -19,7 +18,8 @@ import ( // Keeper of the slashing store type Keeper struct { - environment appmodule.Environment + appmodule.Environment + cdc codec.BinaryCodec legacyAmino *codec.LegacyAmino sk types.StakingKeeper @@ -41,7 +41,7 @@ type Keeper struct { func NewKeeper(environment appmodule.Environment, cdc codec.BinaryCodec, legacyAmino *codec.LegacyAmino, sk types.StakingKeeper, authority string) Keeper { sb := collections.NewSchemaBuilder(environment.KVStoreService) k := Keeper{ - environment: environment, + Environment: environment, cdc: cdc, legacyAmino: legacyAmino, sk: sk, @@ -83,11 +83,6 @@ func (k Keeper) GetAuthority() string { return k.authority } -// Logger returns a module-specific logger. -func (k Keeper) Logger(ctx context.Context) log.Logger { - return k.environment.Logger.With("module", "x/"+types.ModuleName) -} - // GetPubkey returns the pubkey from the adddress-pubkey relation func (k Keeper) GetPubkey(ctx context.Context, a cryptotypes.Address) (cryptotypes.PubKey, error) { return k.AddrPubkeyRelation.Get(ctx, a) @@ -120,7 +115,7 @@ func (k Keeper) SlashWithInfractionReason(ctx context.Context, consAddr sdk.Cons return err } - return k.environment.EventService.EventManager(ctx).EmitKV( + return k.EventService.EventManager(ctx).EmitKV( types.EventTypeSlash, event.NewAttribute(types.AttributeKeyAddress, consStr), event.NewAttribute(types.AttributeKeyPower, fmt.Sprintf("%d", power)), @@ -141,7 +136,7 @@ func (k Keeper) Jail(ctx context.Context, consAddr sdk.ConsAddress) error { return err } - if err := k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( types.EventTypeSlash, event.NewAttribute(types.AttributeKeyJailed, consStr), ); err != nil { diff --git a/x/slashing/keeper/migrations.go b/x/slashing/keeper/migrations.go index 9f00003d315b..6c84523aebaa 100644 --- a/x/slashing/keeper/migrations.go +++ b/x/slashing/keeper/migrations.go @@ -40,7 +40,7 @@ func (m Migrator) Migrate2to3(ctx context.Context) error { // version 3 to version 4. Specifically, it migrates the validator missed block // bitmap. func (m Migrator) Migrate3to4(ctx context.Context) error { - store := runtime.KVStoreAdapter(m.keeper.environment.KVStoreService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(m.keeper.KVStoreService.OpenKVStore(ctx)) params, err := m.keeper.Params.Get(ctx) if err != nil { return err diff --git a/x/slashing/keeper/unjail.go b/x/slashing/keeper/unjail.go index 855c627bb7c5..f41998337593 100644 --- a/x/slashing/keeper/unjail.go +++ b/x/slashing/keeper/unjail.go @@ -62,7 +62,7 @@ func (k Keeper) Unjail(ctx context.Context, validatorAddr sdk.ValAddress) error return types.ErrValidatorJailed } - if k.environment.HeaderService.GetHeaderInfo(ctx).Time.Before(info.JailedUntil) { + if k.HeaderService.HeaderInfo(ctx).Time.Before(info.JailedUntil) { return types.ErrValidatorJailed } } diff --git a/x/staking/keeper/alias_functions.go b/x/staking/keeper/alias_functions.go index b4633943c7b4..0940fccfd219 100644 --- a/x/staking/keeper/alias_functions.go +++ b/x/staking/keeper/alias_functions.go @@ -15,7 +15,7 @@ import ( // IterateValidators iterates through the validator set and perform the provided function func (k Keeper) IterateValidators(ctx context.Context, fn func(index int64, validator sdk.ValidatorI) (stop bool)) error { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) iterator, err := store.Iterator(types.ValidatorsKey, storetypes.PrefixEndBytes(types.ValidatorsKey)) if err != nil { return err @@ -42,7 +42,7 @@ func (k Keeper) IterateValidators(ctx context.Context, fn func(index int64, vali // IterateBondedValidatorsByPower iterates through the bonded validator set and perform the provided function func (k Keeper) IterateBondedValidatorsByPower(ctx context.Context, fn func(index int64, validator sdk.ValidatorI) (stop bool)) error { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) maxValidators, err := k.MaxValidators(ctx) if err != nil { return err @@ -119,7 +119,7 @@ func (k Keeper) IterateDelegations(ctx context.Context, delAddr sdk.AccAddress, // GetAllSDKDelegations returns all delegations used during genesis dump // TODO: remove this func, change all usage for iterate functionality func (k Keeper) GetAllSDKDelegations(ctx context.Context) (delegations []types.Delegation, err error) { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) iterator, err := store.Iterator(types.DelegationKey, storetypes.PrefixEndBytes(types.DelegationKey)) if err != nil { return delegations, err diff --git a/x/staking/keeper/cons_pubkey.go b/x/staking/keeper/cons_pubkey.go index 7c327b5b61e6..12a5baafe48c 100644 --- a/x/staking/keeper/cons_pubkey.go +++ b/x/staking/keeper/cons_pubkey.go @@ -25,7 +25,7 @@ func (k Keeper) setConsPubKeyRotationHistory( ctx context.Context, valAddr sdk.ValAddress, oldPubKey, newPubKey *codectypes.Any, fee sdk.Coin, ) error { - headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + headerInfo := k.HeaderService.HeaderInfo(ctx) height := uint64(headerInfo.Height) history := types.ConsPubKeyRotationHistory{ OperatorAddress: valAddr.Bytes(), @@ -233,7 +233,7 @@ func (k Keeper) getAndRemoveAllMaturedRotatedKeys(ctx context.Context, matureTim // GetBlockConsPubKeyRotationHistory returns the rotation history for the current height. func (k Keeper) GetBlockConsPubKeyRotationHistory(ctx context.Context) ([]types.ConsPubKeyRotationHistory, error) { - headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + headerInfo := k.HeaderService.HeaderInfo(ctx) iterator, err := k.RotationHistory.Indexes.Block.MatchExact(ctx, uint64(headerInfo.Height)) if err != nil { diff --git a/x/staking/keeper/delegation.go b/x/staking/keeper/delegation.go index fc1061df8e83..2ef2b7ec7192 100644 --- a/x/staking/keeper/delegation.go +++ b/x/staking/keeper/delegation.go @@ -165,7 +165,7 @@ func (k Keeper) GetUnbondingDelegation(ctx context.Context, delAddr sdk.AccAddre // GetUnbondingDelegationsFromValidator returns all unbonding delegations from a // particular validator. func (k Keeper) GetUnbondingDelegationsFromValidator(ctx context.Context, valAddr sdk.ValAddress) (ubds []types.UnbondingDelegation, err error) { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) rng := collections.NewPrefixedPairRange[[]byte, []byte](valAddr) err = k.UnbondingDelegationByValIndex.Walk( ctx, @@ -652,7 +652,7 @@ func (k Keeper) InsertRedelegationQueue(ctx context.Context, red types.Redelegat // the queue. func (k Keeper) DequeueAllMatureRedelegationQueue(ctx context.Context, currTime time.Time) (matureRedelegations []types.DVVTriplet, err error) { var keys []time.Time - headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + headerInfo := k.HeaderService.HeaderInfo(ctx) // gets an iterator for all timeslices from time 0 until the current Blockheader time rng := (&collections.Range[time.Time]{}).EndInclusive(headerInfo.Time) @@ -889,7 +889,7 @@ func (k Keeper) getBeginInfo( if err != nil && errors.Is(err, types.ErrNoValidatorFound) { return completionTime, height, false, nil } - headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + headerInfo := k.HeaderService.HeaderInfo(ctx) unbondingTime, err := k.UnbondingTime(ctx) if err != nil { return completionTime, height, false, err @@ -955,7 +955,7 @@ func (k Keeper) Undelegate( return time.Time{}, math.Int{}, err } - headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + headerInfo := k.HeaderService.HeaderInfo(ctx) completionTime := headerInfo.Time.Add(unbondingTime) ubd, err := k.SetUnbondingDelegationEntry(ctx, delAddr, valAddr, headerInfo.Height, completionTime, returnAmount) if err != nil { @@ -985,7 +985,7 @@ func (k Keeper) CompleteUnbonding(ctx context.Context, delAddr sdk.AccAddress, v } balances := sdk.NewCoins() - headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + headerInfo := k.HeaderService.HeaderInfo(ctx) ctxTime := headerInfo.Time delegatorAddress, err := k.authKeeper.AddressCodec().StringToBytes(ubd.DelegatorAddress) @@ -1130,7 +1130,7 @@ func (k Keeper) CompleteRedelegation( } balances := sdk.NewCoins() - headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + headerInfo := k.HeaderService.HeaderInfo(ctx) ctxTime := headerInfo.Time // loop through all the entries and complete mature redelegation entries diff --git a/x/staking/keeper/grpc_query.go b/x/staking/keeper/grpc_query.go index 5dd6f46d6932..277993c5bb41 100644 --- a/x/staking/keeper/grpc_query.go +++ b/x/staking/keeper/grpc_query.go @@ -40,7 +40,7 @@ func (k Querier) Validators(ctx context.Context, req *types.QueryValidatorsReque return nil, status.Errorf(codes.InvalidArgument, "invalid validator status %s", req.Status) } - store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) valStore := prefix.NewStore(store, types.ValidatorsKey) validators, pageRes, err := query.GenericFilteredPaginate(k.cdc, valStore, req.Pagination, func(key []byte, val *types.Validator) (*types.Validator, error) { @@ -143,7 +143,7 @@ func (k Querier) ValidatorDelegations(ctx context.Context, req *types.QueryValid } func (k Querier) getValidatorDelegationsLegacy(ctx context.Context, req *types.QueryValidatorDelegationsRequest) ([]*types.Delegation, *query.PageResponse, error) { - store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) valStore := prefix.NewStore(store, types.DelegationKey) return query.GenericFilteredPaginate(k.cdc, valStore, req.Pagination, func(key []byte, delegation *types.Delegation) (*types.Delegation, error) { @@ -177,7 +177,7 @@ func (k Querier) ValidatorUnbondingDelegations(ctx context.Context, req *types.Q return nil, err } - store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) keys, pageRes, err := query.CollectionPaginate( ctx, k.UnbondingDelegationByValIndex, @@ -414,12 +414,12 @@ func (k Querier) Redelegations(ctx context.Context, req *types.QueryRedelegation var pageRes *query.PageResponse var err error - store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) switch { case req.DelegatorAddr != "" && req.SrcValidatorAddr != "" && req.DstValidatorAddr != "": redels, err = queryRedelegation(ctx, k, req) case req.DelegatorAddr == "" && req.SrcValidatorAddr != "" && req.DstValidatorAddr == "": - redels, pageRes, err = queryRedelegationsFromSrcValidator(ctx, store, k, req) + redels, pageRes, err = queryRedelegationsFromSrcValidator(ctx, k, req) default: redels, pageRes, err = queryAllRedelegations(ctx, store, k, req) } @@ -526,7 +526,7 @@ func queryRedelegation(ctx context.Context, k Querier, req *types.QueryRedelegat return redels, nil } -func queryRedelegationsFromSrcValidator(ctx context.Context, store storetypes.KVStore, k Querier, req *types.QueryRedelegationsRequest) (types.Redelegations, *query.PageResponse, error) { +func queryRedelegationsFromSrcValidator(ctx context.Context, k Querier, req *types.QueryRedelegationsRequest) (types.Redelegations, *query.PageResponse, error) { valAddr, err := k.validatorAddressCodec.StringToBytes(req.SrcValidatorAddr) if err != nil { return nil, nil, err diff --git a/x/staking/keeper/historical_info.go b/x/staking/keeper/historical_info.go index 77cab7424407..9e556b8f88b3 100644 --- a/x/staking/keeper/historical_info.go +++ b/x/staking/keeper/historical_info.go @@ -16,7 +16,7 @@ func (k Keeper) TrackHistoricalInfo(ctx context.Context) error { return err } - headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + headerInfo := k.HeaderService.HeaderInfo(ctx) // Prune store to ensure we only have parameter-defined historical entries. // In most cases, this will involve removing a single historical entry. diff --git a/x/staking/keeper/keeper.go b/x/staking/keeper/keeper.go index ca25c8093c2d..8db9e7dbaa07 100644 --- a/x/staking/keeper/keeper.go +++ b/x/staking/keeper/keeper.go @@ -11,7 +11,6 @@ import ( "cosmossdk.io/collections/indexes" addresscodec "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" - "cosmossdk.io/log" "cosmossdk.io/math" "cosmossdk.io/x/staking/types" @@ -68,7 +67,8 @@ func NewRotationHistoryIndexes(sb *collections.SchemaBuilder) rotationHistoryInd // Keeper of the x/staking store type Keeper struct { - environment appmodule.Environment + appmodule.Environment + cdc codec.BinaryCodec authKeeper types.AccountKeeper bankKeeper types.BankKeeper @@ -159,7 +159,7 @@ func NewKeeper( } k := &Keeper{ - environment: env, + Environment: env, cdc: cdc, authKeeper: ak, bankKeeper: bk, @@ -311,11 +311,6 @@ func NewKeeper( return k } -// Logger returns a module-specific logger. -func (k Keeper) Logger() log.Logger { - return k.environment.Logger.With("module", "x/"+types.ModuleName) -} - // Hooks gets the hooks for staking *Keeper { func (k *Keeper) Hooks() types.StakingHooks { if k.hooks == nil { diff --git a/x/staking/keeper/migrations.go b/x/staking/keeper/migrations.go index 8c9b555a4bb7..576b3fbd5b58 100644 --- a/x/staking/keeper/migrations.go +++ b/x/staking/keeper/migrations.go @@ -38,12 +38,12 @@ func (m Migrator) Migrate3to4(ctx context.Context) error { // Migrate4to5 migrates x/staking state from consensus version 4 to 5. func (m Migrator) Migrate4to5(ctx context.Context) error { - store := runtime.KVStoreAdapter(m.keeper.environment.KVStoreService.OpenKVStore(ctx)) - return v5.MigrateStore(ctx, store, m.keeper.cdc, m.keeper.Logger()) + store := runtime.KVStoreAdapter(m.keeper.KVStoreService.OpenKVStore(ctx)) + return v5.MigrateStore(ctx, store, m.keeper.cdc, m.keeper.Logger) } // Migrate4to5 migrates x/staking state from consensus version 5 to 6. func (m Migrator) Migrate5to6(ctx context.Context) error { - store := runtime.KVStoreAdapter(m.keeper.environment.KVStoreService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(m.keeper.KVStoreService.OpenKVStore(ctx)) return v6.MigrateStore(ctx, store, m.keeper.cdc) } diff --git a/x/staking/keeper/msg_server.go b/x/staking/keeper/msg_server.go index dbbfb7a6499b..53b2dc2ecb58 100644 --- a/x/staking/keeper/msg_server.go +++ b/x/staking/keeper/msg_server.go @@ -150,7 +150,7 @@ func (k msgServer) CreateValidator(ctx context.Context, msg *types.MsgCreateVali return nil, err } - if err := k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( types.EventTypeCreateValidator, event.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress), event.NewAttribute(sdk.AttributeKeyAmount, msg.Value.String()), @@ -239,7 +239,7 @@ func (k msgServer) EditValidator(ctx context.Context, msg *types.MsgEditValidato return nil, err } - if err := k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( types.EventTypeEditValidator, event.NewAttribute(types.AttributeKeyCommissionRate, validator.Commission.String()), event.NewAttribute(types.AttributeKeyMinSelfDelegation, validator.MinSelfDelegation.String()), @@ -302,7 +302,7 @@ func (k msgServer) Delegate(ctx context.Context, msg *types.MsgDelegate) (*types }() } - if err := k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( types.EventTypeDelegate, event.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress), event.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress), @@ -375,7 +375,7 @@ func (k msgServer) BeginRedelegate(ctx context.Context, msg *types.MsgBeginRedel }() } - if err := k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( types.EventTypeRedelegate, event.NewAttribute(types.AttributeKeySrcValidator, msg.ValidatorSrcAddress), event.NewAttribute(types.AttributeKeyDstValidator, msg.ValidatorDstAddress), @@ -445,7 +445,7 @@ func (k msgServer) Undelegate(ctx context.Context, msg *types.MsgUndelegate) (*t }() } - if err := k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( types.EventTypeUnbond, event.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress), event.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress), @@ -544,7 +544,7 @@ func (k msgServer) CancelUnbondingDelegation(ctx context.Context, msg *types.Msg return nil, sdkerrors.ErrInvalidRequest.Wrap("amount is greater than the unbonding delegation entry balance") } - headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + headerInfo := k.HeaderService.HeaderInfo(ctx) if unbondEntry.CompletionTime.Before(headerInfo.Time) { return nil, sdkerrors.ErrInvalidRequest.Wrap("unbonding delegation is already processed") } @@ -576,7 +576,7 @@ func (k msgServer) CancelUnbondingDelegation(ctx context.Context, msg *types.Msg return nil, err } - if err := k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( types.EventTypeCancelUnbondingDelegation, event.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()), event.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress), @@ -628,7 +628,7 @@ func (k msgServer) UpdateParams(ctx context.Context, msg *types.MsgUpdateParams) val.Commission.CommissionRates.MaxRate = minRate } - val.Commission.UpdateTime = k.environment.HeaderService.GetHeaderInfo(ctx).Time + val.Commission.UpdateTime = k.HeaderService.HeaderInfo(ctx).Time if err := k.SetValidator(ctx, val); err != nil { return nil, fmt.Errorf("failed to set validator after MinCommissionRate param change: %w", err) } diff --git a/x/staking/keeper/slash.go b/x/staking/keeper/slash.go index 6e8835ff6523..0f7f245e81ed 100644 --- a/x/staking/keeper/slash.go +++ b/x/staking/keeper/slash.go @@ -35,8 +35,6 @@ import ( // Infraction was committed at the current height or at a past height, // but not at a height in the future func (k Keeper) Slash(ctx context.Context, consAddr sdk.ConsAddress, infractionHeight, power int64, slashFactor math.LegacyDec) (math.Int, error) { - logger := k.Logger() - if slashFactor.IsNegative() { return math.NewInt(0), fmt.Errorf("attempted to slash with a negative slash factor: %v", slashFactor) } @@ -59,7 +57,7 @@ func (k Keeper) Slash(ctx context.Context, consAddr sdk.ConsAddress, infractionH return math.NewInt(0), err } - logger.Error( + k.Logger.Error( "WARNING: ignored attempt to slash a nonexistent validator; we recommend you investigate immediately", "validator", conStr, ) @@ -88,7 +86,7 @@ func (k Keeper) Slash(ctx context.Context, consAddr sdk.ConsAddress, infractionH // redelegations, as that stake has since unbonded remainingSlashAmount := slashAmount - headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + headerInfo := k.HeaderService.HeaderInfo(ctx) height := headerInfo.Height switch { case infractionHeight > height: @@ -100,7 +98,7 @@ func (k Keeper) Slash(ctx context.Context, consAddr sdk.ConsAddress, infractionH case infractionHeight == height: // Special-case slash at current height for efficiency - we don't need to // look through unbonding delegations or redelegations. - logger.Info( + k.Logger.Info( "slashing at current height; not scanning unbonding delegations & redelegations", "height", infractionHeight, ) @@ -152,7 +150,7 @@ func (k Keeper) Slash(ctx context.Context, consAddr sdk.ConsAddress, infractionH // Nothing to burn, we can end this route immediately! We also don't // need to call the k.Hooks().BeforeValidatorSlashed hook as we won't // be slashing at all. - logger.Info( + k.Logger.Info( "no validator slashing because slash amount is zero", "validator", validator.GetOperator(), "slash_factor", slashFactor.String(), @@ -195,7 +193,7 @@ func (k Keeper) Slash(ctx context.Context, consAddr sdk.ConsAddress, infractionH return math.NewInt(0), fmt.Errorf("invalid validator status") } - logger.Info( + k.Logger.Info( "validator slashed by slash factor", "validator", validator.GetOperator(), "slash_factor", slashFactor.String(), @@ -219,7 +217,7 @@ func (k Keeper) Jail(ctx context.Context, consAddr sdk.ConsAddress) error { return err } - k.Logger().Info("validator jailed", "validator", consAddr) + k.Logger.Info("validator jailed", "validator", consAddr) return nil } @@ -233,7 +231,7 @@ func (k Keeper) Unjail(ctx context.Context, consAddr sdk.ConsAddress) error { return err } - k.Logger().Info("validator un-jailed", "validator", consAddr) + k.Logger.Info("validator un-jailed", "validator", consAddr) return nil } @@ -245,7 +243,7 @@ func (k Keeper) Unjail(ctx context.Context, consAddr sdk.ConsAddress) error { func (k Keeper) SlashUnbondingDelegation(ctx context.Context, unbondingDelegation types.UnbondingDelegation, infractionHeight int64, slashFactor math.LegacyDec, ) (totalSlashAmount math.Int, err error) { - now := k.environment.HeaderService.GetHeaderInfo(ctx).Time + now := k.HeaderService.HeaderInfo(ctx).Time totalSlashAmount = math.ZeroInt() burnedAmount := math.ZeroInt() @@ -301,7 +299,7 @@ func (k Keeper) SlashUnbondingDelegation(ctx context.Context, unbondingDelegatio func (k Keeper) SlashRedelegation(ctx context.Context, srcValidator types.Validator, redelegation types.Redelegation, infractionHeight int64, slashFactor math.LegacyDec, ) (totalSlashAmount math.Int, err error) { - now := k.environment.HeaderService.GetHeaderInfo(ctx).Time + now := k.HeaderService.HeaderInfo(ctx).Time totalSlashAmount = math.ZeroInt() bondedBurnedAmount, notBondedBurnedAmount := math.ZeroInt(), math.ZeroInt() diff --git a/x/staking/keeper/test_common.go b/x/staking/keeper/test_common.go index 829b71a40a16..1f8a4babc5e6 100644 --- a/x/staking/keeper/test_common.go +++ b/x/staking/keeper/test_common.go @@ -12,7 +12,7 @@ import ( // ValidatorByPowerIndexExists does a certain by-power index record exist func ValidatorByPowerIndexExists(ctx context.Context, keeper *Keeper, power []byte) bool { - store := keeper.environment.KVStoreService.OpenKVStore(ctx) + store := keeper.KVStoreService.OpenKVStore(ctx) has, err := store.Has(power) if err != nil { panic(err) @@ -28,7 +28,7 @@ func TestingUpdateValidator(keeper *Keeper, ctx sdk.Context, validator types.Val } // Remove any existing power key for validator. - store := keeper.environment.KVStoreService.OpenKVStore(ctx) + store := keeper.KVStoreService.OpenKVStore(ctx) deleted := false iterator, err := store.Iterator(types.ValidatorsByPowerIndexKey, storetypes.PrefixEndBytes(types.ValidatorsByPowerIndexKey)) diff --git a/x/staking/keeper/unbonding.go b/x/staking/keeper/unbonding.go index 22ab6e0f4f6a..7e3a9cd96193 100644 --- a/x/staking/keeper/unbonding.go +++ b/x/staking/keeper/unbonding.go @@ -75,7 +75,7 @@ func (k Keeper) GetUnbondingDelegationByUnbondingID(ctx context.Context, id uint // GetRedelegationByUnbondingID returns a unbonding delegation that has an unbonding delegation entry with a certain ID func (k Keeper) GetRedelegationByUnbondingID(ctx context.Context, id uint64) (red types.Redelegation, err error) { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) redKey, err := k.UnbondingIndex.Get(ctx, id) if err != nil { @@ -109,7 +109,7 @@ func (k Keeper) GetRedelegationByUnbondingID(ctx context.Context, id uint64) (re // GetValidatorByUnbondingID returns the validator that is unbonding with a certain unbonding op ID func (k Keeper) GetValidatorByUnbondingID(ctx context.Context, id uint64) (val types.Validator, err error) { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) valKey, err := k.UnbondingIndex.Get(ctx, id) if err != nil { @@ -283,7 +283,7 @@ func (k Keeper) unbondingDelegationEntryCanComplete(ctx context.Context, id uint ubd.Entries[i].UnbondingOnHoldRefCount-- // Check if entry is matured. - if !ubd.Entries[i].OnHold() && ubd.Entries[i].IsMature(k.environment.HeaderService.GetHeaderInfo(ctx).Time) { + if !ubd.Entries[i].OnHold() && ubd.Entries[i].IsMature(k.HeaderService.HeaderInfo(ctx).Time) { // If matured, complete it. delegatorAddress, err := k.authKeeper.AddressCodec().StringToBytes(ubd.DelegatorAddress) if err != nil { @@ -344,7 +344,7 @@ func (k Keeper) redelegationEntryCanComplete(ctx context.Context, id uint64) err } red.Entries[i].UnbondingOnHoldRefCount-- - headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + headerInfo := k.HeaderService.HeaderInfo(ctx) if !red.Entries[i].OnHold() && red.Entries[i].IsMature(headerInfo.Time) { // If matured, complete it. // Remove entry diff --git a/x/staking/keeper/val_state_change.go b/x/staking/keeper/val_state_change.go index 3279faa001f3..ac6d82eb27ee 100644 --- a/x/staking/keeper/val_state_change.go +++ b/x/staking/keeper/val_state_change.go @@ -43,7 +43,7 @@ func (k Keeper) BlockValidatorUpdates(ctx context.Context) ([]appmodule.Validato return nil, err } - time := k.environment.HeaderService.GetHeaderInfo(ctx).Time + time := k.HeaderService.HeaderInfo(ctx).Time // Remove all mature unbonding delegations from the ubd queue. matureUnbonds, err := k.DequeueAllMatureUBDQueue(ctx, time) if err != nil { @@ -65,7 +65,7 @@ func (k Keeper) BlockValidatorUpdates(ctx context.Context) ([]appmodule.Validato continue } - if err := k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( types.EventTypeCompleteUnbonding, event.NewAttribute(sdk.AttributeKeyAmount, balances.String()), event.NewAttribute(types.AttributeKeyValidator, dvPair.ValidatorAddress), @@ -105,7 +105,7 @@ func (k Keeper) BlockValidatorUpdates(ctx context.Context) ([]appmodule.Validato continue } - if err := k.environment.EventService.EventManager(ctx).EmitKV( + if err := k.EventService.EventManager(ctx).EmitKV( types.EventTypeCompleteRedelegation, event.NewAttribute(sdk.AttributeKeyAmount, balances.String()), event.NewAttribute(types.AttributeKeyDelegator, dvvTriplet.DelegatorAddress), @@ -454,7 +454,7 @@ func (k Keeper) BeginUnbondingValidator(ctx context.Context, validator types.Val validator = validator.UpdateStatus(types.Unbonding) - headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + headerInfo := k.HeaderService.HeaderInfo(ctx) // set the unbonding completion time and completion height appropriately validator.UnbondingTime = headerInfo.Time.Add(params.UnbondingTime) validator.UnbondingHeight = headerInfo.Height diff --git a/x/staking/keeper/validator.go b/x/staking/keeper/validator.go index 6e496f756762..d3e6031ed337 100644 --- a/x/staking/keeper/validator.go +++ b/x/staking/keeper/validator.go @@ -100,7 +100,7 @@ func (k Keeper) SetValidatorByPowerIndex(ctx context.Context, validator types.Va return nil } - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) str, err := k.validatorAddressCodec.StringToBytes(validator.GetOperator()) if err != nil { return err @@ -110,13 +110,13 @@ func (k Keeper) SetValidatorByPowerIndex(ctx context.Context, validator types.Va // DeleteValidatorByPowerIndex deletes a record by power index func (k Keeper) DeleteValidatorByPowerIndex(ctx context.Context, validator types.Validator) error { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) return store.Delete(types.GetValidatorsByPowerIndexKey(validator, k.PowerReduction(ctx), k.validatorAddressCodec)) } // SetNewValidatorByPowerIndex adds new entry by power index func (k Keeper) SetNewValidatorByPowerIndex(ctx context.Context, validator types.Validator) error { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) str, err := k.validatorAddressCodec.StringToBytes(validator.GetOperator()) if err != nil { return err @@ -187,7 +187,7 @@ func (k Keeper) UpdateValidatorCommission(ctx context.Context, validator types.Validator, newRate math.LegacyDec, ) (types.Commission, error) { commission := validator.Commission - blockTime := k.environment.HeaderService.GetHeaderInfo(ctx).Time + blockTime := k.HeaderService.HeaderInfo(ctx).Time if err := commission.ValidateNewRate(newRate, blockTime); err != nil { return commission, err @@ -231,7 +231,7 @@ func (k Keeper) RemoveValidator(ctx context.Context, address sdk.ValAddress) err } // delete the old validator record - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) if err = k.Validators.Remove(ctx, address); err != nil { return err } @@ -260,7 +260,7 @@ func (k Keeper) RemoveValidator(ctx context.Context, address sdk.ValAddress) err // GetAllValidators gets the set of all validators with no limits, used during genesis dump func (k Keeper) GetAllValidators(ctx context.Context) (validators []types.Validator, err error) { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) iterator, err := store.Iterator(types.ValidatorsKey, storetypes.PrefixEndBytes(types.ValidatorsKey)) if err != nil { @@ -281,7 +281,7 @@ func (k Keeper) GetAllValidators(ctx context.Context) (validators []types.Valida // GetValidators returns a given amount of all the validators func (k Keeper) GetValidators(ctx context.Context, maxRetrieve uint32) (validators []types.Validator, err error) { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) validators = make([]types.Validator, maxRetrieve) iterator, err := store.Iterator(types.ValidatorsKey, storetypes.PrefixEndBytes(types.ValidatorsKey)) @@ -335,7 +335,7 @@ func (k Keeper) GetBondedValidatorsByPower(ctx context.Context) ([]types.Validat // ValidatorsPowerStoreIterator returns an iterator for the current validator power store func (k Keeper) ValidatorsPowerStoreIterator(ctx context.Context) (corestore.Iterator, error) { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) return store.ReverseIterator(types.ValidatorsByPowerIndexKey, storetypes.PrefixEndBytes(types.ValidatorsByPowerIndexKey)) } @@ -487,7 +487,7 @@ func (k Keeper) DeleteValidatorQueue(ctx context.Context, val types.Validator) e // UnbondAllMatureValidators unbonds all the mature unbonding validators that // have finished their unbonding period. func (k Keeper) UnbondAllMatureValidators(ctx context.Context) error { - headerInfo := k.environment.HeaderService.GetHeaderInfo(ctx) + headerInfo := k.HeaderService.HeaderInfo(ctx) blockTime := headerInfo.Time blockHeight := uint64(headerInfo.Height) diff --git a/x/upgrade/keeper/abci.go b/x/upgrade/keeper/abci.go index bd2844dcbf23..033df51057d3 100644 --- a/x/upgrade/keeper/abci.go +++ b/x/upgrade/keeper/abci.go @@ -23,7 +23,7 @@ import ( func (k Keeper) PreBlocker(ctx context.Context) error { defer telemetry.ModuleMeasureSince(types.ModuleName, telemetry.Now(), telemetry.MetricKeyBeginBlocker) - blockHeight := k.environment.HeaderService.GetHeaderInfo(ctx).Height + blockHeight := k.HeaderService.HeaderInfo(ctx).Height plan, err := k.GetUpgradePlan(ctx) if err != nil && !errors.Is(err, types.ErrNoUpgradePlanFound) { return err @@ -61,14 +61,12 @@ func (k Keeper) PreBlocker(ctx context.Context) error { return nil } - logger := k.Logger(ctx) - // To make sure clear upgrade is executed at the same block if plan.ShouldExecute(blockHeight) { // If skip upgrade has been set for current height, we clear the upgrade plan if k.IsSkipHeight(blockHeight) { skipUpgradeMsg := fmt.Sprintf("UPGRADE \"%s\" SKIPPED at %d: %s", plan.Name, plan.Height, plan.Info) - logger.Info(skipUpgradeMsg) + k.Logger.Info(skipUpgradeMsg) // Clear the upgrade plan at current height if err := k.ClearUpgradePlan(ctx); err != nil { @@ -87,14 +85,14 @@ func (k Keeper) PreBlocker(ctx context.Context) error { } upgradeMsg := BuildUpgradeNeededMsg(plan) - logger.Error(upgradeMsg) + k.Logger.Error(upgradeMsg) // Returning an error will end up in a panic return errors.New(upgradeMsg) } // We have an upgrade handler for this upgrade name, so apply the upgrade - logger.Info(fmt.Sprintf("applying upgrade \"%s\" at %s", plan.Name, plan.DueAt())) + k.Logger.Info(fmt.Sprintf("applying upgrade \"%s\" at %s", plan.Name, plan.DueAt())) sdkCtx = sdkCtx.WithBlockGasMeter(storetypes.NewInfiniteGasMeter()) if err := k.ApplyUpgrade(sdkCtx, plan); err != nil { return err @@ -106,7 +104,7 @@ func (k Keeper) PreBlocker(ctx context.Context) error { // set the handler already if k.HasHandler(plan.Name) { downgradeMsg := fmt.Sprintf("BINARY UPDATED BEFORE TRIGGER! UPGRADE \"%s\" - in binary but not executed on chain. Downgrade your binary", plan.Name) - logger.Error(downgradeMsg) + k.Logger.Error(downgradeMsg) // Returning an error will end up in a panic return errors.New(downgradeMsg) diff --git a/x/upgrade/keeper/keeper.go b/x/upgrade/keeper/keeper.go index 24588bdf7310..bd957a6de654 100644 --- a/x/upgrade/keeper/keeper.go +++ b/x/upgrade/keeper/keeper.go @@ -16,7 +16,6 @@ import ( "cosmossdk.io/core/appmodule" errorsmod "cosmossdk.io/errors" - "cosmossdk.io/log" "cosmossdk.io/store/prefix" storetypes "cosmossdk.io/store/types" xp "cosmossdk.io/x/upgrade/exported" @@ -31,9 +30,10 @@ import ( ) type Keeper struct { - homePath string // root directory of app config - skipUpgradeHeights map[int64]bool // map of heights to skip for an upgrade - environment appmodule.Environment + appmodule.Environment + + homePath string // root directory of app config + skipUpgradeHeights map[int64]bool // map of heights to skip for an upgrade cdc codec.BinaryCodec // App-wide binary codec upgradeHandlers map[string]types.UpgradeHandler // map of plan name to upgrade handler versionModifier xp.AppVersionModifier // implements setting the protocol version field on BaseApp @@ -50,9 +50,9 @@ type Keeper struct { // vs - the interface implemented by baseapp which allows setting baseapp's protocol version field func NewKeeper(env appmodule.Environment, skipUpgradeHeights map[int64]bool, cdc codec.BinaryCodec, homePath string, vs xp.AppVersionModifier, authority string) *Keeper { k := &Keeper{ + Environment: env, homePath: homePath, skipUpgradeHeights: skipUpgradeHeights, - environment: env, cdc: cdc, upgradeHandlers: map[string]types.UpgradeHandler{}, versionModifier: vs, @@ -88,7 +88,7 @@ func (k Keeper) SetUpgradeHandler(name string, upgradeHandler types.UpgradeHandl // SetModuleVersionMap saves a given version map to state func (k Keeper) SetModuleVersionMap(ctx context.Context, vm module.VersionMap) error { if len(vm) > 0 { - store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx)) + store := runtime.KVStoreAdapter(k.KVStoreService.OpenKVStore(ctx)) versionStore := prefix.NewStore(store, []byte{types.VersionMapByte}) // Even though the underlying store (cachekv) store is sorted, we still // prefer a deterministic iteration order of the map, to avoid undesired @@ -115,7 +115,7 @@ func (k Keeper) SetModuleVersionMap(ctx context.Context, vm module.VersionMap) e // GetModuleVersionMap returns a map of key module name and value module consensus version // as defined in ADR-041. func (k Keeper) GetModuleVersionMap(ctx context.Context) (module.VersionMap, error) { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) prefix := []byte{types.VersionMapByte} it, err := store.Iterator(prefix, storetypes.PrefixEndBytes(prefix)) if err != nil { @@ -137,7 +137,7 @@ func (k Keeper) GetModuleVersionMap(ctx context.Context) (module.VersionMap, err // GetModuleVersions gets a slice of module consensus versions func (k Keeper) GetModuleVersions(ctx context.Context) ([]*types.ModuleVersion, error) { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) prefix := []byte{types.VersionMapByte} it, err := store.Iterator(prefix, storetypes.PrefixEndBytes(prefix)) if err != nil { @@ -162,7 +162,7 @@ func (k Keeper) GetModuleVersions(ctx context.Context) ([]*types.ModuleVersion, // getModuleVersion gets the version for a given module. If it doesn't exist it returns ErrNoModuleVersionFound, other // errors may be returned if there is an error reading from the store. func (k Keeper) getModuleVersion(ctx context.Context, name string) (uint64, error) { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) prefix := []byte{types.VersionMapByte} it, err := store.Iterator(prefix, storetypes.PrefixEndBytes(prefix)) if err != nil { @@ -192,7 +192,7 @@ func (k Keeper) ScheduleUpgrade(ctx context.Context, plan types.Plan) error { // NOTE: allow for the possibility of chains to schedule upgrades in begin block of the same block // as a strategy for emergency hard fork recoveries - if plan.Height < k.environment.HeaderService.GetHeaderInfo(ctx).Height { + if plan.Height < k.HeaderService.HeaderInfo(ctx).Height { return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "upgrade cannot be scheduled in the past") } @@ -205,7 +205,7 @@ func (k Keeper) ScheduleUpgrade(ctx context.Context, plan types.Plan) error { return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "upgrade with name %s has already been completed", plan.Name) } - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) // clear any old IBC state stored by previous plan oldPlan, err := k.GetUpgradePlan(ctx) @@ -238,14 +238,14 @@ func (k Keeper) ScheduleUpgrade(ctx context.Context, plan types.Plan) error { // SetUpgradedClient sets the expected upgraded client for the next version of this chain at the last height the current chain will commit. func (k Keeper) SetUpgradedClient(ctx context.Context, planHeight int64, bz []byte) error { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) return store.Set(types.UpgradedClientKey(planHeight), bz) } // GetUpgradedClient gets the expected upgraded client for the next version of this chain. If not found it returns // ErrNoUpgradedClientFound, but other errors may be returned if there is an error reading from the store. func (k Keeper) GetUpgradedClient(ctx context.Context, height int64) ([]byte, error) { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(types.UpgradedClientKey(height)) if err != nil { return nil, err @@ -261,14 +261,14 @@ func (k Keeper) GetUpgradedClient(ctx context.Context, height int64) ([]byte, er // SetUpgradedConsensusState sets the expected upgraded consensus state for the next version of this chain // using the last height committed on this chain. func (k Keeper) SetUpgradedConsensusState(ctx context.Context, planHeight int64, bz []byte) error { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) return store.Set(types.UpgradedConsStateKey(planHeight), bz) } // GetUpgradedConsensusState gets the expected upgraded consensus state for the next version of this chain. If not found // it returns ErrNoUpgradedConsensusStateFound, but other errors may be returned if there is an error reading from the store. func (k Keeper) GetUpgradedConsensusState(ctx context.Context, lastHeight int64) ([]byte, error) { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(types.UpgradedConsStateKey(lastHeight)) if err != nil { return nil, err @@ -283,7 +283,7 @@ func (k Keeper) GetUpgradedConsensusState(ctx context.Context, lastHeight int64) // GetLastCompletedUpgrade returns the last applied upgrade name and height. func (k Keeper) GetLastCompletedUpgrade(ctx context.Context) (string, int64, error) { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) prefix := []byte{types.DoneByte} it, err := store.ReverseIterator(prefix, storetypes.PrefixEndBytes(prefix)) if err != nil { @@ -318,7 +318,7 @@ func encodeDoneKey(name string, height int64) []byte { // GetDoneHeight returns the height at which the given upgrade was executed func (k Keeper) GetDoneHeight(ctx context.Context, name string) (int64, error) { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) prefix := []byte{types.DoneByte} it, err := store.Iterator(prefix, storetypes.PrefixEndBytes(prefix)) if err != nil { @@ -339,7 +339,7 @@ func (k Keeper) GetDoneHeight(ctx context.Context, name string) (int64, error) { // ClearIBCState clears any planned IBC state func (k Keeper) ClearIBCState(ctx context.Context, lastHeight int64) error { // delete IBC client and consensus state from store if this is IBC plan - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) err := store.Delete(types.UpgradedClientKey(lastHeight)) if err != nil { return err @@ -365,19 +365,14 @@ func (k Keeper) ClearUpgradePlan(ctx context.Context) error { return err } - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) return store.Delete(types.PlanKey()) } -// Logger returns a module-specific logger. -func (k Keeper) Logger(ctx context.Context) log.Logger { - return k.environment.Logger.With("module", "x/"+types.ModuleName) -} - // GetUpgradePlan returns the currently scheduled Plan if any. If not found it returns // ErrNoUpgradePlanFound, but other errors may be returned if there is an error reading from the store. func (k Keeper) GetUpgradePlan(ctx context.Context) (plan types.Plan, err error) { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(types.PlanKey()) if err != nil { return plan, err @@ -397,11 +392,11 @@ func (k Keeper) GetUpgradePlan(ctx context.Context) (plan types.Plan, err error) // setDone marks this upgrade name as being done so the name can't be reused accidentally func (k Keeper) setDone(ctx context.Context, name string) error { - store := k.environment.KVStoreService.OpenKVStore(ctx) + store := k.KVStoreService.OpenKVStore(ctx) - k.Logger(ctx).Debug("setting done", "height", k.environment.HeaderService.GetHeaderInfo(ctx).Height, "name", name) + k.Logger.Debug("setting done", "height", k.HeaderService.HeaderInfo(ctx).Height, "name", name) - return store.Set(encodeDoneKey(name, k.environment.HeaderService.GetHeaderInfo(ctx).Height), []byte{1}) + return store.Set(encodeDoneKey(name, k.HeaderService.HeaderInfo(ctx).Height), []byte{1}) } // HasHandler returns true iff there is a handler registered for this name diff --git a/x/upgrade/keeper/keeper_test.go b/x/upgrade/keeper/keeper_test.go index f17d6ae870d8..76a8dcd0e4c9 100644 --- a/x/upgrade/keeper/keeper_test.go +++ b/x/upgrade/keeper/keeper_test.go @@ -72,7 +72,6 @@ func (s *KeeperTestSuite) SetupTest() { s.encodedAuthority = authority s.upgradeKeeper = keeper.NewKeeper(env, skipUpgradeHeights, s.encCfg.Codec, homeDir, s.baseApp, authority) - s.Require().Equal(testCtx.Ctx.Logger().With("module", "x/"+types.ModuleName), s.upgradeKeeper.Logger(testCtx.Ctx)) s.T().Log("home dir:", homeDir) s.homeDir = homeDir diff --git a/x/upgrade/keeper/migrations.go b/x/upgrade/keeper/migrations.go index 84fbe30af82f..2cee9df2fe67 100644 --- a/x/upgrade/keeper/migrations.go +++ b/x/upgrade/keeper/migrations.go @@ -29,7 +29,7 @@ func NewMigrator(keeper *Keeper) Migrator { // Migrate1to2 migrates from version 1 to 2. func (m Migrator) Migrate1to2(ctx context.Context) error { - return migrateDoneUpgradeKeys(ctx, m.keeper.environment.KVStoreService) + return migrateDoneUpgradeKeys(ctx, m.keeper.KVStoreService) } func migrateDoneUpgradeKeys(ctx context.Context, storeService storetypes.KVStoreService) error { @@ -66,7 +66,7 @@ func migrateAppVersion(ctx context.Context, keeper *Keeper) error { return fmt.Errorf("version modifier is not set") } - store := keeper.environment.KVStoreService.OpenKVStore(ctx) + store := keeper.KVStoreService.OpenKVStore(ctx) // if the key was never set then we don't need to migrate anything exists, err := store.Has([]byte{LegacyProtocolVersionByte}) if err != nil {