refactor(core,x/**): simplify core service api and embed environment in keepers (#20071)

This commit is contained in:
Julien Robert 2024-04-17 20:18:16 +02:00 committed by GitHub
parent a4ff821981
commit 5e7aae0db1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
115 changed files with 546 additions and 651 deletions

View File

@ -154,6 +154,34 @@ The `codectypes.Any` has moved to `github.com/cosmos/gogoproto/types/any`. Modul
#### `**all**`
##### 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` 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 (or depinject will inject the correct environment).
`x/circuit` is used as an example:
```go
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.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.
```diff
-func (AppModule) RegisterInterfaces(registry codectypes.InterfaceRegistry) {
+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
@ -164,34 +192,6 @@ been added to avoid the use of the Accounts.String() method.
+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.
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.
`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())
```
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())
```
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.
```diff
-func (AppModule) RegisterInterfaces(registry codectypes.InterfaceRegistry) {
+func (AppModule) RegisterInterfaces(registry registry.InterfaceRegistrar) {
```
##### Dependency Injection
Previously `cosmossdk.io/core` held functions `Invoke`, `Provide` and `Register` were moved to `cosmossdk.io/depinject/appconfig`.

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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.

View File

@ -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`

View File

@ -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

View File

@ -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()
}

View File

@ -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),
)

View File

@ -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),

View File

@ -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,
)

View File

@ -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 {

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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),

View File

@ -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()

View File

@ -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),

View File

@ -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()

View File

@ -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)

View File

@ -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.

View File

@ -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")

View File

@ -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

View File

@ -20,7 +20,7 @@ type mockAccount struct {
ante.AccountKeeper
}
func (*mockAccount) Environment() appmodule.Environment {
func (*mockAccount) GetEnvironment() appmodule.Environment {
return appmodule.Environment{
TransactionService: &mockTransactionService{},
}

View File

@ -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)

View File

@ -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
}

View File

@ -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 {

View File

@ -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) {

View File

@ -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()

View File

@ -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
}

View File

@ -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)
}

View File

@ -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
}

View File

@ -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()

View File

@ -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{}

View File

@ -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)
}

View File

@ -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()),

View File

@ -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)
}
}

View File

@ -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,

View File

@ -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),

View File

@ -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 {

View File

@ -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 {

View File

@ -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 {

View File

@ -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()),

View File

@ -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()),

View File

@ -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()),
)

View File

@ -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
}

View File

@ -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(),

View File

@ -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

View File

@ -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
},

View File

@ -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
}

View File

@ -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
}

View File

@ -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

View File

@ -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,

View File

@ -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 {

View File

@ -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)
}

View File

@ -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

View File

@ -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)
}

View File

@ -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 {

View File

@ -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)

View File

@ -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,

View File

@ -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()),

View File

@ -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

View File

@ -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)
}

View File

@ -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)
}

View File

@ -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)

View File

@ -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)),

View File

@ -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)
}

View File

@ -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 {

View File

@ -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
}

View File

@ -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
}
}

View File

@ -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")
}
}

View File

@ -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 {

View File

@ -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,

View File

@ -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

View File

@ -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))

View File

@ -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)
}
}

View File

@ -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 {

View File

@ -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()),

View File

@ -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) {

View File

@ -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)

View File

@ -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)

View File

@ -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

View File

@ -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(),
}
}

View File

@ -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,

View File

@ -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 {

View File

@ -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) {

View File

@ -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)

View File

@ -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 = &currentTime
}
@ -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")
}

View File

@ -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 {

View File

@ -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,

View File

@ -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)

View File

@ -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 {

View File

@ -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,
)

View File

@ -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 {

View File

@ -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

View File

@ -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
}
}

View File

@ -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

View File

@ -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 {

Some files were not shown because too many files have changed in this diff Show More