From f3f48f630311f136c8873a8cd5086369ac8e62d9 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Fri, 10 Jan 2020 12:29:56 -0500 Subject: [PATCH 1/8] Refactor use of parameters in x/distribution to match module spec --- x/distribution/alias.go | 37 +++-- x/distribution/client/cli/query.go | 10 +- x/distribution/client/common/common.go | 32 ----- x/distribution/client/common/pretty_params.go | 34 ----- x/distribution/client/rest/query.go | 6 +- x/distribution/genesis.go | 20 +-- x/distribution/keeper/keeper.go | 7 +- x/distribution/keeper/keeper_test.go | 7 +- x/distribution/keeper/key.go | 61 ++------- x/distribution/keeper/params.go | 128 +++--------------- x/distribution/keeper/querier.go | 36 +---- x/distribution/keeper/querier_test.go | 68 +++------- x/distribution/keeper/store.go | 28 ++-- x/distribution/keeper/test_common.go | 11 +- x/distribution/simulation/decoder.go | 19 ++- x/distribution/simulation/decoder_test.go | 4 +- x/distribution/simulation/genesis.go | 12 +- x/distribution/types/genesis.go | 46 +++---- x/distribution/types/keys.go | 33 +++++ x/distribution/types/params.go | 117 ++++++++++++++++ x/distribution/types/querier.go | 5 - x/evidence/internal/types/params.go | 9 +- 22 files changed, 317 insertions(+), 413 deletions(-) delete mode 100644 x/distribution/client/common/pretty_params.go create mode 100644 x/distribution/types/params.go diff --git a/x/distribution/alias.go b/x/distribution/alias.go index ff181d7331e3..4956474af576 100644 --- a/x/distribution/alias.go +++ b/x/distribution/alias.go @@ -9,7 +9,6 @@ import ( // nolint const ( - DefaultParamspace = keeper.DefaultParamspace ModuleName = types.ModuleName StoreKey = types.StoreKey RouterKey = types.RouterKey @@ -24,10 +23,7 @@ const ( QueryDelegatorValidators = types.QueryDelegatorValidators QueryWithdrawAddr = types.QueryWithdrawAddr QueryCommunityPool = types.QueryCommunityPool - ParamCommunityTax = types.ParamCommunityTax - ParamBaseProposerReward = types.ParamBaseProposerReward - ParamBonusProposerReward = types.ParamBonusProposerReward - ParamWithdrawAddrEnabled = types.ParamWithdrawAddrEnabled + DefaultParamspace = types.DefaultParamspace TypeMsgFundCommunityPool = types.TypeMsgFundCommunityPool ) @@ -57,12 +53,13 @@ var ( GetValidatorSlashEventPrefix = keeper.GetValidatorSlashEventPrefix GetValidatorSlashEventKeyPrefix = keeper.GetValidatorSlashEventKeyPrefix GetValidatorSlashEventKey = keeper.GetValidatorSlashEventKey - ParamKeyTable = keeper.ParamKeyTable HandleCommunityPoolSpendProposal = keeper.HandleCommunityPoolSpendProposal NewQuerier = keeper.NewQuerier MakeTestCodec = keeper.MakeTestCodec CreateTestInputDefault = keeper.CreateTestInputDefault CreateTestInputAdvanced = keeper.CreateTestInputAdvanced + ParamKeyTable = types.ParamKeyTable + DefaultParams = types.DefaultParams RegisterCodec = types.RegisterCodec NewDelegatorStartingInfo = types.NewDelegatorStartingInfo ErrEmptyDelegatorAddr = types.ErrEmptyDelegatorAddr @@ -100,20 +97,19 @@ var ( NewValidatorSlashEvent = types.NewValidatorSlashEvent // variable aliases - FeePoolKey = keeper.FeePoolKey - ProposerKey = keeper.ProposerKey - ValidatorOutstandingRewardsPrefix = keeper.ValidatorOutstandingRewardsPrefix - DelegatorWithdrawAddrPrefix = keeper.DelegatorWithdrawAddrPrefix - DelegatorStartingInfoPrefix = keeper.DelegatorStartingInfoPrefix - ValidatorHistoricalRewardsPrefix = keeper.ValidatorHistoricalRewardsPrefix - ValidatorCurrentRewardsPrefix = keeper.ValidatorCurrentRewardsPrefix - ValidatorAccumulatedCommissionPrefix = keeper.ValidatorAccumulatedCommissionPrefix - ValidatorSlashEventPrefix = keeper.ValidatorSlashEventPrefix - ParamStoreKeyCommunityTax = keeper.ParamStoreKeyCommunityTax - ParamStoreKeyBaseProposerReward = keeper.ParamStoreKeyBaseProposerReward - ParamStoreKeyBonusProposerReward = keeper.ParamStoreKeyBonusProposerReward - ParamStoreKeyWithdrawAddrEnabled = keeper.ParamStoreKeyWithdrawAddrEnabled - TestAddrs = keeper.TestAddrs + FeePoolKey = types.FeePoolKey + ProposerKey = types.ProposerKey + ValidatorOutstandingRewardsPrefix = types.ValidatorOutstandingRewardsPrefix + DelegatorWithdrawAddrPrefix = types.DelegatorWithdrawAddrPrefix + DelegatorStartingInfoPrefix = types.DelegatorStartingInfoPrefix + ValidatorHistoricalRewardsPrefix = types.ValidatorHistoricalRewardsPrefix + ValidatorCurrentRewardsPrefix = types.ValidatorCurrentRewardsPrefix + ValidatorAccumulatedCommissionPrefix = types.ValidatorAccumulatedCommissionPrefix + ValidatorSlashEventPrefix = types.ValidatorSlashEventPrefix + ParamStoreKeyCommunityTax = types.ParamStoreKeyCommunityTax + ParamStoreKeyBaseProposerReward = types.ParamStoreKeyBaseProposerReward + ParamStoreKeyBonusProposerReward = types.ParamStoreKeyBonusProposerReward + ParamStoreKeyWithdrawAddrEnabled = types.ParamStoreKeyWithdrawAddrEnabled ModuleCdc = types.ModuleCdc EventTypeSetWithdrawAddress = types.EventTypeSetWithdrawAddress EventTypeRewards = types.EventTypeRewards @@ -139,6 +135,7 @@ type ( ValidatorCurrentRewardsRecord = types.ValidatorCurrentRewardsRecord DelegatorStartingInfoRecord = types.DelegatorStartingInfoRecord ValidatorSlashEventRecord = types.ValidatorSlashEventRecord + Params = types.Params GenesisState = types.GenesisState MsgSetWithdrawAddress = types.MsgSetWithdrawAddress MsgWithdrawDelegatorReward = types.MsgWithdrawDelegatorReward diff --git a/x/distribution/client/cli/query.go b/x/distribution/client/cli/query.go index dff8e5e06a5d..06bc2e677328 100644 --- a/x/distribution/client/cli/query.go +++ b/x/distribution/client/cli/query.go @@ -47,10 +47,18 @@ func GetCmdQueryParams(queryRoute string, cdc *codec.Codec) *cobra.Command { Short: "Query distribution params", RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) - params, err := common.QueryParams(cliCtx, queryRoute) + + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryParams) + res, _, err := cliCtx.QueryWithData(route, nil) if err != nil { return err } + + var params types.Params + if err := cdc.UnmarshalJSON(res, ¶ms); err != nil { + return fmt.Errorf("failed to unmarshal params: %w", err) + } + return cliCtx.PrintOutput(params) }, } diff --git a/x/distribution/client/common/common.go b/x/distribution/client/common/common.go index 44c08e8d5f64..b20e87ec0586 100644 --- a/x/distribution/client/common/common.go +++ b/x/distribution/client/common/common.go @@ -8,38 +8,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/distribution/types" ) -// QueryParams actually queries distribution params. -func QueryParams(cliCtx context.CLIContext, queryRoute string) (PrettyParams, error) { - route := fmt.Sprintf("custom/%s/params/%s", queryRoute, types.ParamCommunityTax) - - retCommunityTax, _, err := cliCtx.QueryWithData(route, []byte{}) - if err != nil { - return PrettyParams{}, err - } - - route = fmt.Sprintf("custom/%s/params/%s", queryRoute, types.ParamBaseProposerReward) - retBaseProposerReward, _, err := cliCtx.QueryWithData(route, []byte{}) - if err != nil { - return PrettyParams{}, err - } - - route = fmt.Sprintf("custom/%s/params/%s", queryRoute, types.ParamBonusProposerReward) - retBonusProposerReward, _, err := cliCtx.QueryWithData(route, []byte{}) - if err != nil { - return PrettyParams{}, err - } - - route = fmt.Sprintf("custom/%s/params/%s", queryRoute, types.ParamWithdrawAddrEnabled) - retWithdrawAddrEnabled, _, err := cliCtx.QueryWithData(route, []byte{}) - if err != nil { - return PrettyParams{}, err - } - - return NewPrettyParams( - retCommunityTax, retBaseProposerReward, retBonusProposerReward, retWithdrawAddrEnabled, - ), nil -} - // QueryDelegatorTotalRewards queries delegator total rewards. func QueryDelegatorTotalRewards(cliCtx context.CLIContext, queryRoute, delAddr string) ([]byte, error) { delegatorAddr, err := sdk.AccAddressFromBech32(delAddr) diff --git a/x/distribution/client/common/pretty_params.go b/x/distribution/client/common/pretty_params.go deleted file mode 100644 index cbe22869b7d8..000000000000 --- a/x/distribution/client/common/pretty_params.go +++ /dev/null @@ -1,34 +0,0 @@ -package common - -import ( - "encoding/json" - "fmt" -) - -// Convenience struct for CLI output -type PrettyParams struct { - CommunityTax json.RawMessage `json:"community_tax"` - BaseProposerReward json.RawMessage `json:"base_proposer_reward"` - BonusProposerReward json.RawMessage `json:"bonus_proposer_reward"` - WithdrawAddrEnabled json.RawMessage `json:"withdraw_addr_enabled"` -} - -// Construct a new PrettyParams -func NewPrettyParams(communityTax json.RawMessage, baseProposerReward json.RawMessage, bonusProposerReward json.RawMessage, withdrawAddrEnabled json.RawMessage) PrettyParams { - return PrettyParams{ - CommunityTax: communityTax, - BaseProposerReward: baseProposerReward, - BonusProposerReward: bonusProposerReward, - WithdrawAddrEnabled: withdrawAddrEnabled, - } -} - -func (pp PrettyParams) String() string { - return fmt.Sprintf(`Distribution Params: - Community Tax: %s - Base Proposer Reward: %s - Bonus Proposer Reward: %s - Withdraw Addr Enabled: %s`, pp.CommunityTax, - pp.BaseProposerReward, pp.BonusProposerReward, pp.WithdrawAddrEnabled) - -} diff --git a/x/distribution/client/rest/query.go b/x/distribution/client/rest/query.go index 15b5c7fe07c7..d242157dd40f 100644 --- a/x/distribution/client/rest/query.go +++ b/x/distribution/client/rest/query.go @@ -216,13 +216,15 @@ func paramsHandlerFn(cliCtx context.CLIContext, queryRoute string) http.HandlerF return } - params, err := common.QueryParams(cliCtx, queryRoute) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryParams) + res, height, err := cliCtx.QueryWithData(route, nil) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - rest.PostProcessResponse(w, cliCtx, params) + cliCtx = cliCtx.WithHeight(height) + rest.PostProcessResponse(w, cliCtx, res) } } diff --git a/x/distribution/genesis.go b/x/distribution/genesis.go index c0fc05b9ea71..6a7f9c1fdbaf 100644 --- a/x/distribution/genesis.go +++ b/x/distribution/genesis.go @@ -12,10 +12,7 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, supplyKeeper types.SupplyKeeper var moduleHoldings sdk.DecCoins keeper.SetFeePool(ctx, data.FeePool) - keeper.SetCommunityTax(ctx, data.CommunityTax) - keeper.SetBaseProposerReward(ctx, data.BaseProposerReward) - keeper.SetBonusProposerReward(ctx, data.BonusProposerReward) - keeper.SetWithdrawAddrEnabled(ctx, data.WithdrawAddrEnabled) + keeper.SetParams(ctx, data.Params) for _, dwi := range data.DelegatorWithdrawInfos { keeper.SetDelegatorWithdrawAddr(ctx, dwi.DelegatorAddress, dwi.WithdrawAddress) @@ -61,10 +58,8 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, supplyKeeper types.SupplyKeeper // ExportGenesis returns a GenesisState for a given context and keeper. func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { feePool := keeper.GetFeePool(ctx) - communityTax := keeper.GetCommunityTax(ctx) - baseProposerRewards := keeper.GetBaseProposerReward(ctx) - bonusProposerRewards := keeper.GetBonusProposerReward(ctx) - withdrawAddrEnabled := keeper.GetWithdrawAddrEnabled(ctx) + params := keeper.GetParams(ctx) + dwi := make([]types.DelegatorWithdrawInfo, 0) keeper.IterateDelegatorWithdrawAddrs(ctx, func(del sdk.AccAddress, addr sdk.AccAddress) (stop bool) { dwi = append(dwi, types.DelegatorWithdrawInfo{ @@ -73,6 +68,7 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { }) return false }) + pp := keeper.GetPreviousProposerConsAddr(ctx) outstanding := make([]types.ValidatorOutstandingRewardsRecord, 0) keeper.IterateValidatorOutstandingRewards(ctx, @@ -84,6 +80,7 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { return false }, ) + acc := make([]types.ValidatorAccumulatedCommissionRecord, 0) keeper.IterateValidatorAccumulatedCommissions(ctx, func(addr sdk.ValAddress, commission types.ValidatorAccumulatedCommission) (stop bool) { @@ -94,6 +91,7 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { return false }, ) + his := make([]types.ValidatorHistoricalRewardsRecord, 0) keeper.IterateValidatorHistoricalRewards(ctx, func(val sdk.ValAddress, period uint64, rewards types.ValidatorHistoricalRewards) (stop bool) { @@ -105,6 +103,7 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { return false }, ) + cur := make([]types.ValidatorCurrentRewardsRecord, 0) keeper.IterateValidatorCurrentRewards(ctx, func(val sdk.ValAddress, rewards types.ValidatorCurrentRewards) (stop bool) { @@ -126,6 +125,7 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { return false }, ) + slashes := make([]types.ValidatorSlashEventRecord, 0) keeper.IterateValidatorSlashEvents(ctx, func(val sdk.ValAddress, height uint64, event types.ValidatorSlashEvent) (stop bool) { @@ -138,6 +138,6 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { return false }, ) - return types.NewGenesisState(feePool, communityTax, baseProposerRewards, bonusProposerRewards, withdrawAddrEnabled, - dwi, pp, outstanding, acc, his, cur, dels, slashes) + + return types.NewGenesisState(params, feePool, dwi, pp, outstanding, acc, his, cur, dels, slashes) } diff --git a/x/distribution/keeper/keeper.go b/x/distribution/keeper/keeper.go index 1ce723d11418..18cbce2b6848 100644 --- a/x/distribution/keeper/keeper.go +++ b/x/distribution/keeper/keeper.go @@ -37,10 +37,15 @@ func NewKeeper( panic(fmt.Sprintf("%s module account has not been set", types.ModuleName)) } + // set KeyTable if it has not already been set + if !paramSpace.HasKeyTable() { + paramSpace = paramSpace.WithKeyTable(types.ParamKeyTable()) + } + return Keeper{ storeKey: key, cdc: cdc, - paramSpace: paramSpace.WithKeyTable(ParamKeyTable()), + paramSpace: paramSpace, stakingKeeper: sk, supplyKeeper: supplyKeeper, feeCollectorName: feeCollectorName, diff --git a/x/distribution/keeper/keeper_test.go b/x/distribution/keeper/keeper_test.go index 2536104c3b6b..5b2d989f7f82 100644 --- a/x/distribution/keeper/keeper_test.go +++ b/x/distribution/keeper/keeper_test.go @@ -13,12 +13,15 @@ import ( func TestSetWithdrawAddr(t *testing.T) { ctx, _, keeper, _, _ := CreateTestInputDefault(t, false, 1000) - keeper.SetWithdrawAddrEnabled(ctx, false) + params := keeper.GetParams(ctx) + params.WithdrawAddrEnabled = false + keeper.SetParams(ctx, params) err := keeper.SetWithdrawAddr(ctx, delAddr1, delAddr2) require.NotNil(t, err) - keeper.SetWithdrawAddrEnabled(ctx, true) + params.WithdrawAddrEnabled = true + keeper.SetParams(ctx, params) err = keeper.SetWithdrawAddr(ctx, delAddr1, delAddr2) require.Nil(t, err) diff --git a/x/distribution/keeper/key.go b/x/distribution/keeper/key.go index 0b8dda21b157..6435ed92249e 100644 --- a/x/distribution/keeper/key.go +++ b/x/distribution/keeper/key.go @@ -7,49 +7,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/distribution/types" ) -const ( - // default paramspace for params keeper - DefaultParamspace = types.ModuleName -) - -// Keys for distribution store -// Items are stored with the following key: values -// -// - 0x00: FeePol -// -// - 0x01: sdk.ConsAddress -// -// - 0x02: ValidatorOutstandingRewards -// -// - 0x03: sdk.AccAddress -// -// - 0x04: DelegatorStartingInfo -// -// - 0x05: ValidatorHistoricalRewards -// -// - 0x06: ValidatorCurrentRewards -// -// - 0x07: ValidatorCurrentRewards -// -// - 0x08: ValidatorSlashEvent -var ( - FeePoolKey = []byte{0x00} // key for global distribution state - ProposerKey = []byte{0x01} // key for the proposer operator address - ValidatorOutstandingRewardsPrefix = []byte{0x02} // key for outstanding rewards - - DelegatorWithdrawAddrPrefix = []byte{0x03} // key for delegator withdraw address - DelegatorStartingInfoPrefix = []byte{0x04} // key for delegator starting info - ValidatorHistoricalRewardsPrefix = []byte{0x05} // key for historical validators rewards / stake - ValidatorCurrentRewardsPrefix = []byte{0x06} // key for current validator rewards - ValidatorAccumulatedCommissionPrefix = []byte{0x07} // key for accumulated validator commission - ValidatorSlashEventPrefix = []byte{0x08} // key for validator slash fraction - - ParamStoreKeyCommunityTax = []byte("communitytax") - ParamStoreKeyBaseProposerReward = []byte("baseproposerreward") - ParamStoreKeyBonusProposerReward = []byte("bonusproposerreward") - ParamStoreKeyWithdrawAddrEnabled = []byte("withdrawaddrenabled") -) - // gets an address from a validator's outstanding rewards key func GetValidatorOutstandingRewardsAddress(key []byte) (valAddr sdk.ValAddress) { addr := key[1:] @@ -131,44 +88,44 @@ func GetValidatorSlashEventAddressHeight(key []byte) (valAddr sdk.ValAddress, he // gets the outstanding rewards key for a validator func GetValidatorOutstandingRewardsKey(valAddr sdk.ValAddress) []byte { - return append(ValidatorOutstandingRewardsPrefix, valAddr.Bytes()...) + return append(types.ValidatorOutstandingRewardsPrefix, valAddr.Bytes()...) } // gets the key for a delegator's withdraw addr func GetDelegatorWithdrawAddrKey(delAddr sdk.AccAddress) []byte { - return append(DelegatorWithdrawAddrPrefix, delAddr.Bytes()...) + return append(types.DelegatorWithdrawAddrPrefix, delAddr.Bytes()...) } // gets the key for a delegator's starting info func GetDelegatorStartingInfoKey(v sdk.ValAddress, d sdk.AccAddress) []byte { - return append(append(DelegatorStartingInfoPrefix, v.Bytes()...), d.Bytes()...) + return append(append(types.DelegatorStartingInfoPrefix, v.Bytes()...), d.Bytes()...) } // gets the prefix key for a validator's historical rewards func GetValidatorHistoricalRewardsPrefix(v sdk.ValAddress) []byte { - return append(ValidatorHistoricalRewardsPrefix, v.Bytes()...) + return append(types.ValidatorHistoricalRewardsPrefix, v.Bytes()...) } // gets the key for a validator's historical rewards func GetValidatorHistoricalRewardsKey(v sdk.ValAddress, k uint64) []byte { b := make([]byte, 8) binary.LittleEndian.PutUint64(b, k) - return append(append(ValidatorHistoricalRewardsPrefix, v.Bytes()...), b...) + return append(append(types.ValidatorHistoricalRewardsPrefix, v.Bytes()...), b...) } // gets the key for a validator's current rewards func GetValidatorCurrentRewardsKey(v sdk.ValAddress) []byte { - return append(ValidatorCurrentRewardsPrefix, v.Bytes()...) + return append(types.ValidatorCurrentRewardsPrefix, v.Bytes()...) } // gets the key for a validator's current commission func GetValidatorAccumulatedCommissionKey(v sdk.ValAddress) []byte { - return append(ValidatorAccumulatedCommissionPrefix, v.Bytes()...) + return append(types.ValidatorAccumulatedCommissionPrefix, v.Bytes()...) } // gets the prefix key for a validator's slash fractions func GetValidatorSlashEventPrefix(v sdk.ValAddress) []byte { - return append(ValidatorSlashEventPrefix, v.Bytes()...) + return append(types.ValidatorSlashEventPrefix, v.Bytes()...) } // gets the prefix key for a validator's slash fraction (ValidatorSlashEventPrefix + height) @@ -176,7 +133,7 @@ func GetValidatorSlashEventKeyPrefix(v sdk.ValAddress, height uint64) []byte { heightBz := make([]byte, 8) binary.BigEndian.PutUint64(heightBz, height) return append( - ValidatorSlashEventPrefix, + types.ValidatorSlashEventPrefix, append( v.Bytes(), heightBz..., diff --git a/x/distribution/keeper/params.go b/x/distribution/keeper/params.go index 764dfdc21731..63d6ecedc8ba 100644 --- a/x/distribution/keeper/params.go +++ b/x/distribution/keeper/params.go @@ -1,127 +1,43 @@ package keeper import ( - "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/params" + "github.com/cosmos/cosmos-sdk/x/distribution/types" ) -// type declaration for parameters -func ParamKeyTable() params.KeyTable { - return params.NewKeyTable( - params.NewParamSetPair(ParamStoreKeyCommunityTax, sdk.Dec{}, validateCommunityTax), - params.NewParamSetPair(ParamStoreKeyBaseProposerReward, sdk.Dec{}, validateBaseProposerReward), - params.NewParamSetPair(ParamStoreKeyBonusProposerReward, sdk.Dec{}, validateBonusProposerReward), - params.NewParamSetPair(ParamStoreKeyWithdrawAddrEnabled, false, validateWithdrawAddrEnabled), - ) -} - -func validateCommunityTax(i interface{}) error { - v, ok := i.(sdk.Dec) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if v.IsNegative() { - return fmt.Errorf("community tax must be positive: %s", v) - } - if v.GT(sdk.OneDec()) { - return fmt.Errorf("community tax too large: %s", v) - } - - return nil -} - -func validateBaseProposerReward(i interface{}) error { - v, ok := i.(sdk.Dec) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if v.IsNegative() { - return fmt.Errorf("base proposer reward must be positive: %s", v) - } - if v.GT(sdk.OneDec()) { - return fmt.Errorf("base proposer reward too large: %s", v) - } - - return nil -} - -func validateBonusProposerReward(i interface{}) error { - v, ok := i.(sdk.Dec) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if v.IsNegative() { - return fmt.Errorf("bonus proposer reward must be positive: %s", v) - } - if v.GT(sdk.OneDec()) { - return fmt.Errorf("bonus proposer reward too large: %s", v) - } - - return nil +// GetParams returns the total set of distribution parameters. +func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { + k.paramSpace.GetParamSet(ctx, ¶ms) + return params } -func validateWithdrawAddrEnabled(i interface{}) error { - _, ok := i.(bool) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - return nil +// SetParams sets the distribution parameters to the param space. +func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { + k.paramSpace.SetParamSet(ctx, ¶ms) } -// returns the current CommunityTax rate from the global param store -// nolint: errcheck -func (k Keeper) GetCommunityTax(ctx sdk.Context) sdk.Dec { - var percent sdk.Dec - k.paramSpace.Get(ctx, ParamStoreKeyCommunityTax, &percent) +// GetCommunityTax returns the current distribution community tax. +func (k Keeper) GetCommunityTax(ctx sdk.Context) (percent sdk.Dec) { + k.paramSpace.Get(ctx, types.ParamStoreKeyCommunityTax, &percent) return percent } -// nolint: errcheck -func (k Keeper) SetCommunityTax(ctx sdk.Context, percent sdk.Dec) { - k.paramSpace.Set(ctx, ParamStoreKeyCommunityTax, &percent) -} - -// returns the current BaseProposerReward rate from the global param store -// nolint: errcheck -func (k Keeper) GetBaseProposerReward(ctx sdk.Context) sdk.Dec { - var percent sdk.Dec - k.paramSpace.Get(ctx, ParamStoreKeyBaseProposerReward, &percent) +// GetBaseProposerReward returns the current distribution base proposer rate. +func (k Keeper) GetBaseProposerReward(ctx sdk.Context) (percent sdk.Dec) { + k.paramSpace.Get(ctx, types.ParamStoreKeyBaseProposerReward, &percent) return percent } -// nolint: errcheck -func (k Keeper) SetBaseProposerReward(ctx sdk.Context, percent sdk.Dec) { - k.paramSpace.Set(ctx, ParamStoreKeyBaseProposerReward, &percent) -} - -// returns the current BaseProposerReward rate from the global param store -// nolint: errcheck -func (k Keeper) GetBonusProposerReward(ctx sdk.Context) sdk.Dec { - var percent sdk.Dec - k.paramSpace.Get(ctx, ParamStoreKeyBonusProposerReward, &percent) +// GetBonusProposerReward returns the current distribution bonus proposer reward +// rate. +func (k Keeper) GetBonusProposerReward(ctx sdk.Context) (percent sdk.Dec) { + k.paramSpace.Get(ctx, types.ParamStoreKeyBonusProposerReward, &percent) return percent } -// nolint: errcheck -func (k Keeper) SetBonusProposerReward(ctx sdk.Context, percent sdk.Dec) { - k.paramSpace.Set(ctx, ParamStoreKeyBonusProposerReward, &percent) -} - -// returns the current WithdrawAddrEnabled -// nolint: errcheck -func (k Keeper) GetWithdrawAddrEnabled(ctx sdk.Context) bool { - var enabled bool - k.paramSpace.Get(ctx, ParamStoreKeyWithdrawAddrEnabled, &enabled) +// GetWithdrawAddrEnabled returns the current distribution withdraw address +// enabled parameter. +func (k Keeper) GetWithdrawAddrEnabled(ctx sdk.Context) (enabled bool) { + k.paramSpace.Get(ctx, types.ParamStoreKeyWithdrawAddrEnabled, &enabled) return enabled } - -// nolint: errcheck -func (k Keeper) SetWithdrawAddrEnabled(ctx sdk.Context, enabled bool) { - k.paramSpace.Set(ctx, ParamStoreKeyWithdrawAddrEnabled, &enabled) -} diff --git a/x/distribution/keeper/querier.go b/x/distribution/keeper/querier.go index 641f59c29123..4757ea5ffe3e 100644 --- a/x/distribution/keeper/querier.go +++ b/x/distribution/keeper/querier.go @@ -49,38 +49,14 @@ func NewQuerier(k Keeper) sdk.Querier { } func queryParams(ctx sdk.Context, path []string, req abci.RequestQuery, k Keeper) ([]byte, error) { - switch path[0] { - case types.ParamCommunityTax: - bz, err := codec.MarshalJSONIndent(k.cdc, k.GetCommunityTax(ctx)) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - return bz, nil - - case types.ParamBaseProposerReward: - bz, err := codec.MarshalJSONIndent(k.cdc, k.GetBaseProposerReward(ctx)) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - return bz, nil - - case types.ParamBonusProposerReward: - bz, err := codec.MarshalJSONIndent(k.cdc, k.GetBonusProposerReward(ctx)) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - return bz, nil + params := k.GetParams(ctx) - case types.ParamWithdrawAddrEnabled: - bz, err := codec.MarshalJSONIndent(k.cdc, k.GetWithdrawAddrEnabled(ctx)) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - return bz, nil - - default: - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "%s is not a valid query request path", req.Path) + res, err := codec.MarshalJSONIndent(k.cdc, params) + if err != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) } + + return res, nil } func queryValidatorOutstandingRewards(ctx sdk.Context, path []string, req abci.RequestQuery, k Keeper) ([]byte, error) { diff --git a/x/distribution/keeper/querier_test.go b/x/distribution/keeper/querier_test.go index e70ca2ea0f4b..b5efd15a3a62 100644 --- a/x/distribution/keeper/querier_test.go +++ b/x/distribution/keeper/querier_test.go @@ -17,45 +17,14 @@ import ( const custom = "custom" -func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier) (communityTax sdk.Dec, baseProposerReward sdk.Dec, bonusProposerReward sdk.Dec, withdrawAddrEnabled bool) { +func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier) types.Params { + var params types.Params - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamCommunityTax}, "/"), - Data: []byte{}, - } - - bz, err := querier(ctx, []string{types.QueryParams, types.ParamCommunityTax}, query) - require.Nil(t, err) - require.Nil(t, cdc.UnmarshalJSON(bz, &communityTax)) - - query = abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamBaseProposerReward}, "/"), - Data: []byte{}, - } - - bz, err = querier(ctx, []string{types.QueryParams, types.ParamBaseProposerReward}, query) - require.Nil(t, err) - require.Nil(t, cdc.UnmarshalJSON(bz, &baseProposerReward)) - - query = abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamBonusProposerReward}, "/"), - Data: []byte{}, - } - - bz, err = querier(ctx, []string{types.QueryParams, types.ParamBonusProposerReward}, query) + bz, err := querier(ctx, []string{types.QueryParams}, abci.RequestQuery{}) require.Nil(t, err) - require.Nil(t, cdc.UnmarshalJSON(bz, &bonusProposerReward)) - - query = abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamWithdrawAddrEnabled}, "/"), - Data: []byte{}, - } + require.Nil(t, cdc.UnmarshalJSON(bz, ¶ms)) - bz, err = querier(ctx, []string{types.QueryParams, types.ParamWithdrawAddrEnabled}, query) - require.Nil(t, err) - require.Nil(t, cdc.UnmarshalJSON(bz, &withdrawAddrEnabled)) - - return communityTax, baseProposerReward, bonusProposerReward, withdrawAddrEnabled + return params } func getQueriedValidatorOutstandingRewards(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, validatorAddr sdk.ValAddress) (outstandingRewards sdk.DecCoins) { @@ -144,19 +113,20 @@ func TestQueries(t *testing.T) { querier := NewQuerier(keeper) // test param queries - communityTax := sdk.NewDecWithPrec(3, 1) - baseProposerReward := sdk.NewDecWithPrec(2, 1) - bonusProposerReward := sdk.NewDecWithPrec(1, 1) - withdrawAddrEnabled := true - keeper.SetCommunityTax(ctx, communityTax) - keeper.SetBaseProposerReward(ctx, baseProposerReward) - keeper.SetBonusProposerReward(ctx, bonusProposerReward) - keeper.SetWithdrawAddrEnabled(ctx, withdrawAddrEnabled) - retCommunityTax, retBaseProposerReward, retBonusProposerReward, retWithdrawAddrEnabled := getQueriedParams(t, ctx, cdc, querier) - require.Equal(t, communityTax, retCommunityTax) - require.Equal(t, baseProposerReward, retBaseProposerReward) - require.Equal(t, bonusProposerReward, retBonusProposerReward) - require.Equal(t, withdrawAddrEnabled, retWithdrawAddrEnabled) + params := types.Params{ + CommunityTax: sdk.NewDecWithPrec(3, 1), + BaseProposerReward: sdk.NewDecWithPrec(2, 1), + BonusProposerReward: sdk.NewDecWithPrec(1, 1), + WithdrawAddrEnabled: true, + } + + keeper.SetParams(ctx, params) + + paramsRes := getQueriedParams(t, ctx, cdc, querier) + require.Equal(t, params.CommunityTax, paramsRes.CommunityTax) + require.Equal(t, params.BaseProposerReward, paramsRes.BaseProposerReward) + require.Equal(t, params.BonusProposerReward, paramsRes.BonusProposerReward) + require.Equal(t, params.WithdrawAddrEnabled, paramsRes.WithdrawAddrEnabled) // test outstanding rewards query outstandingRewards := sdk.DecCoins{{Denom: "mytoken", Amount: sdk.NewDec(3)}, {Denom: "myothertoken", Amount: sdk.NewDecWithPrec(3, 7)}} diff --git a/x/distribution/keeper/store.go b/x/distribution/keeper/store.go index 6bb766ee34b1..fd097b148e60 100644 --- a/x/distribution/keeper/store.go +++ b/x/distribution/keeper/store.go @@ -30,7 +30,7 @@ func (k Keeper) DeleteDelegatorWithdrawAddr(ctx sdk.Context, delAddr, withdrawAd // iterate over delegator withdraw addrs func (k Keeper) IterateDelegatorWithdrawAddrs(ctx sdk.Context, handler func(del sdk.AccAddress, addr sdk.AccAddress) (stop bool)) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, DelegatorWithdrawAddrPrefix) + iter := sdk.KVStorePrefixIterator(store, types.DelegatorWithdrawAddrPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { addr := sdk.AccAddress(iter.Value()) @@ -44,7 +44,7 @@ func (k Keeper) IterateDelegatorWithdrawAddrs(ctx sdk.Context, handler func(del // get the global fee pool distribution info func (k Keeper) GetFeePool(ctx sdk.Context) (feePool types.FeePool) { store := ctx.KVStore(k.storeKey) - b := store.Get(FeePoolKey) + b := store.Get(types.FeePoolKey) if b == nil { panic("Stored fee pool should not have been nil") } @@ -56,13 +56,13 @@ func (k Keeper) GetFeePool(ctx sdk.Context) (feePool types.FeePool) { func (k Keeper) SetFeePool(ctx sdk.Context, feePool types.FeePool) { store := ctx.KVStore(k.storeKey) b := k.cdc.MustMarshalBinaryLengthPrefixed(feePool) - store.Set(FeePoolKey, b) + store.Set(types.FeePoolKey, b) } // get the proposer public key for this block func (k Keeper) GetPreviousProposerConsAddr(ctx sdk.Context) (consAddr sdk.ConsAddress) { store := ctx.KVStore(k.storeKey) - b := store.Get(ProposerKey) + b := store.Get(types.ProposerKey) if b == nil { panic("Previous proposer not set") } @@ -74,7 +74,7 @@ func (k Keeper) GetPreviousProposerConsAddr(ctx sdk.Context) (consAddr sdk.ConsA func (k Keeper) SetPreviousProposerConsAddr(ctx sdk.Context, consAddr sdk.ConsAddress) { store := ctx.KVStore(k.storeKey) b := k.cdc.MustMarshalBinaryLengthPrefixed(consAddr) - store.Set(ProposerKey, b) + store.Set(types.ProposerKey, b) } // get the starting info associated with a delegator @@ -107,7 +107,7 @@ func (k Keeper) DeleteDelegatorStartingInfo(ctx sdk.Context, val sdk.ValAddress, // iterate over delegator starting infos func (k Keeper) IterateDelegatorStartingInfos(ctx sdk.Context, handler func(val sdk.ValAddress, del sdk.AccAddress, info types.DelegatorStartingInfo) (stop bool)) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, DelegatorStartingInfoPrefix) + iter := sdk.KVStorePrefixIterator(store, types.DelegatorStartingInfoPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { var info types.DelegatorStartingInfo @@ -137,7 +137,7 @@ func (k Keeper) SetValidatorHistoricalRewards(ctx sdk.Context, val sdk.ValAddres // iterate over historical rewards func (k Keeper) IterateValidatorHistoricalRewards(ctx sdk.Context, handler func(val sdk.ValAddress, period uint64, rewards types.ValidatorHistoricalRewards) (stop bool)) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, ValidatorHistoricalRewardsPrefix) + iter := sdk.KVStorePrefixIterator(store, types.ValidatorHistoricalRewardsPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { var rewards types.ValidatorHistoricalRewards @@ -168,7 +168,7 @@ func (k Keeper) DeleteValidatorHistoricalRewards(ctx sdk.Context, val sdk.ValAdd // delete all historical rewards func (k Keeper) DeleteAllValidatorHistoricalRewards(ctx sdk.Context) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, ValidatorHistoricalRewardsPrefix) + iter := sdk.KVStorePrefixIterator(store, types.ValidatorHistoricalRewardsPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { store.Delete(iter.Key()) @@ -178,7 +178,7 @@ func (k Keeper) DeleteAllValidatorHistoricalRewards(ctx sdk.Context) { // historical reference count (used for testcases) func (k Keeper) GetValidatorHistoricalReferenceCount(ctx sdk.Context) (count uint64) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, ValidatorHistoricalRewardsPrefix) + iter := sdk.KVStorePrefixIterator(store, types.ValidatorHistoricalRewardsPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { var rewards types.ValidatorHistoricalRewards @@ -212,7 +212,7 @@ func (k Keeper) DeleteValidatorCurrentRewards(ctx sdk.Context, val sdk.ValAddres // iterate over current rewards func (k Keeper) IterateValidatorCurrentRewards(ctx sdk.Context, handler func(val sdk.ValAddress, rewards types.ValidatorCurrentRewards) (stop bool)) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, ValidatorCurrentRewardsPrefix) + iter := sdk.KVStorePrefixIterator(store, types.ValidatorCurrentRewardsPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { var rewards types.ValidatorCurrentRewards @@ -258,7 +258,7 @@ func (k Keeper) DeleteValidatorAccumulatedCommission(ctx sdk.Context, val sdk.Va // iterate over accumulated commissions func (k Keeper) IterateValidatorAccumulatedCommissions(ctx sdk.Context, handler func(val sdk.ValAddress, commission types.ValidatorAccumulatedCommission) (stop bool)) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, ValidatorAccumulatedCommissionPrefix) + iter := sdk.KVStorePrefixIterator(store, types.ValidatorAccumulatedCommissionPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { var commission types.ValidatorAccumulatedCommission @@ -294,7 +294,7 @@ func (k Keeper) DeleteValidatorOutstandingRewards(ctx sdk.Context, val sdk.ValAd // iterate validator outstanding rewards func (k Keeper) IterateValidatorOutstandingRewards(ctx sdk.Context, handler func(val sdk.ValAddress, rewards types.ValidatorOutstandingRewards) (stop bool)) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, ValidatorOutstandingRewardsPrefix) + iter := sdk.KVStorePrefixIterator(store, types.ValidatorOutstandingRewardsPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { var rewards types.ValidatorOutstandingRewards @@ -346,7 +346,7 @@ func (k Keeper) IterateValidatorSlashEventsBetween(ctx sdk.Context, val sdk.ValA // iterate over all slash events func (k Keeper) IterateValidatorSlashEvents(ctx sdk.Context, handler func(val sdk.ValAddress, height uint64, event types.ValidatorSlashEvent) (stop bool)) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, ValidatorSlashEventPrefix) + iter := sdk.KVStorePrefixIterator(store, types.ValidatorSlashEventPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { var event types.ValidatorSlashEvent @@ -371,7 +371,7 @@ func (k Keeper) DeleteValidatorSlashEvents(ctx sdk.Context, val sdk.ValAddress) // delete all slash events func (k Keeper) DeleteAllValidatorSlashEvents(ctx sdk.Context) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, ValidatorSlashEventPrefix) + iter := sdk.KVStorePrefixIterator(store, types.ValidatorSlashEventPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { store.Delete(iter.Key()) diff --git a/x/distribution/keeper/test_common.go b/x/distribution/keeper/test_common.go index 1d53c9d1816a..78425e47c11d 100644 --- a/x/distribution/keeper/test_common.go +++ b/x/distribution/keeper/test_common.go @@ -135,7 +135,7 @@ func CreateTestInputAdvanced(t *testing.T, isCheckTx bool, initPower int64, sk := staking.NewKeeper(cdc, keyStaking, supplyKeeper, pk.Subspace(staking.DefaultParamspace)) sk.SetParams(ctx, staking.DefaultParams()) - keeper := NewKeeper(cdc, keyDistr, pk.Subspace(DefaultParamspace), sk, supplyKeeper, auth.FeeCollectorName, blacklistedAddrs) + keeper := NewKeeper(cdc, keyDistr, pk.Subspace(types.DefaultParamspace), sk, supplyKeeper, auth.FeeCollectorName, blacklistedAddrs) initCoins := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), initTokens)) totalSupply := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), initTokens.MulRaw(int64(len(TestAddrs))))) @@ -158,9 +158,12 @@ func CreateTestInputAdvanced(t *testing.T, isCheckTx bool, initPower int64, // set genesis items required for distribution keeper.SetFeePool(ctx, types.InitialFeePool()) - keeper.SetCommunityTax(ctx, communityTax) - keeper.SetBaseProposerReward(ctx, sdk.NewDecWithPrec(1, 2)) - keeper.SetBonusProposerReward(ctx, sdk.NewDecWithPrec(4, 2)) + + params := types.DefaultParams() + params.CommunityTax = communityTax + params.BaseProposerReward = sdk.NewDecWithPrec(1, 2) + params.BonusProposerReward = sdk.NewDecWithPrec(4, 2) + keeper.SetParams(ctx, params) return ctx, accountKeeper, bankKeeper, keeper, sk, pk, supplyKeeper } diff --git a/x/distribution/simulation/decoder.go b/x/distribution/simulation/decoder.go index c1b8dce42821..d6098a929fe1 100644 --- a/x/distribution/simulation/decoder.go +++ b/x/distribution/simulation/decoder.go @@ -9,56 +9,55 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/distribution/keeper" "github.com/cosmos/cosmos-sdk/x/distribution/types" ) // DecodeStore unmarshals the KVPair's Value to the corresponding distribution type func DecodeStore(cdc *codec.Codec, kvA, kvB cmn.KVPair) string { switch { - case bytes.Equal(kvA.Key[:1], keeper.FeePoolKey): + case bytes.Equal(kvA.Key[:1], types.FeePoolKey): var feePoolA, feePoolB types.FeePool cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &feePoolA) cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &feePoolB) return fmt.Sprintf("%v\n%v", feePoolA, feePoolB) - case bytes.Equal(kvA.Key[:1], keeper.ProposerKey): + case bytes.Equal(kvA.Key[:1], types.ProposerKey): return fmt.Sprintf("%v\n%v", sdk.ConsAddress(kvA.Value), sdk.ConsAddress(kvB.Value)) - case bytes.Equal(kvA.Key[:1], keeper.ValidatorOutstandingRewardsPrefix): + case bytes.Equal(kvA.Key[:1], types.ValidatorOutstandingRewardsPrefix): var rewardsA, rewardsB types.ValidatorOutstandingRewards cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) - case bytes.Equal(kvA.Key[:1], keeper.DelegatorWithdrawAddrPrefix): + case bytes.Equal(kvA.Key[:1], types.DelegatorWithdrawAddrPrefix): return fmt.Sprintf("%v\n%v", sdk.AccAddress(kvA.Value), sdk.AccAddress(kvB.Value)) - case bytes.Equal(kvA.Key[:1], keeper.DelegatorStartingInfoPrefix): + case bytes.Equal(kvA.Key[:1], types.DelegatorStartingInfoPrefix): var infoA, infoB types.DelegatorStartingInfo cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &infoA) cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &infoB) return fmt.Sprintf("%v\n%v", infoA, infoB) - case bytes.Equal(kvA.Key[:1], keeper.ValidatorHistoricalRewardsPrefix): + case bytes.Equal(kvA.Key[:1], types.ValidatorHistoricalRewardsPrefix): var rewardsA, rewardsB types.ValidatorHistoricalRewards cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) - case bytes.Equal(kvA.Key[:1], keeper.ValidatorCurrentRewardsPrefix): + case bytes.Equal(kvA.Key[:1], types.ValidatorCurrentRewardsPrefix): var rewardsA, rewardsB types.ValidatorCurrentRewards cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) - case bytes.Equal(kvA.Key[:1], keeper.ValidatorAccumulatedCommissionPrefix): + case bytes.Equal(kvA.Key[:1], types.ValidatorAccumulatedCommissionPrefix): var commissionA, commissionB types.ValidatorAccumulatedCommission cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &commissionA) cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &commissionB) return fmt.Sprintf("%v\n%v", commissionA, commissionB) - case bytes.Equal(kvA.Key[:1], keeper.ValidatorSlashEventPrefix): + case bytes.Equal(kvA.Key[:1], types.ValidatorSlashEventPrefix): var eventA, eventB types.ValidatorSlashEvent cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &eventA) cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &eventB) diff --git a/x/distribution/simulation/decoder_test.go b/x/distribution/simulation/decoder_test.go index f2c4d5f94d49..b804260acaf9 100644 --- a/x/distribution/simulation/decoder_test.go +++ b/x/distribution/simulation/decoder_test.go @@ -44,8 +44,8 @@ func TestDecodeDistributionStore(t *testing.T) { slashEvent := types.NewValidatorSlashEvent(10, sdk.OneDec()) kvPairs := cmn.KVPairs{ - cmn.KVPair{Key: keeper.FeePoolKey, Value: cdc.MustMarshalBinaryLengthPrefixed(feePool)}, - cmn.KVPair{Key: keeper.ProposerKey, Value: consAddr1.Bytes()}, + cmn.KVPair{Key: types.FeePoolKey, Value: cdc.MustMarshalBinaryLengthPrefixed(feePool)}, + cmn.KVPair{Key: types.ProposerKey, Value: consAddr1.Bytes()}, cmn.KVPair{Key: keeper.GetValidatorOutstandingRewardsKey(valAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(outstanding)}, cmn.KVPair{Key: keeper.GetDelegatorWithdrawAddrKey(delAddr1), Value: delAddr1.Bytes()}, cmn.KVPair{Key: keeper.GetDelegatorStartingInfoKey(valAddr1, delAddr1), Value: cdc.MustMarshalBinaryLengthPrefixed(info)}, diff --git a/x/distribution/simulation/genesis.go b/x/distribution/simulation/genesis.go index 207a14fe2e2c..9bc9df198c8b 100644 --- a/x/distribution/simulation/genesis.go +++ b/x/distribution/simulation/genesis.go @@ -68,11 +68,13 @@ func RandomizedGenState(simState *module.SimulationState) { ) distrGenesis := types.GenesisState{ - FeePool: types.InitialFeePool(), - CommunityTax: communityTax, - BaseProposerReward: baseProposerReward, - BonusProposerReward: bonusProposerReward, - WithdrawAddrEnabled: withdrawEnabled, + FeePool: types.InitialFeePool(), + Params: types.Params{ + CommunityTax: communityTax, + BaseProposerReward: baseProposerReward, + BonusProposerReward: bonusProposerReward, + WithdrawAddrEnabled: withdrawEnabled, + }, } fmt.Printf("Selected randomly generated distribution parameters:\n%s\n", codec.MustMarshalJSONIndent(simState.Cdc, distrGenesis)) diff --git a/x/distribution/types/genesis.go b/x/distribution/types/genesis.go index db4f119668a4..20f2c112e2e0 100644 --- a/x/distribution/types/genesis.go +++ b/x/distribution/types/genesis.go @@ -55,11 +55,8 @@ type ValidatorSlashEventRecord struct { // GenesisState - all distribution state that must be provided at genesis type GenesisState struct { + Params Params `json:"params" yaml:"params"` FeePool FeePool `json:"fee_pool" yaml:"fee_pool"` - CommunityTax sdk.Dec `json:"community_tax" yaml:"community_tax"` - BaseProposerReward sdk.Dec `json:"base_proposer_reward" yaml:"base_proposer_reward"` - BonusProposerReward sdk.Dec `json:"bonus_proposer_reward" yaml:"bonus_proposer_reward"` - WithdrawAddrEnabled bool `json:"withdraw_addr_enabled" yaml:"withdraw_addr_enabled"` DelegatorWithdrawInfos []DelegatorWithdrawInfo `json:"delegator_withdraw_infos" yaml:"delegator_withdraw_infos"` PreviousProposer sdk.ConsAddress `json:"previous_proposer" yaml:"previous_proposer"` OutstandingRewards []ValidatorOutstandingRewardsRecord `json:"outstanding_rewards" yaml:"outstanding_rewards"` @@ -70,18 +67,15 @@ type GenesisState struct { ValidatorSlashEvents []ValidatorSlashEventRecord `json:"validator_slash_events" yaml:"validator_slash_events"` } -func NewGenesisState(feePool FeePool, communityTax, baseProposerReward, bonusProposerReward sdk.Dec, - withdrawAddrEnabled bool, dwis []DelegatorWithdrawInfo, pp sdk.ConsAddress, r []ValidatorOutstandingRewardsRecord, +func NewGenesisState( + params Params, fp FeePool, dwis []DelegatorWithdrawInfo, pp sdk.ConsAddress, r []ValidatorOutstandingRewardsRecord, acc []ValidatorAccumulatedCommissionRecord, historical []ValidatorHistoricalRewardsRecord, - cur []ValidatorCurrentRewardsRecord, dels []DelegatorStartingInfoRecord, - slashes []ValidatorSlashEventRecord) GenesisState { + cur []ValidatorCurrentRewardsRecord, dels []DelegatorStartingInfoRecord, slashes []ValidatorSlashEventRecord, +) GenesisState { return GenesisState{ - FeePool: feePool, - CommunityTax: communityTax, - BaseProposerReward: baseProposerReward, - BonusProposerReward: bonusProposerReward, - WithdrawAddrEnabled: withdrawAddrEnabled, + Params: params, + FeePool: fp, DelegatorWithdrawInfos: dwis, PreviousProposer: pp, OutstandingRewards: r, @@ -97,10 +91,7 @@ func NewGenesisState(feePool FeePool, communityTax, baseProposerReward, bonusPro func DefaultGenesisState() GenesisState { return GenesisState{ FeePool: InitialFeePool(), - CommunityTax: sdk.NewDecWithPrec(2, 2), // 2% - BaseProposerReward: sdk.NewDecWithPrec(1, 2), // 1% - BonusProposerReward: sdk.NewDecWithPrec(4, 2), // 4% - WithdrawAddrEnabled: true, + Params: DefaultParams(), DelegatorWithdrawInfos: []DelegatorWithdrawInfo{}, PreviousProposer: nil, OutstandingRewards: []ValidatorOutstandingRewardsRecord{}, @@ -113,24 +104,25 @@ func DefaultGenesisState() GenesisState { } // ValidateGenesis validates the genesis state of distribution genesis input -func ValidateGenesis(data GenesisState) error { - if data.CommunityTax.IsNegative() || data.CommunityTax.GT(sdk.OneDec()) { +func ValidateGenesis(gs GenesisState) error { + if gs.Params.CommunityTax.IsNegative() || gs.Params.CommunityTax.GT(sdk.OneDec()) { return fmt.Errorf("mint parameter CommunityTax should non-negative and "+ - "less than one, is %s", data.CommunityTax.String()) + "less than one, is %s", gs.Params.CommunityTax.String()) } - if data.BaseProposerReward.IsNegative() { + if gs.Params.BaseProposerReward.IsNegative() { return fmt.Errorf("mint parameter BaseProposerReward should be positive, is %s", - data.BaseProposerReward.String()) + gs.Params.BaseProposerReward.String()) } - if data.BonusProposerReward.IsNegative() { + if gs.Params.BonusProposerReward.IsNegative() { return fmt.Errorf("mint parameter BonusProposerReward should be positive, is %s", - data.BonusProposerReward.String()) + gs.Params.BonusProposerReward.String()) } - if (data.BaseProposerReward.Add(data.BonusProposerReward)). + if (gs.Params.BaseProposerReward.Add(gs.Params.BonusProposerReward)). GT(sdk.OneDec()) { return fmt.Errorf("mint parameters BaseProposerReward and "+ "BonusProposerReward cannot add to be greater than one, "+ - "adds to %s", data.BaseProposerReward.Add(data.BonusProposerReward).String()) + "adds to %s", gs.Params.BaseProposerReward.Add(gs.Params.BonusProposerReward).String()) } - return data.FeePool.ValidateGenesis() + + return gs.FeePool.ValidateGenesis() } diff --git a/x/distribution/types/keys.go b/x/distribution/types/keys.go index 5bdeaecc20cc..86e1dc36a5af 100644 --- a/x/distribution/types/keys.go +++ b/x/distribution/types/keys.go @@ -13,3 +13,36 @@ const ( // QuerierRoute is the querier route for distribution QuerierRoute = ModuleName ) + +// Keys for distribution store +// Items are stored with the following key: values +// +// - 0x00: FeePol +// +// - 0x01: sdk.ConsAddress +// +// - 0x02: ValidatorOutstandingRewards +// +// - 0x03: sdk.AccAddress +// +// - 0x04: DelegatorStartingInfo +// +// - 0x05: ValidatorHistoricalRewards +// +// - 0x06: ValidatorCurrentRewards +// +// - 0x07: ValidatorCurrentRewards +// +// - 0x08: ValidatorSlashEvent +var ( + FeePoolKey = []byte{0x00} // key for global distribution state + ProposerKey = []byte{0x01} // key for the proposer operator address + ValidatorOutstandingRewardsPrefix = []byte{0x02} // key for outstanding rewards + + DelegatorWithdrawAddrPrefix = []byte{0x03} // key for delegator withdraw address + DelegatorStartingInfoPrefix = []byte{0x04} // key for delegator starting info + ValidatorHistoricalRewardsPrefix = []byte{0x05} // key for historical validators rewards / stake + ValidatorCurrentRewardsPrefix = []byte{0x06} // key for current validator rewards + ValidatorAccumulatedCommissionPrefix = []byte{0x07} // key for accumulated validator commission + ValidatorSlashEventPrefix = []byte{0x08} // key for validator slash fraction +) diff --git a/x/distribution/types/params.go b/x/distribution/types/params.go new file mode 100644 index 000000000000..5e25302def30 --- /dev/null +++ b/x/distribution/types/params.go @@ -0,0 +1,117 @@ +package types + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/params" + "gopkg.in/yaml.v2" +) + +const ( + // default paramspace for params keeper + DefaultParamspace = ModuleName +) + +// Parameter keys +var ( + ParamStoreKeyCommunityTax = []byte("communitytax") + ParamStoreKeyBaseProposerReward = []byte("baseproposerreward") + ParamStoreKeyBonusProposerReward = []byte("bonusproposerreward") + ParamStoreKeyWithdrawAddrEnabled = []byte("withdrawaddrenabled") +) + +// Params defines the set of distribution parameters. +type Params struct { + CommunityTax sdk.Dec `json:"community_tax" yaml:"community_tax"` + BaseProposerReward sdk.Dec `json:"base_proposer_reward" yaml:"base_proposer_reward"` + BonusProposerReward sdk.Dec `json:"bonus_proposer_reward" yaml:"bonus_proposer_reward"` + WithdrawAddrEnabled bool `json:"withdraw_addr_enabled" yaml:"withdraw_addr_enabled"` +} + +// ParamKeyTable returns the parameter key table. +func ParamKeyTable() params.KeyTable { + return params.NewKeyTable().RegisterParamSet(&Params{}) +} + +// DefaultParams returns default distribution parameters +func DefaultParams() Params { + return Params{ + CommunityTax: sdk.NewDecWithPrec(2, 2), // 2% + BaseProposerReward: sdk.NewDecWithPrec(1, 2), // 1% + BonusProposerReward: sdk.NewDecWithPrec(4, 2), // 4% + WithdrawAddrEnabled: true, + } +} + +func (p Params) String() string { + out, _ := yaml.Marshal(p) + return string(out) +} + +// ParamSetPairs returns the parameter set pairs. +func (p *Params) ParamSetPairs() params.ParamSetPairs { + return params.ParamSetPairs{ + params.NewParamSetPair(ParamStoreKeyCommunityTax, &p.CommunityTax, validateCommunityTax), + params.NewParamSetPair(ParamStoreKeyBaseProposerReward, &p.BaseProposerReward, validateBaseProposerReward), + params.NewParamSetPair(ParamStoreKeyBonusProposerReward, &p.BonusProposerReward, validateBonusProposerReward), + params.NewParamSetPair(ParamStoreKeyWithdrawAddrEnabled, &p.WithdrawAddrEnabled, validateWithdrawAddrEnabled), + } +} + +func validateCommunityTax(i interface{}) error { + v, ok := i.(sdk.Dec) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if v.IsNegative() { + return fmt.Errorf("community tax must be positive: %s", v) + } + if v.GT(sdk.OneDec()) { + return fmt.Errorf("community tax too large: %s", v) + } + + return nil +} + +func validateBaseProposerReward(i interface{}) error { + v, ok := i.(sdk.Dec) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if v.IsNegative() { + return fmt.Errorf("base proposer reward must be positive: %s", v) + } + if v.GT(sdk.OneDec()) { + return fmt.Errorf("base proposer reward too large: %s", v) + } + + return nil +} + +func validateBonusProposerReward(i interface{}) error { + v, ok := i.(sdk.Dec) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if v.IsNegative() { + return fmt.Errorf("bonus proposer reward must be positive: %s", v) + } + if v.GT(sdk.OneDec()) { + return fmt.Errorf("bonus proposer reward too large: %s", v) + } + + return nil +} + +func validateWithdrawAddrEnabled(i interface{}) error { + _, ok := i.(bool) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + return nil +} diff --git a/x/distribution/types/querier.go b/x/distribution/types/querier.go index 32ed642ddf86..cbf7d8d0a426 100644 --- a/x/distribution/types/querier.go +++ b/x/distribution/types/querier.go @@ -13,11 +13,6 @@ const ( QueryDelegatorValidators = "delegator_validators" QueryWithdrawAddr = "withdraw_addr" QueryCommunityPool = "community_pool" - - ParamCommunityTax = "community_tax" - ParamBaseProposerReward = "base_proposer_reward" - ParamBonusProposerReward = "bonus_proposer_reward" - ParamWithdrawAddrEnabled = "withdraw_addr_enabled" ) // params for query 'custom/distr/validator_outstanding_rewards' diff --git a/x/evidence/internal/types/params.go b/x/evidence/internal/types/params.go index 6865eb2825ab..5c0dbe638fa3 100644 --- a/x/evidence/internal/types/params.go +++ b/x/evidence/internal/types/params.go @@ -36,14 +36,9 @@ func ParamKeyTable() params.KeyTable { return params.NewKeyTable().RegisterParamSet(&Params{}) } -func (p Params) MarshalYAML() (interface{}, error) { - bz, err := yaml.Marshal(p) - return string(bz), err -} - func (p Params) String() string { - out, _ := p.MarshalYAML() - return out.(string) + out, _ := yaml.Marshal(p) + return string(out) } // ParamSetPairs returns the parameter set pairs. From c7126fe943c9ce517d7caaca2c21c861813d0f3a Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Fri, 10 Jan 2020 12:35:19 -0500 Subject: [PATCH 2/8] Add changelog entries --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 63226c53c871..44932a03c28a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,8 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### State Machine Breaking +* (genesis) [\#5506](https://github.com/cosmos/cosmos-sdk/pull/5506) The `x/distribution` genesis state + now includes `params` instead of individual parameters. * (genesis) [\#5017](https://github.com/cosmos/cosmos-sdk/pull/5017) The `x/genaccounts` module has been deprecated and all components removed except the `legacy/` package. This requires changes to the genesis state. Namely, `accounts` now exist under `app_state.auth.accounts`. The corresponding migration @@ -50,6 +52,8 @@ logic has been implemented for v0.38 target version. Applications can migrate vi ### API Breaking Changes +* (modules) [\#5506](https://github.com/cosmos/cosmos-sdk/pull/5506) Remove individual setters of `x/distribution` parameters. + Instead, follow the module spec in getting parameters, setting new value(s) and finally calling `SetParams`. * (types) [\#5495](https://github.com/cosmos/cosmos-sdk/pull/5495) Remove redundant `(Must)Bech32ify*` and `(Must)Get*KeyBech32` functions in favor of `(Must)Bech32ifyPubKey` and `(Must)GetPubKeyFromBech32` respectively, both of which take a `Bech32PubKeyType` (string). @@ -245,6 +249,8 @@ to detail this new feature and how state transitions occur. * (docs/interfaces/) Add documentation on building interfaces for the Cosmos SDK. * Redesigned user interface that features new dynamically generated sidebar, build-time code embedding from GitHub, new homepage as well as many other improvements. * (types) [\#5428](https://github.com/cosmos/cosmos-sdk/pull/5428) Add `Mod` (modulo) method and `RelativePow` (exponentation) function for `Uint`. +* (modules) [\#5506](https://github.com/cosmos/cosmos-sdk/pull/5506) Remove redundancy in `x/distribution`s use of parameters. There + now exists a single `Params` type with a getter and setter along with a getter for each individual parameter. ### Bug Fixes From 0db8634089ea5069725cc6b192ef49e8fc82ecdd Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Fri, 10 Jan 2020 13:37:08 -0500 Subject: [PATCH 3/8] Fix delegatorRewardsHandlerFn to return height --- x/distribution/client/rest/query.go | 31 +++++++++++++++-------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/x/distribution/client/rest/query.go b/x/distribution/client/rest/query.go index d242157dd40f..79c8db155f21 100644 --- a/x/distribution/client/rest/query.go +++ b/x/distribution/client/rest/query.go @@ -73,12 +73,26 @@ func delegatorRewardsHandlerFn(cliCtx context.CLIContext, queryRoute string) htt return } - // query for rewards from a particular delegator - res, ok := checkResponseQueryDelegatorTotalRewards(w, cliCtx, queryRoute, mux.Vars(r)["delegatorAddr"]) + delegatorAddr, ok := checkDelegatorAddressVar(w, r) if !ok { return } + params := types.NewQueryDelegatorParams(delegatorAddr) + bz, err := cliCtx.Codec.MarshalJSON(params) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("failed to marshal params: %s", err)) + return + } + + route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegatorTotalRewards) + res, height, err := cliCtx.QueryWithData(route, bz) + if err != nil { + rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + cliCtx = cliCtx.WithHeight(height) rest.PostProcessResponse(w, cliCtx, res) } } @@ -277,19 +291,6 @@ func outstandingRewardsHandlerFn(cliCtx context.CLIContext, queryRoute string) h } } -func checkResponseQueryDelegatorTotalRewards( - w http.ResponseWriter, cliCtx context.CLIContext, queryRoute, delAddr string, -) (res []byte, ok bool) { - - res, err := common.QueryDelegatorTotalRewards(cliCtx, queryRoute, delAddr) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return nil, false - } - - return res, true -} - func checkResponseQueryDelegationRewards( w http.ResponseWriter, cliCtx context.CLIContext, queryRoute, delAddr, valAddr string, ) (res []byte, ok bool) { From 14f0bfc84c167dfea6e1f5e9e8ed0ce6a2980195 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Fri, 10 Jan 2020 13:45:51 -0500 Subject: [PATCH 4/8] Cleanup GetCmdQueryDelegatorRewards --- x/distribution/client/cli/query.go | 19 +++++++++++++++++-- x/distribution/client/rest/query.go | 13 ------------- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/x/distribution/client/cli/query.go b/x/distribution/client/cli/query.go index 06bc2e677328..06dd23c07382 100644 --- a/x/distribution/client/cli/query.go +++ b/x/distribution/client/cli/query.go @@ -229,14 +229,29 @@ $ %s query distribution rewards cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p co return cliCtx.PrintOutput(result) } + delegatorAddr, err := sdk.AccAddressFromBech32(args[0]) + if err != nil { + return err + } + + params := types.NewQueryDelegatorParams(delegatorAddr) + bz, err := cdc.MarshalJSON(params) + if err != nil { + return fmt.Errorf("failed to marshal params: %w", err) + } + // query for delegator total rewards - resp, err := common.QueryDelegatorTotalRewards(cliCtx, queryRoute, args[0]) + route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegatorTotalRewards) + res, _, err := cliCtx.QueryWithData(route, bz) if err != nil { return err } var result types.QueryDelegatorTotalRewardsResponse - cdc.MustUnmarshalJSON(resp, &result) + if err = cdc.UnmarshalJSON(res, &result); err != nil { + return fmt.Errorf("failed to unmarshal response: %w", err) + } + return cliCtx.PrintOutput(result) }, } diff --git a/x/distribution/client/rest/query.go b/x/distribution/client/rest/query.go index 79c8db155f21..d953238068e5 100644 --- a/x/distribution/client/rest/query.go +++ b/x/distribution/client/rest/query.go @@ -290,16 +290,3 @@ func outstandingRewardsHandlerFn(cliCtx context.CLIContext, queryRoute string) h rest.PostProcessResponse(w, cliCtx, res) } } - -func checkResponseQueryDelegationRewards( - w http.ResponseWriter, cliCtx context.CLIContext, queryRoute, delAddr, valAddr string, -) (res []byte, ok bool) { - - res, err := common.QueryDelegationRewards(cliCtx, queryRoute, delAddr, valAddr) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return nil, false - } - - return res, true -} From 3c74a28ba7c692060151f2e8fc682cbbaef626d7 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Fri, 10 Jan 2020 13:53:48 -0500 Subject: [PATCH 5/8] Fix /distribution/delegators/{delegatorAddr}/rewards/{validatorAddr} --- x/distribution/client/cli/query.go | 9 +++++--- x/distribution/client/common/common.go | 32 +++++++++----------------- x/distribution/client/rest/query.go | 19 ++++++++++++++- 3 files changed, 35 insertions(+), 25 deletions(-) diff --git a/x/distribution/client/cli/query.go b/x/distribution/client/cli/query.go index 06dd23c07382..92af18275233 100644 --- a/x/distribution/client/cli/query.go +++ b/x/distribution/client/cli/query.go @@ -217,15 +217,18 @@ $ %s query distribution rewards cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p co RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) + // query for rewards from a particular delegation if len(args) == 2 { - // query for rewards from a particular delegation - resp, err := common.QueryDelegationRewards(cliCtx, queryRoute, args[0], args[1]) + resp, _, err := common.QueryDelegationRewards(cliCtx, queryRoute, args[0], args[1]) if err != nil { return err } var result sdk.DecCoins - cdc.MustUnmarshalJSON(resp, &result) + if err = cdc.UnmarshalJSON(resp, &result); err != nil { + return fmt.Errorf("failed to unmarshal response: %w", err) + } + return cliCtx.PrintOutput(result) } diff --git a/x/distribution/client/common/common.go b/x/distribution/client/common/common.go index b20e87ec0586..06860012c8cf 100644 --- a/x/distribution/client/common/common.go +++ b/x/distribution/client/common/common.go @@ -8,37 +8,27 @@ import ( "github.com/cosmos/cosmos-sdk/x/distribution/types" ) -// QueryDelegatorTotalRewards queries delegator total rewards. -func QueryDelegatorTotalRewards(cliCtx context.CLIContext, queryRoute, delAddr string) ([]byte, error) { +// QueryDelegationRewards queries a delegation rewards between a delegator and a +// validator. +func QueryDelegationRewards(cliCtx context.CLIContext, queryRoute, delAddr, valAddr string) ([]byte, int64, error) { delegatorAddr, err := sdk.AccAddressFromBech32(delAddr) if err != nil { - return nil, err + return nil, 0, err } - res, _, err := cliCtx.QueryWithData( - fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegatorTotalRewards), - cliCtx.Codec.MustMarshalJSON(types.NewQueryDelegatorParams(delegatorAddr)), - ) - return res, err -} - -// QueryDelegationRewards queries a delegation rewards. -func QueryDelegationRewards(cliCtx context.CLIContext, queryRoute, delAddr, valAddr string) ([]byte, error) { - delegatorAddr, err := sdk.AccAddressFromBech32(delAddr) + validatorAddr, err := sdk.ValAddressFromBech32(valAddr) if err != nil { - return nil, err + return nil, 0, err } - validatorAddr, err := sdk.ValAddressFromBech32(valAddr) + params := types.NewQueryDelegationRewardsParams(delegatorAddr, validatorAddr) + bz, err := cliCtx.Codec.MarshalJSON(params) if err != nil { - return nil, err + return nil, 0, fmt.Errorf("failed to marshal params: %w", err) } - res, _, err := cliCtx.QueryWithData( - fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegationRewards), - cliCtx.Codec.MustMarshalJSON(types.NewQueryDelegationRewardsParams(delegatorAddr, validatorAddr)), - ) - return res, err + route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegationRewards) + return cliCtx.QueryWithData(route, bz) } // QueryDelegatorValidators returns delegator's list of validators diff --git a/x/distribution/client/rest/query.go b/x/distribution/client/rest/query.go index d953238068e5..65aec637908a 100644 --- a/x/distribution/client/rest/query.go +++ b/x/distribution/client/rest/query.go @@ -105,12 +105,16 @@ func delegationRewardsHandlerFn(cliCtx context.CLIContext, queryRoute string) ht return } + delAddr := mux.Vars(r)["delegatorAddr"] + valAddr := mux.Vars(r)["validatorAddr"] + // query for rewards from a particular delegation - res, ok := checkResponseQueryDelegationRewards(w, cliCtx, queryRoute, mux.Vars(r)["delegatorAddr"], mux.Vars(r)["validatorAddr"]) + res, height, ok := checkResponseQueryDelegationRewards(w, cliCtx, queryRoute, delAddr, valAddr) if !ok { return } + cliCtx = cliCtx.WithHeight(height) rest.PostProcessResponse(w, cliCtx, res) } } @@ -290,3 +294,16 @@ func outstandingRewardsHandlerFn(cliCtx context.CLIContext, queryRoute string) h rest.PostProcessResponse(w, cliCtx, res) } } + +func checkResponseQueryDelegationRewards( + w http.ResponseWriter, cliCtx context.CLIContext, queryRoute, delAddr, valAddr string, +) (res []byte, height int64, ok bool) { + + res, height, err := common.QueryDelegationRewards(cliCtx, queryRoute, delAddr, valAddr) + if err != nil { + rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return nil, 0, false + } + + return res, height, true +} From e742380fdbea0d8c6830957721546785ccc3e54e Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Fri, 10 Jan 2020 15:22:19 -0500 Subject: [PATCH 6/8] Fix remaining endpoints --- x/distribution/client/rest/query.go | 32 ++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/x/distribution/client/rest/query.go b/x/distribution/client/rest/query.go index 65aec637908a..e9185a6094a5 100644 --- a/x/distribution/client/rest/query.go +++ b/x/distribution/client/rest/query.go @@ -177,28 +177,39 @@ func validatorInfoHandlerFn(cliCtx context.CLIContext, queryRoute string) http.H } // query commission - commissionRes, err := common.QueryValidatorCommission(cliCtx, queryRoute, validatorAddr) + bz, err := common.QueryValidatorCommission(cliCtx, queryRoute, validatorAddr) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - var valCom types.ValidatorAccumulatedCommission - cliCtx.Codec.MustUnmarshalJSON(commissionRes, &valCom) + var commission types.ValidatorAccumulatedCommission + if err := cliCtx.Codec.UnmarshalJSON(bz, &commission); err != nil { + rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } // self bond rewards delAddr := sdk.AccAddress(validatorAddr) - rewardsRes, ok := checkResponseQueryDelegationRewards(w, cliCtx, queryRoute, delAddr.String(), valAddr) + bz, height, ok := checkResponseQueryDelegationRewards(w, cliCtx, queryRoute, delAddr.String(), valAddr) if !ok { return } var rewards sdk.DecCoins - cliCtx.Codec.MustUnmarshalJSON(rewardsRes, &rewards) + if err := cliCtx.Codec.UnmarshalJSON(bz, &rewards); err != nil { + rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } - // Prepare response - res := cliCtx.Codec.MustMarshalJSON(NewValidatorDistInfo(delAddr, rewards, valCom)) - rest.PostProcessResponse(w, cliCtx, res) + bz, err = cliCtx.Codec.MarshalJSON(NewValidatorDistInfo(delAddr, rewards, commission)) + if err != nil { + rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + cliCtx = cliCtx.WithHeight(height) + rest.PostProcessResponse(w, cliCtx, bz) } } @@ -217,12 +228,13 @@ func validatorRewardsHandlerFn(cliCtx context.CLIContext, queryRoute string) htt } delAddr := sdk.AccAddress(validatorAddr).String() - res, ok := checkResponseQueryDelegationRewards(w, cliCtx, queryRoute, delAddr, valAddr) + bz, height, ok := checkResponseQueryDelegationRewards(w, cliCtx, queryRoute, delAddr, valAddr) if !ok { return } - rest.PostProcessResponse(w, cliCtx, res) + cliCtx = cliCtx.WithHeight(height) + rest.PostProcessResponse(w, cliCtx, bz) } } From cd8125338c288e78164c5e338498c0c831beb795 Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Fri, 10 Jan 2020 15:44:27 -0500 Subject: [PATCH 7/8] Add changelog entry --- CHANGELOG.md | 1 + x/distribution/client/rest/query.go | 9 ++++----- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 44932a03c28a..4e2b582c6180 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -254,6 +254,7 @@ to detail this new feature and how state transitions occur. ### Bug Fixes +* (rest) [\#5508](https://github.com/cosmos/cosmos-sdk/pull/5508) Fix `x/distribution` endpoints to properly return height in the response. * (x/genutil) [\#5499](https://github.com/cosmos/cosmos-sdk/pull/) Ensure `DefaultGenesis` returns valid and non-nil default genesis state. * (client) [\#5303](https://github.com/cosmos/cosmos-sdk/issues/5303) Fix ignored error in tx generate only mode. * (cli) [\#4763](https://github.com/cosmos/cosmos-sdk/issues/4763) Fix flag `--min-self-delegation` for staking `EditValidator` diff --git a/x/distribution/client/rest/query.go b/x/distribution/client/rest/query.go index e9185a6094a5..4c362409dd13 100644 --- a/x/distribution/client/rest/query.go +++ b/x/distribution/client/rest/query.go @@ -165,8 +165,7 @@ func NewValidatorDistInfo(operatorAddr sdk.AccAddress, rewards sdk.DecCoins, // HTTP request handler to query validator's distribution information func validatorInfoHandlerFn(cliCtx context.CLIContext, queryRoute string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - valAddr := mux.Vars(r)["validatorAddr"] - validatorAddr, ok := checkValidatorAddressVar(w, r) + valAddr, ok := checkValidatorAddressVar(w, r) if !ok { return } @@ -177,7 +176,7 @@ func validatorInfoHandlerFn(cliCtx context.CLIContext, queryRoute string) http.H } // query commission - bz, err := common.QueryValidatorCommission(cliCtx, queryRoute, validatorAddr) + bz, err := common.QueryValidatorCommission(cliCtx, queryRoute, valAddr) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -190,8 +189,8 @@ func validatorInfoHandlerFn(cliCtx context.CLIContext, queryRoute string) http.H } // self bond rewards - delAddr := sdk.AccAddress(validatorAddr) - bz, height, ok := checkResponseQueryDelegationRewards(w, cliCtx, queryRoute, delAddr.String(), valAddr) + delAddr := sdk.AccAddress(valAddr) + bz, height, ok := checkResponseQueryDelegationRewards(w, cliCtx, queryRoute, delAddr.String(), valAddr.String()) if !ok { return } From 068147ea6cec89eaa7b738b0e75470d7d33f3fde Mon Sep 17 00:00:00 2001 From: Aleksandr Bezobchuk Date: Fri, 10 Jan 2020 15:55:56 -0500 Subject: [PATCH 8/8] Fix common test --- x/distribution/client/common/common_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/distribution/client/common/common_test.go b/x/distribution/client/common/common_test.go index e4a554a31782..5954f9850742 100644 --- a/x/distribution/client/common/common_test.go +++ b/x/distribution/client/common/common_test.go @@ -30,7 +30,7 @@ func TestQueryDelegationRewardsAddrValidation(t *testing.T) { for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { - _, err := QueryDelegationRewards(ctx, "", tt.args.delAddr, tt.args.valAddr) + _, _, err := QueryDelegationRewards(ctx, "", tt.args.delAddr, tt.args.valAddr) require.True(t, err != nil, tt.wantErr) }) }