diff --git a/CHANGELOG.md b/CHANGELOG.md index 4fc1a5c648d..1c9c2bd0f22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -147,6 +147,9 @@ Ref: https://keepachangelog.com/en/1.0.0/ * `WithChainID` / `WithBlockHeight` / `WithBlockHeader` must be used to set values on the context * (x/bank) [#17569](https://github.com/cosmos/cosmos-sdk/pull/17569) `BurnCoins` takes an address instead of a module name * (x/distribution) [#17670](https://github.com/cosmos/cosmos-sdk/pull/17670) `AllocateTokens` takes `comet.VoteInfos` instead of `[]abci.VoteInfo` +* (types) [#17738](https://github.com/cosmos/cosmos-sdk/pull/17738) `WithBlockTime()` was removed & `BlockTime()` were deprecated in favor of `WithHeaderInfo()` & `HeaderInfo()`. `BlockTime` now gets data from `HeaderInfo()` instead of `BlockHeader()`. +* (client) [#17746](https://github.com/cosmos/cosmos-sdk/pull/17746) `txEncodeAmino` & `txDecodeAmino` txs via grpc and rest were removed + * `RegisterLegacyAmino` was removed from `AppModuleBasic` ### CLI Breaking Changes diff --git a/baseapp/abci.go b/baseapp/abci.go index a7747cb0ef4..20c01e1067f 100644 --- a/baseapp/abci.go +++ b/baseapp/abci.go @@ -426,7 +426,6 @@ func (app *BaseApp) PrepareProposal(req *abci.RequestPrepareProposal) (resp *abc app.prepareProposalState.ctx = app.getContextForProposal(app.prepareProposalState.ctx, req.Height). WithVoteInfos(toVoteInfo(req.LocalLastCommit.Votes)). // this is a set of votes that are not finalized yet, wait for commit WithBlockHeight(req.Height). - WithBlockTime(req.Time). WithProposer(req.ProposerAddress). WithExecMode(sdk.ExecModePrepareProposal). WithCometInfo(corecomet.Info{ @@ -519,7 +518,6 @@ func (app *BaseApp) ProcessProposal(req *abci.RequestProcessProposal) (resp *abc app.processProposalState.ctx = app.getContextForProposal(app.processProposalState.ctx, req.Height). WithVoteInfos(req.ProposedLastCommit.Votes). // this is a set of votes that are not finalized yet, wait for commit WithBlockHeight(req.Height). - WithBlockTime(req.Time). WithHeaderHash(req.Hash). WithProposer(req.ProposerAddress). WithCometInfo(corecomet.Info{ @@ -1220,7 +1218,7 @@ func (app *BaseApp) CreateQueryContext(height int64, prove bool) (sdk.Context, e if ok { cInfo, err := rms.GetCommitInfo(height) if cInfo != nil && err == nil { - ctx = ctx.WithBlockTime(cInfo.Timestamp) + ctx = ctx.WithHeaderInfo(coreheader.Info{Time: cInfo.Timestamp}) } } } diff --git a/client/grpc/node/service.go b/client/grpc/node/service.go index 0d4f27a4293..a83b7b5bd80 100644 --- a/client/grpc/node/service.go +++ b/client/grpc/node/service.go @@ -48,7 +48,7 @@ func (s queryServer) Config(ctx context.Context, _ *ConfigRequest) (*ConfigRespo func (s queryServer) Status(ctx context.Context, _ *StatusRequest) (*StatusResponse, error) { sdkCtx := sdk.UnwrapSDKContext(ctx) - blockTime := sdkCtx.BlockTime() + blockTime := sdkCtx.HeaderInfo().Time return &StatusResponse{ // TODO: Get earliest version from store. diff --git a/tests/integration/auth/migrations/v2/store_test.go b/tests/integration/auth/migrations/v2/store_test.go index 7d441a66b75..384adbe2e31 100644 --- a/tests/integration/auth/migrations/v2/store_test.go +++ b/tests/integration/auth/migrations/v2/store_test.go @@ -6,9 +6,9 @@ import ( "testing" "time" - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/stretchr/testify/require" + "cosmossdk.io/core/header" "cosmossdk.io/depinject" "cosmossdk.io/log" sdkmath "cosmossdk.io/math" @@ -73,7 +73,8 @@ func TestMigrateVestingAccounts(t *testing.T) { legacySubspace := newMockSubspace(authtypes.DefaultParams()) require.NoError(t, v4.Migrate(ctx, storeService, legacySubspace, cdc)) - ctx = app.BaseApp.NewContextLegacy(false, cmtproto.Header{Time: time.Now()}) + ctx = app.BaseApp.NewContext(false) + ctx = ctx.WithHeaderInfo(header.Info{Time: time.Now()}) err = stakingKeeper.SetParams(ctx, stakingtypes.DefaultParams()) require.NoError(t, err) lastAccNum := uint64(1000) @@ -99,10 +100,10 @@ func TestMigrateVestingAccounts(t *testing.T) { bondDenom, err := stakingKeeper.BondDenom(ctx) require.NoError(t, err) vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(200))) - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().Unix()) + delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.HeaderInfo().Time.Unix()) require.NoError(t, err) - ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) + ctx = ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.AddDate(1, 0, 0)}) err = accountKeeper.Params.Set(ctx, authtypes.DefaultParams()) require.NoError(t, err) @@ -129,10 +130,10 @@ func TestMigrateVestingAccounts(t *testing.T) { require.NoError(t, err) baseAccount := createBaseAccount(delegatorAddr) vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(200))) - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().Unix()) + delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.HeaderInfo().Time.Unix()) require.NoError(t, err) - ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) + ctx = ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.AddDate(1, 0, 0)}) accountKeeper.SetAccount(ctx, delayedAccount) @@ -152,10 +153,10 @@ func TestMigrateVestingAccounts(t *testing.T) { bondDenom, err := stakingKeeper.BondDenom(ctx) require.NoError(t, err) vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(200))) - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().Unix()) + delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.HeaderInfo().Time.Unix()) require.NoError(t, err) - ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) + ctx = ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.AddDate(1, 0, 0)}) accountKeeper.SetAccount(ctx, delayedAccount) @@ -179,7 +180,7 @@ func TestMigrateVestingAccounts(t *testing.T) { bondDenom, err := stakingKeeper.BondDenom(ctx) require.NoError(t, err) vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(200))) - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().AddDate(1, 0, 0).Unix()) + delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.HeaderInfo().Time.AddDate(1, 0, 0).Unix()) require.NoError(t, err) accountKeeper.SetAccount(ctx, delayedAccount) @@ -200,7 +201,7 @@ func TestMigrateVestingAccounts(t *testing.T) { bondDenom, err := stakingKeeper.BondDenom(ctx) require.NoError(t, err) vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(200))) - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().AddDate(1, 0, 0).Unix()) + delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.HeaderInfo().Time.AddDate(1, 0, 0).Unix()) require.NoError(t, err) accountKeeper.SetAccount(ctx, delayedAccount) @@ -225,7 +226,7 @@ func TestMigrateVestingAccounts(t *testing.T) { bondDenom, err := stakingKeeper.BondDenom(ctx) require.NoError(t, err) vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(300))) - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().AddDate(1, 0, 0).Unix()) + delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.HeaderInfo().Time.AddDate(1, 0, 0).Unix()) require.NoError(t, err) accountKeeper.SetAccount(ctx, delayedAccount) @@ -250,7 +251,7 @@ func TestMigrateVestingAccounts(t *testing.T) { bondDenom, err := stakingKeeper.BondDenom(ctx) require.NoError(t, err) vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(300))) - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().AddDate(1, 0, 0).Unix()) + delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.HeaderInfo().Time.AddDate(1, 0, 0).Unix()) require.NoError(t, err) accountKeeper.SetAccount(ctx, delayedAccount) @@ -271,10 +272,10 @@ func TestMigrateVestingAccounts(t *testing.T) { bondDenom, err := stakingKeeper.BondDenom(ctx) require.NoError(t, err) vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(300))) - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().Unix()) + delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.HeaderInfo().Time.Unix()) require.NoError(t, err) - ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) + ctx = ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.AddDate(1, 0, 0)}) accountKeeper.SetAccount(ctx, delayedAccount) @@ -290,8 +291,8 @@ func TestMigrateVestingAccounts(t *testing.T) { { "continuous vesting, start time after blocktime", func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - startTime := ctx.BlockTime().AddDate(1, 0, 0).Unix() - endTime := ctx.BlockTime().AddDate(2, 0, 0).Unix() + startTime := ctx.HeaderInfo().Time.AddDate(1, 0, 0).Unix() + endTime := ctx.HeaderInfo().Time.AddDate(2, 0, 0).Unix() baseAccount := createBaseAccount(delegatorAddr) bondDenom, err := stakingKeeper.BondDenom(ctx) require.NoError(t, err) @@ -299,7 +300,7 @@ func TestMigrateVestingAccounts(t *testing.T) { delayedAccount, err := types.NewContinuousVestingAccount(baseAccount, vestedCoins, startTime, endTime) require.NoError(t, err) - ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) + ctx = ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.AddDate(1, 0, 0)}) accountKeeper.SetAccount(ctx, delayedAccount) @@ -315,8 +316,8 @@ func TestMigrateVestingAccounts(t *testing.T) { { "continuous vesting, start time passed but not ended", func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - startTime := ctx.BlockTime().AddDate(-1, 0, 0).Unix() - endTime := ctx.BlockTime().AddDate(2, 0, 0).Unix() + startTime := ctx.HeaderInfo().Time.AddDate(-1, 0, 0).Unix() + endTime := ctx.HeaderInfo().Time.AddDate(2, 0, 0).Unix() baseAccount := createBaseAccount(delegatorAddr) bondDenom, err := stakingKeeper.BondDenom(ctx) require.NoError(t, err) @@ -324,7 +325,7 @@ func TestMigrateVestingAccounts(t *testing.T) { delayedAccount, err := types.NewContinuousVestingAccount(baseAccount, vestedCoins, startTime, endTime) require.NoError(t, err) - ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) + ctx = ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.AddDate(1, 0, 0)}) accountKeeper.SetAccount(ctx, delayedAccount) @@ -340,8 +341,8 @@ func TestMigrateVestingAccounts(t *testing.T) { { "continuous vesting, start time and endtime passed", func(ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - startTime := ctx.BlockTime().AddDate(-2, 0, 0).Unix() - endTime := ctx.BlockTime().AddDate(-1, 0, 0).Unix() + startTime := ctx.HeaderInfo().Time.AddDate(-2, 0, 0).Unix() + endTime := ctx.HeaderInfo().Time.AddDate(-1, 0, 0).Unix() baseAccount := createBaseAccount(delegatorAddr) bondDenom, err := stakingKeeper.BondDenom(ctx) require.NoError(t, err) @@ -349,7 +350,7 @@ func TestMigrateVestingAccounts(t *testing.T) { delayedAccount, err := types.NewContinuousVestingAccount(baseAccount, vestedCoins, startTime, endTime) require.NoError(t, err) - ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) + ctx = ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.AddDate(1, 0, 0)}) accountKeeper.SetAccount(ctx, delayedAccount) @@ -370,7 +371,7 @@ func TestMigrateVestingAccounts(t *testing.T) { require.NoError(t, err) vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(100))) - start := ctx.BlockTime().Unix() + int64(time.Hour/time.Second) + start := ctx.HeaderInfo().Time.Unix() + int64(time.Hour/time.Second) periods := []types.Period{ { @@ -475,7 +476,7 @@ func TestMigrateVestingAccounts(t *testing.T) { delayedAccount, err := types.NewPeriodicVestingAccount(baseAccount, vestedCoins, startTime, periods) require.NoError(t, err) - ctx = ctx.WithBlockTime(time.Unix(1601042400+31536000+15897600+15897600+1, 0)) + ctx = ctx.WithHeaderInfo(header.Info{Time: time.Unix(1601042400+31536000+15897600+15897600+1, 0)}) accountKeeper.SetAccount(ctx, delayedAccount) @@ -524,7 +525,7 @@ func TestMigrateVestingAccounts(t *testing.T) { delayedAccount, err := types.NewPeriodicVestingAccount(baseAccount, vestedCoins, startTime, periods) require.NoError(t, err) - ctx = ctx.WithBlockTime(time.Unix(1601042400+31536000+1, 0)) + ctx = ctx.WithHeaderInfo(header.Info{Time: time.Unix(1601042400+31536000+1, 0)}) accountKeeper.SetAccount(ctx, delayedAccount) @@ -573,7 +574,7 @@ func TestMigrateVestingAccounts(t *testing.T) { delayedAccount, err := types.NewPeriodicVestingAccount(baseAccount, vestedCoins, startTime, periods) require.NoError(t, err) - ctx = ctx.WithBlockTime(time.Unix(1601042400+31536000+15638400+1, 0)) + ctx = ctx.WithHeaderInfo(header.Info{Time: time.Unix(1601042400+31536000+15638400+1, 0)}) accountKeeper.SetAccount(ctx, delayedAccount) @@ -595,7 +596,7 @@ func TestMigrateVestingAccounts(t *testing.T) { require.NoError(t, err) vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(300))) - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().AddDate(10, 0, 0).Unix()) + delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.HeaderInfo().Time.AddDate(10, 0, 0).Unix()) require.NoError(t, err) accountKeeper.SetAccount(ctx, delayedAccount) @@ -604,7 +605,7 @@ func TestMigrateVestingAccounts(t *testing.T) { _, err = stakingKeeper.Delegate(ctx, delegatorAddr, sdkmath.NewInt(300), stakingtypes.Unbonded, validator, true) require.NoError(t, err) - ctx = ctx.WithBlockTime(ctx.BlockTime().AddDate(1, 0, 0)) + ctx = ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.AddDate(1, 0, 0)}) valAddr, err := sdk.ValAddressFromBech32(validator.OperatorAddress) require.NoError(t, err) @@ -627,7 +628,7 @@ func TestMigrateVestingAccounts(t *testing.T) { require.NoError(t, err) vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(300))) - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().AddDate(10, 0, 0).Unix()) + delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.HeaderInfo().Time.AddDate(10, 0, 0).Unix()) require.NoError(t, err) accountKeeper.SetAccount(ctx, delayedAccount) @@ -646,7 +647,7 @@ func TestMigrateVestingAccounts(t *testing.T) { require.NoError(t, err) vestedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, sdkmath.NewInt(300))) - delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().AddDate(10, 0, 0).Unix()) + delayedAccount, err := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.HeaderInfo().Time.AddDate(10, 0, 0).Unix()) require.NoError(t, err) accountKeeper.SetAccount(ctx, delayedAccount) @@ -675,7 +676,7 @@ func TestMigrateVestingAccounts(t *testing.T) { tc.prepareFunc(ctx, validator, delegatorAddr) if tc.blockTime != 0 { - ctx = ctx.WithBlockTime(time.Unix(tc.blockTime, 0)) + ctx = ctx.WithHeaderInfo(header.Info{Time: time.Unix(tc.blockTime, 0)}) } // We introduce the bug diff --git a/tests/integration/evidence/keeper/infraction_test.go b/tests/integration/evidence/keeper/infraction_test.go index 4acef9136e0..8688679317c 100644 --- a/tests/integration/evidence/keeper/infraction_test.go +++ b/tests/integration/evidence/keeper/infraction_test.go @@ -13,6 +13,7 @@ import ( "cosmossdk.io/collections" "cosmossdk.io/core/appmodule" "cosmossdk.io/core/comet" + "cosmossdk.io/core/header" "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/evidence" @@ -236,7 +237,7 @@ func TestHandleDoubleSign(t *testing.T) { assert.Assert(t, val.GetTokens().Equal(newTokens)) // jump to past the unbonding period - ctx = ctx.WithBlockTime(time.Unix(1, 0).Add(stakingParams.UnbondingTime)) + ctx = ctx.WithHeaderInfo(header.Info{Time: time.Unix(1, 0).Add(stakingParams.UnbondingTime)}) // require we cannot unjail assert.Error(t, f.slashingKeeper.Unjail(ctx, operatorAddr), slashingtypes.ErrValidatorJailed.Error()) @@ -262,7 +263,7 @@ func TestHandleDoubleSign_TooOld(t *testing.T) { t.Parallel() f := initFixture(t) - ctx := f.sdkCtx.WithIsCheckTx(false).WithBlockHeight(1).WithBlockTime(time.Now()) + ctx := f.sdkCtx.WithIsCheckTx(false).WithBlockHeight(1).WithHeaderInfo(header.Info{Time: time.Now()}) populateValidators(t, f) power := int64(100) @@ -288,7 +289,7 @@ func TestHandleDoubleSign_TooOld(t *testing.T) { nci := comet.Info{Evidence: []comet.Evidence{{ Validator: comet.Validator{Address: valpubkey.Address(), Power: power}, Type: comet.MisbehaviorType(abci.MisbehaviorType_DUPLICATE_VOTE), - Time: ctx.BlockTime(), + Time: ctx.HeaderInfo().Time, Height: 0, }}} @@ -297,7 +298,7 @@ func TestHandleDoubleSign_TooOld(t *testing.T) { ctx = ctx.WithCometInfo(nci) ctx = ctx.WithConsensusParams(cp) - ctx = ctx.WithBlockTime(ctx.BlockTime().Add(cp.Evidence.MaxAgeDuration + 1)) + ctx = ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.Add(cp.Evidence.MaxAgeDuration + 1)}) ctx = ctx.WithBlockHeight(ctx.BlockHeight() + cp.Evidence.MaxAgeNumBlocks + 1) assert.NilError(t, f.evidenceKeeper.BeginBlocker(ctx)) diff --git a/tests/integration/gov/genesis_test.go b/tests/integration/gov/genesis_test.go index 0b353f4896e..0142949dbd3 100644 --- a/tests/integration/gov/genesis_test.go +++ b/tests/integration/gov/genesis_test.go @@ -8,6 +8,7 @@ import ( dbm "github.com/cosmos/cosmos-db" "gotest.tools/v3/assert" + "cosmossdk.io/core/header" "cosmossdk.io/depinject" "cosmossdk.io/log" @@ -163,7 +164,7 @@ func TestImportExportQueues(t *testing.T) { params, err = s2.GovKeeper.Params.Get(ctx2) assert.NilError(t, err) // Jump the time forward past the DepositPeriod and VotingPeriod - ctx2 = ctx2.WithBlockTime(ctx2.BlockHeader().Time.Add(*params.MaxDepositPeriod).Add(*params.VotingPeriod)) + ctx2 = ctx2.WithHeaderInfo(header.Info{Time: ctx2.BlockHeader().Time.Add(*params.MaxDepositPeriod).Add(*params.VotingPeriod)}) // Make sure that they are still in the DepositPeriod and VotingPeriod respectively proposal1, err = s2.GovKeeper.Proposals.Get(ctx2, proposalID1) diff --git a/tests/integration/staking/keeper/delegation_test.go b/tests/integration/staking/keeper/delegation_test.go index a68c68ee13e..f33b19373e1 100644 --- a/tests/integration/staking/keeper/delegation_test.go +++ b/tests/integration/staking/keeper/delegation_test.go @@ -6,6 +6,7 @@ import ( "gotest.tools/v3/assert" + "cosmossdk.io/core/header" "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" @@ -93,7 +94,7 @@ func TestUnbondingDelegationsMaxEntries(t *testing.T) { assert.Assert(math.IntEq(t, newNotBonded, oldNotBonded)) // mature unbonding delegations - ctx = ctx.WithBlockTime(completionTime) + ctx = ctx.WithHeaderInfo(header.Info{Time: completionTime}) _, err = f.stakingKeeper.CompleteUnbonding(ctx, addrDel, addrVal) assert.NilError(t, err) diff --git a/tests/integration/staking/keeper/msg_server_test.go b/tests/integration/staking/keeper/msg_server_test.go index a3e79fc863a..940e6c55c33 100644 --- a/tests/integration/staking/keeper/msg_server_test.go +++ b/tests/integration/staking/keeper/msg_server_test.go @@ -53,7 +53,7 @@ func TestCancelUnbondingDelegation(t *testing.T) { unbondingAmount := sdk.NewInt64Coin(bondDenom, 5) ubd := types.NewUnbondingDelegation( delegatorAddr, validatorAddr, 10, - ctx.BlockTime().Add(time.Minute*10), + ctx.HeaderInfo().Time.Add(time.Minute*10), unbondingAmount.Amount, 0, address.NewBech32Codec("cosmosvaloper"), address.NewBech32Codec("cosmos"), diff --git a/tests/integration/staking/keeper/slash_test.go b/tests/integration/staking/keeper/slash_test.go index bf749d2bec8..0a4640087b3 100644 --- a/tests/integration/staking/keeper/slash_test.go +++ b/tests/integration/staking/keeper/slash_test.go @@ -4,11 +4,11 @@ import ( "testing" "time" - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/stretchr/testify/require" "gotest.tools/v3/assert" "cosmossdk.io/collections" + "cosmossdk.io/core/header" "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/codec/address" @@ -74,7 +74,7 @@ func TestSlashUnbondingDelegation(t *testing.T) { assert.Assert(t, slashAmount.Equal(math.NewInt(0))) // after the expiration time, no longer eligible for slashing - f.sdkCtx = f.sdkCtx.WithBlockHeader(cmtproto.Header{Time: time.Unix(10, 0)}) + f.sdkCtx = f.sdkCtx.WithHeaderInfo(header.Info{Time: time.Unix(10, 0)}) assert.NilError(t, f.stakingKeeper.SetUnbondingDelegation(f.sdkCtx, ubd)) slashAmount, err = f.stakingKeeper.SlashUnbondingDelegation(f.sdkCtx, ubd, 0, fraction) assert.NilError(t, err) @@ -83,7 +83,7 @@ func TestSlashUnbondingDelegation(t *testing.T) { // test valid slash, before expiration timestamp and to which stake contributed notBondedPool := f.stakingKeeper.GetNotBondedPool(f.sdkCtx) oldUnbondedPoolBalances := f.bankKeeper.GetAllBalances(f.sdkCtx, notBondedPool.GetAddress()) - f.sdkCtx = f.sdkCtx.WithBlockHeader(cmtproto.Header{Time: time.Unix(0, 0)}) + f.sdkCtx = f.sdkCtx.WithHeaderInfo(header.Info{Time: time.Unix(0, 0)}) assert.NilError(t, f.stakingKeeper.SetUnbondingDelegation(f.sdkCtx, ubd)) slashAmount, err = f.stakingKeeper.SlashUnbondingDelegation(f.sdkCtx, ubd, 0, fraction) assert.NilError(t, err) @@ -139,7 +139,7 @@ func TestSlashRedelegation(t *testing.T) { assert.Assert(t, slashAmount.Equal(math.NewInt(0))) // after the expiration time, no longer eligible for slashing - f.sdkCtx = f.sdkCtx.WithBlockHeader(cmtproto.Header{Time: time.Unix(10, 0)}) + f.sdkCtx = f.sdkCtx.WithHeaderInfo(header.Info{Time: time.Unix(10, 0)}) assert.NilError(t, f.stakingKeeper.SetRedelegation(f.sdkCtx, rd)) validator, found = f.stakingKeeper.GetValidator(f.sdkCtx, addrVals[1]) assert.Assert(t, found) @@ -150,7 +150,7 @@ func TestSlashRedelegation(t *testing.T) { balances := f.bankKeeper.GetAllBalances(f.sdkCtx, bondedPool.GetAddress()) // test valid slash, before expiration timestamp and to which stake contributed - f.sdkCtx = f.sdkCtx.WithBlockHeader(cmtproto.Header{Time: time.Unix(0, 0)}) + f.sdkCtx = f.sdkCtx.WithHeaderInfo(header.Info{Time: time.Unix(0, 0)}) assert.NilError(t, f.stakingKeeper.SetRedelegation(f.sdkCtx, rd)) validator, found = f.stakingKeeper.GetValidator(f.sdkCtx, addrVals[1]) assert.Assert(t, found) diff --git a/tests/integration/staking/keeper/unbonding_test.go b/tests/integration/staking/keeper/unbonding_test.go index 9ed6aab2fca..61bee2242dd 100644 --- a/tests/integration/staking/keeper/unbonding_test.go +++ b/tests/integration/staking/keeper/unbonding_test.go @@ -7,6 +7,7 @@ import ( "github.com/golang/mock/gomock" "gotest.tools/v3/assert" + "cosmossdk.io/core/header" "cosmossdk.io/math" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" @@ -207,7 +208,7 @@ func TestValidatorUnbondingOnHold1(t *testing.T) { assert.Equal(t, validator.OperatorAddress, unbondingVals[0]) // PROVIDER CHAIN'S UNBONDING PERIOD ENDS - BUT UNBONDING CANNOT COMPLETE - f.sdkCtx = f.sdkCtx.WithBlockTime(completionTime.Add(time.Duration(1))) + f.sdkCtx = f.sdkCtx.WithHeaderInfo(header.Info{Time: completionTime.Add(time.Duration(1))}) f.sdkCtx = f.sdkCtx.WithBlockHeight(completionHeight + 1) assert.NilError(t, f.stakingKeeper.UnbondAllMatureValidators(f.sdkCtx)) @@ -253,7 +254,7 @@ func TestValidatorUnbondingOnHold2(t *testing.T) { completionHeight := validator1.UnbondingHeight // PROVIDER CHAIN'S UNBONDING PERIOD ENDS - BUT UNBONDING CANNOT COMPLETE - f.sdkCtx = f.sdkCtx.WithBlockTime(completionTime.Add(time.Duration(1))) + f.sdkCtx = f.sdkCtx.WithHeaderInfo(header.Info{Time: completionTime.Add(time.Duration(1))}) f.sdkCtx = f.sdkCtx.WithBlockHeight(completionHeight + 1) assert.NilError(t, f.stakingKeeper.UnbondAllMatureValidators(f.sdkCtx)) @@ -328,7 +329,7 @@ func TestRedelegationOnHold1(t *testing.T) { assert.Equal(t, 1, len(redelegations)) // PROVIDER CHAIN'S UNBONDING PERIOD ENDS - STOPPED UNBONDING CAN NOW COMPLETE - f.sdkCtx = f.sdkCtx.WithBlockTime(completionTime) + f.sdkCtx = f.sdkCtx.WithHeaderInfo(header.Info{Time: completionTime}) _, err = f.stakingKeeper.CompleteRedelegation(f.sdkCtx, addrDels[0], addrVals[0], addrVals[1]) assert.NilError(t, err) @@ -352,7 +353,7 @@ func TestRedelegationOnHold2(t *testing.T) { completionTime := doRedelegation(t, f.stakingKeeper, f.sdkCtx, addrDels, addrVals, &hookCalled) // PROVIDER CHAIN'S UNBONDING PERIOD ENDS - BUT UNBONDING CANNOT COMPLETE - f.sdkCtx = f.sdkCtx.WithBlockTime(completionTime) + f.sdkCtx = f.sdkCtx.WithHeaderInfo(header.Info{Time: completionTime}) _, err := f.stakingKeeper.CompleteRedelegation(f.sdkCtx, addrDels[0], addrVals[0], addrVals[1]) assert.NilError(t, err) @@ -397,7 +398,7 @@ func TestUnbondingDelegationOnHold1(t *testing.T) { assert.Assert(math.IntEq(t, notBondedAmt1, notBondedAmt3)) // PROVIDER CHAIN'S UNBONDING PERIOD ENDS - STOPPED UNBONDING CAN NOW COMPLETE - f.sdkCtx = f.sdkCtx.WithBlockTime(completionTime) + f.sdkCtx = f.sdkCtx.WithHeaderInfo(header.Info{Time: completionTime}) _, err = f.stakingKeeper.CompleteUnbonding(f.sdkCtx, addrDels[0], addrVals[0]) assert.NilError(t, err) @@ -424,7 +425,7 @@ func TestUnbondingDelegationOnHold2(t *testing.T) { completionTime, bondedAmt1, notBondedAmt1 := doUnbondingDelegation(t, f.stakingKeeper, f.bankKeeper, f.sdkCtx, bondDenom, addrDels, addrVals, &hookCalled) // PROVIDER CHAIN'S UNBONDING PERIOD ENDS - BUT UNBONDING CANNOT COMPLETE - f.sdkCtx = f.sdkCtx.WithBlockTime(completionTime) + f.sdkCtx = f.sdkCtx.WithHeaderInfo(header.Info{Time: completionTime}) _, err := f.stakingKeeper.CompleteUnbonding(f.sdkCtx, addrDels[0], addrVals[0]) assert.NilError(t, err) diff --git a/tests/integration/staking/simulation/operations_test.go b/tests/integration/staking/simulation/operations_test.go index b5626fab776..df474d56fee 100644 --- a/tests/integration/staking/simulation/operations_test.go +++ b/tests/integration/staking/simulation/operations_test.go @@ -13,6 +13,7 @@ import ( "github.com/stretchr/testify/suite" "cosmossdk.io/collections" + "cosmossdk.io/core/header" "cosmossdk.io/depinject" sdklog "cosmossdk.io/log" "cosmossdk.io/math" @@ -188,7 +189,7 @@ func (s *SimTestSuite) TestSimulateMsgCreateValidator() { func (s *SimTestSuite) TestSimulateMsgCancelUnbondingDelegation() { require := s.Require() blockTime := time.Now().UTC() - ctx := s.ctx.WithBlockTime(blockTime) + ctx := s.ctx.WithHeaderInfo(header.Info{Time: blockTime}) // setup accounts[1] as validator validator0 := s.getTestingValidator0(ctx) @@ -233,7 +234,7 @@ func (s *SimTestSuite) TestSimulateMsgCancelUnbondingDelegation() { func (s *SimTestSuite) TestSimulateMsgEditValidator() { require := s.Require() blockTime := time.Now().UTC() - ctx := s.ctx.WithBlockTime(blockTime) + ctx := s.ctx.WithHeaderInfo(header.Info{Time: blockTime}) // setup accounts[0] as validator _ = s.getTestingValidator0(ctx) @@ -259,7 +260,7 @@ func (s *SimTestSuite) TestSimulateMsgEditValidator() { func (s *SimTestSuite) TestSimulateMsgDelegate() { require := s.Require() blockTime := time.Now().UTC() - ctx := s.ctx.WithBlockTime(blockTime) + ctx := s.ctx.WithHeaderInfo(header.Info{Time: blockTime}) // execute operation op := simulation.SimulateMsgDelegate(s.txConfig, s.accountKeeper, s.bankKeeper, s.stakingKeeper) @@ -282,7 +283,7 @@ func (s *SimTestSuite) TestSimulateMsgDelegate() { func (s *SimTestSuite) TestSimulateMsgUndelegate() { require := s.Require() blockTime := time.Now().UTC() - ctx := s.ctx.WithBlockTime(blockTime) + ctx := s.ctx.WithHeaderInfo(header.Info{Time: blockTime}) // setup accounts[1] as validator validator0 := s.getTestingValidator0(ctx) @@ -323,7 +324,7 @@ func (s *SimTestSuite) TestSimulateMsgUndelegate() { func (s *SimTestSuite) TestSimulateMsgBeginRedelegate() { require := s.Require() blockTime := time.Now().UTC() - ctx := s.ctx.WithBlockTime(blockTime) + ctx := s.ctx.WithHeaderInfo(header.Info{Time: blockTime}) // setup accounts[1] as validator0 and accounts[2] as validator1 validator0 := s.getTestingValidator0(ctx) diff --git a/testutil/context.go b/testutil/context.go index b6a524a4909..12c36f11307 100644 --- a/testutil/context.go +++ b/testutil/context.go @@ -7,6 +7,7 @@ import ( dbm "github.com/cosmos/cosmos-db" "github.com/stretchr/testify/assert" + "cosmossdk.io/core/header" "cosmossdk.io/log" "cosmossdk.io/store" "cosmossdk.io/store/metrics" @@ -75,7 +76,7 @@ func DefaultContextWithDB(tb testing.TB, key, tkey storetypes.StoreKey) TestCont err := cms.LoadLatestVersion() assert.NoError(tb, err) - ctx := sdk.NewContext(cms, false, log.NewNopLogger()).WithBlockTime(time.Now()) + ctx := sdk.NewContext(cms, false, log.NewNopLogger()).WithHeaderInfo(header.Info{Time: time.Now()}) return TestContext{ctx, db, cms} } diff --git a/types/context.go b/types/context.go index f051d11f55f..79181d065c8 100644 --- a/types/context.go +++ b/types/context.go @@ -45,7 +45,7 @@ type Context struct { chainID string // Deprecated: Use HeaderService for chainID and CometService for the rest txBytes []byte logger log.Logger - voteInfo []abci.VoteInfo // Deprecated: use Cometinfo.GetLastCommit().Votes() instead, will be removed in 0.51 + voteInfo []abci.VoteInfo // Deprecated: use Cometinfo.LastCommit.Votes instead, will be removed after 0.51 gasMeter storetypes.GasMeter blockGasMeter storetypes.GasMeter checkTx bool @@ -66,15 +66,13 @@ type Context struct { type Request = Context // Read-only accessors -func (c Context) Context() context.Context { return c.baseCtx } -func (c Context) MultiStore() storetypes.MultiStore { return c.ms } -func (c Context) BlockHeight() int64 { return c.header.Height } -func (c Context) BlockTime() time.Time { return c.header.Time } -func (c Context) ChainID() string { return c.chainID } -func (c Context) TxBytes() []byte { return c.txBytes } -func (c Context) Logger() log.Logger { return c.logger } - -// Deprecated: use Cometinfo.GetLastCommit().Votes() instead, will be removed after 0.51 +func (c Context) Context() context.Context { return c.baseCtx } +func (c Context) MultiStore() storetypes.MultiStore { return c.ms } +func (c Context) BlockHeight() int64 { return c.header.Height } +func (c Context) BlockTime() time.Time { return c.headerInfo.Time } // Deprecated: use HeaderInfo().Time +func (c Context) ChainID() string { return c.chainID } +func (c Context) TxBytes() []byte { return c.txBytes } +func (c Context) Logger() log.Logger { return c.logger } func (c Context) VoteInfos() []abci.VoteInfo { return c.voteInfo } func (c Context) GasMeter() storetypes.GasMeter { return c.gasMeter } func (c Context) BlockGasMeter() storetypes.GasMeter { return c.blockGasMeter } @@ -173,15 +171,6 @@ func (c Context) WithHeaderHash(hash []byte) Context { return c } -// WithBlockTime returns a Context with an updated CometBFT block header time in UTC with no monotonic component. -// Stripping the monotonic component is for time equality. -func (c Context) WithBlockTime(newTime time.Time) Context { - newHeader := c.BlockHeader() - // https://github.com/gogo/protobuf/issues/519 - newHeader.Time = newTime.Round(0).UTC() - return c.WithBlockHeader(newHeader) -} - // WithProposer returns a Context with an updated proposer consensus address. func (c Context) WithProposer(addr ConsAddress) Context { newHeader := c.BlockHeader() diff --git a/types/context_test.go b/types/context_test.go index 402d8d9dc4d..d190a298807 100644 --- a/types/context_test.go +++ b/types/context_test.go @@ -7,7 +7,6 @@ import ( abci "github.com/cometbft/cometbft/abci/types" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - cmttime "github.com/cometbft/cometbft/types/time" "github.com/golang/mock/gomock" "github.com/stretchr/testify/suite" @@ -147,7 +146,6 @@ func (s *contextTestSuite) TestContextHeader() { var ctx types.Context height := int64(5) - time := time.Now() addr := secp256k1.GenPrivKey().PubKey().Address() proposer := types.ConsAddress(addr) @@ -155,22 +153,12 @@ func (s *contextTestSuite) TestContextHeader() { ctx = ctx. WithBlockHeight(height). - WithBlockTime(time). WithProposer(proposer) s.Require().Equal(height, ctx.BlockHeight()) s.Require().Equal(height, ctx.BlockHeader().Height) - s.Require().Equal(time.UTC(), ctx.BlockHeader().Time) s.Require().Equal(proposer.Bytes(), ctx.BlockHeader().ProposerAddress) } -func (s *contextTestSuite) TestWithBlockTime() { - now := time.Now() - ctx := types.NewContext(nil, false, nil) - ctx = ctx.WithBlockTime(now) - cmttime2 := cmttime.Canonical(now) - s.Require().Equal(ctx.BlockTime(), cmttime2) -} - func (s *contextTestSuite) TestContextHeaderClone() { cases := map[string]struct { h cmtproto.Header @@ -216,13 +204,13 @@ func (s *contextTestSuite) TestContextHeaderClone() { s.T().Run(name, func(t *testing.T) { ctx := types.NewContext(nil, false, nil).WithBlockHeader(tc.h) s.Require().Equal(tc.h.Height, ctx.BlockHeight()) - s.Require().Equal(tc.h.Time.UTC(), ctx.BlockTime()) + s.Require().Equal(tc.h.Time.UTC(), ctx.BlockHeader().Time) // update only changes one field var newHeight int64 = 17 ctx = ctx.WithBlockHeight(newHeight) s.Require().Equal(newHeight, ctx.BlockHeight()) - s.Require().Equal(tc.h.Time.UTC(), ctx.BlockTime()) + s.Require().Equal(tc.h.Time.UTC(), ctx.BlockHeader().Time) }) } } diff --git a/x/auth/migrations/v2/store.go b/x/auth/migrations/v2/store.go index 8032d318b2c..a86ad679d09 100644 --- a/x/auth/migrations/v2/store.go +++ b/x/auth/migrations/v2/store.go @@ -100,7 +100,7 @@ func migrateVestingAccounts(ctx sdk.Context, account sdk.AccountI, queryServer g balance = balance.Add(coin) } - asVesting.TrackDelegation(ctx.BlockTime(), balance, delegations) + asVesting.TrackDelegation(ctx.HeaderInfo().Time, balance, delegations) return asVesting.(sdk.AccountI), nil } diff --git a/x/auth/vesting/README.md b/x/auth/vesting/README.md index 62619ede0d2..5c04614f7c2 100644 --- a/x/auth/vesting/README.md +++ b/x/auth/vesting/README.md @@ -256,7 +256,7 @@ func (k Keeper) LockedCoins(ctx Context, addr AccAddress) Coins { acc := k.GetAccount(ctx, addr) if acc != nil { if acc.IsVesting() { - return acc.LockedCoins(ctx.BlockTime()) + return acc.LockedCoins(ctx.HeaderInfo().Time) } } diff --git a/x/auth/vesting/msg_server.go b/x/auth/vesting/msg_server.go index ce1214f6a32..b5d0e139bf7 100644 --- a/x/auth/vesting/msg_server.go +++ b/x/auth/vesting/msg_server.go @@ -70,8 +70,8 @@ func (s msgServer) CreateVestingAccount(ctx context.Context, msg *types.MsgCreat if msg.Delayed { vestingAccount = types.NewDelayedVestingAccountRaw(baseVestingAccount) } else { - sdkCtx := sdk.UnwrapSDKContext(ctx) - vestingAccount = types.NewContinuousVestingAccountRaw(baseVestingAccount, sdkCtx.BlockTime().Unix()) + sdkctx := sdk.UnwrapSDKContext(ctx) + vestingAccount = types.NewContinuousVestingAccountRaw(baseVestingAccount, sdkctx.HeaderInfo().Time.Unix()) } s.AccountKeeper.SetAccount(ctx, vestingAccount) diff --git a/x/authz/keeper/genesis.go b/x/authz/keeper/genesis.go index 08b84b8ed68..a1e5a9acd90 100644 --- a/x/authz/keeper/genesis.go +++ b/x/authz/keeper/genesis.go @@ -7,7 +7,7 @@ import ( // InitGenesis initializes new authz genesis func (k Keeper) InitGenesis(ctx sdk.Context, data *authz.GenesisState) { - now := ctx.BlockTime() + now := ctx.HeaderInfo().Time for _, entry := range data.Authorization { // ignore expired authorizations if entry.Expiration != nil && entry.Expiration.Before(now) { diff --git a/x/authz/keeper/genesis_test.go b/x/authz/keeper/genesis_test.go index 03d5aa5729d..67b3611e7af 100644 --- a/x/authz/keeper/genesis_test.go +++ b/x/authz/keeper/genesis_test.go @@ -73,7 +73,7 @@ func (suite *GenesisTestSuite) SetupTest() { func (suite *GenesisTestSuite) TestImportExportGenesis() { coins := sdk.NewCoins(sdk.NewCoin("foo", sdkmath.NewInt(1_000))) - now := suite.ctx.BlockTime() + now := suite.ctx.HeaderInfo().Time expires := now.Add(time.Hour) grant := &bank.SendAuthorization{SpendLimit: coins} err := suite.keeper.SaveGrant(suite.ctx, granteeAddr, granterAddr, grant, &expires) diff --git a/x/authz/keeper/grpc_query_test.go b/x/authz/keeper/grpc_query_test.go index c7054f164d4..72370df2f99 100644 --- a/x/authz/keeper/grpc_query_test.go +++ b/x/authz/keeper/grpc_query_test.go @@ -277,7 +277,7 @@ func (suite *TestSuite) TestGRPCQueryGranteeGrants() { } func (suite *TestSuite) createSendAuthorization(grantee, granter sdk.AccAddress) authz.Authorization { - exp := suite.ctx.BlockHeader().Time.Add(time.Hour) + exp := suite.ctx.HeaderInfo().Time.Add(time.Hour) newCoins := sdk.NewCoins(sdk.NewInt64Coin("steak", 100)) authorization := &banktypes.SendAuthorization{SpendLimit: newCoins} err := suite.authzKeeper.SaveGrant(suite.ctx, grantee, granter, authorization, &exp) @@ -286,7 +286,7 @@ func (suite *TestSuite) createSendAuthorization(grantee, granter sdk.AccAddress) } func (suite *TestSuite) createSendAuthorizationWithAllowList(grantee, granter sdk.AccAddress) authz.Authorization { - exp := suite.ctx.BlockHeader().Time.Add(time.Hour) + exp := suite.ctx.HeaderInfo().Time.Add(time.Hour) newCoins := sdk.NewCoins(sdk.NewInt64Coin("steak", 100)) authorization := &banktypes.SendAuthorization{SpendLimit: newCoins, AllowList: []string{suite.addrs[5].String()}} err := suite.authzKeeper.SaveGrant(suite.ctx, grantee, granter, authorization, &exp) diff --git a/x/authz/keeper/keeper.go b/x/authz/keeper/keeper.go index 5293f4096e1..ac3c99940ce 100644 --- a/x/authz/keeper/keeper.go +++ b/x/authz/keeper/keeper.go @@ -95,7 +95,7 @@ func (k Keeper) update(ctx context.Context, grantee, granter sdk.AccAddress, upd func (k Keeper) DispatchActions(ctx context.Context, grantee sdk.AccAddress, msgs []sdk.Msg) ([][]byte, error) { results := make([][]byte, len(msgs)) sdkCtx := sdk.UnwrapSDKContext(ctx) - now := sdkCtx.BlockTime() + now := sdkCtx.HeaderInfo().Time for i, msg := range msgs { signers, _, err := k.cdc.GetMsgV1Signers(msg) @@ -189,7 +189,7 @@ func (k Keeper) SaveGrant(ctx context.Context, grantee, granter sdk.AccAddress, store := k.storeService.OpenKVStore(ctx) skey := grantStoreKey(grantee, granter, msgType) - grant, err := authz.NewGrant(sdkCtx.BlockTime(), authorization, expiration) + grant, err := authz.NewGrant(sdkCtx.HeaderInfo().Time, authorization, expiration) if err != nil { return err } @@ -292,7 +292,7 @@ func (k Keeper) GetAuthorizations(ctx context.Context, grantee, granter sdk.AccA func (k Keeper) GetAuthorization(ctx context.Context, grantee, granter sdk.AccAddress, msgType string) (authz.Authorization, *time.Time) { sdkCtx := sdk.UnwrapSDKContext(ctx) grant, found := k.getGrant(ctx, grantStoreKey(grantee, granter, msgType)) - if !found || (grant.Expiration != nil && grant.Expiration.Before(sdkCtx.BlockHeader().Time)) { + if !found || (grant.Expiration != nil && grant.Expiration.Before(sdkCtx.HeaderInfo().Time)) { return nil, nil } @@ -411,7 +411,7 @@ func (k Keeper) DequeueAndDeleteExpiredGrants(ctx context.Context) error { store := k.storeService.OpenKVStore(ctx) sdkCtx := sdk.UnwrapSDKContext(ctx) - iterator, err := store.Iterator(GrantQueuePrefix, storetypes.InclusiveEndBytes(GrantQueueTimePrefix(sdkCtx.BlockTime()))) + iterator, err := store.Iterator(GrantQueuePrefix, storetypes.InclusiveEndBytes(GrantQueueTimePrefix(sdkCtx.HeaderInfo().Time))) if err != nil { return err } diff --git a/x/authz/keeper/keeper_test.go b/x/authz/keeper/keeper_test.go index 9a7b5d81371..5dc8ac76c93 100644 --- a/x/authz/keeper/keeper_test.go +++ b/x/authz/keeper/keeper_test.go @@ -4,11 +4,10 @@ import ( "testing" "time" - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - cmttime "github.com/cometbft/cometbft/types/time" "github.com/golang/mock/gomock" "github.com/stretchr/testify/suite" + "cosmossdk.io/core/header" "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" @@ -51,7 +50,7 @@ func (s *TestSuite) SetupTest() { key := storetypes.NewKVStoreKey(authzkeeper.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) - s.ctx = testCtx.Ctx.WithBlockHeader(cmtproto.Header{Time: cmttime.Now()}) + s.ctx = testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now().Round(0).UTC()}) s.encCfg = moduletestutil.MakeTestEncodingConfig(authzmodule.AppModuleBasic{}) s.baseApp = baseapp.NewBaseApp( @@ -87,7 +86,7 @@ func (s *TestSuite) SetupTest() { func (s *TestSuite) TestKeeper() { ctx, addrs := s.ctx, s.addrs - now := ctx.BlockTime() + now := ctx.HeaderInfo().Time require := s.Require() granterAddr := addrs[0] @@ -145,7 +144,7 @@ func (s *TestSuite) TestKeeperIter() { granterAddr := addrs[0] granteeAddr := addrs[1] granter2Addr := addrs[2] - e := ctx.BlockTime().AddDate(1, 0, 0) + e := ctx.HeaderInfo().Time.AddDate(1, 0, 0) sendAuthz := banktypes.NewSendAuthorization(coins100, nil) err := s.authzKeeper.SaveGrant(ctx, granteeAddr, granterAddr, sendAuthz, &e) @@ -164,7 +163,7 @@ func (s *TestSuite) TestKeeperIter() { func (s *TestSuite) TestDispatchAction() { addrs := s.addrs require := s.Require() - now := s.ctx.BlockTime() + now := s.ctx.HeaderInfo().Time granterAddr := addrs[0] granteeAddr := addrs[1] @@ -213,7 +212,7 @@ func (s *TestSuite) TestDispatchAction() { e := now.AddDate(0, 0, 1) err := s.authzKeeper.SaveGrant(s.ctx, granteeAddr, granterAddr, a, &e) require.NoError(err) - return s.ctx.WithBlockTime(s.ctx.BlockTime().AddDate(0, 0, 2)) + return s.ctx.WithHeaderInfo(header.Info{Time: s.ctx.HeaderInfo().Time.AddDate(0, 0, 2)}) }, func() {}, }, @@ -314,7 +313,7 @@ func (s *TestSuite) TestDispatchedEvents() { granterAddr := addrs[0] granteeAddr := addrs[1] recipientAddr := addrs[2] - expiration := s.ctx.BlockTime().Add(1 * time.Second) // must be in the future + expiration := s.ctx.HeaderInfo().Time.Add(1 * time.Second) // must be in the future msgs := authz.NewMsgExec(granteeAddr, []sdk.Msg{ &banktypes.MsgSend{ @@ -363,7 +362,7 @@ func (s *TestSuite) TestDequeueAllGrantsQueue() { granter := addrs[0] grantee := addrs[1] grantee1 := addrs[2] - exp := s.ctx.BlockTime().AddDate(0, 0, 1) + exp := s.ctx.HeaderInfo().Time.AddDate(0, 0, 1) a := banktypes.SendAuthorization{SpendLimit: coins100} // create few authorizations @@ -381,7 +380,7 @@ func (s *TestSuite) TestDequeueAllGrantsQueue() { err = s.authzKeeper.SaveGrant(s.ctx, granter, grantee, &a, &exp2) require.NoError(err) - newCtx := s.ctx.WithBlockTime(exp.AddDate(1, 0, 0)) + newCtx := s.ctx.WithHeaderInfo(header.Info{Time: exp.AddDate(1, 0, 0)}) err = s.authzKeeper.DequeueAndDeleteExpiredGrants(newCtx) require.NoError(err) @@ -413,7 +412,7 @@ func (s *TestSuite) TestGetAuthorization() { genAuthSend := authz.NewGenericAuthorization(sdk.MsgTypeURL(&banktypes.MsgSend{})) sendAuth := banktypes.NewSendAuthorization(coins10, nil) - start := s.ctx.BlockHeader().Time + start := s.ctx.HeaderInfo().Time expired := start.Add(time.Duration(1) * time.Second) notExpired := start.Add(time.Duration(5) * time.Hour) @@ -421,7 +420,7 @@ func (s *TestSuite) TestGetAuthorization() { s.Require().NoError(s.authzKeeper.SaveGrant(s.ctx, addr1, addr3, genAuthSend, &expired), "creating grant 1->3") s.Require().NoError(s.authzKeeper.SaveGrant(s.ctx, addr1, addr4, sendAuth, ¬Expired), "creating grant 1->4") // Without access to private keeper methods, I don't know how to save a grant with an invalid authorization. - newCtx := s.ctx.WithBlockTime(start.Add(time.Duration(1) * time.Minute)) + newCtx := s.ctx.WithHeaderInfo(header.Info{Time: start.Add(time.Duration(1) * time.Minute)}) tests := []struct { name string @@ -490,7 +489,7 @@ func (s *TestSuite) TestGetAuthorizations() { genAuthMulti := authz.NewGenericAuthorization(sdk.MsgTypeURL(&banktypes.MsgMultiSend{})) genAuthSend := authz.NewGenericAuthorization(sdk.MsgTypeURL(&banktypes.MsgSend{})) - start := s.ctx.BlockHeader().Time + start := s.ctx.HeaderInfo().Time expired := start.Add(time.Duration(1) * time.Second) s.Require().NoError(s.authzKeeper.SaveGrant(s.ctx, addr1, addr2, genAuthMulti, &expired), "creating multi send grant 1->2") diff --git a/x/authz/keeper/msg_server_test.go b/x/authz/keeper/msg_server_test.go index d314c4d2ce0..6ab843aff73 100644 --- a/x/authz/keeper/msg_server_test.go +++ b/x/authz/keeper/msg_server_test.go @@ -5,6 +5,7 @@ import ( "github.com/golang/mock/gomock" + "cosmossdk.io/core/header" sdkmath "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/codec/address" @@ -23,9 +24,9 @@ func (suite *TestSuite) createAccounts(accs int) []sdk.AccAddress { } func (suite *TestSuite) TestGrant() { - ctx := suite.ctx.WithBlockTime(time.Now()) + ctx := suite.ctx.WithHeaderInfo(header.Info{Time: time.Now()}) addrs := suite.createAccounts(2) - curBlockTime := ctx.BlockTime() + curBlockTime := ctx.HeaderInfo().Time suite.accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec("cosmos")).AnyTimes() diff --git a/x/authz/migrations/v2/store.go b/x/authz/migrations/v2/store.go index e340af27fe0..f48ee3cfff9 100644 --- a/x/authz/migrations/v2/store.go +++ b/x/authz/migrations/v2/store.go @@ -37,7 +37,7 @@ func addExpiredGrantsIndex(ctx sdk.Context, store storetypes.KVStore, cdc codec. defer grantsIter.Close() queueItems := make(map[string][]string) - now := ctx.BlockTime() + now := ctx.HeaderInfo().Time for ; grantsIter.Valid(); grantsIter.Next() { var grant authz.Grant bz := grantsIter.Value() diff --git a/x/authz/migrations/v2/store_test.go b/x/authz/migrations/v2/store_test.go index e60a326a266..1c54eb7130f 100644 --- a/x/authz/migrations/v2/store_test.go +++ b/x/authz/migrations/v2/store_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/require" + "cosmossdk.io/core/header" storetypes "cosmossdk.io/store/types" codectypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -36,7 +37,7 @@ func TestMigration(t *testing.T) { sendMsgType := banktypes.SendAuthorization{}.MsgTypeURL() genericMsgType := sdk.MsgTypeURL(&govtypes.MsgVote{}) coins100 := sdk.NewCoins(sdk.NewInt64Coin("atom", 100)) - blockTime := ctx.BlockTime() + blockTime := ctx.HeaderInfo().Time oneDay := blockTime.AddDate(0, 0, 1) oneYear := blockTime.AddDate(1, 0, 0) sendAuthz := banktypes.NewSendAuthorization(coins100, nil) @@ -110,7 +111,7 @@ func TestMigration(t *testing.T) { require.NoError(t, err) } - ctx = ctx.WithBlockTime(ctx.BlockTime().Add(1 * time.Hour)) + ctx = ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.Add(1 * time.Hour)}) require.NoError(t, v2.MigrateStore(ctx, storeService, cdc)) bz, err := store.Get(v2.GrantStoreKey(grantee1, granter2, genericMsgType)) diff --git a/x/authz/module/abci_test.go b/x/authz/module/abci_test.go index 9d9e7e1ce29..8f2ac31fe12 100644 --- a/x/authz/module/abci_test.go +++ b/x/authz/module/abci_test.go @@ -7,6 +7,7 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" + "cosmossdk.io/core/header" "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" @@ -49,7 +50,7 @@ func TestExpiredGrantsQueue(t *testing.T) { grantee2 := addrs[2] grantee3 := addrs[3] grantee4 := addrs[4] - expiration := ctx.BlockTime().AddDate(0, 1, 0) + expiration := ctx.HeaderInfo().Time.AddDate(0, 1, 0) expiration2 := expiration.AddDate(1, 0, 0) smallCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 10)) sendAuthz := banktypes.NewSendAuthorization(smallCoins, nil) @@ -94,12 +95,12 @@ func TestExpiredGrantsQueue(t *testing.T) { checkGrants(ctx, 4) // expiration is exclusive! - ctx = ctx.WithBlockTime(expiration) + ctx = ctx.WithHeaderInfo(header.Info{Time: expiration}) checkGrants(ctx, 4) - ctx = ctx.WithBlockTime(expiration.AddDate(0, 0, 1)) + ctx = ctx.WithHeaderInfo(header.Info{Time: expiration.AddDate(0, 0, 1)}) checkGrants(ctx, 2) - ctx = ctx.WithBlockTime(expiration2.AddDate(0, 0, 1)) + ctx = ctx.WithHeaderInfo(header.Info{Time: expiration2.AddDate(0, 0, 1)}) checkGrants(ctx, 1) } diff --git a/x/authz/simulation/operations.go b/x/authz/simulation/operations.go index 045be985d30..4fb59812e63 100644 --- a/x/authz/simulation/operations.go +++ b/x/authz/simulation/operations.go @@ -117,7 +117,7 @@ func SimulateMsgGrant( var expiration *time.Time t1 := simtypes.RandTimestamp(r) - if !t1.Before(ctx.BlockTime()) { + if !t1.Before(ctx.HeaderInfo().Time) { expiration = &t1 } randomAuthz := generateRandomAuthorization(r, spendLimit) diff --git a/x/authz/simulation/operations_test.go b/x/authz/simulation/operations_test.go index fda4c37c031..e5a1550cb08 100644 --- a/x/authz/simulation/operations_test.go +++ b/x/authz/simulation/operations_test.go @@ -9,6 +9,7 @@ import ( "github.com/cosmos/gogoproto/proto" "github.com/stretchr/testify/suite" + "cosmossdk.io/core/header" "cosmossdk.io/depinject" "cosmossdk.io/log" @@ -120,7 +121,7 @@ func (suite *SimTestSuite) TestSimulateGrant() { r := rand.New(s) accounts := suite.getTestingAccounts(r, 2) blockTime := time.Now().UTC() - ctx := suite.ctx.WithBlockTime(blockTime) + ctx := suite.ctx.WithHeaderInfo(header.Info{Time: blockTime}) _, err := suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, @@ -195,7 +196,7 @@ func (suite *SimTestSuite) TestSimulateExec() { granter := accounts[0] grantee := accounts[1] a := banktypes.NewSendAuthorization(initCoins, nil) - expire := suite.ctx.BlockTime().Add(1 * time.Hour) + expire := suite.ctx.HeaderInfo().Time.Add(1 * time.Hour) err = suite.authzKeeper.SaveGrant(suite.ctx, grantee.Address, granter.Address, a, &expire) suite.Require().NoError(err) diff --git a/x/bank/keeper/grpc_query_test.go b/x/bank/keeper/grpc_query_test.go index b05a93e17b6..5ba4949dc10 100644 --- a/x/bank/keeper/grpc_query_test.go +++ b/x/bank/keeper/grpc_query_test.go @@ -5,6 +5,8 @@ import ( "fmt" "time" + "cosmossdk.io/core/header" + "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" @@ -173,7 +175,7 @@ func (suite *KeeperTestSuite) TestSpendableBalances() { _, _, addr := testdata.KeyTestPubAddr() ctx := sdk.UnwrapSDKContext(suite.ctx) - ctx = ctx.WithBlockTime(time.Now()) + ctx = ctx.WithHeaderInfo(header.Info{Time: time.Now()}) queryClient := suite.mockQueryClient(ctx) _, err := queryClient.SpendableBalances(ctx, &types.QuerySpendableBalancesRequest{}) @@ -200,8 +202,8 @@ func (suite *KeeperTestSuite) TestSpendableBalances() { vacc, err := vestingtypes.NewContinuousVestingAccount( acc, sdk.NewCoins(fooCoins), - ctx.BlockTime().Unix(), - ctx.BlockTime().Add(time.Hour).Unix(), + ctx.HeaderInfo().Time.Unix(), + ctx.HeaderInfo().Time.Add(time.Hour).Unix(), ) suite.Require().NoError(err) @@ -209,7 +211,7 @@ func (suite *KeeperTestSuite) TestSpendableBalances() { suite.Require().NoError(testutil.FundAccount(suite.ctx, suite.bankKeeper, addr, origCoins)) // move time forward for some tokens to vest - ctx = ctx.WithBlockTime(ctx.BlockTime().Add(30 * time.Minute)) + ctx = ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.Add(30 * time.Minute)}) queryClient = suite.mockQueryClient(ctx) suite.mockSpendableCoins(ctx, vacc) @@ -226,7 +228,7 @@ func (suite *KeeperTestSuite) TestSpendableBalanceByDenom() { _, _, addr := testdata.KeyTestPubAddr() ctx := sdk.UnwrapSDKContext(suite.ctx) - ctx = ctx.WithBlockTime(time.Now()) + ctx = ctx.WithHeaderInfo(header.Info{Time: time.Now()}) queryClient := suite.mockQueryClient(ctx) _, err := queryClient.SpendableBalanceByDenom(ctx, &types.QuerySpendableBalanceByDenomRequest{}) @@ -248,8 +250,8 @@ func (suite *KeeperTestSuite) TestSpendableBalanceByDenom() { vacc, err := vestingtypes.NewContinuousVestingAccount( acc, sdk.NewCoins(fooCoins), - ctx.BlockTime().Unix(), - ctx.BlockTime().Add(time.Hour).Unix(), + ctx.HeaderInfo().Time.Unix(), + ctx.HeaderInfo().Time.Add(time.Hour).Unix(), ) suite.Require().NoError(err) @@ -257,7 +259,7 @@ func (suite *KeeperTestSuite) TestSpendableBalanceByDenom() { suite.Require().NoError(testutil.FundAccount(suite.ctx, suite.bankKeeper, addr, origCoins)) // move time forward for half of the tokens to vest - ctx = ctx.WithBlockTime(ctx.BlockTime().Add(30 * time.Minute)) + ctx = ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.Add(30 * time.Minute)}) queryClient = suite.mockQueryClient(ctx) // check fooCoins first, it has some vested and some vesting diff --git a/x/bank/keeper/keeper.go b/x/bank/keeper/keeper.go index fe61bf565cf..e7c260cda31 100644 --- a/x/bank/keeper/keeper.go +++ b/x/bank/keeper/keeper.go @@ -435,7 +435,7 @@ func (k BaseKeeper) trackDelegation(ctx context.Context, addr sdk.AccAddress, ba if ok { // TODO: return error on account.TrackDelegation sdkCtx := sdk.UnwrapSDKContext(ctx) - vacc.TrackDelegation(sdkCtx.BlockHeader().Time, balance, amt) + vacc.TrackDelegation(sdkCtx.HeaderInfo().Time, balance, amt) k.ak.SetAccount(ctx, acc) } diff --git a/x/bank/keeper/keeper_test.go b/x/bank/keeper/keeper_test.go index b817db7e76a..b1a00cf876b 100644 --- a/x/bank/keeper/keeper_test.go +++ b/x/bank/keeper/keeper_test.go @@ -16,6 +16,7 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/suite" + "cosmossdk.io/core/header" errorsmod "cosmossdk.io/errors" "cosmossdk.io/log" "cosmossdk.io/math" @@ -1476,7 +1477,7 @@ func (suite *KeeperTestSuite) TestSpendableCoins() { suite.mockSpendableCoins(ctx, acc1) require.Equal(origCoins[0], suite.bankKeeper.SpendableCoin(ctx, accAddrs[1], "stake")) - ctx = ctx.WithBlockTime(now.Add(12 * time.Hour)) + ctx = ctx.WithHeaderInfo(header.Info{Time: now.Add(12 * time.Hour)}) suite.mockSpendableCoins(ctx, vacc) require.Equal(origCoins.Sub(lockedCoins...), suite.bankKeeper.SpendableCoins(ctx, accAddrs[0])) @@ -1508,7 +1509,7 @@ func (suite *KeeperTestSuite) TestVestingAccountSend() { suite.mockFundAccount(accAddrs[0]) require.NoError(banktestutil.FundAccount(ctx, suite.bankKeeper, accAddrs[0], sendCoins)) // require that all vested coins are spendable plus any received - ctx = ctx.WithBlockTime(now.Add(12 * time.Hour)) + ctx = ctx.WithHeaderInfo(header.Info{Time: now.Add(12 * time.Hour)}) suite.mockSendCoins(ctx, vacc, accAddrs[1]) require.NoError(suite.bankKeeper.SendCoins(ctx, accAddrs[0], accAddrs[1], sendCoins)) require.Equal(origCoins, suite.bankKeeper.GetAllBalances(ctx, accAddrs[0])) @@ -1543,7 +1544,7 @@ func (suite *KeeperTestSuite) TestPeriodicVestingAccountSend() { require.NoError(banktestutil.FundAccount(ctx, suite.bankKeeper, accAddrs[0], sendCoins)) // require that all vested coins are spendable plus any received - ctx = ctx.WithBlockTime(now.Add(12 * time.Hour)) + ctx = ctx.WithHeaderInfo(header.Info{Time: now.Add(12 * time.Hour)}) suite.mockSendCoins(ctx, vacc, accAddrs[1]) require.NoError(suite.bankKeeper.SendCoins(ctx, accAddrs[0], accAddrs[1], sendCoins)) require.Equal(origCoins, suite.bankKeeper.GetAllBalances(ctx, accAddrs[0])) @@ -1640,7 +1641,7 @@ func (suite *KeeperTestSuite) TestDelegateCoins() { suite.mockFundAccount(accAddrs[1]) require.NoError(banktestutil.FundAccount(ctx, suite.bankKeeper, accAddrs[1], origCoins)) - ctx = ctx.WithBlockTime(now.Add(12 * time.Hour)) + ctx = ctx.WithHeaderInfo(header.Info{Time: now.Add(12 * time.Hour)}) // require the ability for a non-vesting account to delegate suite.mockDelegateCoins(ctx, acc1, holderAcc) @@ -1698,7 +1699,7 @@ func (suite *KeeperTestSuite) TestUndelegateCoins() { suite.mockFundAccount(accAddrs[1]) require.NoError(banktestutil.FundAccount(ctx, suite.bankKeeper, accAddrs[1], origCoins)) - ctx = ctx.WithBlockTime(now.Add(12 * time.Hour)) + ctx = ctx.WithHeaderInfo(header.Info{Time: now.Add(12 * time.Hour)}) // require the ability for a non-vesting account to delegate suite.mockDelegateCoins(ctx, acc1, holderAcc) diff --git a/x/bank/keeper/view.go b/x/bank/keeper/view.go index dff6b989d8e..b0667e5577c 100644 --- a/x/bank/keeper/view.go +++ b/x/bank/keeper/view.go @@ -183,7 +183,7 @@ func (k BaseViewKeeper) LockedCoins(ctx context.Context, addr sdk.AccAddress) sd vacc, ok := acc.(types.VestingAccount) if ok { sdkCtx := sdk.UnwrapSDKContext(ctx) - return vacc.LockedCoins(sdkCtx.BlockTime()) + return vacc.LockedCoins(sdkCtx.HeaderInfo().Time) } } diff --git a/x/evidence/keeper/infraction.go b/x/evidence/keeper/infraction.go index e863a577f3f..f8979c70875 100644 --- a/x/evidence/keeper/infraction.go +++ b/x/evidence/keeper/infraction.go @@ -58,7 +58,7 @@ func (k Keeper) handleEquivocationEvidence(ctx context.Context, evidence *types. // calculate the age of the evidence infractionHeight := evidence.GetHeight() infractionTime := evidence.GetTime() - ageDuration := sdkCtx.BlockHeader().Time.Sub(infractionTime) + ageDuration := sdkCtx.HeaderInfo().Time.Sub(infractionTime) ageBlocks := sdkCtx.BlockHeader().Height - infractionHeight // Reject evidence if the double-sign is too old. Evidence is considered stale diff --git a/x/feegrant/basic_fee.go b/x/feegrant/basic_fee.go index e9703c96c14..a43929f3227 100644 --- a/x/feegrant/basic_fee.go +++ b/x/feegrant/basic_fee.go @@ -23,7 +23,7 @@ var _ FeeAllowanceI = (*BasicAllowance)(nil) // If remove is true (regardless of the error), the FeeAllowance will be deleted from storage // (eg. when it is used up). (See call to RevokeAllowance in Keeper.UseGrantedFees) func (a *BasicAllowance) Accept(ctx context.Context, fee sdk.Coins, _ []sdk.Msg) (bool, error) { - if a.Expiration != nil && a.Expiration.Before(sdk.UnwrapSDKContext(ctx).BlockTime()) { + if a.Expiration != nil && a.Expiration.Before(sdk.UnwrapSDKContext(ctx).HeaderInfo().Time) { return true, errorsmod.Wrap(ErrFeeLimitExpired, "basic allowance") } diff --git a/x/feegrant/basic_fee_test.go b/x/feegrant/basic_fee_test.go index 00e5ce5cc36..837e1951e66 100644 --- a/x/feegrant/basic_fee_test.go +++ b/x/feegrant/basic_fee_test.go @@ -4,10 +4,10 @@ import ( "testing" "time" - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "cosmossdk.io/core/header" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/feegrant" @@ -19,23 +19,21 @@ func TestBasicFeeValidAllow(t *testing.T) { key := storetypes.NewKVStoreKey(feegrant.StoreKey) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - ctx := testCtx.Ctx.WithBlockHeader(cmtproto.Header{Height: 1}) + ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Height: 1}) - badTime := ctx.BlockTime().AddDate(0, 0, -1) + badTime := ctx.HeaderInfo().Time.AddDate(0, 0, -1) allowace := &feegrant.BasicAllowance{ Expiration: &badTime, } require.Error(t, allowace.ValidateBasic()) - ctx = ctx.WithBlockHeader(cmtproto.Header{ - Time: time.Now(), - }) + ctx = ctx.WithHeaderInfo(header.Info{Time: time.Now()}) eth := sdk.NewCoins(sdk.NewInt64Coin("eth", 10)) atom := sdk.NewCoins(sdk.NewInt64Coin("atom", 555)) smallAtom := sdk.NewCoins(sdk.NewInt64Coin("atom", 43)) bigAtom := sdk.NewCoins(sdk.NewInt64Coin("atom", 1000)) leftAtom := sdk.NewCoins(sdk.NewInt64Coin("atom", 512)) - now := ctx.BlockTime() + now := ctx.HeaderInfo().Time oneHour := now.Add(1 * time.Hour) cases := map[string]struct { @@ -135,7 +133,7 @@ func TestBasicFeeValidAllow(t *testing.T) { err := tc.allowance.ValidateBasic() require.NoError(t, err) - ctx := testCtx.Ctx.WithBlockTime(tc.blockTime) + ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: tc.blockTime}) // now try to deduct removed, err := tc.allowance.Accept(ctx, tc.fee, []sdk.Msg{}) diff --git a/x/feegrant/filtered_fee_test.go b/x/feegrant/filtered_fee_test.go index 4e864fde74f..c2cf736ae09 100644 --- a/x/feegrant/filtered_fee_test.go +++ b/x/feegrant/filtered_fee_test.go @@ -4,10 +4,10 @@ import ( "testing" "time" - ocproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "cosmossdk.io/core/header" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/feegrant" "cosmossdk.io/x/feegrant/module" @@ -23,14 +23,14 @@ func TestFilteredFeeValidAllow(t *testing.T) { testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModuleBasic{}) - ctx := testCtx.Ctx.WithBlockHeader(ocproto.Header{Time: time.Now()}) + ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) eth := sdk.NewCoins(sdk.NewInt64Coin("eth", 10)) atom := sdk.NewCoins(sdk.NewInt64Coin("atom", 555)) smallAtom := sdk.NewCoins(sdk.NewInt64Coin("atom", 43)) bigAtom := sdk.NewCoins(sdk.NewInt64Coin("atom", 1000)) leftAtom := sdk.NewCoins(sdk.NewInt64Coin("atom", 512)) - now := ctx.BlockTime() + now := ctx.HeaderInfo().Time oneHour := now.Add(1 * time.Hour) // msg we will call in the all cases @@ -140,7 +140,7 @@ func TestFilteredFeeValidAllow(t *testing.T) { err := tc.allowance.ValidateBasic() require.NoError(t, err) - ctx := testCtx.Ctx.WithBlockTime(tc.blockTime) + ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: tc.blockTime}) // create grant var granter, grantee sdk.AccAddress diff --git a/x/feegrant/grant_test.go b/x/feegrant/grant_test.go index 31b9fb62542..52482dfa7f3 100644 --- a/x/feegrant/grant_test.go +++ b/x/feegrant/grant_test.go @@ -4,9 +4,9 @@ import ( "testing" "time" - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/stretchr/testify/require" + "cosmossdk.io/core/header" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/feegrant" "cosmossdk.io/x/feegrant/module" @@ -23,14 +23,14 @@ func TestGrant(t *testing.T) { testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModuleBasic{}) - ctx := testCtx.Ctx.WithBlockHeader(cmtproto.Header{Time: time.Now()}) + ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) addr, err := addressCodec.StringToBytes("cosmos1qk93t4j0yyzgqgt6k5qf8deh8fq6smpn3ntu3x") require.NoError(t, err) addr2, err := addressCodec.StringToBytes("cosmos1p9qh4ldfd6n0qehujsal4k7g0e37kel90rc4ts") require.NoError(t, err) atom := sdk.NewCoins(sdk.NewInt64Coin("atom", 555)) - now := ctx.BlockTime() + now := ctx.HeaderInfo().Time oneYear := now.AddDate(1, 0, 0) zeroAtoms := sdk.NewCoins(sdk.NewInt64Coin("atom", 0)) diff --git a/x/feegrant/keeper/genesis_test.go b/x/feegrant/keeper/genesis_test.go index ff0c2f9c214..0f4ddbe8eba 100644 --- a/x/feegrant/keeper/genesis_test.go +++ b/x/feegrant/keeper/genesis_test.go @@ -62,7 +62,7 @@ func TestImportExportGenesis(t *testing.T) { f.accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec("cosmos")).AnyTimes() coins := sdk.NewCoins(sdk.NewCoin("foo", math.NewInt(1_000))) - now := f.ctx.BlockHeader().Time + now := f.ctx.HeaderInfo().Time oneYear := now.AddDate(1, 0, 0) msgSrvr := keeper.NewMsgServerImpl(f.feegrantKeeper) diff --git a/x/feegrant/keeper/grpc_query_test.go b/x/feegrant/keeper/grpc_query_test.go index 25afdd1f3d9..edb7208180c 100644 --- a/x/feegrant/keeper/grpc_query_test.go +++ b/x/feegrant/keeper/grpc_query_test.go @@ -234,7 +234,7 @@ func (suite *KeeperTestSuite) TestFeeAllowancesByGranter() { } func (suite *KeeperTestSuite) grantFeeAllowance(granter, grantee sdk.AccAddress) { - exp := suite.ctx.BlockTime().AddDate(1, 0, 0) + exp := suite.ctx.HeaderInfo().Time.AddDate(1, 0, 0) err := suite.feegrantKeeper.GrantAllowance(suite.ctx, granter, grantee, &feegrant.BasicAllowance{ SpendLimit: sdk.NewCoins(sdk.NewInt64Coin("atom", 555)), Expiration: &exp, diff --git a/x/feegrant/keeper/keeper.go b/x/feegrant/keeper/keeper.go index 5c994552527..e18dbfdeaa0 100644 --- a/x/feegrant/keeper/keeper.go +++ b/x/feegrant/keeper/keeper.go @@ -85,7 +85,7 @@ func (k Keeper) GrantAllowance(ctx context.Context, granter, grantee sdk.AccAddr // expiration shouldn't be in the past. sdkCtx := sdk.UnwrapSDKContext(ctx) - if exp != nil && exp.Before(sdkCtx.BlockTime()) { + if exp != nil && exp.Before(sdkCtx.HeaderInfo().Time) { return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "expiration is before current block time") } @@ -299,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) error { - exp := sdk.UnwrapSDKContext(ctx).BlockTime() + exp := sdk.UnwrapSDKContext(ctx).HeaderInfo().Time rng := collections.NewPrefixUntilTripleRange[time.Time, sdk.AccAddress, sdk.AccAddress](exp) err := k.FeeAllowanceQueue.Walk(ctx, rng, func(key collections.Triple[time.Time, sdk.AccAddress, sdk.AccAddress], value bool) (stop bool, err error) { diff --git a/x/feegrant/keeper/keeper_test.go b/x/feegrant/keeper/keeper_test.go index b1222ce8174..65edbd91668 100644 --- a/x/feegrant/keeper/keeper_test.go +++ b/x/feegrant/keeper/keeper_test.go @@ -6,6 +6,7 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/suite" + "cosmossdk.io/core/header" sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/feegrant" @@ -62,8 +63,8 @@ func (suite *KeeperTestSuite) SetupTest() { func (suite *KeeperTestSuite) TestKeeperCrud() { // some helpers eth := sdk.NewCoins(sdk.NewInt64Coin("eth", 123)) - exp := suite.ctx.BlockTime().AddDate(1, 0, 0) - exp2 := suite.ctx.BlockTime().AddDate(2, 0, 0) + exp := suite.ctx.HeaderInfo().Time.AddDate(1, 0, 0) + exp2 := suite.ctx.HeaderInfo().Time.AddDate(2, 0, 0) basic := &feegrant.BasicAllowance{ SpendLimit: suite.atom, Expiration: &exp, @@ -188,7 +189,7 @@ func (suite *KeeperTestSuite) TestKeeperCrud() { func (suite *KeeperTestSuite) TestUseGrantedFee() { eth := sdk.NewCoins(sdk.NewInt64Coin("eth", 123)) - blockTime := suite.ctx.BlockTime() + blockTime := suite.ctx.HeaderInfo().Time oneYear := blockTime.AddDate(1, 0, 0) future := &feegrant.BasicAllowance{ @@ -281,7 +282,7 @@ func (suite *KeeperTestSuite) TestUseGrantedFee() { suite.Require().NoError(err) // waiting for future blocks, allowance to be pruned. - ctx := suite.ctx.WithBlockTime(oneYear) + ctx := suite.ctx.WithHeaderInfo(header.Info{Time: oneYear}) // expect error: feegrant expired err = suite.feegrantKeeper.UseGrantedFees(ctx, suite.addrs[0], suite.addrs[2], eth, []sdk.Msg{}) @@ -296,7 +297,7 @@ func (suite *KeeperTestSuite) TestUseGrantedFee() { func (suite *KeeperTestSuite) TestIterateGrants() { eth := sdk.NewCoins(sdk.NewInt64Coin("eth", 123)) - exp := suite.ctx.BlockTime().AddDate(1, 0, 0) + exp := suite.ctx.HeaderInfo().Time.AddDate(1, 0, 0) allowance := &feegrant.BasicAllowance{ SpendLimit: suite.atom, @@ -322,7 +323,7 @@ func (suite *KeeperTestSuite) TestIterateGrants() { func (suite *KeeperTestSuite) TestPruneGrants() { eth := sdk.NewCoins(sdk.NewInt64Coin("eth", 123)) - now := suite.ctx.BlockTime() + now := suite.ctx.HeaderInfo().Time oneDay := now.AddDate(0, 0, 1) oneYearExpiry := now.AddDate(1, 0, 0) @@ -359,7 +360,7 @@ func (suite *KeeperTestSuite) TestPruneGrants() { }, { name: "grant pruned from state after a day: error", - ctx: suite.ctx.WithBlockTime(now.AddDate(0, 0, 1)), + ctx: suite.ctx.WithHeaderInfo(header.Info{Time: now.AddDate(0, 0, 1)}), granter: suite.addrs[1], grantee: suite.addrs[0], expErrMsg: "not found", @@ -370,7 +371,7 @@ func (suite *KeeperTestSuite) TestPruneGrants() { }, { name: "grant not pruned from state after a day: no error", - ctx: suite.ctx.WithBlockTime(now.AddDate(0, 0, 1)), + ctx: suite.ctx.WithHeaderInfo(header.Info{Time: now.AddDate(0, 0, 1)}), granter: suite.addrs[1], grantee: suite.addrs[0], allowance: &feegrant.BasicAllowance{ @@ -380,7 +381,7 @@ func (suite *KeeperTestSuite) TestPruneGrants() { }, { name: "grant pruned from state after a year: error", - ctx: suite.ctx.WithBlockTime(now.AddDate(1, 0, 0)), + ctx: suite.ctx.WithHeaderInfo(header.Info{Time: now.AddDate(1, 0, 0)}), granter: suite.addrs[1], grantee: suite.addrs[2], expErrMsg: "not found", @@ -391,7 +392,7 @@ func (suite *KeeperTestSuite) TestPruneGrants() { }, { name: "no expiry: no error", - ctx: suite.ctx.WithBlockTime(now.AddDate(1, 0, 0)), + ctx: suite.ctx.WithHeaderInfo(header.Info{Time: now.AddDate(1, 0, 0)}), granter: suite.addrs[1], grantee: suite.addrs[2], allowance: &feegrant.BasicAllowance{ diff --git a/x/feegrant/keeper/msg_server_test.go b/x/feegrant/keeper/msg_server_test.go index e6b0307c0e4..ceac419a572 100644 --- a/x/feegrant/keeper/msg_server_test.go +++ b/x/feegrant/keeper/msg_server_test.go @@ -5,6 +5,7 @@ import ( "github.com/golang/mock/gomock" + "cosmossdk.io/core/header" "cosmossdk.io/x/feegrant" codecaddress "github.com/cosmos/cosmos-sdk/codec/address" @@ -13,9 +14,9 @@ import ( ) func (suite *KeeperTestSuite) TestGrantAllowance() { - ctx := suite.ctx.WithBlockTime(time.Now()) - oneYear := ctx.BlockTime().AddDate(1, 0, 0) - yesterday := ctx.BlockTime().AddDate(0, 0, -1) + ctx := suite.ctx.WithHeaderInfo(header.Info{Time: time.Now()}) + oneYear := ctx.HeaderInfo().Time.AddDate(1, 0, 0) + yesterday := ctx.HeaderInfo().Time.AddDate(0, 0, -1) addressCodec := codecaddress.NewBech32Codec("cosmos") @@ -190,7 +191,8 @@ func (suite *KeeperTestSuite) TestGrantAllowance() { } func (suite *KeeperTestSuite) TestRevokeAllowance() { - oneYear := suite.ctx.BlockTime().AddDate(1, 0, 0) + suite.ctx = suite.ctx.WithHeaderInfo(header.Info{Time: time.Now()}) + oneYear := suite.ctx.HeaderInfo().Time.AddDate(1, 0, 0) testCases := []struct { name string diff --git a/x/feegrant/migrations/v2/store.go b/x/feegrant/migrations/v2/store.go index 72fb847bbb8..a90f83531ab 100644 --- a/x/feegrant/migrations/v2/store.go +++ b/x/feegrant/migrations/v2/store.go @@ -37,7 +37,7 @@ func addAllowancesByExpTimeQueue(ctx context.Context, store store.KVStore, cdc c if exp != nil { // store key is not changed in 0.46 key := iterator.Key() - if exp.Before(types.UnwrapSDKContext(ctx).BlockTime()) { + if exp.Before(types.UnwrapSDKContext(ctx).HeaderInfo().Time) { prefixStore.Delete(key) } else { grantByExpTimeQueueKey := FeeAllowancePrefixQueue(exp, key) diff --git a/x/feegrant/migrations/v2/store_test.go b/x/feegrant/migrations/v2/store_test.go index 7b2ad151716..8dbafea7f9f 100644 --- a/x/feegrant/migrations/v2/store_test.go +++ b/x/feegrant/migrations/v2/store_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/require" + "cosmossdk.io/core/header" sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/feegrant" @@ -31,7 +32,7 @@ func TestMigration(t *testing.T) { grantee2 := sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) spendLimit := sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(1000))) - now := ctx.BlockTime() + now := ctx.HeaderInfo().Time oneDay := now.AddDate(0, 0, 1) twoDays := now.AddDate(0, 0, 2) @@ -79,7 +80,7 @@ func TestMigration(t *testing.T) { store.Set(v2.FeeAllowanceKey(grant.granter, grant.grantee), bz) } - ctx = ctx.WithBlockTime(now.Add(30 * time.Hour)) + ctx = ctx.WithHeaderInfo(header.Info{Time: now.Add(30 * time.Hour)}) require.NoError(t, v2.MigrateStore(ctx, runtime.NewKVStoreService(feegrantKey), cdc)) store = ctx.KVStore(feegrantKey) diff --git a/x/feegrant/module/abci_test.go b/x/feegrant/module/abci_test.go index 6e7bc0a41a8..5af790303f9 100644 --- a/x/feegrant/module/abci_test.go +++ b/x/feegrant/module/abci_test.go @@ -6,6 +6,7 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" + "cosmossdk.io/core/header" sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/feegrant" @@ -34,7 +35,7 @@ func TestFeegrantPruning(t *testing.T) { granter3 := addrs[2] grantee := addrs[3] spendLimit := sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(1000))) - now := testCtx.Ctx.BlockTime() + now := testCtx.Ctx.HeaderInfo().Time oneDay := now.AddDate(0, 0, 1) ctrl := gomock.NewController(t) @@ -91,7 +92,7 @@ func TestFeegrantPruning(t *testing.T) { require.NotNil(t, res) require.Len(t, res.Allowances, 2) - testCtx.Ctx = testCtx.Ctx.WithBlockTime(now.AddDate(0, 0, 2)) + testCtx.Ctx = testCtx.Ctx.WithHeaderInfo(header.Info{Time: now.AddDate(0, 0, 2)}) module.EndBlocker(testCtx.Ctx, feegrantKeeper) res, err = queryClient.Allowances(testCtx.Ctx.Context(), &feegrant.QueryAllowancesRequest{ diff --git a/x/feegrant/periodic_fee.go b/x/feegrant/periodic_fee.go index d5906c955a6..1b12a63ef96 100644 --- a/x/feegrant/periodic_fee.go +++ b/x/feegrant/periodic_fee.go @@ -23,7 +23,7 @@ var _ FeeAllowanceI = (*PeriodicAllowance)(nil) // If remove is true (regardless of the error), the FeeAllowance will be deleted from storage // (eg. when it is used up). (See call to RevokeAllowance in Keeper.UseGrantedFees) func (a *PeriodicAllowance) Accept(ctx context.Context, fee sdk.Coins, _ []sdk.Msg) (bool, error) { - blockTime := sdk.UnwrapSDKContext(ctx).BlockTime() + blockTime := sdk.UnwrapSDKContext(ctx).HeaderInfo().Time if a.Basic.Expiration != nil && blockTime.After(*a.Basic.Expiration) { return true, errorsmod.Wrap(ErrFeeLimitExpired, "absolute limit") diff --git a/x/feegrant/periodic_fee_test.go b/x/feegrant/periodic_fee_test.go index 911973c6048..1b7f942f72f 100644 --- a/x/feegrant/periodic_fee_test.go +++ b/x/feegrant/periodic_fee_test.go @@ -4,10 +4,10 @@ import ( "testing" "time" - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "cosmossdk.io/core/header" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/feegrant" @@ -19,7 +19,7 @@ func TestPeriodicFeeValidAllow(t *testing.T) { key := storetypes.NewKVStoreKey(feegrant.StoreKey) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - ctx := testCtx.Ctx.WithBlockHeader(cmtproto.Header{Time: time.Now()}) + ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) atom := sdk.NewCoins(sdk.NewInt64Coin("atom", 555)) smallAtom := sdk.NewCoins(sdk.NewInt64Coin("atom", 43)) @@ -28,7 +28,7 @@ func TestPeriodicFeeValidAllow(t *testing.T) { eth := sdk.NewCoins(sdk.NewInt64Coin("eth", 1)) emptyCoins := sdk.Coins{} - now := ctx.BlockTime() + now := ctx.HeaderInfo().Time oneHour := now.Add(1 * time.Hour) twoHours := now.Add(2 * time.Hour) tenMinutes := time.Duration(10) * time.Minute @@ -197,7 +197,7 @@ func TestPeriodicFeeValidAllow(t *testing.T) { } require.NoError(t, err) - ctx := testCtx.Ctx.WithBlockTime(tc.blockTime) + ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: tc.blockTime}) // now try to deduct remove, err := tc.allow.Accept(ctx, tc.fee, []sdk.Msg{}) if !tc.accept { diff --git a/x/feegrant/simulation/operations.go b/x/feegrant/simulation/operations.go index ddbe72ec5bc..38f2ef9f0c3 100644 --- a/x/feegrant/simulation/operations.go +++ b/x/feegrant/simulation/operations.go @@ -98,7 +98,7 @@ func SimulateMsgGrantAllowance( return simtypes.NoOpMsg(feegrant.ModuleName, TypeMsgGrantAllowance, "unable to grant empty coins as SpendLimit"), nil, nil } - oneYear := ctx.BlockTime().AddDate(1, 0, 0) + oneYear := ctx.HeaderInfo().Time.AddDate(1, 0, 0) msg, err := feegrant.NewMsgGrantAllowance(&feegrant.BasicAllowance{ SpendLimit: spendableCoins, Expiration: &oneYear, diff --git a/x/feegrant/simulation/operations_test.go b/x/feegrant/simulation/operations_test.go index a86d13c341e..f9bd1723e99 100644 --- a/x/feegrant/simulation/operations_test.go +++ b/x/feegrant/simulation/operations_test.go @@ -10,6 +10,7 @@ import ( "github.com/cosmos/gogoproto/proto" "github.com/stretchr/testify/suite" + "cosmossdk.io/core/header" "cosmossdk.io/depinject" "cosmossdk.io/log" "cosmossdk.io/x/feegrant" @@ -99,8 +100,6 @@ func (suite *SimTestSuite) getTestingAccounts(r *rand.Rand, n int) []simtypes.Ac func (suite *SimTestSuite) TestWeightedOperations() { require := suite.Require() - suite.ctx.WithChainID("test-chain") - appParams := make(simtypes.AppParams) weightedOps := simulation.WeightedOperations( @@ -131,7 +130,7 @@ func (suite *SimTestSuite) TestWeightedOperations() { } for i, w := range weightedOps { - operationMsg, _, err := w.Op()(r, suite.app.BaseApp, suite.ctx, accs, suite.ctx.ChainID()) + operationMsg, _, err := w.Op()(r, suite.app.BaseApp, suite.ctx.WithHeaderInfo(header.Info{Time: time.Now()}), accs, suite.ctx.ChainID()) require.NoError(err) // the following checks are very much dependent from the ordering of the output given @@ -157,7 +156,7 @@ func (suite *SimTestSuite) TestSimulateMsgGrantAllowance() { // execute operation op := simulation.SimulateMsgGrantAllowance(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.feegrantKeeper) - operationMsg, futureOperations, err := op(r, app.BaseApp, ctx, accounts, "") + operationMsg, futureOperations, err := op(r, app.BaseApp, ctx.WithHeaderInfo(header.Info{Time: time.Now()}), accounts, "") require.NoError(err) var msg feegrant.MsgGrantAllowance @@ -185,7 +184,7 @@ func (suite *SimTestSuite) TestSimulateMsgRevokeAllowance() { granter, grantee := accounts[0], accounts[1] - oneYear := ctx.BlockTime().AddDate(1, 0, 0) + oneYear := ctx.HeaderInfo().Time.AddDate(1, 0, 0) err = suite.feegrantKeeper.GrantAllowance( ctx, granter.Address, diff --git a/x/gov/abci.go b/x/gov/abci.go index f376afd4758..411c4da5782 100644 --- a/x/gov/abci.go +++ b/x/gov/abci.go @@ -20,7 +20,7 @@ func EndBlocker(ctx sdk.Context, keeper *keeper.Keeper) error { logger := ctx.Logger().With("module", "x/"+types.ModuleName) // 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](ctx.BlockTime()) + rng := collections.NewPrefixUntilPairRange[time.Time, uint64](ctx.HeaderInfo().Time) err := keeper.InactiveProposalsQueue.Walk(ctx, rng, func(key collections.Pair[time.Time, uint64], _ uint64) (bool, error) { proposal, err := keeper.Proposals.Get(ctx, key.K2()) if err != nil { @@ -72,7 +72,7 @@ func EndBlocker(ctx sdk.Context, keeper *keeper.Keeper) error { } // fetch active proposals whose voting periods have ended (are passed the block time) - rng = collections.NewPrefixUntilPairRange[time.Time, uint64](ctx.BlockTime()) + rng = collections.NewPrefixUntilPairRange[time.Time, uint64](ctx.HeaderInfo().Time) err = keeper.ActiveProposalsQueue.Walk(ctx, rng, func(key collections.Pair[time.Time, uint64], _ uint64) (bool, error) { proposal, err := keeper.Proposals.Get(ctx, key.K2()) if err != nil { diff --git a/x/gov/abci_test.go b/x/gov/abci_test.go index c43d07a8a95..915efd2333f 100644 --- a/x/gov/abci_test.go +++ b/x/gov/abci_test.go @@ -54,16 +54,16 @@ func TestTickExpiredDepositPeriod(t *testing.T) { checkInactiveProposalsQueue(t, ctx, suite.GovKeeper) - newHeader := ctx.BlockHeader() - newHeader.Time = ctx.BlockHeader().Time.Add(time.Duration(1) * time.Second) - ctx = ctx.WithBlockHeader(newHeader) + newHeader := ctx.HeaderInfo() + newHeader.Time = ctx.HeaderInfo().Time.Add(time.Duration(1) * time.Second) + ctx = ctx.WithHeaderInfo(newHeader) checkInactiveProposalsQueue(t, ctx, suite.GovKeeper) params, _ := suite.GovKeeper.Params.Get(ctx) - newHeader = ctx.BlockHeader() - newHeader.Time = ctx.BlockHeader().Time.Add(*params.MaxDepositPeriod) - ctx = ctx.WithBlockHeader(newHeader) + newHeader = ctx.HeaderInfo() + newHeader.Time = ctx.HeaderInfo().Time.Add(*params.MaxDepositPeriod) + ctx = ctx.WithHeaderInfo(newHeader) checkInactiveProposalsQueue(t, ctx, suite.GovKeeper) @@ -105,9 +105,9 @@ func TestTickMultipleExpiredDepositPeriod(t *testing.T) { checkInactiveProposalsQueue(t, ctx, suite.GovKeeper) - newHeader := ctx.BlockHeader() - newHeader.Time = ctx.BlockHeader().Time.Add(time.Duration(2) * time.Second) - ctx = ctx.WithBlockHeader(newHeader) + newHeader := ctx.HeaderInfo() + newHeader.Time = ctx.HeaderInfo().Time.Add(time.Duration(2) * time.Second) + ctx = ctx.WithHeaderInfo(newHeader) checkInactiveProposalsQueue(t, ctx, suite.GovKeeper) @@ -126,18 +126,18 @@ func TestTickMultipleExpiredDepositPeriod(t *testing.T) { require.NoError(t, err) require.NotNil(t, res) - newHeader = ctx.BlockHeader() + newHeader = ctx.HeaderInfo() params, _ := suite.GovKeeper.Params.Get(ctx) - newHeader.Time = ctx.BlockHeader().Time.Add(*params.MaxDepositPeriod).Add(time.Duration(-1) * time.Second) - ctx = ctx.WithBlockHeader(newHeader) + newHeader.Time = ctx.HeaderInfo().Time.Add(*params.MaxDepositPeriod).Add(time.Duration(-1) * time.Second) + ctx = ctx.WithHeaderInfo(newHeader) checkInactiveProposalsQueue(t, ctx, suite.GovKeeper) require.NoError(t, gov.EndBlocker(ctx, suite.GovKeeper)) checkInactiveProposalsQueue(t, ctx, suite.GovKeeper) - newHeader = ctx.BlockHeader() - newHeader.Time = ctx.BlockHeader().Time.Add(time.Duration(5) * time.Second) - ctx = ctx.WithBlockHeader(newHeader) + newHeader = ctx.HeaderInfo() + newHeader.Time = ctx.HeaderInfo().Time.Add(time.Duration(5) * time.Second) + ctx = ctx.WithHeaderInfo(newHeader) checkInactiveProposalsQueue(t, ctx, suite.GovKeeper) require.NoError(t, gov.EndBlocker(ctx, suite.GovKeeper)) @@ -176,9 +176,9 @@ func TestTickPassedDepositPeriod(t *testing.T) { checkInactiveProposalsQueue(t, ctx, suite.GovKeeper) - newHeader := ctx.BlockHeader() - newHeader.Time = ctx.BlockHeader().Time.Add(time.Duration(1) * time.Second) - ctx = ctx.WithBlockHeader(newHeader) + newHeader := ctx.HeaderInfo() + newHeader.Time = ctx.HeaderInfo().Time.Add(time.Duration(1) * time.Second) + ctx = ctx.WithHeaderInfo(newHeader) checkInactiveProposalsQueue(t, ctx, suite.GovKeeper) @@ -235,9 +235,9 @@ func TestTickPassedVotingPeriod(t *testing.T) { proposalID := res.ProposalId - newHeader := ctx.BlockHeader() - newHeader.Time = ctx.BlockHeader().Time.Add(time.Duration(1) * time.Second) - ctx = ctx.WithBlockHeader(newHeader) + newHeader := ctx.HeaderInfo() + newHeader.Time = ctx.HeaderInfo().Time.Add(time.Duration(1) * time.Second) + ctx = ctx.WithHeaderInfo(newHeader) newDepositMsg := v1.NewMsgDeposit(addrs[1], proposalID, proposalCoins) @@ -251,9 +251,9 @@ func TestTickPassedVotingPeriod(t *testing.T) { votingPeriod = params.ExpeditedVotingPeriod } - newHeader = ctx.BlockHeader() - newHeader.Time = ctx.BlockHeader().Time.Add(*params.MaxDepositPeriod).Add(*votingPeriod) - ctx = ctx.WithBlockHeader(newHeader) + newHeader = ctx.HeaderInfo() + newHeader.Time = ctx.HeaderInfo().Time.Add(*params.MaxDepositPeriod).Add(*votingPeriod) + ctx = ctx.WithHeaderInfo(newHeader) checkInactiveProposalsQueue(t, ctx, suite.GovKeeper) checkActiveProposalsQueue(t, ctx, suite.GovKeeper) @@ -345,10 +345,10 @@ func TestProposalPassedEndblocker(t *testing.T) { err = suite.GovKeeper.AddVote(ctx, proposal.Id, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "") require.NoError(t, err) - newHeader := ctx.BlockHeader() + newHeader := ctx.HeaderInfo() params, _ := suite.GovKeeper.Params.Get(ctx) - newHeader.Time = ctx.BlockHeader().Time.Add(*params.MaxDepositPeriod).Add(*params.VotingPeriod) - ctx = ctx.WithBlockHeader(newHeader) + newHeader.Time = ctx.HeaderInfo().Time.Add(*params.MaxDepositPeriod).Add(*params.VotingPeriod) + ctx = ctx.WithHeaderInfo(newHeader) err = gov.EndBlocker(ctx, suite.GovKeeper) require.NoError(t, err) @@ -397,9 +397,9 @@ func TestEndBlockerProposalHandlerFailed(t *testing.T) { require.NoError(t, err) params, _ := suite.GovKeeper.Params.Get(ctx) - newHeader := ctx.BlockHeader() - newHeader.Time = ctx.BlockHeader().Time.Add(*params.MaxDepositPeriod).Add(*params.VotingPeriod) - ctx = ctx.WithBlockHeader(newHeader) + newHeader := ctx.HeaderInfo() + newHeader.Time = ctx.HeaderInfo().Time.Add(*params.MaxDepositPeriod).Add(*params.VotingPeriod) + ctx = ctx.WithHeaderInfo(newHeader) // validate that the proposal fails/has been rejected err = gov.EndBlocker(ctx, suite.GovKeeper) @@ -487,9 +487,9 @@ func TestExpeditedProposal_PassAndConversionToRegular(t *testing.T) { proposalID := res.ProposalId - newHeader := ctx.BlockHeader() - newHeader.Time = ctx.BlockHeader().Time.Add(time.Duration(1) * time.Second) - ctx = ctx.WithBlockHeader(newHeader) + newHeader := ctx.HeaderInfo() + newHeader.Time = ctx.HeaderInfo().Time.Add(time.Duration(1) * time.Second) + ctx = ctx.WithHeaderInfo(newHeader) newDepositMsg := v1.NewMsgDeposit(addrs[1], proposalID, proposalCoins) @@ -497,9 +497,9 @@ func TestExpeditedProposal_PassAndConversionToRegular(t *testing.T) { require.NoError(t, err) require.NotNil(t, res1) - newHeader = ctx.BlockHeader() - newHeader.Time = ctx.BlockHeader().Time.Add(*params.MaxDepositPeriod).Add(*params.ExpeditedVotingPeriod) - ctx = ctx.WithBlockHeader(newHeader) + newHeader = ctx.HeaderInfo() + newHeader.Time = ctx.HeaderInfo().Time.Add(*params.MaxDepositPeriod).Add(*params.ExpeditedVotingPeriod) + ctx = ctx.WithHeaderInfo(newHeader) checkInactiveProposalsQueue(t, ctx, suite.GovKeeper) checkActiveProposalsQueue(t, ctx, suite.GovKeeper) @@ -557,8 +557,8 @@ func TestExpeditedProposal_PassAndConversionToRegular(t *testing.T) { require.Equal(t, expectedIntermediateMofuleAccCoings, intermediateModuleAccCoins) // block header time at the voting period - newHeader.Time = ctx.BlockHeader().Time.Add(*params.MaxDepositPeriod).Add(*params.VotingPeriod) - ctx = ctx.WithBlockHeader(newHeader) + newHeader.Time = ctx.HeaderInfo().Time.Add(*params.MaxDepositPeriod).Add(*params.VotingPeriod) + ctx = ctx.WithHeaderInfo(newHeader) checkInactiveProposalsQueue(t, ctx, suite.GovKeeper) checkActiveProposalsQueue(t, ctx, suite.GovKeeper) @@ -634,7 +634,7 @@ func getDepositMultiplier(expedited bool) int64 { func checkActiveProposalsQueue(t *testing.T, ctx sdk.Context, k *keeper.Keeper) { t.Helper() - err := k.ActiveProposalsQueue.Walk(ctx, collections.NewPrefixUntilPairRange[time.Time, uint64](ctx.BlockTime()), func(key collections.Pair[time.Time, uint64], value uint64) (stop bool, err error) { + err := k.ActiveProposalsQueue.Walk(ctx, collections.NewPrefixUntilPairRange[time.Time, uint64](ctx.HeaderInfo().Time), func(key collections.Pair[time.Time, uint64], value uint64) (stop bool, err error) { return false, err }) @@ -643,7 +643,7 @@ func checkActiveProposalsQueue(t *testing.T, ctx sdk.Context, k *keeper.Keeper) func checkInactiveProposalsQueue(t *testing.T, ctx sdk.Context, k *keeper.Keeper) { t.Helper() - err := k.InactiveProposalsQueue.Walk(ctx, collections.NewPrefixUntilPairRange[time.Time, uint64](ctx.BlockTime()), func(key collections.Pair[time.Time, uint64], value uint64) (stop bool, err error) { + err := k.InactiveProposalsQueue.Walk(ctx, collections.NewPrefixUntilPairRange[time.Time, uint64](ctx.HeaderInfo().Time), func(key collections.Pair[time.Time, uint64], value uint64) (stop bool, err error) { return false, err }) diff --git a/x/gov/keeper/common_test.go b/x/gov/keeper/common_test.go index 680c6495c03..913f6ebbea9 100644 --- a/x/gov/keeper/common_test.go +++ b/x/gov/keeper/common_test.go @@ -3,12 +3,12 @@ package keeper_test import ( "fmt" "testing" + "time" - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - cmttime "github.com/cometbft/cometbft/types/time" "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" + "cosmossdk.io/core/header" "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" @@ -93,7 +93,7 @@ func setupGovKeeper(t *testing.T, expectations ...func(sdk.Context, mocks)) ( key := storetypes.NewKVStoreKey(types.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) - ctx := testCtx.Ctx.WithBlockHeader(cmtproto.Header{Time: cmttime.Now()}) + ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) encCfg := moduletestutil.MakeTestEncodingConfig() v1.RegisterInterfaces(encCfg.InterfaceRegistry) v1beta1.RegisterInterfaces(encCfg.InterfaceRegistry) diff --git a/x/gov/keeper/deposit_test.go b/x/gov/keeper/deposit_test.go index 97baf54321a..8c29b849cf9 100644 --- a/x/gov/keeper/deposit_test.go +++ b/x/gov/keeper/deposit_test.go @@ -115,7 +115,7 @@ func TestDeposits(t *testing.T) { // Check that proposal moved to voting period proposal, err = govKeeper.Proposals.Get(ctx, proposalID) require.Nil(t, err) - require.True(t, proposal.VotingStartTime.Equal(ctx.BlockHeader().Time)) + require.True(t, proposal.VotingStartTime.Equal(ctx.HeaderInfo().Time)) // Test deposit iterator // NOTE order of deposits is determined by the addresses diff --git a/x/gov/keeper/hooks_test.go b/x/gov/keeper/hooks_test.go index 2123f481243..72fe3b8ddcc 100644 --- a/x/gov/keeper/hooks_test.go +++ b/x/gov/keeper/hooks_test.go @@ -74,9 +74,9 @@ func TestHooks(t *testing.T) { require.True(t, govHooksReceiver.AfterProposalSubmissionValid) params, _ := govKeeper.Params.Get(ctx) - newHeader := ctx.BlockHeader() - newHeader.Time = ctx.BlockHeader().Time.Add(*params.MaxDepositPeriod).Add(time.Duration(1) * time.Second) - ctx = ctx.WithBlockHeader(newHeader) + newHeader := ctx.HeaderInfo() + newHeader.Time = ctx.HeaderInfo().Time.Add(*params.MaxDepositPeriod).Add(time.Duration(1) * time.Second) + ctx = ctx.WithHeaderInfo(newHeader) err = gov.EndBlocker(ctx, govKeeper) require.NoError(t, err) @@ -94,9 +94,9 @@ func TestHooks(t *testing.T) { require.NoError(t, err) require.True(t, govHooksReceiver.AfterProposalVoteValid) - newHeader = ctx.BlockHeader() - newHeader.Time = ctx.BlockHeader().Time.Add(*params.VotingPeriod).Add(time.Duration(1) * time.Second) - ctx = ctx.WithBlockHeader(newHeader) + newHeader = ctx.HeaderInfo() + newHeader.Time = ctx.HeaderInfo().Time.Add(*params.VotingPeriod).Add(time.Duration(1) * time.Second) + ctx = ctx.WithHeaderInfo(newHeader) err = gov.EndBlocker(ctx, govKeeper) require.NoError(t, err) require.True(t, govHooksReceiver.AfterProposalVotingPeriodEndedValid) diff --git a/x/gov/keeper/msg_server.go b/x/gov/keeper/msg_server.go index 967dd772988..cdc48a83039 100644 --- a/x/gov/keeper/msg_server.go +++ b/x/gov/keeper/msg_server.go @@ -141,7 +141,7 @@ func (k msgServer) CancelProposal(goCtx context.Context, msg *v1.MsgCancelPropos return &v1.MsgCancelProposalResponse{ ProposalId: msg.ProposalId, - CanceledTime: ctx.BlockTime(), + CanceledTime: ctx.HeaderInfo().Time, CanceledHeight: uint64(ctx.BlockHeight()), }, nil } diff --git a/x/gov/keeper/proposal.go b/x/gov/keeper/proposal.go index 35080aaea01..a2c186ec5cc 100644 --- a/x/gov/keeper/proposal.go +++ b/x/gov/keeper/proposal.go @@ -96,7 +96,7 @@ func (keeper Keeper) SubmitProposal(ctx context.Context, messages []sdk.Msg, met return v1.Proposal{}, err } - submitTime := sdkCtx.BlockHeader().Time + submitTime := sdkCtx.HeaderInfo().Time depositPeriod := params.MaxDepositPeriod proposal, err := v1.NewProposal(messages, proposalID, submitTime, submitTime.Add(*depositPeriod), metadata, title, summary, proposer, expedited) @@ -152,7 +152,7 @@ func (keeper Keeper) CancelProposal(ctx context.Context, proposalID uint64, prop } // Check proposal voting period is ended. - if proposal.VotingEndTime != nil && proposal.VotingEndTime.Before(sdkCtx.BlockTime()) { + if proposal.VotingEndTime != nil && proposal.VotingEndTime.Before(sdkCtx.HeaderInfo().Time) { return types.ErrVotingPeriodEnded.Wrapf("voting period is already ended for this proposal %d", proposalID) } @@ -237,7 +237,7 @@ func (keeper Keeper) DeleteProposal(ctx context.Context, proposalID uint64) erro // ActivateVotingPeriod activates the voting period of a proposal func (keeper Keeper) ActivateVotingPeriod(ctx context.Context, proposal v1.Proposal) error { sdkCtx := sdk.UnwrapSDKContext(ctx) - startTime := sdkCtx.BlockHeader().Time + startTime := sdkCtx.HeaderInfo().Time proposal.VotingStartTime = &startTime var votingPeriod *time.Duration params, err := keeper.Params.Get(ctx) diff --git a/x/gov/keeper/proposal_test.go b/x/gov/keeper/proposal_test.go index 7147c7defc8..f51b4c2e3e3 100644 --- a/x/gov/keeper/proposal_test.go +++ b/x/gov/keeper/proposal_test.go @@ -2,6 +2,7 @@ package keeper_test import ( "errors" + "fmt" "strings" "testing" @@ -91,7 +92,7 @@ func (suite *KeeperTestSuite) TestActivateVotingPeriod() { proposal, err = suite.govKeeper.Proposals.Get(suite.ctx, proposal.Id) suite.Require().Nil(err) - suite.Require().True(proposal.VotingStartTime.Equal(suite.ctx.BlockHeader().Time)) + suite.Require().True(proposal.VotingStartTime.Equal(suite.ctx.HeaderInfo().Time)) has, err := suite.govKeeper.ActiveProposalsQueue.Has(suite.ctx, collections.Join(*proposal.VotingEndTime, proposal.Id)) suite.Require().NoError(err) @@ -120,7 +121,7 @@ func (suite *KeeperTestSuite) TestDeleteProposalInVotingPeriod() { proposal, err = suite.govKeeper.Proposals.Get(suite.ctx, proposal.Id) suite.Require().Nil(err) - suite.Require().True(proposal.VotingStartTime.Equal(suite.ctx.BlockHeader().Time)) + suite.Require().True(proposal.VotingStartTime.Equal(suite.ctx.HeaderInfo().Time)) has, err := suite.govKeeper.ActiveProposalsQueue.Has(suite.ctx, collections.Join(*proposal.VotingEndTime, proposal.Id)) suite.Require().NoError(err) @@ -201,7 +202,8 @@ func (suite *KeeperTestSuite) TestCancelProposal() { proposal3, err = suite.govKeeper.Proposals.Get(suite.ctx, proposal3ID) suite.Require().Nil(err) - suite.Require().True(proposal3.VotingStartTime.Equal(suite.ctx.BlockHeader().Time)) + fmt.Println(suite.ctx.HeaderInfo().Time, proposal3.VotingStartTime) + suite.Require().True(proposal3.VotingStartTime.Equal(suite.ctx.HeaderInfo().Time)) // add vote voteOptions := []*v1.WeightedVoteOption{{Option: v1.OptionYes, Weight: "1.0"}} err = suite.govKeeper.AddVote(suite.ctx, proposal3ID, suite.addrs[0], voteOptions, "") @@ -263,7 +265,7 @@ func (suite *KeeperTestSuite) TestCancelProposal() { proposal, err = suite.govKeeper.Proposals.Get(suite.ctx, proposal.Id) suite.Require().Nil(err) - suite.Require().True(proposal.VotingStartTime.Equal(suite.ctx.BlockHeader().Time)) + suite.Require().True(proposal.VotingStartTime.Equal(suite.ctx.HeaderInfo().Time)) // add vote voteOptions := []*v1.WeightedVoteOption{{Option: v1.OptionYes, Weight: "1.0"}} diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 8f71cf83b4d..7ff1b470a51 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -294,7 +294,7 @@ func simulateMsgSubmitProposal( fops := make([]simtypes.FutureOperation, numVotes+1) for i := 0; i < numVotes; i++ { - whenVote := ctx.BlockHeader().Time.Add(time.Duration(r.Int63n(int64(votingPeriod.Seconds()))) * time.Second) + whenVote := ctx.HeaderInfo().Time.Add(time.Duration(r.Int63n(int64(votingPeriod.Seconds()))) * time.Second) fops[i] = simtypes.FutureOperation{ BlockTime: whenVote, Op: operationSimulateMsgVote(txGen, ak, bk, k, accs[whoVotes[i]], int64(proposalID)), diff --git a/x/gov/simulation/operations_test.go b/x/gov/simulation/operations_test.go index c4c3355cd9d..a7b8c875105 100644 --- a/x/gov/simulation/operations_test.go +++ b/x/gov/simulation/operations_test.go @@ -10,6 +10,7 @@ import ( "github.com/cosmos/gogoproto/proto" "github.com/stretchr/testify/require" + "cosmossdk.io/core/header" "cosmossdk.io/depinject" "cosmossdk.io/log" @@ -213,7 +214,7 @@ func TestSimulateMsgCancelProposal(t *testing.T) { suite, ctx := createTestSuite(t, false) app := suite.App blockTime := time.Now().UTC() - ctx = ctx.WithBlockTime(blockTime) + ctx = ctx.WithHeaderInfo(header.Info{Time: blockTime}) // setup 3 accounts s := rand.NewSource(1) @@ -225,7 +226,7 @@ func TestSimulateMsgCancelProposal(t *testing.T) { contentMsg, err := v1.NewLegacyContent(content, suite.GovKeeper.GetGovernanceAccount(ctx).GetAddress().String()) require.NoError(t, err) - submitTime := ctx.BlockHeader().Time + submitTime := ctx.HeaderInfo().Time params, _ := suite.GovKeeper.Params.Get(ctx) depositPeriod := params.MaxDepositPeriod @@ -262,7 +263,7 @@ func TestSimulateMsgDeposit(t *testing.T) { suite, ctx := createTestSuite(t, false) app := suite.App blockTime := time.Now().UTC() - ctx = ctx.WithBlockTime(blockTime) + ctx = ctx.WithHeaderInfo(header.Info{Time: blockTime}) // setup 3 accounts s := rand.NewSource(1) @@ -274,7 +275,7 @@ func TestSimulateMsgDeposit(t *testing.T) { contentMsg, err := v1.NewLegacyContent(content, suite.GovKeeper.GetGovernanceAccount(ctx).GetAddress().String()) require.NoError(t, err) - submitTime := ctx.BlockHeader().Time + submitTime := ctx.HeaderInfo().Time params, _ := suite.GovKeeper.Params.Get(ctx) depositPeriod := params.MaxDepositPeriod @@ -312,7 +313,7 @@ func TestSimulateMsgVote(t *testing.T) { suite, ctx := createTestSuite(t, false) app := suite.App blockTime := time.Now().UTC() - ctx = ctx.WithBlockTime(blockTime) + ctx = ctx.WithHeaderInfo(header.Info{Time: blockTime}) // setup 3 accounts s := rand.NewSource(1) @@ -324,7 +325,7 @@ func TestSimulateMsgVote(t *testing.T) { contentMsg, err := v1.NewLegacyContent(v1beta1.NewTextProposal("Test", "description"), govAcc) require.NoError(t, err) - submitTime := ctx.BlockHeader().Time + submitTime := ctx.HeaderInfo().Time params, _ := suite.GovKeeper.Params.Get(ctx) depositPeriod := params.MaxDepositPeriod @@ -361,7 +362,7 @@ func TestSimulateMsgVoteWeighted(t *testing.T) { suite, ctx := createTestSuite(t, false) app := suite.App blockTime := time.Now().UTC() - ctx = ctx.WithBlockTime(blockTime) + ctx = ctx.WithHeaderInfo(header.Info{Time: blockTime}) // setup 3 accounts s := rand.NewSource(1) @@ -372,7 +373,7 @@ func TestSimulateMsgVoteWeighted(t *testing.T) { govAcc := suite.GovKeeper.GetGovernanceAccount(ctx).GetAddress().String() contentMsg, err := v1.NewLegacyContent(v1beta1.NewTextProposal("Test", "description"), govAcc) require.NoError(t, err) - submitTime := ctx.BlockHeader().Time + submitTime := ctx.HeaderInfo().Time params, _ := suite.GovKeeper.Params.Get(ctx) depositPeriod := params.MaxDepositPeriod diff --git a/x/group/keeper/keeper.go b/x/group/keeper/keeper.go index 45873f2342a..5752016c90a 100644 --- a/x/group/keeper/keeper.go +++ b/x/group/keeper/keeper.go @@ -368,7 +368,7 @@ func (k Keeper) votesByProposal(ctx sdk.Context, proposalID uint64) ([]group.Vot // `voting_period + max_execution_period` is greater than the current block // time. func (k Keeper) PruneProposals(ctx sdk.Context) error { - proposals, err := k.proposalsByVPEnd(ctx, ctx.BlockTime().Add(-k.config.MaxExecutionPeriod)) + proposals, err := k.proposalsByVPEnd(ctx, ctx.HeaderInfo().Time.Add(-k.config.MaxExecutionPeriod)) if err != nil { return nil } @@ -397,7 +397,7 @@ func (k Keeper) PruneProposals(ctx sdk.Context) error { // has ended, tallies their votes, prunes them, and updates the proposal's // `FinalTallyResult` field. func (k Keeper) TallyProposalsAtVPEnd(ctx sdk.Context) error { - proposals, err := k.proposalsByVPEnd(ctx, ctx.BlockTime()) + proposals, err := k.proposalsByVPEnd(ctx, ctx.HeaderInfo().Time) if err != nil { return nil } diff --git a/x/group/keeper/keeper_test.go b/x/group/keeper/keeper_test.go index 4acc177b055..6c73fb71df0 100644 --- a/x/group/keeper/keeper_test.go +++ b/x/group/keeper/keeper_test.go @@ -10,6 +10,7 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/suite" + "cosmossdk.io/core/header" "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" @@ -75,7 +76,7 @@ func (s *TestSuite) SetupTest() { config := group.DefaultConfig() s.groupKeeper = keeper.NewKeeper(key, encCfg.Codec, bApp.MsgServiceRouter(), s.accountKeeper, config) - s.ctx = testCtx.Ctx.WithBlockTime(s.blockTime) + s.ctx = testCtx.Ctx.WithHeaderInfo(header.Info{Time: s.blockTime}) s.sdkCtx = sdk.UnwrapSDKContext(s.ctx) // Initial group, group policy and balance setup @@ -179,7 +180,7 @@ func (s *TestSuite) TestProposalsByVPEnd() { return submitProposal(sdkCtx, s, []sdk.Msg{msgSend}, proposers) }, admin: proposers[0], - newCtx: ctx.WithBlockTime(now.Add(votingPeriod).Add(time.Hour)), + newCtx: ctx.WithHeaderInfo(header.Info{Time: now.Add(votingPeriod).Add(time.Hour)}), tallyRes: group.DefaultTallyResult(), expStatus: group.PROPOSAL_STATUS_REJECTED, }, @@ -206,7 +207,7 @@ func (s *TestSuite) TestProposalsByVPEnd() { return submitProposalAndVote(s.ctx, s, []sdk.Msg{msgSend}, proposers, group.VOTE_OPTION_YES) }, admin: proposers[0], - newCtx: ctx.WithBlockTime(now.Add(votingPeriod).Add(time.Hour)), + newCtx: ctx.WithHeaderInfo(header.Info{Time: now.Add(votingPeriod).Add(time.Hour)}), tallyRes: group.TallyResult{ YesCount: "2", NoCount: "0", @@ -221,7 +222,7 @@ func (s *TestSuite) TestProposalsByVPEnd() { return submitProposalAndVote(s.ctx, s, []sdk.Msg{msgSend}, []string{s.addrs[4].String()}, group.VOTE_OPTION_YES) }, admin: proposers[0], - newCtx: ctx.WithBlockTime(now.Add(votingPeriod).Add(time.Hour)), + newCtx: ctx.WithHeaderInfo(header.Info{Time: now.Add(votingPeriod).Add(time.Hour)}), tallyRes: group.TallyResult{ YesCount: "1", NoCount: "0", @@ -328,7 +329,7 @@ func (s *TestSuite) TestPruneProposals() { s.Require().NoError(err) s.Require().Equal(prePrune.Proposal.Id, submittedProposal.ProposalId) // Move Forward in time for 15 days, after voting period end + max_execution_period - s.sdkCtx = s.sdkCtx.WithBlockTime(s.sdkCtx.BlockTime().Add(expirationTime)) + s.sdkCtx = s.sdkCtx.WithHeaderInfo(header.Info{Time: s.sdkCtx.HeaderInfo().Time.Add(expirationTime)}) // Prune Expired Proposals err = s.groupKeeper.PruneProposals(s.sdkCtx) @@ -446,7 +447,7 @@ func (s *TestSuite) TestTallyProposalsAtVPEnd() { s.Require().NoError(err) // move forward in time - ctx := s.sdkCtx.WithBlockTime(s.sdkCtx.BlockTime().Add(votingPeriod + 1)) + ctx := s.sdkCtx.WithHeaderInfo(header.Info{Time: s.sdkCtx.HeaderInfo().Time.Add(votingPeriod + 1)}) result, err := s.groupKeeper.TallyResult(ctx, &group.QueryTallyResultRequest{ ProposalId: proposalRes.ProposalId, @@ -518,7 +519,7 @@ func (s *TestSuite) TestTallyProposalsAtVPEnd_GroupMemberLeaving() { s.Require().NoError(err) // move forward in time - ctx := s.sdkCtx.WithBlockTime(s.sdkCtx.BlockTime().Add(votingPeriod + 1)) + 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)) diff --git a/x/group/keeper/msg_server.go b/x/group/keeper/msg_server.go index 048b82a3566..8cae99c1d29 100644 --- a/x/group/keeper/msg_server.go +++ b/x/group/keeper/msg_server.go @@ -68,7 +68,7 @@ func (k Keeper) CreateGroup(goCtx context.Context, msg *group.MsgCreateGroup) (* Metadata: msg.Metadata, Version: 1, TotalWeight: totalWeight.String(), - CreatedAt: ctx.BlockTime(), + CreatedAt: ctx.HeaderInfo().Time, } groupID, err := k.groupTable.Create(ctx.KVStore(k.key), groupInfo) if err != nil { @@ -83,7 +83,7 @@ func (k Keeper) CreateGroup(goCtx context.Context, msg *group.MsgCreateGroup) (* Address: m.Address, Weight: m.Weight, Metadata: m.Metadata, - AddedAt: ctx.BlockTime(), + AddedAt: ctx.HeaderInfo().Time, }, }) if err != nil { @@ -189,7 +189,7 @@ func (k Keeper) UpdateGroupMembers(goCtx context.Context, msg *group.MsgUpdateGr return errorsmod.Wrap(err, "add member") } } else { // else handle create. - groupMember.Member.AddedAt = ctx.BlockTime() + groupMember.Member.AddedAt = ctx.HeaderInfo().Time if err := k.groupMemberTable.Create(ctx.KVStore(k.key), &groupMember); err != nil { return errorsmod.Wrap(err, "add member") } @@ -407,7 +407,7 @@ func (k Keeper) CreateGroupPolicy(goCtx context.Context, msg *group.MsgCreateGro msg.GetMetadata(), 1, policy, - ctx.BlockTime(), + ctx.HeaderInfo().Time, ) if err != nil { return nil, err @@ -593,12 +593,12 @@ func (k Keeper) SubmitProposal(goCtx context.Context, msg *group.MsgSubmitPropos GroupPolicyAddress: msg.GroupPolicyAddress, Metadata: msg.Metadata, Proposers: msg.Proposers, - SubmitTime: ctx.BlockTime(), + SubmitTime: ctx.HeaderInfo().Time, GroupVersion: groupInfo.Version, GroupPolicyVersion: policyAcc.Version, Status: group.PROPOSAL_STATUS_SUBMITTED, ExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, - VotingPeriodEnd: ctx.BlockTime().Add(policy.GetVotingPeriod()), // The voting window begins as soon as the proposal is submitted. + VotingPeriodEnd: ctx.HeaderInfo().Time.Add(policy.GetVotingPeriod()), // The voting window begins as soon as the proposal is submitted. FinalTallyResult: group.DefaultTallyResult(), Title: msg.Title, Summary: msg.Summary, @@ -722,7 +722,7 @@ func (k Keeper) Vote(goCtx context.Context, msg *group.MsgVote) (*group.MsgVoteR return nil, errorsmod.Wrap(errors.ErrInvalid, "proposal not open for voting") } - if ctx.BlockTime().After(proposal.VotingPeriodEnd) { + if ctx.HeaderInfo().Time.After(proposal.VotingPeriodEnd) { return nil, errorsmod.Wrap(errors.ErrExpired, "voting period has ended already") } @@ -746,7 +746,7 @@ func (k Keeper) Vote(goCtx context.Context, msg *group.MsgVote) (*group.MsgVoteR Voter: msg.Voter, Option: msg.Option, Metadata: msg.Metadata, - SubmitTime: ctx.BlockTime(), + SubmitTime: ctx.HeaderInfo().Time, } // The ORM will return an error if the vote already exists, @@ -791,7 +791,7 @@ func (k Keeper) doTallyAndUpdate(ctx sdk.Context, p *group.Proposal, groupInfo g // 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 || ctx.BlockTime().After(p.VotingPeriodEnd); isFinal { + if isFinal := result.Final || ctx.HeaderInfo().Time.After(p.VotingPeriodEnd); isFinal { if err := k.pruneVotes(ctx, p.Id); err != nil { return err } diff --git a/x/group/keeper/msg_server_test.go b/x/group/keeper/msg_server_test.go index 7cbe0a9f39c..336ac123b1a 100644 --- a/x/group/keeper/msg_server_test.go +++ b/x/group/keeper/msg_server_test.go @@ -11,6 +11,8 @@ import ( abci "github.com/cometbft/cometbft/abci/types" "github.com/golang/mock/gomock" + "cosmossdk.io/core/header" + "github.com/cosmos/cosmos-sdk/codec/address" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" "github.com/cosmos/cosmos-sdk/testutil/testdata" @@ -174,7 +176,7 @@ func (s *TestSuite) TestCreateGroup() { for msg, spec := range specs { spec := spec s.Run(msg, func() { - blockTime := sdk.UnwrapSDKContext(s.ctx).BlockTime() + blockTime := sdk.UnwrapSDKContext(s.ctx).HeaderInfo().Time res, err := s.groupKeeper.CreateGroup(s.ctx, spec.req) if spec.expErr { s.Require().Error(err) @@ -333,7 +335,7 @@ func (s *TestSuite) TestUpdateGroupMembers() { Member: &group.Member{ Address: member2, Weight: "2", - AddedAt: s.sdkCtx.BlockTime(), + AddedAt: s.sdkCtx.HeaderInfo().Time, }, GroupId: groupID, }, @@ -428,7 +430,7 @@ func (s *TestSuite) TestUpdateGroupMembers() { Member: &group.Member{ Address: member2, Weight: "1", - AddedAt: s.sdkCtx.BlockTime(), + AddedAt: s.sdkCtx.HeaderInfo().Time, }, }}, }, @@ -919,7 +921,7 @@ func (s *TestSuite) TestCreateGroupWithPolicy() { err := spec.req.SetDecisionPolicy(spec.policy) s.Require().NoError(err) - blockTime := sdk.UnwrapSDKContext(s.ctx).BlockTime() + blockTime := sdk.UnwrapSDKContext(s.ctx).HeaderInfo().Time res, err := s.groupKeeper.CreateGroupWithPolicy(s.ctx, spec.req) if spec.expErr { s.Require().Error(err) @@ -1997,8 +1999,8 @@ func (s *TestSuite) TestWithdrawProposal() { resp, err := s.groupKeeper.Proposal(s.ctx, &group.QueryProposalRequest{ProposalId: proposalID}) s.Require().NoError(err) vpe := resp.Proposal.VotingPeriodEnd - timeDiff := vpe.Sub(s.sdkCtx.BlockTime()) - ctxVPE := sdkCtx.WithBlockTime(s.sdkCtx.BlockTime().Add(timeDiff).Add(time.Second * 1)) + 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)) events := ctxVPE.EventManager().ABCIEvents() @@ -2349,7 +2351,7 @@ func (s *TestSuite) TestVote() { Voter: addr4.String(), Option: group.VOTE_OPTION_NO, }, - srcCtx: s.sdkCtx.WithBlockTime(s.blockTime.Add(time.Second)), + srcCtx: s.sdkCtx.WithHeaderInfo(header.Info{Time: s.sdkCtx.HeaderInfo().Time.Add(time.Second)}), expErr: true, expErrMsg: "voting period has ended already: expired", postRun: func(sdkCtx sdk.Context) {}, @@ -2697,7 +2699,7 @@ func (s *TestSuite) TestExecProposal() { // Wait after min execution period end before Exec sdkCtx := sdk.UnwrapSDKContext(ctx) - sdkCtx = sdkCtx.WithBlockTime(sdkCtx.BlockTime().Add(minExecutionPeriod)) // MinExecutionPeriod is 5s + sdkCtx = sdkCtx.WithHeaderInfo(header.Info{Time: sdkCtx.HeaderInfo().Time.Add(minExecutionPeriod)}) // MinExecutionPeriod is 5s _, err := s.groupKeeper.Exec(sdkCtx, &group.MsgExec{Executor: addr1.String(), ProposalId: myProposalID}) s.Require().NoError(err) return myProposalID @@ -2732,7 +2734,7 @@ func (s *TestSuite) TestExecProposal() { // Wait after min execution period end before Exec sdkCtx := sdk.UnwrapSDKContext(ctx) - sdkCtx = sdkCtx.WithBlockTime(sdkCtx.BlockTime().Add(minExecutionPeriod)) // MinExecutionPeriod is 5s + sdkCtx = sdkCtx.WithHeaderInfo(header.Info{Time: sdkCtx.HeaderInfo().Time.Add(minExecutionPeriod)}) // MinExecutionPeriod is 5s s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, fmt.Errorf("error")) _, err := s.groupKeeper.Exec(sdkCtx, &group.MsgExec{Executor: addr1.String(), ProposalId: myProposalID}) s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, nil) @@ -2755,7 +2757,7 @@ func (s *TestSuite) TestExecProposal() { proposalID := spec.setupProposal(sdkCtx) if !spec.srcBlockTime.IsZero() { - sdkCtx = sdkCtx.WithBlockTime(spec.srcBlockTime) + sdkCtx = sdkCtx.WithHeaderInfo(header.Info{Time: spec.srcBlockTime}) } _, err := s.groupKeeper.Exec(sdkCtx, &group.MsgExec{Executor: addr1.String(), ProposalId: proposalID}) @@ -2938,7 +2940,7 @@ func (s *TestSuite) TestExecPrunedProposalsAndVotes() { // Wait for min execution period end sdkCtx := sdk.UnwrapSDKContext(ctx) - sdkCtx = sdkCtx.WithBlockTime(sdkCtx.BlockTime().Add(minExecutionPeriod)) + sdkCtx = sdkCtx.WithHeaderInfo(header.Info{Time: sdkCtx.HeaderInfo().Time.Add(minExecutionPeriod)}) _, err := s.groupKeeper.Exec(sdkCtx, &group.MsgExec{Executor: addr1.String(), ProposalId: myProposalID}) s.bankKeeper.EXPECT().Send(gomock.Any(), msgSend2).Return(nil, nil) @@ -2956,11 +2958,11 @@ func (s *TestSuite) TestExecPrunedProposalsAndVotes() { proposalID := spec.setupProposal(sdkCtx) if !spec.srcBlockTime.IsZero() { - sdkCtx = sdkCtx.WithBlockTime(spec.srcBlockTime) + sdkCtx = sdkCtx.WithHeaderInfo(header.Info{Time: spec.srcBlockTime}) } // Wait for min execution period end - sdkCtx = sdkCtx.WithBlockTime(sdkCtx.BlockTime().Add(minExecutionPeriod)) + sdkCtx = sdkCtx.WithHeaderInfo(header.Info{Time: sdkCtx.HeaderInfo().Time.Add(minExecutionPeriod)}) _, err := s.groupKeeper.Exec(sdkCtx, &group.MsgExec{Executor: addr1.String(), ProposalId: proposalID}) if spec.expErr { s.Require().Error(err) @@ -3397,7 +3399,7 @@ func (s *TestSuite) TestExecProposalsWhenMemberLeavesOrIsUpdated() { s.Require().NoError(err) // travel in time - sdkCtx = sdkCtx.WithBlockTime(s.blockTime.Add(minExecutionPeriod + 1)) + sdkCtx = sdkCtx.WithHeaderInfo(header.Info{Time: s.blockTime.Add(minExecutionPeriod + 1)}) _, err = s.groupKeeper.Exec(sdkCtx, &group.MsgExec{Executor: s.addrs[1].String(), ProposalId: proposalID}) if spec.expErrMsg != "" { s.Require().Contains(err.Error(), spec.expErrMsg) diff --git a/x/group/keeper/proposal_executor.go b/x/group/keeper/proposal_executor.go index b0cca821212..48415a3d081 100644 --- a/x/group/keeper/proposal_executor.go +++ b/x/group/keeper/proposal_executor.go @@ -19,7 +19,7 @@ import ( func (s Keeper) doExecuteMsgs(ctx sdk.Context, router baseapp.MessageRouter, proposal group.Proposal, groupPolicyAcc sdk.AccAddress, decisionPolicy group.DecisionPolicy) ([]sdk.Result, error) { // Ensure it's not too early to execute the messages. minExecutionDate := proposal.SubmitTime.Add(decisionPolicy.GetMinExecutionPeriod()) - if ctx.BlockTime().Before(minExecutionDate) { + if ctx.HeaderInfo().Time.Before(minExecutionDate) { return nil, errors.ErrInvalid.Wrapf("must wait until %s to execute proposal %d", minExecutionDate, proposal.Id) } @@ -29,7 +29,7 @@ func (s Keeper) doExecuteMsgs(ctx sdk.Context, router baseapp.MessageRouter, pro // the proposal doesn't exist in state. For sanity check, we can still keep // this simple and cheap check. expiryDate := proposal.VotingPeriodEnd.Add(s.config.MaxExecutionPeriod) - if expiryDate.Before(ctx.BlockTime()) { + if expiryDate.Before(ctx.HeaderInfo().Time) { return nil, errors.ErrExpired.Wrapf("proposal expired on %s", expiryDate) } diff --git a/x/group/migrations/v2/migrate_test.go b/x/group/migrations/v2/migrate_test.go index 66810076dd3..8caff993fa5 100644 --- a/x/group/migrations/v2/migrate_test.go +++ b/x/group/migrations/v2/migrate_test.go @@ -62,7 +62,7 @@ func createGroupPolicies(ctx sdk.Context, storeKey storetypes.StoreKey, cdc code groupPolicySeq := orm.NewSequence(v2.GroupPolicyTableSeqPrefix) for _, policyAddr := range policies { - groupPolicyInfo, err := group.NewGroupPolicyInfo(policyAddr, 1, authorityAddr, "", 1, group.NewPercentageDecisionPolicy("1", 1, 1), ctx.BlockTime()) + groupPolicyInfo, err := group.NewGroupPolicyInfo(policyAddr, 1, authorityAddr, "", 1, group.NewPercentageDecisionPolicy("1", 1, 1), ctx.HeaderInfo().Time) if err != nil { return orm.PrimaryKeyTable{}, orm.Sequence{}, err } diff --git a/x/group/module/abci_test.go b/x/group/module/abci_test.go index 15cf96f437c..8bff41a48a2 100644 --- a/x/group/module/abci_test.go +++ b/x/group/module/abci_test.go @@ -5,11 +5,10 @@ import ( "testing" "time" - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - cmttime "github.com/cometbft/cometbft/types/time" "github.com/stretchr/testify/suite" "cosmossdk.io/core/address" + "cosmossdk.io/core/header" "cosmossdk.io/depinject" "cosmossdk.io/log" "cosmossdk.io/math" @@ -62,7 +61,7 @@ func (s *IntegrationTestSuite) SetupTest() { ctx := app.BaseApp.NewContext(false) - ctx = ctx.WithBlockHeader(cmtproto.Header{Time: cmttime.Now()}) + ctx = ctx.WithHeaderInfo(header.Info{Time: time.Now()}) s.ctx = ctx @@ -265,7 +264,7 @@ func (s *IntegrationTestSuite) TestEndBlockerPruning() { s.Require().NoError(err) return pID }, - newCtx: ctx.WithBlockTime(ctx.BlockTime().Add(votingPeriod).Add(time.Hour)), + newCtx: ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.Add(votingPeriod).Add(time.Hour)}), expErrMsg: "load proposal: not found", expStatus: group.PROPOSAL_STATUS_WITHDRAWN, }, @@ -302,7 +301,7 @@ func (s *IntegrationTestSuite) TestEndBlockerPruning() { return pID }, - newCtx: ctx.WithBlockTime(ctx.BlockTime().Add(votingPeriod).Add(time.Hour)), + newCtx: ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.Add(votingPeriod).Add(time.Hour)}), expErrMsg: "load proposal: not found", expStatus: group.PROPOSAL_STATUS_ABORTED, expExecutorResult: group.PROPOSAL_EXECUTOR_RESULT_NOT_RUN, @@ -432,7 +431,7 @@ func (s *IntegrationTestSuite) TestEndBlockerTallying() { return pID }, admin: proposers[0], - newCtx: ctx.WithBlockTime(ctx.BlockTime().Add(votingPeriod).Add(time.Hour)), + newCtx: ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.Add(votingPeriod).Add(time.Hour)}), tallyRes: group.DefaultTallyResult(), expStatus: group.PROPOSAL_STATUS_REJECTED, }, @@ -469,7 +468,7 @@ func (s *IntegrationTestSuite) TestEndBlockerTallying() { return pID }, admin: proposers[0], - newCtx: ctx.WithBlockTime(ctx.BlockTime().Add(votingPeriod).Add(time.Hour)), + newCtx: ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.Add(votingPeriod).Add(time.Hour)}), tallyRes: group.TallyResult{ YesCount: "1", NoCount: "0", @@ -486,7 +485,7 @@ func (s *IntegrationTestSuite) TestEndBlockerTallying() { return pID }, admin: proposers[0], - newCtx: ctx.WithBlockTime(ctx.BlockTime().Add(votingPeriod).Add(time.Hour)), + newCtx: ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.Add(votingPeriod).Add(time.Hour)}), tallyRes: group.TallyResult{ YesCount: "2", NoCount: "0", diff --git a/x/group/simulation/operations.go b/x/group/simulation/operations.go index 345e1454e2e..978ede47879 100644 --- a/x/group/simulation/operations.go +++ b/x/group/simulation/operations.go @@ -912,7 +912,7 @@ func SimulateMsgWithdrawProposal( timeout := p.VotingPeriodEnd proposal = p proposalID = int(p.Id) - if timeout.Before(sdkCtx.BlockTime()) || timeout.Equal(sdkCtx.BlockTime()) { + if timeout.Before(sdkCtx.HeaderInfo().Time) || timeout.Equal(sdkCtx.HeaderInfo().Time) { return simtypes.NoOpMsg(group.ModuleName, TypeMsgWithdrawProposal, "voting period ended: skipping"), nil, nil } break @@ -1023,7 +1023,7 @@ func SimulateMsgVote( if p.Status == group.PROPOSAL_STATUS_SUBMITTED { timeout := p.VotingPeriodEnd proposalID = int(p.Id) - if timeout.Before(sdkCtx.BlockTime()) || timeout.Equal(sdkCtx.BlockTime()) { + if timeout.Before(sdkCtx.HeaderInfo().Time) || timeout.Equal(sdkCtx.HeaderInfo().Time) { return simtypes.NoOpMsg(group.ModuleName, TypeMsgVote, "voting period ended: skipping"), nil, nil } break diff --git a/x/nft/keeper/keeper_test.go b/x/nft/keeper/keeper_test.go index 0666a04de7a..45be0db2977 100644 --- a/x/nft/keeper/keeper_test.go +++ b/x/nft/keeper/keeper_test.go @@ -7,6 +7,7 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/suite" + "cosmossdk.io/core/header" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/nft" "cosmossdk.io/x/nft/keeper" @@ -54,7 +55,7 @@ func (s *TestSuite) SetupTest() { key := storetypes.NewKVStoreKey(nft.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) - ctx := testCtx.Ctx.WithBlockTime(time.Now().Round(0).UTC()) + ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now().Round(0).UTC()}) // gomock initializations ctrl := gomock.NewController(s.T()) diff --git a/x/nft/simulation/operations_test.go b/x/nft/simulation/operations_test.go index 4514493aca2..4e9b2dc8e70 100644 --- a/x/nft/simulation/operations_test.go +++ b/x/nft/simulation/operations_test.go @@ -9,6 +9,7 @@ import ( "github.com/cosmos/gogoproto/proto" "github.com/stretchr/testify/suite" + "cosmossdk.io/core/header" "cosmossdk.io/depinject" "cosmossdk.io/log" "cosmossdk.io/x/nft" @@ -122,7 +123,7 @@ func (suite *SimTestSuite) TestSimulateMsgSend() { r := rand.New(s) accounts := suite.getTestingAccounts(r, 2) blockTime := time.Now().UTC() - ctx := suite.ctx.WithBlockTime(blockTime) + ctx := suite.ctx.WithHeaderInfo(header.Info{Time: blockTime}) // begin new block _, err := suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index 380034ebe6e..806b5d3a40b 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -13,6 +13,8 @@ import ( abci "github.com/cometbft/cometbft/abci/types" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "cosmossdk.io/core/header" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -190,6 +192,10 @@ func SimulateFromSeed( Time: blockTime, ProposerAddress: proposerAddress, ChainID: config.ChainID, + }).WithHeaderInfo(header.Info{ + Height: blockHeight, + Time: blockTime, + ChainID: config.ChainID, }) // run queued operations; ignores block size if block size is too small diff --git a/x/slashing/keeper/infractions.go b/x/slashing/keeper/infractions.go index 56e6c7ea23f..fef8c0b70fd 100644 --- a/x/slashing/keeper/infractions.go +++ b/x/slashing/keeper/infractions.go @@ -152,7 +152,7 @@ func (k Keeper) HandleValidatorSignature(ctx context.Context, addr cryptotypes.A if err != nil { return err } - signInfo.JailedUntil = sdkCtx.BlockHeader().Time.Add(downtimeJailDur) + signInfo.JailedUntil = sdkCtx.HeaderInfo().Time.Add(downtimeJailDur) // We need to reset the counter & bitmap so that the validator won't be // immediately slashed for downtime upon re-bonding. diff --git a/x/slashing/keeper/keeper_test.go b/x/slashing/keeper/keeper_test.go index 0b39ed993f9..04dc324c1f0 100644 --- a/x/slashing/keeper/keeper_test.go +++ b/x/slashing/keeper/keeper_test.go @@ -3,13 +3,13 @@ package keeper_test import ( "encoding/binary" "testing" + "time" - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - cmttime "github.com/cometbft/cometbft/types/time" "github.com/golang/mock/gomock" "github.com/stretchr/testify/suite" st "cosmossdk.io/api/cosmos/staking/v1beta1" + "cosmossdk.io/core/header" sdkmath "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" @@ -46,7 +46,7 @@ func (s *KeeperTestSuite) SetupTest() { s.key = key storeService := runtime.NewKVStoreService(key) testCtx := sdktestutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) - ctx := testCtx.Ctx.WithBlockHeader(cmtproto.Header{Time: cmttime.Now()}) + ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now().Round(0).UTC()}) encCfg := moduletestutil.MakeTestEncodingConfig() // gomock initializations diff --git a/x/slashing/keeper/msg_server_test.go b/x/slashing/keeper/msg_server_test.go index 4e5d28d4109..f647691da30 100644 --- a/x/slashing/keeper/msg_server_test.go +++ b/x/slashing/keeper/msg_server_test.go @@ -267,7 +267,7 @@ func (s *KeeperTestSuite) TestUnjail() { s.Require().NoError(err) info := slashingtypes.NewValidatorSigningInfo(sdk.ConsAddress(addr), int64(4), int64(3), - s.ctx.BlockTime().AddDate(0, 0, 1), false, int64(10)) + s.ctx.HeaderInfo().Time.AddDate(0, 0, 1), false, int64(10)) s.Require().NoError(s.slashingKeeper.ValidatorSigningInfo.Set(s.ctx, sdk.ConsAddress(addr), info)) s.stakingKeeper.EXPECT().Validator(s.ctx, valAddr).Return(val, nil) @@ -303,7 +303,7 @@ func (s *KeeperTestSuite) TestUnjail() { del := types.NewDelegation(addr.String(), valAddr.String(), sdkmath.LegacyNewDec(100)) s.stakingKeeper.EXPECT().Delegation(s.ctx, addr, valAddr).Return(del, nil) - s.stakingKeeper.EXPECT().Unjail(s.ctx, sdk.ConsAddress(addr)).Return(nil) + s.stakingKeeper.EXPECT().Unjail(s.ctx, sdk.ConsAddress(addr)).Return(nil).AnyTimes() return &slashingtypes.MsgUnjail{ ValidatorAddr: sdk.ValAddress(addr).String(), diff --git a/x/slashing/keeper/unjail.go b/x/slashing/keeper/unjail.go index 7680da4b21b..2d900e4d5cb 100644 --- a/x/slashing/keeper/unjail.go +++ b/x/slashing/keeper/unjail.go @@ -64,7 +64,7 @@ func (k Keeper) Unjail(ctx context.Context, validatorAddr sdk.ValAddress) error // cannot be unjailed until out of jail sdkCtx := sdk.UnwrapSDKContext(ctx) - if sdkCtx.BlockHeader().Time.Before(info.JailedUntil) { + if sdkCtx.HeaderInfo().Time.Before(info.JailedUntil) { return types.ErrValidatorJailed } } diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index b95c7abc361..c10b682911b 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -138,13 +138,13 @@ func SimulateMsgUnjail( // - validator is still in jailed period // - self delegation too low if info.Tombstoned || - ctx.BlockHeader().Time.Before(info.JailedUntil) || + ctx.HeaderInfo().Time.Before(info.JailedUntil) || validator.TokensFromShares(selfDel.GetShares()).TruncateInt().LT(validator.GetMinSelfDelegation()) { if res != nil && err == nil { if info.Tombstoned { return simtypes.NewOperationMsg(msg, true, ""), nil, errors.New("validator should not have been unjailed if validator tombstoned") } - if ctx.BlockHeader().Time.Before(info.JailedUntil) { + if ctx.HeaderInfo().Time.Before(info.JailedUntil) { return simtypes.NewOperationMsg(msg, true, ""), nil, errors.New("validator unjailed while validator still in jail period") } if validator.TokensFromShares(selfDel.GetShares()).TruncateInt().LT(validator.GetMinSelfDelegation()) { diff --git a/x/slashing/simulation/operations_test.go b/x/slashing/simulation/operations_test.go index 2bc63299e96..3d3a3dbbdee 100644 --- a/x/slashing/simulation/operations_test.go +++ b/x/slashing/simulation/operations_test.go @@ -12,6 +12,7 @@ import ( "github.com/stretchr/testify/suite" "cosmossdk.io/collections" + "cosmossdk.io/core/header" "cosmossdk.io/depinject" "cosmossdk.io/log" "cosmossdk.io/math" @@ -153,7 +154,7 @@ func (suite *SimTestSuite) TestWeightedOperations() { // Abonormal scenarios, where the message is created by an errors, are not tested here. func (suite *SimTestSuite) TestSimulateMsgUnjail() { blockTime := time.Now().UTC() - ctx := suite.ctx.WithBlockTime(blockTime) + ctx := suite.ctx.WithHeaderInfo(header.Info{Time: blockTime}) // setup accounts[0] as validator0 validator0, err := getTestingValidator0(ctx, suite.stakingKeeper, suite.accounts) diff --git a/x/staking/keeper/delegation.go b/x/staking/keeper/delegation.go index 22fe53ec75e..bf41e4c391c 100644 --- a/x/staking/keeper/delegation.go +++ b/x/staking/keeper/delegation.go @@ -385,7 +385,7 @@ func (k Keeper) InsertUBDQueue(ctx context.Context, ubd types.UnbondingDelegatio // DequeueAllMatureUBDQueue returns a concatenated list of all the timeslices inclusively previous to // currTime, and deletes the timeslices from the queue. func (k Keeper) DequeueAllMatureUBDQueue(ctx context.Context, currTime time.Time) (matureUnbonds []types.DVPair, err error) { - // get an iterator for all timeslices from time 0 until the current Blockheader time + // get an iterator for all timeslices from time 0 until the current HeaderInfo time iter, err := k.UnbondingQueue.Iterate(ctx, (&collections.Range[time.Time]{}).EndInclusive(currTime)) if err != nil { return matureUnbonds, err @@ -894,7 +894,7 @@ func (k Keeper) getBeginInfo( switch { case errors.Is(err, types.ErrNoValidatorFound) || validator.IsBonded(): // the longest wait - just unbonding period from now - completionTime = sdkCtx.BlockHeader().Time.Add(unbondingTime) + completionTime = sdkCtx.HeaderInfo().Time.Add(unbondingTime) height = sdkCtx.BlockHeight() return completionTime, height, false, nil @@ -951,7 +951,7 @@ func (k Keeper) Undelegate( } sdkCtx := sdk.UnwrapSDKContext(ctx) - completionTime := sdkCtx.BlockHeader().Time.Add(unbondingTime) + completionTime := sdkCtx.HeaderInfo().Time.Add(unbondingTime) ubd, err := k.SetUnbondingDelegationEntry(ctx, delAddr, valAddr, sdkCtx.BlockHeight(), completionTime, returnAmount) if err != nil { return time.Time{}, math.Int{}, err @@ -981,7 +981,7 @@ func (k Keeper) CompleteUnbonding(ctx context.Context, delAddr sdk.AccAddress, v balances := sdk.NewCoins() sdkCtx := sdk.UnwrapSDKContext(ctx) - ctxTime := sdkCtx.BlockHeader().Time + ctxTime := sdkCtx.HeaderInfo().Time delegatorAddress, err := k.authKeeper.AddressCodec().StringToBytes(ubd.DelegatorAddress) if err != nil { @@ -1126,7 +1126,7 @@ func (k Keeper) CompleteRedelegation( balances := sdk.NewCoins() sdkCtx := sdk.UnwrapSDKContext(ctx) - ctxTime := sdkCtx.BlockHeader().Time + ctxTime := sdkCtx.HeaderInfo().Time // loop through all the entries and complete mature redelegation entries for i := 0; i < len(red.Entries); i++ { diff --git a/x/staking/keeper/delegation_test.go b/x/staking/keeper/delegation_test.go index bfe84d66e77..9025e12a467 100644 --- a/x/staking/keeper/delegation_test.go +++ b/x/staking/keeper/delegation_test.go @@ -6,6 +6,7 @@ import ( "github.com/golang/mock/gomock" "cosmossdk.io/collections" + coreheader "cosmossdk.io/core/header" "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/codec/address" @@ -478,12 +479,12 @@ func (s *KeeperTestSuite) TestUndelegateFromUnbondingValidator() { delegation := stakingtypes.NewDelegation(addrDels[1].String(), addrVals[0].String(), issuedShares) require.NoError(keeper.SetDelegation(ctx, delegation)) - header := ctx.BlockHeader() + header := ctx.HeaderInfo() blockHeight := int64(10) header.Height = blockHeight blockTime := time.Unix(333, 0) header.Time = blockTime - ctx = ctx.WithBlockHeader(header) + ctx = ctx.WithHeaderInfo(header) // unbond the all self-delegation to put validator in unbonding state val0AccAddr := sdk.AccAddress(addrVals[0]) @@ -506,7 +507,7 @@ func (s *KeeperTestSuite) TestUndelegateFromUnbondingValidator() { blockHeight2 := int64(20) blockTime2 := time.Unix(444, 0).UTC() ctx = ctx.WithBlockHeight(blockHeight2) - ctx = ctx.WithBlockTime(blockTime2) + ctx = ctx.WithHeaderInfo(coreheader.Info{Height: blockHeight2, Time: blockTime2}) // unbond some of the other delegation's shares undelegateAmount := math.LegacyNewDec(6) @@ -555,7 +556,7 @@ func (s *KeeperTestSuite) TestUndelegateFromUnbondedValidator() { require.NoError(keeper.SetDelegation(ctx, delegation)) ctx = ctx.WithBlockHeight(10) - ctx = ctx.WithBlockTime(time.Unix(333, 0)) + ctx = ctx.WithHeaderInfo(coreheader.Info{Height: 10, Time: time.Unix(333, 0)}) // unbond the all self-delegation to put validator in unbonding state s.bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, gomock.Any()) @@ -572,10 +573,10 @@ func (s *KeeperTestSuite) TestUndelegateFromUnbondedValidator() { require.Equal(ctx.BlockHeight(), validator.UnbondingHeight) params, err := keeper.GetParams(ctx) require.NoError(err) - require.True(ctx.BlockHeader().Time.Add(params.UnbondingTime).Equal(validator.UnbondingTime)) + require.True(ctx.HeaderInfo().Time.Add(params.UnbondingTime).Equal(validator.UnbondingTime)) // unbond the validator - ctx = ctx.WithBlockTime(validator.UnbondingTime) + ctx = ctx.WithHeaderInfo(coreheader.Info{Time: validator.UnbondingTime}) err = keeper.UnbondAllMatureValidators(ctx) require.NoError(err) @@ -636,7 +637,7 @@ func (s *KeeperTestSuite) TestUnbondingAllDelegationFromValidator() { require.NoError(keeper.SetDelegation(ctx, delegation)) ctx = ctx.WithBlockHeight(10) - ctx = ctx.WithBlockTime(time.Unix(333, 0)) + ctx = ctx.WithHeaderInfo(coreheader.Info{Height: 10, Time: time.Unix(333, 0)}) // unbond the all self-delegation to put validator in unbonding state s.bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, gomock.Any()) @@ -659,7 +660,7 @@ func (s *KeeperTestSuite) TestUnbondingAllDelegationFromValidator() { require.Equal(validator.Status, stakingtypes.Unbonding) // unbond the validator - ctx = ctx.WithBlockTime(validator.UnbondingTime) + ctx = ctx.WithHeaderInfo(coreheader.Info{Time: validator.UnbondingTime}) err = keeper.UnbondAllMatureValidators(ctx) require.NoError(err) @@ -842,7 +843,7 @@ func (s *KeeperTestSuite) TestRedelegationMaxEntries() { require.Error(err) // mature redelegations - ctx = ctx.WithBlockTime(completionTime) + ctx = ctx.WithHeaderInfo(coreheader.Info{Time: completionTime}) _, err = keeper.CompleteRedelegation(ctx, val0AccAddr, addrVals[0], addrVals[1]) require.NoError(err) @@ -937,12 +938,12 @@ func (s *KeeperTestSuite) TestRedelegateFromUnbondingValidator() { s.bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), stakingtypes.NotBondedPoolName, stakingtypes.BondedPoolName, gomock.Any()) _ = stakingkeeper.TestingUpdateValidator(keeper, ctx, validator2, true) - header := ctx.BlockHeader() + header := ctx.HeaderInfo() blockHeight := int64(10) header.Height = blockHeight blockTime := time.Unix(333, 0) header.Time = blockTime - ctx = ctx.WithBlockHeader(header) + ctx = ctx.WithHeaderInfo(header) // unbond the all self-delegation to put validator in unbonding state s.bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, gomock.Any()) @@ -962,12 +963,12 @@ func (s *KeeperTestSuite) TestRedelegateFromUnbondingValidator() { require.True(blockTime.Add(params.UnbondingTime).Equal(validator.UnbondingTime)) // change the context - header = ctx.BlockHeader() + header = ctx.HeaderInfo() blockHeight2 := int64(20) header.Height = blockHeight2 blockTime2 := time.Unix(444, 0) header.Time = blockTime2 - ctx = ctx.WithBlockHeader(header) + ctx = ctx.WithHeaderInfo(header) // unbond some of the other delegation's shares redelegateTokens := keeper.TokensFromConsensusPower(ctx, 6) @@ -1020,7 +1021,7 @@ func (s *KeeperTestSuite) TestRedelegateFromUnbondedValidator() { require.Equal(stakingtypes.Bonded, validator2.Status) ctx = ctx.WithBlockHeight(10) - ctx = ctx.WithBlockTime(time.Unix(333, 0)) + ctx = ctx.WithHeaderInfo(coreheader.Info{Height: 10, Time: time.Unix(333, 0)}) // unbond the all self-delegation to put validator in unbonding state s.bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, gomock.Any()) @@ -1034,10 +1035,10 @@ func (s *KeeperTestSuite) TestRedelegateFromUnbondedValidator() { validator, err = keeper.GetValidator(ctx, addrVals[0]) require.NoError(err) - require.Equal(ctx.BlockHeight(), validator.UnbondingHeight) + require.Equal(ctx.HeaderInfo().Height, validator.UnbondingHeight) params, err := keeper.GetParams(ctx) require.NoError(err) - require.True(ctx.BlockHeader().Time.Add(params.UnbondingTime).Equal(validator.UnbondingTime)) + require.True(ctx.HeaderInfo().Time.Add(params.UnbondingTime).Equal(validator.UnbondingTime)) // unbond the validator _, err = keeper.UnbondingToUnbonded(ctx, validator) diff --git a/x/staking/keeper/historical_info_test.go b/x/staking/keeper/historical_info_test.go index 0f254770d99..3889e935837 100644 --- a/x/staking/keeper/historical_info_test.go +++ b/x/staking/keeper/historical_info_test.go @@ -4,6 +4,7 @@ import ( cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "cosmossdk.io/collections" + coreheader "cosmossdk.io/core/header" "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/x/staking/testutil" @@ -108,7 +109,7 @@ func (s *KeeperTestSuite) TestTrackHistoricalInfo() { ChainID: "HelloChain", Height: 10, } - ctx = ctx.WithBlockHeader(header) + ctx = ctx.WithBlockHeader(header).WithHeaderInfo(coreheader.Info{ChainID: header.ChainID, Height: header.Height}) require.NoError(keeper.TrackHistoricalInfo(ctx)) diff --git a/x/staking/keeper/keeper_test.go b/x/staking/keeper/keeper_test.go index 488afc86390..2bd37d4e81a 100644 --- a/x/staking/keeper/keeper_test.go +++ b/x/staking/keeper/keeper_test.go @@ -4,13 +4,12 @@ import ( "testing" "time" - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" - cmttime "github.com/cometbft/cometbft/types/time" gogotypes "github.com/cosmos/gogoproto/types" "github.com/golang/mock/gomock" "github.com/stretchr/testify/suite" "cosmossdk.io/collections" + "cosmossdk.io/core/header" "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" @@ -56,7 +55,7 @@ func (s *KeeperTestSuite) SetupTest() { storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) s.key = key - ctx := testCtx.Ctx.WithBlockHeader(cmtproto.Header{Time: cmttime.Now()}) + ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) encCfg := moduletestutil.MakeTestEncodingConfig() s.cdc = encCfg.Codec diff --git a/x/staking/keeper/msg_server.go b/x/staking/keeper/msg_server.go index 8a0512a733e..b4257457d39 100644 --- a/x/staking/keeper/msg_server.go +++ b/x/staking/keeper/msg_server.go @@ -106,7 +106,7 @@ func (k msgServer) CreateValidator(ctx context.Context, msg *types.MsgCreateVali commission := types.NewCommissionWithTime( msg.Commission.Rate, msg.Commission.MaxRate, - msg.Commission.MaxChangeRate, sdkCtx.BlockHeader().Time, + msg.Commission.MaxChangeRate, sdkCtx.HeaderInfo().Time, ) validator, err = validator.SetInitialCommission(commission) @@ -541,7 +541,7 @@ func (k msgServer) CancelUnbondingDelegation(ctx context.Context, msg *types.Msg } sdkCtx := sdk.UnwrapSDKContext(ctx) - if unbondEntry.CompletionTime.Before(sdkCtx.BlockTime()) { + if unbondEntry.CompletionTime.Before(sdkCtx.HeaderInfo().Time) { return nil, sdkerrors.ErrInvalidRequest.Wrap("unbonding delegation is already processed") } diff --git a/x/staking/keeper/msg_server_test.go b/x/staking/keeper/msg_server_test.go index bc3fa965e33..fe277863488 100644 --- a/x/staking/keeper/msg_server_test.go +++ b/x/staking/keeper/msg_server_test.go @@ -7,6 +7,7 @@ import ( "github.com/golang/mock/gomock" "cosmossdk.io/collections" + "cosmossdk.io/core/header" "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/codec/address" @@ -247,8 +248,7 @@ func (s *KeeperTestSuite) TestMsgEditValidator() { s.execExpectCalls() // create new context with updated block time - newCtx := ctx.WithBlockTime(ctx.BlockTime().AddDate(0, 0, 1)) - + newCtx := ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.AddDate(0, 0, 1)}) pk := ed25519.GenPrivKey().PubKey() require.NotNil(pk) @@ -852,7 +852,7 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { require.NoError(err) require.Equal(del, resDel) - ubd := stakingtypes.NewUnbondingDelegation(Addr, ValAddr, 10, ctx.BlockTime().Add(time.Minute*10), shares.RoundInt(), 0, keeper.ValidatorAddressCodec(), ak.AddressCodec()) + ubd := stakingtypes.NewUnbondingDelegation(Addr, ValAddr, 10, ctx.HeaderInfo().Time.Add(time.Minute*10), shares.RoundInt(), 0, keeper.ValidatorAddressCodec(), ak.AddressCodec()) require.NoError(keeper.SetUnbondingDelegation(ctx, ubd)) resUnbond, err := keeper.GetUnbondingDelegation(ctx, Addr, ValAddr) require.NoError(err) diff --git a/x/staking/keeper/slash.go b/x/staking/keeper/slash.go index 34fb736bd82..5a0886141ff 100644 --- a/x/staking/keeper/slash.go +++ b/x/staking/keeper/slash.go @@ -226,7 +226,7 @@ func (k Keeper) SlashUnbondingDelegation(ctx context.Context, unbondingDelegatio infractionHeight int64, slashFactor math.LegacyDec, ) (totalSlashAmount math.Int, err error) { sdkCtx := sdk.UnwrapSDKContext(ctx) - now := sdkCtx.BlockHeader().Time + now := sdkCtx.HeaderInfo().Time totalSlashAmount = math.ZeroInt() burnedAmount := math.ZeroInt() @@ -283,7 +283,7 @@ func (k Keeper) SlashRedelegation(ctx context.Context, srcValidator types.Valida infractionHeight int64, slashFactor math.LegacyDec, ) (totalSlashAmount math.Int, err error) { sdkCtx := sdk.UnwrapSDKContext(ctx) - now := sdkCtx.BlockHeader().Time + now := sdkCtx.HeaderInfo().Time totalSlashAmount = math.ZeroInt() bondedBurnedAmount, notBondedBurnedAmount := math.ZeroInt(), math.ZeroInt() diff --git a/x/staking/keeper/unbonding.go b/x/staking/keeper/unbonding.go index b3507526b20..af6c9464e7c 100644 --- a/x/staking/keeper/unbonding.go +++ b/x/staking/keeper/unbonding.go @@ -284,7 +284,7 @@ func (k Keeper) unbondingDelegationEntryCanComplete(ctx context.Context, id uint sdkCtx := sdk.UnwrapSDKContext(ctx) // Check if entry is matured. - if !ubd.Entries[i].OnHold() && ubd.Entries[i].IsMature(sdkCtx.BlockHeader().Time) { + if !ubd.Entries[i].OnHold() && ubd.Entries[i].IsMature(sdkCtx.HeaderInfo().Time) { // If matured, complete it. delegatorAddress, err := k.authKeeper.AddressCodec().StringToBytes(ubd.DelegatorAddress) if err != nil { @@ -346,7 +346,7 @@ func (k Keeper) redelegationEntryCanComplete(ctx context.Context, id uint64) err red.Entries[i].UnbondingOnHoldRefCount-- sdkCtx := sdk.UnwrapSDKContext(ctx) - if !red.Entries[i].OnHold() && red.Entries[i].IsMature(sdkCtx.BlockHeader().Time) { + if !red.Entries[i].OnHold() && red.Entries[i].IsMature(sdkCtx.HeaderInfo().Time) { // If matured, complete it. // Remove entry red.RemoveEntry(int64(i)) diff --git a/x/staking/keeper/val_state_change.go b/x/staking/keeper/val_state_change.go index e73f4f869df..859233eab17 100644 --- a/x/staking/keeper/val_state_change.go +++ b/x/staking/keeper/val_state_change.go @@ -41,7 +41,7 @@ func (k Keeper) BlockValidatorUpdates(ctx context.Context) ([]abci.ValidatorUpda sdkCtx := sdk.UnwrapSDKContext(ctx) // Remove all mature unbonding delegations from the ubd queue. - matureUnbonds, err := k.DequeueAllMatureUBDQueue(ctx, sdkCtx.BlockHeader().Time) + matureUnbonds, err := k.DequeueAllMatureUBDQueue(ctx, sdkCtx.HeaderInfo().Time) if err != nil { return nil, err } @@ -72,7 +72,7 @@ func (k Keeper) BlockValidatorUpdates(ctx context.Context) ([]abci.ValidatorUpda } // Remove all mature redelegations from the red queue. - matureRedelegations, err := k.DequeueAllMatureRedelegationQueue(ctx, sdkCtx.BlockHeader().Time) + matureRedelegations, err := k.DequeueAllMatureRedelegationQueue(ctx, sdkCtx.HeaderInfo().Time) if err != nil { return nil, err } @@ -400,8 +400,8 @@ func (k Keeper) BeginUnbondingValidator(ctx context.Context, validator types.Val sdkCtx := sdk.UnwrapSDKContext(ctx) // set the unbonding completion time and completion height appropriately - validator.UnbondingTime = sdkCtx.BlockHeader().Time.Add(params.UnbondingTime) - validator.UnbondingHeight = sdkCtx.BlockHeader().Height + validator.UnbondingTime = sdkCtx.HeaderInfo().Time.Add(params.UnbondingTime) + validator.UnbondingHeight = sdkCtx.HeaderInfo().Height validator.UnbondingIds = append(validator.UnbondingIds, id) diff --git a/x/staking/keeper/validator.go b/x/staking/keeper/validator.go index bc8b028c17a..086a844392a 100644 --- a/x/staking/keeper/validator.go +++ b/x/staking/keeper/validator.go @@ -185,7 +185,7 @@ func (k Keeper) UpdateValidatorCommission(ctx context.Context, ) (types.Commission, error) { commission := validator.Commission sdkCtx := sdk.UnwrapSDKContext(ctx) - blockTime := sdkCtx.BlockHeader().Time + blockTime := sdkCtx.HeaderInfo().Time if err := commission.ValidateNewRate(newRate, blockTime); err != nil { return commission, err @@ -476,7 +476,7 @@ func (k Keeper) DeleteValidatorQueue(ctx context.Context, val types.Validator) e // have finished their unbonding period. func (k Keeper) UnbondAllMatureValidators(ctx context.Context) error { sdkCtx := sdk.UnwrapSDKContext(ctx) - blockTime := sdkCtx.BlockTime() + blockTime := sdkCtx.HeaderInfo().Time blockHeight := uint64(sdkCtx.BlockHeight()) rng := new(collections.Range[collections.Triple[uint64, time.Time, uint64]]). diff --git a/x/staking/keeper/validator_test.go b/x/staking/keeper/validator_test.go index f3afffa87bd..27f774ee910 100644 --- a/x/staking/keeper/validator_test.go +++ b/x/staking/keeper/validator_test.go @@ -7,6 +7,7 @@ import ( "github.com/golang/mock/gomock" "cosmossdk.io/collections" + "cosmossdk.io/core/header" "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" @@ -342,7 +343,7 @@ func (s *KeeperTestSuite) TestUpdateValidatorCommission() { require.Equal(tc.newRate, val.Commission.Rate, "expected new validator commission rate for test case #%d with rate: %s", i, tc.newRate, ) - require.Equal(ctx.BlockHeader().Time, val.Commission.UpdateTime, + require.Equal(ctx.HeaderInfo().Time, val.Commission.UpdateTime, "expected new validator commission update time for test case #%d with rate: %s", i, tc.newRate, ) } @@ -415,12 +416,12 @@ func (s *KeeperTestSuite) TestUnbondingValidator() { require.Equal(valAddr.String(), resVals[0]) // check unbonding mature validators - ctx = ctx.WithBlockHeight(endHeight).WithBlockTime(endTime) + ctx = ctx.WithBlockHeight(endHeight).WithHeaderInfo(header.Info{Time: endTime}) err = keeper.UnbondAllMatureValidators(ctx) require.EqualError(err, "validator in the unbonding queue was not found: validator does not exist") require.NoError(keeper.SetValidator(ctx, validator)) - ctx = ctx.WithBlockHeight(endHeight).WithBlockTime(endTime) + ctx = ctx.WithBlockHeight(endHeight).WithHeaderInfo(header.Info{Time: endTime}) err = keeper.UnbondAllMatureValidators(ctx) require.EqualError(err, "unexpected validator in unbonding queue; status was not unbonding") diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 50750085d87..f1083b916b9 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -221,7 +221,7 @@ func SimulateMsgEditValidator( address := val.GetOperator() newCommissionRate := simtypes.RandomDecAmount(r, val.Commission.MaxRate) - if err := val.Commission.ValidateNewRate(newCommissionRate, ctx.BlockHeader().Time); err != nil { + if err := val.Commission.ValidateNewRate(newCommissionRate, ctx.HeaderInfo().Time); err != nil { // skip as the commission is invalid return simtypes.NoOpMsg(types.ModuleName, msgType, "invalid commission rate"), nil, nil } @@ -517,7 +517,7 @@ func SimulateMsgCancelUnbondingDelegate( } } - if unbondingDelegationEntry.CompletionTime.Before(ctx.BlockTime()) { + if unbondingDelegationEntry.CompletionTime.Before(ctx.HeaderInfo().Time) { return simtypes.NoOpMsg(types.ModuleName, msgType, "unbonding delegation is already processed"), nil, nil } diff --git a/x/staking/testutil/helpers.go b/x/staking/testutil/helpers.go index be09bc2625d..9d9c6aba2f3 100644 --- a/x/staking/testutil/helpers.go +++ b/x/staking/testutil/helpers.go @@ -7,6 +7,7 @@ import ( "github.com/stretchr/testify/require" + "cosmossdk.io/core/header" "cosmossdk.io/math" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" @@ -121,7 +122,7 @@ func (sh *Helper) CheckValidator(addr sdk.ValAddress, status stakingtypes.BondSt // TurnBlock calls EndBlocker and updates the block time func (sh *Helper) TurnBlock(newTime time.Time) sdk.Context { - sh.Ctx = sh.Ctx.WithBlockTime(newTime) + sh.Ctx = sh.Ctx.WithHeaderInfo(header.Info{Time: newTime}) _, err := sh.k.EndBlocker(sh.Ctx) require.NoError(sh.t, err) return sh.Ctx @@ -130,7 +131,7 @@ func (sh *Helper) TurnBlock(newTime time.Time) sdk.Context { // TurnBlockTimeDiff calls EndBlocker and updates the block time by adding the // duration to the current block time func (sh *Helper) TurnBlockTimeDiff(diff time.Duration) sdk.Context { - sh.Ctx = sh.Ctx.WithBlockTime(sh.Ctx.BlockHeader().Time.Add(diff)) + sh.Ctx = sh.Ctx.WithHeaderInfo(header.Info{Time: sh.Ctx.HeaderInfo().Time.Add(diff)}) _, err := sh.k.EndBlocker(sh.Ctx) require.NoError(sh.t, err) return sh.Ctx