Skip to content

Commit

Permalink
feat(x/distribution): add env bundler to distribution module (cosmos#…
Browse files Browse the repository at this point in the history
…19445)

Co-authored-by: marbar3778 <[email protected]>
  • Loading branch information
likhita-809 and tac0turtle authored Feb 27, 2024
1 parent 8585d53 commit a248d05
Show file tree
Hide file tree
Showing 19 changed files with 150 additions and 125 deletions.
9 changes: 7 additions & 2 deletions baseapp/abci.go
Original file line number Diff line number Diff line change
Expand Up @@ -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})
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion simapp/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/distribution/keeper/msg_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
5 changes: 2 additions & 3 deletions testutil/sims/app_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions x/distribution/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
9 changes: 4 additions & 5 deletions x/distribution/depinject.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
Expand Down Expand Up @@ -60,7 +59,7 @@ func ProvideModule(in ModuleInputs) ModuleOutputs {

k := keeper.NewKeeper(
in.Cdc,
in.StoreService,
in.Environment,
in.AccountKeeper,
in.BankKeeper,
in.StakingKeeper,
Expand Down
1 change: 1 addition & 0 deletions x/distribution/keeper/abci.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
30 changes: 15 additions & 15 deletions x/distribution/keeper/allocation.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (

"cosmossdk.io/collections"
"cosmossdk.io/core/comet"
"cosmossdk.io/core/event"
"cosmossdk.io/math"
"cosmossdk.io/x/distribution/types"

Expand Down Expand Up @@ -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
Expand All @@ -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) {
Expand Down
16 changes: 10 additions & 6 deletions x/distribution/keeper/allocation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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()})
Expand All @@ -39,14 +39,16 @@ 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())
stakingKeeper.EXPECT().ValidatorAddressCodec().Return(valCodec).AnyTimes()

distrKeeper := keeper.NewKeeper(
encCfg.Codec,
storeService,
env,
accountKeeper,
bankKeeper,
stakingKeeper,
Expand Down Expand Up @@ -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()})
Expand All @@ -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,
Expand Down Expand Up @@ -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()})
Expand All @@ -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,
Expand Down
28 changes: 14 additions & 14 deletions x/distribution/keeper/delegation.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"

"cosmossdk.io/collections"
"cosmossdk.io/core/event"
"cosmossdk.io/math"
"cosmossdk.io/x/distribution/types"

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
}

Expand All @@ -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,
Expand Down Expand Up @@ -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
}
Loading

0 comments on commit a248d05

Please sign in to comment.