From a248d05f70f4ad7b8ff7b521e3d23086867d07dc Mon Sep 17 00:00:00 2001 From: Likhita Polavarapu <78951027+likhita-809@users.noreply.github.com> Date: Wed, 28 Feb 2024 03:48:13 +0530 Subject: [PATCH] feat(x/distribution): add env bundler to distribution module (#19445) Co-authored-by: marbar3778 --- baseapp/abci.go | 9 +- simapp/app.go | 2 +- .../distribution/keeper/msg_server_test.go | 2 +- testutil/sims/app_helpers.go | 5 +- x/distribution/CHANGELOG.md | 1 + x/distribution/depinject.go | 9 +- x/distribution/keeper/abci.go | 1 + x/distribution/keeper/allocation.go | 30 ++--- x/distribution/keeper/allocation_test.go | 16 ++- x/distribution/keeper/delegation.go | 28 ++--- x/distribution/keeper/delegation_test.go | 104 ++++++++++-------- x/distribution/keeper/keeper.go | 39 ++++--- x/distribution/keeper/keeper_test.go | 6 +- x/distribution/keeper/migrations.go | 2 +- x/distribution/keeper/validator.go | 5 +- x/distribution/migrations/v4/migrate.go | 7 +- .../migrations/v4/migrate_funds_test.go | 2 +- x/distribution/migrations/v4/migrate_test.go | 5 +- x/distribution/module.go | 2 +- 19 files changed, 150 insertions(+), 125 deletions(-) diff --git a/baseapp/abci.go b/baseapp/abci.go index 0daed3f1597e..f851338acbae 100644 --- a/baseapp/abci.go +++ b/baseapp/abci.go @@ -1251,14 +1251,19 @@ func (app *BaseApp) CreateQueryContext(height int64, prove bool) (sdk.Context, e ctx := sdk.NewContext(cacheMS, true, app.logger). WithMinGasPrices(app.minGasPrices). WithBlockHeight(height). - WithGasMeter(storetypes.NewGasMeter(app.queryGasLimit)).WithBlockHeader(app.checkState.Context().BlockHeader()) + WithGasMeter(storetypes.NewGasMeter(app.queryGasLimit)). + WithHeaderInfo(coreheader.Info{ + ChainID: app.chainID, + Height: height, + }). + WithBlockHeader(app.checkState.Context().BlockHeader()) if height != lastBlockHeight { rms, ok := app.cms.(*rootmulti.Store) if ok { cInfo, err := rms.GetCommitInfo(height) if cInfo != nil && err == nil { - ctx = ctx.WithHeaderInfo(coreheader.Info{Time: cInfo.Timestamp}) + ctx = ctx.WithHeaderInfo(coreheader.Info{Height: height, Time: cInfo.Timestamp}) } } } diff --git a/simapp/app.go b/simapp/app.go index a37ccf732404..510af074c4aa 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -332,7 +332,7 @@ func NewSimApp( 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.DistrKeeper = distrkeeper.NewKeeper(appCodec, runtime.NewKVStoreService(keys[distrtypes.StoreKey]), 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), 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), appCodec, legacyAmino, app.StakingKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), diff --git a/tests/integration/distribution/keeper/msg_server_test.go b/tests/integration/distribution/keeper/msg_server_test.go index ac6197269770..4c4ee67abc76 100644 --- a/tests/integration/distribution/keeper/msg_server_test.go +++ b/tests/integration/distribution/keeper/msg_server_test.go @@ -110,7 +110,7 @@ func initFixture(t *testing.T) *fixture { poolKeeper := poolkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[pooltypes.StoreKey]), log.NewNopLogger()), accountKeeper, bankKeeper, stakingKeeper, authority.String()) distrKeeper := distrkeeper.NewKeeper( - cdc, runtime.NewKVStoreService(keys[distrtypes.StoreKey]), accountKeeper, bankKeeper, stakingKeeper, poolKeeper, distrtypes.ModuleName, authority.String(), + cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[distrtypes.StoreKey]), logger), accountKeeper, bankKeeper, stakingKeeper, poolKeeper, distrtypes.ModuleName, authority.String(), ) authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts) diff --git a/testutil/sims/app_helpers.go b/testutil/sims/app_helpers.go index ffac149f4c4c..c97b70c0a0b0 100644 --- a/testutil/sims/app_helpers.go +++ b/testutil/sims/app_helpers.go @@ -11,19 +11,18 @@ import ( cmttypes "github.com/cometbft/cometbft/types" dbm "github.com/cosmos/cosmos-db" + coreheader "cosmossdk.io/core/header" "cosmossdk.io/depinject" sdkmath "cosmossdk.io/math" authtypes "cosmossdk.io/x/auth/types" banktypes "cosmossdk.io/x/bank/types" stakingtypes "cosmossdk.io/x/staking/types" - coreheader "cosmossdk.io/core/header" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - "github.com/cosmos/cosmos-sdk/runtime" servertypes "github.com/cosmos/cosmos-sdk/server/types" "github.com/cosmos/cosmos-sdk/testutil/mock" @@ -124,7 +123,7 @@ func NextBlock(app *runtime.App, ctx sdk.Context, jumpTime time.Duration) (sdk.C header := ctx.BlockHeader() header.Time = newBlockTime - header.Height = header.Height + 1 + header.Height++ newCtx := app.BaseApp.NewUncachedContext(false, header).WithHeaderInfo(coreheader.Info{ Height: header.Height, diff --git a/x/distribution/CHANGELOG.md b/x/distribution/CHANGELOG.md index 7bf4484c429c..f1c3f4c59689 100644 --- a/x/distribution/CHANGELOG.md +++ b/x/distribution/CHANGELOG.md @@ -31,6 +31,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### API Breaking Changes +* [#19445](https://github.com/cosmos/cosmos-sdk/pull/19445) `appmodule.Environment` is received on the Keeper to get access to different application services * [#17115](https://github.com/cosmos/cosmos-sdk/pull/17115) Use collections for `PreviousProposer` and `ValidatorSlashEvents`: * remove from `Keeper`: `GetPreviousProposerConsAddr`, `SetPreviousProposerConsAddr`, `GetValidatorHistoricalReferenceCount`, `GetValidatorSlashEvent`, `SetValidatorSlashEvent`. * [#16483](https://github.com/cosmos/cosmos-sdk/pull/16483) use collections for `DelegatorStartingInfo` state management: diff --git a/x/distribution/depinject.go b/x/distribution/depinject.go index 78b0fea3a2e4..09303459a44a 100644 --- a/x/distribution/depinject.go +++ b/x/distribution/depinject.go @@ -3,7 +3,6 @@ package distribution import ( modulev1 "cosmossdk.io/api/cosmos/distribution/module/v1" "cosmossdk.io/core/appmodule" - "cosmossdk.io/core/store" "cosmossdk.io/depinject" "cosmossdk.io/depinject/appconfig" authtypes "cosmossdk.io/x/auth/types" @@ -28,9 +27,9 @@ func init() { type ModuleInputs struct { depinject.In - Config *modulev1.Module - StoreService store.KVStoreService - Cdc codec.Codec + Config *modulev1.Module + Environment appmodule.Environment + Cdc codec.Codec AccountKeeper types.AccountKeeper BankKeeper types.BankKeeper @@ -60,7 +59,7 @@ func ProvideModule(in ModuleInputs) ModuleOutputs { k := keeper.NewKeeper( in.Cdc, - in.StoreService, + in.Environment, in.AccountKeeper, in.BankKeeper, in.StakingKeeper, diff --git a/x/distribution/keeper/abci.go b/x/distribution/keeper/abci.go index d4db46c60977..544b62e1e69e 100644 --- a/x/distribution/keeper/abci.go +++ b/x/distribution/keeper/abci.go @@ -11,6 +11,7 @@ import ( // BeginBlocker sets the proposer for determining distribution during endblock // and distribute rewards for the previous block. +// TODO: use context.Context after including the comet service func (k Keeper) BeginBlocker(ctx sdk.Context) error { defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) diff --git a/x/distribution/keeper/allocation.go b/x/distribution/keeper/allocation.go index 0e6f80ff1025..667a05c58377 100644 --- a/x/distribution/keeper/allocation.go +++ b/x/distribution/keeper/allocation.go @@ -6,6 +6,7 @@ import ( "cosmossdk.io/collections" "cosmossdk.io/core/comet" + "cosmossdk.io/core/event" "cosmossdk.io/math" "cosmossdk.io/x/distribution/types" @@ -103,14 +104,13 @@ func (k Keeper) AllocateTokensToValidator(ctx context.Context, val sdk.Validator } // update current commission - sdkCtx := sdk.UnwrapSDKContext(ctx) - sdkCtx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCommission, - sdk.NewAttribute(sdk.AttributeKeyAmount, commission.String()), - sdk.NewAttribute(types.AttributeKeyValidator, val.GetOperator()), - ), - ) + if err = k.environment.EventService.EventManager(ctx).EmitKV( + types.EventTypeCommission, + event.NewAttribute(sdk.AttributeKeyAmount, commission.String()), + event.NewAttribute(types.AttributeKeyValidator, val.GetOperator()), + ); err != nil { + return err + } currentCommission, err := k.ValidatorsAccumulatedCommission.Get(ctx, valBz) if err != nil && !errors.Is(err, collections.ErrNotFound) { return err @@ -136,13 +136,13 @@ func (k Keeper) AllocateTokensToValidator(ctx context.Context, val sdk.Validator } // update outstanding rewards - sdkCtx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeRewards, - sdk.NewAttribute(sdk.AttributeKeyAmount, tokens.String()), - sdk.NewAttribute(types.AttributeKeyValidator, val.GetOperator()), - ), - ) + if err = k.environment.EventService.EventManager(ctx).EmitKV( + types.EventTypeRewards, + event.NewAttribute(sdk.AttributeKeyAmount, tokens.String()), + event.NewAttribute(types.AttributeKeyValidator, val.GetOperator()), + ); err != nil { + return err + } outstanding, err := k.ValidatorOutstandingRewards.Get(ctx, valBz) if err != nil && !errors.Is(err, collections.ErrNotFound) { diff --git a/x/distribution/keeper/allocation_test.go b/x/distribution/keeper/allocation_test.go index f067964415d9..fbc79d8f514a 100644 --- a/x/distribution/keeper/allocation_test.go +++ b/x/distribution/keeper/allocation_test.go @@ -10,6 +10,7 @@ import ( "cosmossdk.io/collections" "cosmossdk.io/core/comet" "cosmossdk.io/core/header" + "cosmossdk.io/log" "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" @@ -29,7 +30,6 @@ import ( func TestAllocateTokensToValidatorWithCommission(t *testing.T) { ctrl := gomock.NewController(t) key := storetypes.NewKVStoreKey(disttypes.StoreKey) - storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) @@ -39,6 +39,8 @@ func TestAllocateTokensToValidatorWithCommission(t *testing.T) { accountKeeper := distrtestutil.NewMockAccountKeeper(ctrl) poolKeeper := distrtestutil.NewMockPoolKeeper(ctrl) + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + valCodec := address.NewBech32Codec("cosmosvaloper") accountKeeper.EXPECT().GetModuleAddress("distribution").Return(distrAcc.GetAddress()) @@ -46,7 +48,7 @@ func TestAllocateTokensToValidatorWithCommission(t *testing.T) { distrKeeper := keeper.NewKeeper( encCfg.Codec, - storeService, + env, accountKeeper, bankKeeper, stakingKeeper, @@ -88,7 +90,6 @@ func TestAllocateTokensToValidatorWithCommission(t *testing.T) { func TestAllocateTokensToManyValidators(t *testing.T) { ctrl := gomock.NewController(t) key := storetypes.NewKVStoreKey(disttypes.StoreKey) - storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) @@ -103,9 +104,11 @@ func TestAllocateTokensToManyValidators(t *testing.T) { accountKeeper.EXPECT().GetModuleAccount(gomock.Any(), "fee_collector").Return(feeCollectorAcc) stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec("cosmosvaloper")).AnyTimes() + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + distrKeeper := keeper.NewKeeper( encCfg.Codec, - storeService, + env, accountKeeper, bankKeeper, stakingKeeper, @@ -219,7 +222,6 @@ func TestAllocateTokensToManyValidators(t *testing.T) { func TestAllocateTokensTruncation(t *testing.T) { ctrl := gomock.NewController(t) key := storetypes.NewKVStoreKey(disttypes.StoreKey) - storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) @@ -234,9 +236,11 @@ func TestAllocateTokensTruncation(t *testing.T) { accountKeeper.EXPECT().GetModuleAccount(gomock.Any(), "fee_collector").Return(feeCollectorAcc) stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec("cosmosvaloper")).AnyTimes() + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + distrKeeper := keeper.NewKeeper( encCfg.Codec, - storeService, + env, accountKeeper, bankKeeper, stakingKeeper, diff --git a/x/distribution/keeper/delegation.go b/x/distribution/keeper/delegation.go index 36482b407b68..50c4e6e8799f 100644 --- a/x/distribution/keeper/delegation.go +++ b/x/distribution/keeper/delegation.go @@ -6,6 +6,7 @@ import ( "fmt" "cosmossdk.io/collections" + "cosmossdk.io/core/event" "cosmossdk.io/math" "cosmossdk.io/x/distribution/types" @@ -41,8 +42,8 @@ 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()) - sdkCtx := sdk.UnwrapSDKContext(ctx) - return k.DelegatorStartingInfo.Set(ctx, collections.Join(val, del), types.NewDelegatorStartingInfo(previousPeriod, stake, uint64(sdkCtx.BlockHeight()))) + headerinfo := k.environment.HeaderService.GetHeaderInfo(ctx) + return k.DelegatorStartingInfo.Set(ctx, collections.Join(val, del), types.NewDelegatorStartingInfo(previousPeriod, stake, uint64(headerinfo.Height))) } // calculate the rewards accrued by a delegation between two periods @@ -103,9 +104,8 @@ func (k Keeper) CalculateDelegationRewards(ctx context.Context, val sdk.Validato return sdk.DecCoins{}, err } - sdkCtx := sdk.UnwrapSDKContext(ctx) - if startingInfo.Height == uint64(sdkCtx.BlockHeight()) { - // started this height, no rewards yet + headerinfo := k.environment.HeaderService.GetHeaderInfo(ctx) + if startingInfo.Height == uint64(headerinfo.Height) { // started this height, no rewards yet return sdk.DecCoins{}, nil } @@ -122,7 +122,7 @@ func (k Keeper) CalculateDelegationRewards(ctx context.Context, val sdk.Validato startingHeight := startingInfo.Height // Slashes this block happened after reward allocation, but we have to account // for them for the stake sanity check below. - endingHeight := uint64(sdkCtx.BlockHeight()) + endingHeight := uint64(headerinfo.Height) var iterErr error if endingHeight > startingHeight { err = k.IterateValidatorSlashEventsBetween(ctx, valAddr, startingHeight, endingHeight, @@ -313,15 +313,15 @@ func (k Keeper) withdrawDelegationRewards(ctx context.Context, val sdk.Validator finalRewards = sdk.Coins{sdk.NewCoin(baseDenom, math.ZeroInt())} } - sdkCtx := sdk.UnwrapSDKContext(ctx) - sdkCtx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeWithdrawRewards, - sdk.NewAttribute(sdk.AttributeKeyAmount, finalRewards.String()), - sdk.NewAttribute(types.AttributeKeyValidator, val.GetOperator()), - sdk.NewAttribute(types.AttributeKeyDelegator, del.GetDelegatorAddr()), - ), + err = k.environment.EventService.EventManager(ctx).EmitKV( + types.EventTypeWithdrawRewards, + event.NewAttribute(sdk.AttributeKeyAmount, finalRewards.String()), + event.NewAttribute(types.AttributeKeyValidator, val.GetOperator()), + event.NewAttribute(types.AttributeKeyDelegator, del.GetDelegatorAddr()), ) + if err != nil { + return nil, err + } return finalRewards, nil } diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go index 140249e62741..09970ed39a55 100644 --- a/x/distribution/keeper/delegation_test.go +++ b/x/distribution/keeper/delegation_test.go @@ -8,6 +8,7 @@ import ( "cosmossdk.io/collections" "cosmossdk.io/core/header" + "cosmossdk.io/log" "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" @@ -27,7 +28,6 @@ import ( func TestCalculateRewardsBasic(t *testing.T) { ctrl := gomock.NewController(t) key := storetypes.NewKVStoreKey(disttypes.StoreKey) - storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1}) @@ -41,9 +41,11 @@ func TestCalculateRewardsBasic(t *testing.T) { stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec(sdk.Bech32PrefixValAddr)).AnyTimes() accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec(sdk.Bech32MainPrefix)).AnyTimes() + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + distrKeeper := keeper.NewKeeper( encCfg.Codec, - storeService, + env, accountKeeper, bankKeeper, stakingKeeper, @@ -72,7 +74,7 @@ func TestCalculateRewardsBasic(t *testing.T) { err = distrtestutil.CallCreateValidatorHooks(ctx, distrKeeper, addr, valAddr) require.NoError(t, err) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 1}) // historical count should be 2 (once for validator init, once for delegation init) require.Equal(t, 2, getValHistoricalReferenceCount(distrKeeper, ctx)) @@ -129,7 +131,6 @@ func getValHistoricalReferenceCount(k keeper.Keeper, ctx sdk.Context) int { func TestCalculateRewardsAfterSlash(t *testing.T) { ctrl := gomock.NewController(t) key := storetypes.NewKVStoreKey(disttypes.StoreKey) - storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1}) @@ -143,9 +144,11 @@ func TestCalculateRewardsAfterSlash(t *testing.T) { stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec(sdk.Bech32PrefixValAddr)).AnyTimes() accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec(sdk.Bech32MainPrefix)).AnyTimes() + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + distrKeeper := keeper.NewKeeper( encCfg.Codec, - storeService, + env, accountKeeper, bankKeeper, stakingKeeper, @@ -178,7 +181,7 @@ func TestCalculateRewardsAfterSlash(t *testing.T) { require.NoError(t, err) // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 1}) // end period endingPeriod, _ := distrKeeper.IncrementValidatorPeriod(ctx, val) @@ -191,7 +194,7 @@ func TestCalculateRewardsAfterSlash(t *testing.T) { require.True(t, rewards.IsZero()) // start out block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 3}) // slash the validator by 50% (simulated with manual calls; we assume the validator is bonded) slashedTokens := distrtestutil.SlashValidator( @@ -207,7 +210,7 @@ func TestCalculateRewardsAfterSlash(t *testing.T) { require.True(t, slashedTokens.IsPositive(), "expected positive slashed tokens, got: %s", slashedTokens) // increase block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 3}) // allocate some rewards initial := sdk.TokensFromConsensusPower(10, sdk.DefaultPowerReduction) @@ -234,7 +237,6 @@ func TestCalculateRewardsAfterSlash(t *testing.T) { func TestCalculateRewardsAfterManySlashes(t *testing.T) { ctrl := gomock.NewController(t) key := storetypes.NewKVStoreKey(disttypes.StoreKey) - storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1}) @@ -248,9 +250,11 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec(sdk.Bech32PrefixValAddr)).AnyTimes() accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec(sdk.Bech32MainPrefix)).AnyTimes() + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + distrKeeper := keeper.NewKeeper( encCfg.Codec, - storeService, + env, accountKeeper, bankKeeper, stakingKeeper, @@ -282,7 +286,7 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { require.NoError(t, err) // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 1}) // end period endingPeriod, _ := distrKeeper.IncrementValidatorPeriod(ctx, val) @@ -295,7 +299,7 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { require.True(t, rewards.IsZero()) // start out block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 3}) // slash the validator by 50% (simulated with manual calls; we assume the validator is bonded) slashedTokens := distrtestutil.SlashValidator( @@ -314,7 +318,7 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val, nil).Times(1) // increase block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 3}) // allocate some rewards initial := sdk.TokensFromConsensusPower(10, sdk.DefaultPowerReduction) @@ -335,7 +339,7 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { require.True(t, slashedTokens.IsPositive(), "expected positive slashed tokens, got: %s", slashedTokens) // increase block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 3}) // allocate some more rewards require.NoError(t, distrKeeper.AllocateTokensToValidator(ctx, val, tokens)) @@ -360,7 +364,6 @@ func TestCalculateRewardsAfterManySlashes(t *testing.T) { func TestCalculateRewardsMultiDelegator(t *testing.T) { ctrl := gomock.NewController(t) key := storetypes.NewKVStoreKey(disttypes.StoreKey) - storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1}) @@ -374,9 +377,11 @@ func TestCalculateRewardsMultiDelegator(t *testing.T) { stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec(sdk.Bech32PrefixValAddr)).AnyTimes() accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec(sdk.Bech32MainPrefix)).AnyTimes() + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + distrKeeper := keeper.NewKeeper( encCfg.Codec, - storeService, + env, accountKeeper, bankKeeper, stakingKeeper, @@ -408,7 +413,7 @@ func TestCalculateRewardsMultiDelegator(t *testing.T) { require.NoError(t, err) // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 1}) // allocate some rewards initial := int64(20) @@ -428,7 +433,7 @@ func TestCalculateRewardsMultiDelegator(t *testing.T) { require.NoError(t, err) // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 1}) // allocate some more rewards require.NoError(t, distrKeeper.AllocateTokensToValidator(ctx, val, tokens)) @@ -459,7 +464,6 @@ func TestCalculateRewardsMultiDelegator(t *testing.T) { func TestWithdrawDelegationRewardsBasic(t *testing.T) { ctrl := gomock.NewController(t) key := storetypes.NewKVStoreKey(disttypes.StoreKey) - storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1}) @@ -473,9 +477,11 @@ func TestWithdrawDelegationRewardsBasic(t *testing.T) { stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec(sdk.Bech32PrefixValAddr)).AnyTimes() accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec(sdk.Bech32MainPrefix)).AnyTimes() + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + distrKeeper := keeper.NewKeeper( encCfg.Codec, - storeService, + env, accountKeeper, bankKeeper, stakingKeeper, @@ -506,7 +512,7 @@ func TestWithdrawDelegationRewardsBasic(t *testing.T) { require.NoError(t, err) // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 1}) // allocate some rewards initial := sdk.TokensFromConsensusPower(10, sdk.DefaultPowerReduction) @@ -536,7 +542,6 @@ func TestWithdrawDelegationRewardsBasic(t *testing.T) { func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { ctrl := gomock.NewController(t) key := storetypes.NewKVStoreKey(disttypes.StoreKey) - storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1}) @@ -550,9 +555,11 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec(sdk.Bech32PrefixValAddr)).AnyTimes() accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec(sdk.Bech32MainPrefix)).AnyTimes() + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + distrKeeper := keeper.NewKeeper( encCfg.Codec, - storeService, + env, accountKeeper, bankKeeper, stakingKeeper, @@ -583,7 +590,7 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { require.NoError(t, err) // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 1}) // end period endingPeriod, _ := distrKeeper.IncrementValidatorPeriod(ctx, val) @@ -596,7 +603,7 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { require.True(t, rewards.IsZero()) // start out block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 3}) // allocate some rewards initial := math.LegacyNewDecFromInt(sdk.TokensFromConsensusPower(10, sdk.DefaultPowerReduction)) @@ -630,7 +637,7 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { ) // increase block height - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 3}) // allocate some more rewards require.NoError(t, distrKeeper.AllocateTokensToValidator(ctx, val, tokens)) @@ -654,7 +661,6 @@ func TestCalculateRewardsAfterManySlashesInSameBlock(t *testing.T) { func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { ctrl := gomock.NewController(t) key := storetypes.NewKVStoreKey(disttypes.StoreKey) - storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1}) @@ -668,9 +674,11 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec(sdk.Bech32PrefixValAddr)).AnyTimes() accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec(sdk.Bech32MainPrefix)).AnyTimes() + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + distrKeeper := keeper.NewKeeper( encCfg.Codec, - storeService, + env, accountKeeper, bankKeeper, stakingKeeper, @@ -703,7 +711,7 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val, nil).Times(2) // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 1}) // allocate some rewards initial := math.LegacyNewDecFromInt(sdk.TokensFromConsensusPower(30, sdk.DefaultPowerReduction)) @@ -711,7 +719,8 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { require.NoError(t, distrKeeper.AllocateTokensToValidator(ctx, val, tokens)) // slash the validator - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 3}) + distrtestutil.SlashValidator( ctx, valConsAddr0, @@ -722,7 +731,7 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { &distrKeeper, stakingKeeper, ) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 3}) // update validator mock stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val, nil).Times(1) @@ -748,13 +757,14 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { require.NoError(t, err) // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 1}) // allocate some more rewards require.NoError(t, distrKeeper.AllocateTokensToValidator(ctx, val, tokens)) // slash the validator again - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 3}) + distrtestutil.SlashValidator( ctx, valConsAddr0, @@ -765,7 +775,7 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { &distrKeeper, stakingKeeper, ) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 3) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 3}) // end period endingPeriod, _ := distrKeeper.IncrementValidatorPeriod(ctx, val) @@ -793,7 +803,6 @@ func TestCalculateRewardsMultiDelegatorMultiSlash(t *testing.T) { func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { ctrl := gomock.NewController(t) key := storetypes.NewKVStoreKey(disttypes.StoreKey) - storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1}) @@ -807,9 +816,11 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { stakingKeeper.EXPECT().ValidatorAddressCodec().Return(address.NewBech32Codec(sdk.Bech32PrefixValAddr)).AnyTimes() accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec(sdk.Bech32MainPrefix)).AnyTimes() + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + distrKeeper := keeper.NewKeeper( encCfg.Codec, - storeService, + env, accountKeeper, bankKeeper, stakingKeeper, @@ -840,7 +851,7 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val, nil).Times(2) // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 1}) // allocate some rewards initial := int64(20) @@ -874,7 +885,7 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { require.Equal(t, 3, getValHistoricalReferenceCount(distrKeeper, ctx)) // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 1}) // allocate some more rewards require.NoError(t, distrKeeper.AllocateTokensToValidator(ctx, val, tokens)) @@ -923,7 +934,7 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { require.True(t, valCommission.Commission.IsZero()) // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 1}) // allocate some more rewards require.NoError(t, distrKeeper.AllocateTokensToValidator(ctx, val, tokens)) @@ -957,7 +968,7 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { require.Equal(t, sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: math.LegacyNewDec(initial / 2)}}, valCommission.Commission) // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 1}) // allocate some more rewards require.NoError(t, distrKeeper.AllocateTokensToValidator(ctx, val, tokens)) @@ -994,7 +1005,6 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { func Test100PercentCommissionReward(t *testing.T) { ctrl := gomock.NewController(t) key := storetypes.NewKVStoreKey(disttypes.StoreKey) - storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1}) @@ -1009,9 +1019,11 @@ func Test100PercentCommissionReward(t *testing.T) { stakingKeeper.EXPECT().BondDenom(gomock.Any()).Return("stake", nil).AnyTimes() accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec(sdk.Bech32MainPrefix)).AnyTimes() + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + distrKeeper := keeper.NewKeeper( encCfg.Codec, - storeService, + env, accountKeeper, bankKeeper, stakingKeeper, @@ -1042,7 +1054,7 @@ func Test100PercentCommissionReward(t *testing.T) { stakingKeeper.EXPECT().Validator(gomock.Any(), valAddr).Return(val, nil).Times(2) // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 1}) // allocate some rewards initial := int64(20) @@ -1050,19 +1062,19 @@ func Test100PercentCommissionReward(t *testing.T) { require.NoError(t, distrKeeper.AllocateTokensToValidator(ctx, val, tokens)) // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 1}) // allocate some rewards require.NoError(t, distrKeeper.AllocateTokensToValidator(ctx, val, tokens)) // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 1}) // allocate some more rewards require.NoError(t, distrKeeper.AllocateTokensToValidator(ctx, val, tokens)) // next block - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) + ctx = ctx.WithHeaderInfo(header.Info{Height: ctx.HeaderInfo().Height + 1}) // allocate some more rewards require.NoError(t, distrKeeper.AllocateTokensToValidator(ctx, val, tokens)) diff --git a/x/distribution/keeper/keeper.go b/x/distribution/keeper/keeper.go index 1b018349b8e9..fab55212f68b 100644 --- a/x/distribution/keeper/keeper.go +++ b/x/distribution/keeper/keeper.go @@ -8,7 +8,8 @@ import ( "cosmossdk.io/collections" collcodec "cosmossdk.io/collections/codec" - "cosmossdk.io/core/store" + "cosmossdk.io/core/appmodule" + "cosmossdk.io/core/event" errorsmod "cosmossdk.io/errors" "cosmossdk.io/log" "cosmossdk.io/x/distribution/types" @@ -20,7 +21,7 @@ import ( // Keeper of the distribution store type Keeper struct { - storeService store.KVStoreService + environment appmodule.Environment cdc codec.BinaryCodec authKeeper types.AccountKeeper bankKeeper types.BankKeeper @@ -57,7 +58,7 @@ type Keeper struct { // NewKeeper creates a new distribution Keeper instance func NewKeeper( - cdc codec.BinaryCodec, storeService store.KVStoreService, + cdc codec.BinaryCodec, env appmodule.Environment, ak types.AccountKeeper, bk types.BankKeeper, sk types.StakingKeeper, pk types.PoolKeeper, feeCollectorName, authority string, ) Keeper { @@ -66,9 +67,9 @@ func NewKeeper( panic(fmt.Sprintf("%s module account has not been set", types.ModuleName)) } - sb := collections.NewSchemaBuilder(storeService) + sb := collections.NewSchemaBuilder(env.KVStoreService) k := Keeper{ - storeService: storeService, + environment: env, cdc: cdc, authKeeper: ak, bankKeeper: bk, @@ -146,8 +147,7 @@ func (k Keeper) GetAuthority() string { // Logger returns a module-specific logger. func (k Keeper) Logger(ctx context.Context) log.Logger { - sdkCtx := sdk.UnwrapSDKContext(ctx) - return sdkCtx.Logger().With(log.ModuleKey, "x/"+types.ModuleName) + return k.environment.Logger.With(log.ModuleKey, "x/"+types.ModuleName) } // SetWithdrawAddr sets a new address that will receive the rewards upon withdrawal @@ -165,13 +165,12 @@ func (k Keeper) SetWithdrawAddr(ctx context.Context, delegatorAddr, withdrawAddr return types.ErrSetWithdrawAddrDisabled } - sdkCtx := sdk.UnwrapSDKContext(ctx) - sdkCtx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeSetWithdrawAddress, - sdk.NewAttribute(types.AttributeKeyWithdrawAddress, withdrawAddr.String()), - ), - ) + if err = k.environment.EventService.EventManager(ctx).EmitKV( + types.EventTypeSetWithdrawAddress, + event.NewAttribute(types.AttributeKeyWithdrawAddress, withdrawAddr.String()), + ); err != nil { + return err + } return k.DelegatorsWithdrawAddress.Set(ctx, delegatorAddr, withdrawAddr) } @@ -251,13 +250,13 @@ func (k Keeper) WithdrawValidatorCommission(ctx context.Context, valAddr sdk.Val } } - sdkCtx := sdk.UnwrapSDKContext(ctx) - sdkCtx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeWithdrawCommission, - sdk.NewAttribute(sdk.AttributeKeyAmount, commission.String()), - ), + err = k.environment.EventService.EventManager(ctx).EmitKV( + types.EventTypeWithdrawCommission, + event.NewAttribute(sdk.AttributeKeyAmount, commission.String()), ) + if err != nil { + return nil, err + } return commission, nil } diff --git a/x/distribution/keeper/keeper_test.go b/x/distribution/keeper/keeper_test.go index 65acdccab18e..0a1a64eb53e2 100644 --- a/x/distribution/keeper/keeper_test.go +++ b/x/distribution/keeper/keeper_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/require" "cosmossdk.io/core/header" + "cosmossdk.io/log" "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" authtypes "cosmossdk.io/x/auth/types" @@ -36,7 +37,6 @@ func initFixture(t *testing.T) (sdk.Context, []sdk.AccAddress, keeper.Keeper, de ctrl := gomock.NewController(t) key := storetypes.NewKVStoreKey(types.StoreKey) - storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) encCfg := moduletestutil.MakeTestEncodingConfig(distribution.AppModule{}) ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) @@ -56,9 +56,11 @@ func initFixture(t *testing.T) (sdk.Context, []sdk.AccAddress, keeper.Keeper, de bankKeeper.EXPECT().BlockedAddr(withdrawAddr).Return(false).AnyTimes() bankKeeper.EXPECT().BlockedAddr(distrAcc.GetAddress()).Return(true).AnyTimes() + env := runtime.NewEnvironment(runtime.NewKVStoreService(key), log.NewNopLogger()) + distrKeeper := keeper.NewKeeper( encCfg.Codec, - storeService, + env, accountKeeper, bankKeeper, stakingKeeper, diff --git a/x/distribution/keeper/migrations.go b/x/distribution/keeper/migrations.go index 6d32eae61ebe..28b014c4ea7c 100644 --- a/x/distribution/keeper/migrations.go +++ b/x/distribution/keeper/migrations.go @@ -33,7 +33,7 @@ func (m Migrator) Migrate2to3(ctx context.Context) error { // Migrate3to4 migrates the x/distribution module state to use collections // Additionally it migrates distribution fee pool to use protocol pool module account func (m Migrator) Migrate3to4(ctx context.Context) error { - if err := v4.MigrateStore(ctx, m.keeper.storeService, m.keeper.cdc); err != nil { + if err := v4.MigrateStore(ctx, m.keeper.environment, m.keeper.cdc); err != nil { return err } diff --git a/x/distribution/keeper/validator.go b/x/distribution/keeper/validator.go index fe87cd34821f..fe39d44f4337 100644 --- a/x/distribution/keeper/validator.go +++ b/x/distribution/keeper/validator.go @@ -155,7 +155,7 @@ func (k Keeper) updateValidatorSlashFraction(ctx context.Context, valAddr sdk.Va panic(fmt.Sprintf("fraction must be >=0 and <=1, current fraction: %v", fraction)) } - sdkCtx := sdk.UnwrapSDKContext(ctx) + headerinfo := k.environment.HeaderService.GetHeaderInfo(ctx) val, err := k.stakingKeeper.Validator(ctx, valAddr) if err != nil { return err @@ -174,8 +174,7 @@ func (k Keeper) updateValidatorSlashFraction(ctx context.Context, valAddr sdk.Va } slashEvent := types.NewValidatorSlashEvent(newPeriod, fraction) - height := uint64(sdkCtx.BlockHeight()) - + height := uint64(headerinfo.Height) return k.ValidatorSlashEvents.Set( ctx, collections.Join3[sdk.ValAddress, uint64, uint64]( diff --git a/x/distribution/migrations/v4/migrate.go b/x/distribution/migrations/v4/migrate.go index b09902b0dd22..355bd854a65a 100644 --- a/x/distribution/migrations/v4/migrate.go +++ b/x/distribution/migrations/v4/migrate.go @@ -8,6 +8,7 @@ import ( "cosmossdk.io/collections" collcodec "cosmossdk.io/collections/codec" + "cosmossdk.io/core/appmodule" "cosmossdk.io/core/store" "github.com/cosmos/cosmos-sdk/codec" @@ -19,8 +20,8 @@ var ( NewProposerKey = collections.NewPrefix(1) ) -func MigrateStore(ctx context.Context, storeService store.KVStoreService, cdc codec.BinaryCodec) error { - store := storeService.OpenKVStore(ctx) +func MigrateStore(ctx context.Context, env appmodule.Environment, cdc codec.BinaryCodec) error { + store := env.KVStoreService.OpenKVStore(ctx) bz, err := store.Get(OldProposerKey) if err != nil { return err @@ -37,7 +38,7 @@ func MigrateStore(ctx context.Context, storeService store.KVStoreService, cdc co return err } - sb := collections.NewSchemaBuilder(storeService) + sb := collections.NewSchemaBuilder(env.KVStoreService) prevProposer := collections.NewItem(sb, NewProposerKey, "previous_proposer", collcodec.KeyToValueCodec(sdk.ConsAddressKey)) _, err = sb.Build() if err != nil { diff --git a/x/distribution/migrations/v4/migrate_funds_test.go b/x/distribution/migrations/v4/migrate_funds_test.go index 86c0262c1d5f..9ccf4f81ad4f 100644 --- a/x/distribution/migrations/v4/migrate_funds_test.go +++ b/x/distribution/migrations/v4/migrate_funds_test.go @@ -72,7 +72,7 @@ func TestFundsMigration(t *testing.T) { // create distribution keeper distrKeeper := keeper.NewKeeper( encCfg.Codec, - runtime.NewKVStoreService(keys[disttypes.StoreKey]), + runtime.NewEnvironment(runtime.NewKVStoreService(keys[disttypes.StoreKey]), log.NewNopLogger()), accountKeeper, bankKeeper, stakingKeeper, diff --git a/x/distribution/migrations/v4/migrate_test.go b/x/distribution/migrations/v4/migrate_test.go index 86001ccd12ac..ed4cc8f79868 100644 --- a/x/distribution/migrations/v4/migrate_test.go +++ b/x/distribution/migrations/v4/migrate_test.go @@ -7,6 +7,7 @@ import ( "cosmossdk.io/collections" collcodec "cosmossdk.io/collections/codec" + "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/distribution" v4 "cosmossdk.io/x/distribution/migrations/v4" @@ -25,6 +26,8 @@ func TestMigration(t *testing.T) { tKey := storetypes.NewTransientStoreKey("transient_test") ctx := testutil.DefaultContext(storeKey, tKey) + env := runtime.NewEnvironment(storeService, log.NewNopLogger()) + addr1 := secp256k1.GenPrivKey().PubKey().Address() consAddr1 := sdk.ConsAddress(addr1) @@ -35,7 +38,7 @@ func TestMigration(t *testing.T) { require.NoError(t, err) require.Equal(t, consAddr1, gotAddr) - err = v4.MigrateStore(ctx, storeService, cdc) + err = v4.MigrateStore(ctx, env, cdc) require.NoError(t, err) sb := collections.NewSchemaBuilder(storeService) diff --git a/x/distribution/module.go b/x/distribution/module.go index 2caf7ab534ee..c9e351eb93e4 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -161,7 +161,7 @@ func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } // BeginBlock returns the begin blocker for the distribution module. func (am AppModule) BeginBlock(ctx context.Context) error { - c := sdk.UnwrapSDKContext(ctx) + c := sdk.UnwrapSDKContext(ctx) // TODO: remove and use context.Context after including the comet service return am.keeper.BeginBlocker(c) }