From 864756a546e23c49ee65fa141214452ecbd55223 Mon Sep 17 00:00:00 2001 From: yys Date: Sun, 17 Nov 2019 16:38:45 +0900 Subject: [PATCH] change treasury keeper to store only indicators for the each epoch (#269) * change treasury keeper to store only indicators for the epoch data * records tax-proceeds only for the tax-rate not whole tx.Fee * add keeper testcode * change stored indicators from TRL,SR,MR to TR,SR,TSL * swagger update --- app/export.go | 19 +- client/lcd/swagger-ui/swagger.yaml | 125 -------- docs/specifications/treasury.md | 77 +++-- tools-stamp | 0 x/auth/ante.go | 4 +- x/auth/client/utils/feeutils.go | 13 +- x/auth/internal/types/expected_keeper.go | 4 +- x/auth/test_utils.go | 7 +- x/treasury/abci.go | 6 +- x/treasury/abci_test.go | 28 +- x/treasury/alias.go | 82 ++--- x/treasury/client/cli/query.go | 205 ++---------- x/treasury/client/rest/query.go | 170 +--------- x/treasury/genesis.go | 51 +-- x/treasury/genesis_test.go | 22 +- x/treasury/handler.go | 10 +- x/treasury/internal/keeper/indicator.go | 113 ++++--- x/treasury/internal/keeper/indicator_test.go | 299 +++++++++--------- x/treasury/internal/keeper/keeper.go | 211 +++++++----- x/treasury/internal/keeper/keeper_test.go | 80 +++-- x/treasury/internal/keeper/policy.go | 17 +- x/treasury/internal/keeper/policy_test.go | 18 +- x/treasury/internal/keeper/querier.go | 93 +----- x/treasury/internal/keeper/querier_test.go | 119 +------ x/treasury/internal/keeper/seigniorage.go | 5 +- .../internal/keeper/seigniorage_test.go | 9 +- x/treasury/internal/keeper/test_utils.go | 18 ++ x/treasury/internal/types/genesis.go | 63 ++-- x/treasury/internal/types/genesis_test.go | 14 +- x/treasury/internal/types/keys.go | 65 ++-- x/treasury/internal/types/querier.go | 67 ---- x/treasury/proposal_handler_test.go | 5 +- 32 files changed, 693 insertions(+), 1326 deletions(-) create mode 100644 tools-stamp diff --git a/app/export.go b/app/export.go index 4478cfe2b..3b0e7499a 100644 --- a/app/export.go +++ b/app/export.go @@ -10,7 +10,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - core "github.com/terra-project/core/types" "github.com/terra-project/core/x/oracle" "github.com/terra-project/core/x/slashing" "github.com/terra-project/core/x/staking" @@ -194,18 +193,10 @@ func (app *TerraApp) prepForZeroHeightGenesis(ctx sdk.Context, jailWhiteList []s /* Handle treasury state. */ - // clear all historical issuance info - app.treasuryKeeper.ClearHistoricalIssuance(ctx) - // clear all tax proceeds - app.treasuryKeeper.ClearTaxProceeds(ctx) + // clear all indicators + app.treasuryKeeper.ClearTRs(ctx) + app.treasuryKeeper.ClearSRs(ctx) + app.treasuryKeeper.ClearTSLs(ctx) - // left last tax rate - lastTaxRate := app.treasuryKeeper.GetTaxRate(ctx, core.GetEpoch(ctx)) - app.treasuryKeeper.ClearTaxRates(ctx) - app.treasuryKeeper.SetTaxRate(ctx, 0, lastTaxRate) - - // left last reward weight - lastRewardWeight := app.treasuryKeeper.GetRewardWeight(ctx, core.GetEpoch(ctx)) - app.treasuryKeeper.ClearRewardWeights(ctx) - app.treasuryKeeper.SetRewardWeight(ctx, 0, lastRewardWeight) + app.treasuryKeeper.RecordEpochInitialIssuance(ctx) } diff --git a/client/lcd/swagger-ui/swagger.yaml b/client/lcd/swagger-ui/swagger.yaml index 30c700a6f..b23b81d46 100644 --- a/client/lcd/swagger-ui/swagger.yaml +++ b/client/lcd/swagger-ui/swagger.yaml @@ -2477,28 +2477,6 @@ paths: example: "0.05" 500: description: Internal Server Error - /treasury/tax_rate/{epoch}: - get: - summary: Get tax rate at epoch - tags: - - Treasury - produces: - - application/json - parameters: - - in: path - name: epoch - description: Epoch number - required: true - type: number - responses: - 200: - description: OK - schema: - type: number - format: float - example: "0.05" - 500: - description: Internal Server Error /treasury/tax_cap/{denom}: get: summary: Get tax cap of the denom @@ -2537,51 +2515,6 @@ paths: description: 5% 500: description: Internal Server Error - /treasury/reward_weight/{epoch}: - get: - summary: Get reward weight at epoch - tags: - - Treasury - produces: - - application/json - parameters: - - in: path - name: epoch - description: Epoch number - required: true - type: string - responses: - 200: - description: OK - schema: - type: number - format: float - example: "0.05" - description: 5% - 500: - description: Internal Server Error - /treasury/historical_issuance/{epoch}: - get: - summary: Get total issuance at the epoch - tags: - - Treasury - produces: - - application/json - parameters: - - in: path - name: epoch - description: Epoch number - required: true - type: integer - responses: - 200: - description: OK - schema: - type: array - items: - $ref: "#/definitions/Coin" - 500: - description: Internal Server Error /treasury/tax_proceeds: get: summary: Get current tax proceeds @@ -2598,28 +2531,6 @@ paths: $ref: "#/definitions/Coin" 500: description: Internal Server Error - /treasury/tax_proceeds/{epoch}: - get: - summary: Get tax proceeds at epoch - tags: - - Treasury - produces: - - application/json - parameters: - - in: path - name: epoch - description: Epoch number - required: true - type: integer - responses: - 200: - description: OK - schema: - type: array - items: - $ref: "#/definitions/Coin" - 500: - description: Internal Server Error /treasury/seigniorage_proceeds: get: summary: retrieves the size of the seigniorage pool @@ -2635,42 +2546,6 @@ paths: example: "0" 500: description: Internal Server - /treasury/seigniorage_proceeds/{epoch}: - get: - summary: retrieves the size of the seigniorage pool at epoch - tags: - - Treasury - produces: - - application/json - parameters: - - in: path - name: epoch - description: Epoch number - required: true - type: integer - responses: - 200: - description: OK - schema: - type: integer - example: "0" - 500: - description: Internal Server Error - /treasury/current_epoch: - get: - summary: Get current epoch - tags: - - Treasury - produces: - - application/json - responses: - 200: - description: OK - schema: - type: number - example: "724" - 404: - description: Not Found /treasury/parameters: get: summary: Get treasury module params diff --git a/docs/specifications/treasury.md b/docs/specifications/treasury.md index 8cd3ec694..3148c2634 100644 --- a/docs/specifications/treasury.md +++ b/docs/specifications/treasury.md @@ -19,26 +19,26 @@ The treasury module has two monetary policy levers in its toolkit. The tax rate, ```go // t(t+1) = t(t) * (TL_year(t) + INC) / TL_month(t) -func updateTaxPolicy(ctx sdk.Context, k Keeper) (newTaxRate sdk.Dec) { - params := k.GetParams(ctx) - - oldTaxRate := k.GetTaxRate(ctx, util.GetEpoch(ctx)) - inc := params.MiningIncrement - tlYear := RollingAverageIndicator(ctx, k, params.WindowLong, TRL) - tlMonth := RollingAverageIndicator(ctx, k, params.WindowShort, TRL) - - // No revenues, hike as much as possible. - if tlMonth.Equal(sdk.ZeroDec()) { - newTaxRate = params.TaxPolicy.RateMax - } else { - newTaxRate = oldTaxRate.Mul(tlYear.Mul(inc)).Quo(tlMonth) - } - - newTaxRate = params.TaxPolicy.Clamp(oldTaxRate, newTaxRate) - - // Set the new tax rate to the store - k.SetTaxRate(ctx, newTaxRate) - return +func (k Keeper) UpdateTaxPolicy(ctx sdk.Context) (newTaxRate sdk.Dec) { + params := k.GetParams(ctx) + + oldTaxRate := k.GetTaxRate(ctx) + inc := params.MiningIncrement + tlYear := k.rollingAverageIndicator(ctx, params.WindowLong, types.TRLKey) + tlMonth := k.rollingAverageIndicator(ctx, params.WindowShort, types.TRLKey) + + // No revenues, hike as much as possible. + if tlMonth.Equal(sdk.ZeroDec()) { + newTaxRate = params.TaxPolicy.RateMax + } else { + newTaxRate = oldTaxRate.Mul(tlYear.Mul(inc)).Quo(tlMonth) + } + + newTaxRate = params.TaxPolicy.Clamp(oldTaxRate, newTaxRate) + + // Set the new tax rate to the store + k.SetTaxRate(ctx, newTaxRate) + return } ``` @@ -48,30 +48,29 @@ At the point of evaluation, the treasury hikes up tax rates when tax revenues in ```go // w(t+1) = w(t)*SB_target/SB_rolling(t) -func updateRewardPolicy(ctx sdk.Context, k Keeper) (newRewardWeight sdk.Dec) { - params := k.GetParams(ctx) +func (k Keeper) UpdateRewardPolicy(ctx sdk.Context) (newRewardWeight sdk.Dec) { + params := k.GetParams(ctx) - curEpoch := util.GetEpoch(ctx) - oldWeight := k.GetRewardWeight(ctx, curEpoch) - sbTarget := params.SeigniorageBurdenTarget + oldWeight := k.GetRewardWeight(ctx) + sbTarget := params.SeigniorageBurdenTarget - seigniorageSum := SumIndicator(ctx, k, params.WindowShort, SeigniorageRewardsForEpoch) - totalSum := SumIndicator(ctx, k, params.WindowShort, MiningRewardForEpoch) + seigniorageSum := k.sumIndicator(ctx, params.WindowShort, types.SRKey) + totalSum := k.sumIndicator(ctx, params.WindowShort, types.MRKey) - // No revenues; hike as much as possible - if totalSum.Equal(sdk.ZeroDec()) || seigniorageSum.Equal(sdk.ZeroDec()) { - newRewardWeight = params.RewardPolicy.RateMax - } else { - // Seigniorage burden out of total rewards - sb := seigniorageSum.Quo(totalSum) - newRewardWeight = oldWeight.Mul(sbTarget.Quo(sb)) - } + // No revenues; hike as much as possible + if totalSum.Equal(sdk.ZeroDec()) || seigniorageSum.Equal(sdk.ZeroDec()) { + newRewardWeight = params.RewardPolicy.RateMax + } else { + // Seigniorage burden out of total rewards + sb := seigniorageSum.Quo(totalSum) + newRewardWeight = oldWeight.Mul(sbTarget.Quo(sb)) + } - newRewardWeight = params.RewardPolicy.Clamp(oldWeight, newRewardWeight) + newRewardWeight = params.RewardPolicy.Clamp(oldWeight, newRewardWeight) - // Set the new reward weight - k.SetRewardWeight(ctx, newRewardWeight) - return + // Set the new reward weight + k.SetRewardWeight(ctx, newRewardWeight) + return } ``` diff --git a/tools-stamp b/tools-stamp new file mode 100644 index 000000000..e69de29bb diff --git a/x/auth/ante.go b/x/auth/ante.go index 3ea0876d8..bf2d48a98 100644 --- a/x/auth/ante.go +++ b/x/auth/ante.go @@ -138,7 +138,7 @@ func NewAnteHandler(ak AccountKeeper, supplyKeeper types.SupplyKeeper, } // record tax proceeds - treasuryKeeper.RecordTaxProceeds(newCtx, stdTx.Fee.Amount) + treasuryKeeper.RecordEpochTaxProceeds(newCtx, taxes) // reload the account as fees have been deducted signerAccs[0] = ak.GetAccount(newCtx, signerAccs[0].GetAddress()) @@ -402,7 +402,7 @@ func filterMsgAndComputeTax(ctx sdk.Context, tk TreasuryKeeper, msgs []sdk.Msg) // computes the stability tax according to tax-rate and tax-cap func computeTax(ctx sdk.Context, tk TreasuryKeeper, principal sdk.Coins) (taxes sdk.Coins) { - taxRate := tk.GetTaxRate(ctx, core.GetEpoch(ctx)) + taxRate := tk.GetTaxRate(ctx) if taxRate.Equal(sdk.ZeroDec()) { return } diff --git a/x/auth/client/utils/feeutils.go b/x/auth/client/utils/feeutils.go index 15a1cfef5..8d9b11258 100644 --- a/x/auth/client/utils/feeutils.go +++ b/x/auth/client/utils/feeutils.go @@ -226,20 +226,9 @@ func computeTax(cliCtx context.CLIContext, taxRate sdk.Dec, principal sdk.Coins) } func queryTaxRate(cliCtx context.CLIContext) (sdk.Dec, error) { - // Query current-epoch - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", treasury.QuerierRoute, treasury.QueryCurrentEpoch), nil) - if err != nil { - return sdk.Dec{}, err - } - - var epoch int64 - cliCtx.Codec.MustUnmarshalJSON(res, &epoch) - - params := treasury.NewQueryTaxRateParams(epoch) - bz := cliCtx.Codec.MustMarshalJSON(params) // Query tax-rate - res, _, err = cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", treasury.QuerierRoute, treasury.QueryTaxRate), bz) + res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", treasury.QuerierRoute, treasury.QueryTaxRate), nil) if err != nil { return sdk.Dec{}, err } diff --git a/x/auth/internal/types/expected_keeper.go b/x/auth/internal/types/expected_keeper.go index a87f0ee2b..302dcf146 100644 --- a/x/auth/internal/types/expected_keeper.go +++ b/x/auth/internal/types/expected_keeper.go @@ -7,9 +7,9 @@ import ( // TreasuryKeeper is expected keeper for treasury type TreasuryKeeper interface { - GetTaxRate(ctx sdk.Context, epoch int64) (rate sdk.Dec) + GetTaxRate(ctx sdk.Context) (rate sdk.Dec) GetTaxCap(ctx sdk.Context, denom string) (taxCap sdk.Int) - RecordTaxProceeds(ctx sdk.Context, delta sdk.Coins) + RecordEpochTaxProceeds(ctx sdk.Context, delta sdk.Coins) } // SupplyKeeper defines the expected supply Keeper (noalias) diff --git a/x/auth/test_utils.go b/x/auth/test_utils.go index 28f0a47f8..a51ea4ed7 100644 --- a/x/auth/test_utils.go +++ b/x/auth/test_utils.go @@ -87,10 +87,11 @@ func setupTestInput() testInput { // DummyTreasuryKeeper no-lint type DummyTreasuryKeeper struct{} +// NewDummyTreasuryKeeper no-lint func NewDummyTreasuryKeeper() DummyTreasuryKeeper { return DummyTreasuryKeeper{} } // GetTaxRate for the dummy treasury keeper -func (tk DummyTreasuryKeeper) GetTaxRate(_ sdk.Context, _ int64) (rate sdk.Dec) { +func (tk DummyTreasuryKeeper) GetTaxRate(_ sdk.Context) (rate sdk.Dec) { return sdk.NewDecWithPrec(1, 3) // 0.1% } @@ -99,8 +100,8 @@ func (tk DummyTreasuryKeeper) GetTaxCap(_ sdk.Context, _ string) (taxCap sdk.Int return sdk.OneInt() } -// RecordTaxProceeds for the dummy treasury keeper -func (tk DummyTreasuryKeeper) RecordTaxProceeds(_ sdk.Context, _ sdk.Coins) { +// RecordEpochTaxProceeds for the dummy treasury keeper +func (tk DummyTreasuryKeeper) RecordEpochTaxProceeds(_ sdk.Context, _ sdk.Coins) { return } diff --git a/x/treasury/abci.go b/x/treasury/abci.go index 469d84297..ee9e3261f 100644 --- a/x/treasury/abci.go +++ b/x/treasury/abci.go @@ -17,13 +17,17 @@ func EndBlocker(ctx sdk.Context, k Keeper) { } // Update luna issuance after finish all works - defer k.RecordHistoricalIssuance(ctx) + defer k.RecordEpochInitialIssuance(ctx) + + // Compute & Update internal indicators for the current epoch + k.UpdateIndicators(ctx) // Check probation period if ctx.BlockHeight() < (core.BlocksPerEpoch * k.WindowProbation(ctx)) { return } + // Settle seiniorage to oracle & distribution(community-pool) module-account k.SettleSeigniorage(ctx) // Update tax-rate and reward-weight of next epoch diff --git a/x/treasury/abci_test.go b/x/treasury/abci_test.go index ad3b2cddc..af46c522d 100644 --- a/x/treasury/abci_test.go +++ b/x/treasury/abci_test.go @@ -15,6 +15,12 @@ import ( func TestEndBlockerIssuanceUpdate(t *testing.T) { input := keeper.CreateTestInput(t) + // Set total staked luna to prevent divide by zero error when computing TRL + bondedModuleAcc := input.SupplyKeeper.GetModuleAccount(input.Ctx, stakingtypes.BondedPoolName) + err := bondedModuleAcc.SetCoins(sdk.NewCoins(sdk.NewInt64Coin(core.MicroLunaDenom, 100000000000))) + require.NoError(t, err) + input.SupplyKeeper.SetModuleAccount(input.Ctx, bondedModuleAcc) + targetIssuance := sdk.NewInt(1000) input.Ctx = input.Ctx.WithBlockHeight(core.BlocksPerEpoch - 1) supply := input.SupplyKeeper.GetSupply(input.Ctx) @@ -22,29 +28,39 @@ func TestEndBlockerIssuanceUpdate(t *testing.T) { input.SupplyKeeper.SetSupply(input.Ctx, supply) EndBlocker(input.Ctx, input.TreasuryKeeper) - issuance := input.TreasuryKeeper.GetHistoricalIssuance(input.Ctx, 0).AmountOf(core.MicroLunaDenom) + issuance := input.TreasuryKeeper.GetEpochInitialIssuance(input.Ctx).AmountOf(core.MicroLunaDenom) require.Equal(t, targetIssuance, issuance) } func TestUpdate(t *testing.T) { input := keeper.CreateTestInput(t) + windowProbation := input.TreasuryKeeper.WindowProbation(input.Ctx) + + // Set total staked luna to prevent divide by zero error when computing TRL bondedModuleAcc := input.SupplyKeeper.GetModuleAccount(input.Ctx, stakingtypes.BondedPoolName) err := bondedModuleAcc.SetCoins(sdk.NewCoins(sdk.NewInt64Coin(core.MicroLunaDenom, 100000000000))) require.NoError(t, err) input.SupplyKeeper.SetModuleAccount(input.Ctx, bondedModuleAcc) targetEpoch := windowProbation + 1 + for epoch := int64(0); epoch < targetEpoch; epoch++ { + input.Ctx = input.Ctx.WithBlockHeight(core.BlocksPerEpoch*epoch - 1) + EndBlocker(input.Ctx, input.TreasuryKeeper) + } + + // load old tax rate & reward weight + taxRate := input.TreasuryKeeper.GetTaxRate(input.Ctx) + rewardWeight := input.TreasuryKeeper.GetRewardWeight(input.Ctx) + input.Ctx = input.Ctx.WithBlockHeight(core.BlocksPerEpoch*targetEpoch - 1) + EndBlocker(input.Ctx, input.TreasuryKeeper) // zero tax proceeds will increase tax rate with change max amount - EndBlocker(input.Ctx, input.TreasuryKeeper) - taxRate := input.TreasuryKeeper.GetTaxRate(input.Ctx, targetEpoch-1) - newTaxRate := input.TreasuryKeeper.GetTaxRate(input.Ctx, targetEpoch) + newTaxRate := input.TreasuryKeeper.GetTaxRate(input.Ctx) require.Equal(t, taxRate.Add(input.TreasuryKeeper.TaxPolicy(input.Ctx).ChangeRateMax), newTaxRate) // zero mining rewards will increase reward weight with change max amount - rewardWeight := input.TreasuryKeeper.GetRewardWeight(input.Ctx, targetEpoch-1) - newRewardWeight := input.TreasuryKeeper.GetRewardWeight(input.Ctx, targetEpoch) + newRewardWeight := input.TreasuryKeeper.GetRewardWeight(input.Ctx) require.Equal(t, rewardWeight.Add(input.TreasuryKeeper.RewardPolicy(input.Ctx).ChangeRateMax), newRewardWeight) } diff --git a/x/treasury/alias.go b/x/treasury/alias.go index 8cfd9bc0f..07e4ca63b 100644 --- a/x/treasury/alias.go +++ b/x/treasury/alias.go @@ -20,49 +20,33 @@ const ( DefaultParamspace = types.DefaultParamspace ProposalTypeTaxRateUpdate = types.ProposalTypeTaxRateUpdate ProposalTypeRewardWeightUpdate = types.ProposalTypeRewardWeightUpdate - QueryCurrentEpoch = types.QueryCurrentEpoch QueryTaxRate = types.QueryTaxRate QueryTaxCap = types.QueryTaxCap QueryRewardWeight = types.QueryRewardWeight QuerySeigniorageProceeds = types.QuerySeigniorageProceeds QueryTaxProceeds = types.QueryTaxProceeds QueryParameters = types.QueryParameters - QueryHistoricalIssuance = types.QueryHistoricalIssuance ) var ( // functions aliases - RegisterCodec = types.RegisterCodec - ErrInvalidEpoch = types.ErrInvalidEpoch - NewGenesisState = types.NewGenesisState - DefaultGenesisState = types.DefaultGenesisState - ValidateGenesis = types.ValidateGenesis - GetTaxRateKey = types.GetTaxRateKey - GetRewardWeightKey = types.GetRewardWeightKey - GetTaxCapKey = types.GetTaxCapKey - GetTaxProceedsKey = types.GetTaxProceedsKey - GetHistoricalIssuanceKey = types.GetHistoricalIssuanceKey - DefaultParams = types.DefaultParams - NewTaxRateUpdateProposal = types.NewTaxRateUpdateProposal - NewRewardWeightUpdateProposal = types.NewRewardWeightUpdateProposal - NewQueryTaxCapParams = types.NewQueryTaxCapParams - NewQueryTaxRateParams = types.NewQueryTaxRateParams - NewQueryRewardWeightParams = types.NewQueryRewardWeightParams - NewQuerySeigniorageParams = types.NewQuerySeigniorageParams - NewQueryTaxProceedsParams = types.NewQueryTaxProceedsParams - NewQueryHistoricalIssuanceParams = types.NewQueryHistoricalIssuanceParams - TaxRewardsForEpoch = keeper.TaxRewardsForEpoch - SeigniorageRewardsForEpoch = keeper.SeigniorageRewardsForEpoch - MiningRewardForEpoch = keeper.MiningRewardForEpoch - TRL = keeper.TRL - SRL = keeper.SRL - MRL = keeper.MRL - UnitLunaIndicator = keeper.UnitLunaIndicator - SumIndicator = keeper.SumIndicator - RollingAverageIndicator = keeper.RollingAverageIndicator - NewKeeper = keeper.NewKeeper - ParamKeyTable = keeper.ParamKeyTable - NewQuerier = keeper.NewQuerier + RegisterCodec = types.RegisterCodec + ErrInvalidEpoch = types.ErrInvalidEpoch + NewGenesisState = types.NewGenesisState + DefaultGenesisState = types.DefaultGenesisState + ValidateGenesis = types.ValidateGenesis + GetTaxCapKey = types.GetTaxCapKey + GetTRKey = types.GetTRKey + GetSRKey = types.GetSRKey + GetTSLKey = types.GetTSLKey + GetSubkeyByEpoch = types.GetSubkeyByEpoch + DefaultParams = types.DefaultParams + NewTaxRateUpdateProposal = types.NewTaxRateUpdateProposal + NewRewardWeightUpdateProposal = types.NewRewardWeightUpdateProposal + NewQueryTaxCapParams = types.NewQueryTaxCapParams + NewKeeper = keeper.NewKeeper + ParamKeyTable = keeper.ParamKeyTable + NewQuerier = keeper.NewQuerier // variable aliases ModuleCdc = types.ModuleCdc @@ -70,7 +54,10 @@ var ( RewardWeightKey = types.RewardWeightKey TaxCapKey = types.TaxCapKey TaxProceedsKey = types.TaxProceedsKey - HistoricalIssuanceKey = types.HistoricalIssuanceKey + EpochInitialIssuanceKey = types.EpochInitialIssuanceKey + TRKey = types.TRKey + SRKey = types.SRKey + TSLKey = types.TSLKey ParamStoreKeyTaxPolicy = types.ParamStoreKeyTaxPolicy ParamStoreKeyRewardPolicy = types.ParamStoreKeyRewardPolicy ParamStoreKeySeigniorageBurdenTarget = types.ParamStoreKeySeigniorageBurdenTarget @@ -90,20 +77,15 @@ var ( ) type ( - PolicyConstraints = types.PolicyConstraints - SupplyKeeper = types.SupplyKeeper - MarketKeeper = types.MarketKeeper - StakingKeeper = types.StakingKeeper - DistributionKeeper = types.DistributionKeeper - GenesisState = types.GenesisState - Params = types.Params - TaxRateUpdateProposal = types.TaxRateUpdateProposal - RewardWeightUpdateProposal = types.RewardWeightUpdateProposal - QueryTaxCapParams = types.QueryTaxCapParams - QueryTaxRateParams = types.QueryTaxRateParams - QueryRewardWeightParams = types.QueryRewardWeightParams - QuerySeigniorageProceedsParams = types.QuerySeigniorageProceedsParams - QueryTaxProceedsParams = types.QueryTaxProceedsParams - QueryHistoricalIssuanceParams = types.QueryHistoricalIssuanceParams - Keeper = keeper.Keeper + PolicyConstraints = types.PolicyConstraints + SupplyKeeper = types.SupplyKeeper + MarketKeeper = types.MarketKeeper + StakingKeeper = types.StakingKeeper + DistributionKeeper = types.DistributionKeeper + GenesisState = types.GenesisState + Params = types.Params + TaxRateUpdateProposal = types.TaxRateUpdateProposal + RewardWeightUpdateProposal = types.RewardWeightUpdateProposal + QueryTaxCapParams = types.QueryTaxCapParams + Keeper = keeper.Keeper ) diff --git a/x/treasury/client/cli/query.go b/x/treasury/client/cli/query.go index a5feb3a0b..004d535e8 100644 --- a/x/treasury/client/cli/query.go +++ b/x/treasury/client/cli/query.go @@ -1,9 +1,7 @@ package cli import ( - "errors" "fmt" - "strconv" "strings" "github.com/terra-project/core/x/treasury/internal/types" @@ -33,12 +31,10 @@ func GetQueryCmd(cdc *codec.Codec) *cobra.Command { oracleQueryCmd.AddCommand(client.GetCommands( GetCmdQueryTaxRate(cdc), GetCmdQueryTaxCap(cdc), - GetCmdQueryHistoricalIssuance(cdc), GetCmdQueryRewardWeight(cdc), GetCmdQueryParams(cdc), GetCmdQueryTaxProceeds(cdc), GetCmdQuerySeigniorageProceeds(cdc), - GetCmdQueryCurrentEpoch(cdc), GetCmdQueryParams(cdc), )...) @@ -49,37 +45,17 @@ func GetQueryCmd(cdc *codec.Codec) *cobra.Command { // GetCmdQueryTaxRate implements the query tax-rate command. func GetCmdQueryTaxRate(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "tax-rate [epoch]", - Args: cobra.RangeArgs(0, 1), + Use: "tax-rate", + Args: cobra.NoArgs, Short: "Query the stability tax rate", Long: strings.TrimSpace(` -Query the stability tax rate at the specified epoch. +Query the stability tax rate of the current epoch. -$ terracli query treasury tax-rate 14 +$ terracli query treasury tax-rate `), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) - - var epoch int64 - if len(args) == 0 { - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryCurrentEpoch), nil) - if err != nil { - return err - } - - cdc.MustUnmarshalJSON(res, &epoch) - } else { - var err error - epoch, err = strconv.ParseInt(args[0], 10, 64) - if err != nil { - return errors.New(sdk.AppendMsgToErr("Falied to parse epoch", err.Error())) - } - } - - params := types.NewQueryTaxRateParams(epoch) - bz := cdc.MustMarshalJSON(params) - - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryTaxRate), bz) + res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryTaxRate), nil) if err != nil { return err } @@ -127,87 +103,20 @@ $ terracli query treasury tax-cap ukrw return cmd } -// GetCmdQueryHistoricalIssuance implements the query historical issuance command. -func GetCmdQueryHistoricalIssuance(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "historical-issuance [epoch]", - Args: cobra.RangeArgs(0, 1), - Short: "Query the epoch historical issuance", - Long: strings.TrimSpace(` -Query the epoch issuance - -$ terracli query treasury historical-issuance 0" -`), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - - var epoch int64 - if len(args) == 0 { - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryCurrentEpoch), nil) - if err != nil { - return err - } - - cdc.MustUnmarshalJSON(res, &epoch) - } else { - var err error - epoch, err = strconv.ParseInt(args[0], 10, 64) - if err != nil { - return errors.New(sdk.AppendMsgToErr("Falied to parse epoch", err.Error())) - } - } - - params := types.NewQueryHistoricalIssuanceParams(epoch) - bz := cdc.MustMarshalJSON(params) - - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryHistoricalIssuance), bz) - if err != nil { - return err - } - - var issuance sdk.Coins - cdc.MustUnmarshalJSON(res, &issuance) - return cliCtx.PrintOutput(issuance) - }, - } - - return cmd -} - // GetCmdQueryRewardWeight implements the query reward-weight command. func GetCmdQueryRewardWeight(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "reward-weight [epoch]", - Args: cobra.RangeArgs(0, 1), + Use: "reward-weight", + Args: cobra.NoArgs, Short: "Query the reward weight", Long: strings.TrimSpace(` -Query the reward rate at the specified epoch. +Query the reward rate of the current epoch. -$ terracli query treasury reward-weight 14 +$ terracli query treasury reward-weight `), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) - - var epoch int64 - if len(args) == 0 { - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryCurrentEpoch), nil) - if err != nil { - return err - } - - cdc.MustUnmarshalJSON(res, &epoch) - } else { - var err error - epoch, err = strconv.ParseInt(args[0], 10, 64) - if err != nil { - return errors.New(sdk.AppendMsgToErr("Falied to parse epoch", err.Error())) - } - } - - params := types.NewQueryRewardWeightParams(epoch) - bz := cdc.MustMarshalJSON(params) - - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryRewardWeight), bz) + res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryRewardWeight), nil) if err != nil { return err } @@ -224,37 +133,17 @@ $ terracli query treasury reward-weight 14 // GetCmdQueryTaxProceeds implements the query tax-proceeds command. func GetCmdQueryTaxProceeds(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "tax-proceeds [epoch]", - Args: cobra.RangeArgs(0, 1), - Short: "Query the tax proceeds for the epoch", + Use: "tax-proceeds", + Args: cobra.NoArgs, + Short: "Query the tax proceeds for the current epoch", Long: strings.TrimSpace(` -Query the tax proceeds corresponding to the given epoch. The return value will be sdk.Coins{} of all the taxes collected. +Query the tax proceeds corresponding to the current epoch. The return value will be sdk.Coins{} of all the taxes collected. -$ terracli query treasury tax-proceeds 14 +$ terracli query treasury tax-proceeds `), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) - - var epoch int64 - if len(args) == 0 { - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryCurrentEpoch), nil) - if err != nil { - return err - } - - cdc.MustUnmarshalJSON(res, &epoch) - } else { - var err error - epoch, err = strconv.ParseInt(args[0], 10, 64) - if err != nil { - return errors.New(sdk.AppendMsgToErr("Falied to parse epoch", err.Error())) - } - } - - params := types.NewQueryTaxProceedsParams(epoch) - bz := cdc.MustMarshalJSON(params) - - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryTaxProceeds), bz) + res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryTaxProceeds), nil) if err != nil { return err } @@ -265,45 +154,23 @@ $ terracli query treasury tax-proceeds 14 }, } - cmd.Flags().String(flagEpoch, "", "(optional) an epoch number which you wants to get tax proceeds of; default is current epoch") - return cmd } // GetCmdQuerySeigniorageProceeds implements the query seigniorage-proceeds command. func GetCmdQuerySeigniorageProceeds(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "seigniorage-proceeds [epoch]", - Args: cobra.RangeArgs(0, 1), - Short: "Query the seigniorage proceeds for the epoch", + Use: "seigniorage-proceeds", + Args: cobra.NoArgs, + Short: "Query the seigniorage proceeds for the current epoch", Long: strings.TrimSpace(` -Query the seigniorage proceeds corresponding to the given epoch. The return value will be in units of 'uluna' coins. +Query the seigniorage proceeds corresponding to the current epoch. The return value will be in units of 'uluna' coins. -$ terracli query treasury seigniorage-proceeds 14 +$ terracli query treasury seigniorage-proceeds `), RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) - - var epoch int64 - if len(args) == 0 { - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryCurrentEpoch), nil) - if err != nil { - return err - } - - cdc.MustUnmarshalJSON(res, &epoch) - } else { - var err error - epoch, err = strconv.ParseInt(args[0], 10, 64) - if err != nil { - return errors.New(sdk.AppendMsgToErr("Falied to parse epoch", err.Error())) - } - } - - params := types.NewQuerySeigniorageParams(epoch) - bz := cdc.MustMarshalJSON(params) - - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySeigniorageProceeds), bz) + res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySeigniorageProceeds), nil) if err != nil { return err } @@ -317,34 +184,6 @@ $ terracli query treasury seigniorage-proceeds 14 return cmd } -// GetCmdQueryCurrentEpoch implements the query seigniorage-proceeds command. -func GetCmdQueryCurrentEpoch(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "current-epoch", - Args: cobra.NoArgs, - Short: "Query the current epoch number", - Long: strings.TrimSpace(` -Query the current epoch, starting at 0. - -$ terracli query treasury current-epoch -`), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) - - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryCurrentEpoch), nil) - if err != nil { - return err - } - - var curEpoch int64 - cdc.MustUnmarshalJSON(res, &curEpoch) - return cliCtx.PrintOutput(sdk.NewInt(curEpoch)) - }, - } - - return cmd -} - // GetCmdQueryParams implements the query params command. func GetCmdQueryParams(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ diff --git a/x/treasury/client/rest/query.go b/x/treasury/client/rest/query.go index c27561ccd..cdc32dd85 100644 --- a/x/treasury/client/rest/query.go +++ b/x/treasury/client/rest/query.go @@ -3,29 +3,20 @@ package rest import ( "fmt" "net/http" - "strconv" "github.com/terra-project/core/x/treasury/internal/types" "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/gorilla/mux" ) func registerQueryRoute(cliCtx context.CLIContext, r *mux.Router) { r.HandleFunc("/treasury/tax_rate", queryTaxRateHandlerFunction(cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/treasury/tax_rate/{%s}", RestEpoch), queryTaxRateHandlerFunction(cliCtx)).Methods("GET") r.HandleFunc(fmt.Sprintf("/treasury/tax_cap/{%s}", RestDenom), queryTaxCapHandlerFunction(cliCtx)).Methods("GET") r.HandleFunc("/treasury/reward_weight", queryRewardWeightHandlerFunction(cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/treasury/reward_weight/{%s}", RestEpoch), queryRewardWeightHandlerFunction(cliCtx)).Methods("GET") - r.HandleFunc("/treasury/historical_issuance", queryHistoricalIssuanceHandlerFunction(cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/treasury/historical_issuance/{%s}", RestEpoch), queryHistoricalIssuanceHandlerFunction(cliCtx)).Methods("GET") r.HandleFunc("/treasury/tax_proceeds", queryTaxProceedsHandlerFunction(cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/treasury/tax_proceeds/{%s}", RestEpoch), queryTaxProceedsHandlerFunction(cliCtx)).Methods("GET") r.HandleFunc("/treasury/seigniorage_proceeds", querySeigniorageProceedsHandlerFunction(cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/treasury/seigniorage_proceeds/{%s}", RestEpoch), querySeigniorageProceedsHandlerFunction(cliCtx)).Methods("GET") - r.HandleFunc("/treasury/current_epoch", queryCurrentEpochHandlerFunction(cliCtx)).Methods("GET") r.HandleFunc("/treasury/parameters", queryParametersHandlerFn(cliCtx)).Methods("GET") } @@ -36,31 +27,7 @@ func queryTaxRateHandlerFunction(cliCtx context.CLIContext) http.HandlerFunc { return } - vars := mux.Vars(r) - epochStr := vars[RestEpoch] - - var epoch int64 - if len(epochStr) == 0 { - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryCurrentEpoch), nil) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx.Codec.MustUnmarshalJSON(res, &epoch) - } else { - var err error - epoch, err = strconv.ParseInt(epochStr, 10, 64) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, sdk.AppendMsgToErr("Falied to parse epoch", err.Error())) - return - } - } - - params := types.NewQueryTaxRateParams(epoch) - bz := cliCtx.Codec.MustMarshalJSON(params) - - res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryTaxRate), bz) + res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryTaxRate), nil) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -102,73 +69,7 @@ func queryRewardWeightHandlerFunction(cliCtx context.CLIContext) http.HandlerFun return } - vars := mux.Vars(r) - epochStr := vars[RestEpoch] - - var epoch int64 - if len(epochStr) == 0 { - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryCurrentEpoch), nil) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx.Codec.MustUnmarshalJSON(res, &epoch) - } else { - var err error - epoch, err = strconv.ParseInt(epochStr, 10, 64) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, sdk.AppendMsgToErr("Falied to parse epoch", err.Error())) - return - } - } - - params := types.NewQueryRewardWeightParams(epoch) - bz := cliCtx.Codec.MustMarshalJSON(params) - - res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryRewardWeight), bz) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) - } -} - -func queryHistoricalIssuanceHandlerFunction(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - vars := mux.Vars(r) - epochStr := vars[RestEpoch] - - var epoch int64 - if len(epochStr) == 0 { - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryCurrentEpoch), nil) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx.Codec.MustUnmarshalJSON(res, &epoch) - } else { - var err error - epoch, err = strconv.ParseInt(epochStr, 10, 64) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, sdk.AppendMsgToErr("Falied to parse epoch", err.Error())) - return - } - } - - params := types.NewQueryHistoricalIssuanceParams(epoch) - bz := cliCtx.Codec.MustMarshalJSON(params) - - res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryHistoricalIssuance), bz) + res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryRewardWeight), nil) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -186,32 +87,7 @@ func queryTaxProceedsHandlerFunction(cliCtx context.CLIContext) http.HandlerFunc return } - vars := mux.Vars(r) - epochStr := vars[RestEpoch] - - var epoch int64 - if len(epochStr) == 0 { - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryCurrentEpoch), nil) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx.Codec.MustUnmarshalJSON(res, &epoch) - - } else { - var err error - epoch, err = strconv.ParseInt(epochStr, 10, 64) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, sdk.AppendMsgToErr("Falied to parse epoch", err.Error())) - return - } - } - - params := types.NewQueryTaxProceedsParams(epoch) - bz := cliCtx.Codec.MustMarshalJSON(params) - - res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryTaxProceeds), bz) + res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryTaxProceeds), nil) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -223,51 +99,13 @@ func queryTaxProceedsHandlerFunction(cliCtx context.CLIContext) http.HandlerFunc } func querySeigniorageProceedsHandlerFunction(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - epochStr := vars[RestEpoch] - - var epoch int64 - if len(epochStr) == 0 { - res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryCurrentEpoch), nil) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx.Codec.MustUnmarshalJSON(res, &epoch) - - } else { - var err error - epoch, err = strconv.ParseInt(epochStr, 10, 64) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, sdk.AppendMsgToErr("Falied to parse epoch", err.Error())) - return - } - } - - params := types.NewQuerySeigniorageParams(epoch) - bz := cliCtx.Codec.MustMarshalJSON(params) - - res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySeigniorageProceeds), bz) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) - } -} - -func queryCurrentEpochHandlerFunction(cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) if !ok { return } - res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryCurrentEpoch), nil) + res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySeigniorageProceeds), nil) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return diff --git a/x/treasury/genesis.go b/x/treasury/genesis.go index f72eed32b..1e6533f0d 100644 --- a/x/treasury/genesis.go +++ b/x/treasury/genesis.go @@ -10,25 +10,24 @@ import ( func InitGenesis(ctx sdk.Context, keeper Keeper, data GenesisState) { keeper.SetParams(ctx, data.Params) - for epoch, taxRate := range data.TaxRates { - keeper.SetTaxRate(ctx, int64(epoch), taxRate) - } - - for epoch, rewardWeight := range data.RewardWeights { - keeper.SetRewardWeight(ctx, int64(epoch), rewardWeight) - } + keeper.SetTaxRate(ctx, data.TaxRate) + keeper.SetRewardWeight(ctx, data.RewardWeight) + keeper.SetEpochInitialIssuance(ctx, data.EpochInitialIssuance) + keeper.SetEpochTaxProceeds(ctx, data.TaxProceed) // store tax caps for denom, taxCap := range data.TaxCaps { keeper.SetTaxCap(ctx, denom, taxCap) } - for epoch, historicalIssuance := range data.HistoricalIssuances { - keeper.SetHistoricalIssuance(ctx, int64(epoch), historicalIssuance) + for epoch, TR := range data.TRs { + keeper.SetTR(ctx, int64(epoch), TR) } - - for epoch, taxProceed := range data.TaxProceeds { - keeper.SetTaxProceeds(ctx, int64(epoch), taxProceed) + for epoch, SR := range data.SRs { + keeper.SetSR(ctx, int64(epoch), SR) + } + for epoch, TSL := range data.TSLs { + keeper.SetTSL(ctx, int64(epoch), TSL) } } @@ -38,22 +37,30 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, data GenesisState) { func ExportGenesis(ctx sdk.Context, keeper Keeper) (data GenesisState) { params := keeper.GetParams(ctx) + taxRate := keeper.GetTaxRate(ctx) + rewardWeight := keeper.GetRewardWeight(ctx) + taxProceeds := keeper.PeekEpochTaxProceeds(ctx) + epochInitialIssuance := keeper.GetEpochInitialIssuance(ctx) + taxCaps := make(map[string]sdk.Int) keeper.IterateTaxCap(ctx, func(denom string, taxCap sdk.Int) bool { taxCaps[denom] = taxCap return false }) - var taxRates []sdk.Dec - var rewardWeights []sdk.Dec - var taxProceeds []sdk.Coins - var historicalIssuancees []sdk.Coins - for e := int64(0); e <= core.GetEpoch(ctx); e++ { - taxRates = append(taxRates, keeper.GetTaxRate(ctx, e)) - rewardWeights = append(rewardWeights, keeper.GetRewardWeight(ctx, e)) - taxProceeds = append(taxProceeds, keeper.PeekTaxProceeds(ctx, e)) - historicalIssuancees = append(historicalIssuancees, keeper.GetHistoricalIssuance(ctx, e)) + var TRs []sdk.Dec + var SRs []sdk.Dec + var TSLs []sdk.Int + + curEpoch := core.GetEpoch(ctx) + for e := int64(0); e < curEpoch || + (e == curEpoch && core.IsPeriodLastBlock(ctx, core.BlocksPerEpoch)); e++ { + + TRs = append(TRs, keeper.GetTR(ctx, e)) + SRs = append(SRs, keeper.GetSR(ctx, e)) + TSLs = append(TSLs, keeper.GetTSL(ctx, e)) } - return NewGenesisState(params, taxRates, rewardWeights, taxCaps, taxProceeds, historicalIssuancees) + return NewGenesisState(params, taxRate, rewardWeight, + taxCaps, taxProceeds, epochInitialIssuance, TRs, SRs, TSLs) } diff --git a/x/treasury/genesis_test.go b/x/treasury/genesis_test.go index 252c97865..aba857a10 100644 --- a/x/treasury/genesis_test.go +++ b/x/treasury/genesis_test.go @@ -6,21 +6,25 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - core "github.com/terra-project/core/types" "github.com/terra-project/core/x/treasury/internal/keeper" ) func TestExportInitGenesis(t *testing.T) { input := keeper.CreateTestInput(t) - input.TreasuryKeeper.SetHistoricalIssuance(input.Ctx, 0, sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(33)))) - input.TreasuryKeeper.SetHistoricalIssuance(input.Ctx, 1, sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(123)))) - input.TreasuryKeeper.SetHistoricalIssuance(input.Ctx, 2, sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(131)))) - input.TreasuryKeeper.SetRewardWeight(input.Ctx, core.GetEpoch(input.Ctx), sdk.NewDec(1123)) + input.TreasuryKeeper.SetEpochInitialIssuance(input.Ctx, sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(33)))) + input.TreasuryKeeper.SetRewardWeight(input.Ctx, sdk.NewDec(1123)) input.TreasuryKeeper.SetTaxCap(input.Ctx, "foo", sdk.NewInt(1234)) - input.TreasuryKeeper.SetTaxRate(input.Ctx, core.GetEpoch(input.Ctx), sdk.NewDec(5435)) - input.TreasuryKeeper.SetTaxProceeds(input.Ctx, 0, sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(923)))) - input.TreasuryKeeper.SetTaxProceeds(input.Ctx, 1, sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(123)))) - input.TreasuryKeeper.SetTaxProceeds(input.Ctx, 2, sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(623)))) + input.TreasuryKeeper.SetTaxRate(input.Ctx, sdk.NewDec(5435)) + input.TreasuryKeeper.SetEpochTaxProceeds(input.Ctx, sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(923)))) + input.TreasuryKeeper.SetTR(input.Ctx, int64(0), sdk.NewDec(123)) + input.TreasuryKeeper.SetTR(input.Ctx, int64(1), sdk.NewDec(345)) + input.TreasuryKeeper.SetTR(input.Ctx, int64(2), sdk.NewDec(567)) + input.TreasuryKeeper.SetSR(input.Ctx, int64(0), sdk.NewDec(123)) + input.TreasuryKeeper.SetSR(input.Ctx, int64(1), sdk.NewDec(345)) + input.TreasuryKeeper.SetSR(input.Ctx, int64(2), sdk.NewDec(567)) + input.TreasuryKeeper.SetTSL(input.Ctx, int64(0), sdk.NewInt(123)) + input.TreasuryKeeper.SetTSL(input.Ctx, int64(1), sdk.NewInt(345)) + input.TreasuryKeeper.SetTSL(input.Ctx, int64(2), sdk.NewInt(567)) genesis := ExportGenesis(input.Ctx, input.TreasuryKeeper) newInput := keeper.CreateTestInput(t) diff --git a/x/treasury/handler.go b/x/treasury/handler.go index fd2b5b511..c51969818 100644 --- a/x/treasury/handler.go +++ b/x/treasury/handler.go @@ -5,8 +5,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - - core "github.com/terra-project/core/types" ) // NewTreasuryPolicyUpdateHandler custom gov proposal handler @@ -28,11 +26,11 @@ func NewTreasuryPolicyUpdateHandler(k Keeper) govtypes.Handler { // handleTaxRateUpdateProposal is a handler for updating tax rate func handleTaxRateUpdateProposal(ctx sdk.Context, k Keeper, p TaxRateUpdateProposal) sdk.Error { taxPolicy := k.TaxPolicy(ctx) - taxRate := k.GetTaxRate(ctx, core.GetEpoch(ctx)) + taxRate := k.GetTaxRate(ctx) newTaxRate := taxPolicy.Clamp(taxRate, p.TaxRate) // Set the new tax rate to the store - k.SetTaxRate(ctx, core.GetEpoch(ctx), newTaxRate) + k.SetTaxRate(ctx, newTaxRate) logger := k.Logger(ctx) logger.Info(fmt.Sprintf("updated tax-rate to %s", newTaxRate)) @@ -42,11 +40,11 @@ func handleTaxRateUpdateProposal(ctx sdk.Context, k Keeper, p TaxRateUpdatePropo // handleRewardWeightUpdateProposal is a handler for updating reward weight func handleRewardWeightUpdateProposal(ctx sdk.Context, k Keeper, p RewardWeightUpdateProposal) sdk.Error { rewardPolicy := k.RewardPolicy(ctx) - rewardWeight := k.GetRewardWeight(ctx, core.GetEpoch(ctx)) + rewardWeight := k.GetRewardWeight(ctx) newRewardWeight := rewardPolicy.Clamp(rewardWeight, p.RewardWeight) // Set the new reward rate to the store - k.SetRewardWeight(ctx, core.GetEpoch(ctx), newRewardWeight) + k.SetRewardWeight(ctx, newRewardWeight) logger := k.Logger(ctx) logger.Info(fmt.Sprintf("updated reward-weight to %s", newRewardWeight)) diff --git a/x/treasury/internal/keeper/indicator.go b/x/treasury/internal/keeper/indicator.go index 24a2d8a62..1e6eee2f0 100644 --- a/x/treasury/internal/keeper/indicator.go +++ b/x/treasury/internal/keeper/indicator.go @@ -11,103 +11,96 @@ import ( // // Three important concepts: // - MR: Fees + Seigniorage for a given epoch sums to Mining Rewards -// - MRL: Computes the Mining Reward per unit Luna -// - SMR: Computes the ratio of seigniorage rewards to overall mining rewards -// -// Rolling averages are also computed for MRL and SMR respectively. -// - -// TaxRewardsForEpoch returns tax rewards that have been collected in the epoch -func TaxRewardsForEpoch(ctx sdk.Context, k Keeper, epoch int64) sdk.Dec { - taxRewards := sdk.NewDecCoins(k.PeekTaxProceeds(ctx, epoch)) - - taxRewardInMicroSDR := sdk.ZeroDec() - for _, coinReward := range taxRewards { - if coinReward.Denom != core.MicroSDRDenom { - swappedReward, err := k.marketKeeper.ComputeInternalSwap(ctx, coinReward, core.MicroSDRDenom) +// - SR: Computes the Seigniorage Reward +// - TR: Computes the Tax Reward +// - TSL: Total Staked Luna +// - TRL: Computes the Tax Reward per unit Luna (TR/TSL) + +// alignCoins align the coins to the given denom through the market swap +func (k Keeper) alignCoins(ctx sdk.Context, coins sdk.DecCoins, denom string) (alignedAmt sdk.Dec) { + alignedAmt = sdk.ZeroDec() + for _, coinReward := range coins { + if coinReward.Denom != denom { + swappedReward, err := k.marketKeeper.ComputeInternalSwap(ctx, coinReward, denom) if err != nil { continue } - taxRewardInMicroSDR = taxRewardInMicroSDR.Add(swappedReward.Amount) + alignedAmt = alignedAmt.Add(swappedReward.Amount) } else { - taxRewardInMicroSDR = taxRewardInMicroSDR.Add(coinReward.Amount) + alignedAmt = alignedAmt.Add(coinReward.Amount) } } - return taxRewardInMicroSDR + return alignedAmt } -// SeigniorageRewardsForEpoch returns seigniorage rewards for the epoch -func SeigniorageRewardsForEpoch(ctx sdk.Context, k Keeper, epoch int64) sdk.Dec { - seignioragePool := k.PeekEpochSeigniorage(ctx, epoch) - rewardAmt := k.GetRewardWeight(ctx, epoch).MulInt(seignioragePool) - seigniorageReward := sdk.NewDecCoinFromDec(core.MicroLunaDenom, rewardAmt) +// UpdateIndicators updates interal indicators +func (k Keeper) UpdateIndicators(ctx sdk.Context) { + epoch := core.GetEpoch(ctx) - microSDRReward, err := k.marketKeeper.ComputeInternalSwap(ctx, seigniorageReward, core.MicroSDRDenom) - if err != nil { - return sdk.ZeroDec() - } + // Compute Total Staked Luna (TSL) + totalStakedLuna := k.stakingKeeper.TotalBondedTokens(ctx) - return microSDRReward.Amount -} + k.SetTSL(ctx, epoch, totalStakedLuna) -// MiningRewardForEpoch returns the sum of tax and seigniorage rewards for the epoch -func MiningRewardForEpoch(ctx sdk.Context, k Keeper, epoch int64) sdk.Dec { - taxRewards := TaxRewardsForEpoch(ctx, k, epoch) - seigniorageRewards := SeigniorageRewardsForEpoch(ctx, k, epoch) + // Compute Tax Rewards (TR) + taxRewards := sdk.NewDecCoins(k.PeekEpochTaxProceeds(ctx)) + TR := k.alignCoins(ctx, taxRewards, core.MicroSDRDenom) - return taxRewards.Add(seigniorageRewards) -} + k.SetTR(ctx, epoch, TR) -// TRL returns tax rewards per luna at the epoch -func TRL(ctx sdk.Context, k Keeper, epoch int64) sdk.Dec { - return UnitLunaIndicator(ctx, k, epoch, TaxRewardsForEpoch) -} + // Reset tax proceeds after computing TRL for the next epoch + k.SetEpochTaxProceeds(ctx, sdk.Coins{}) -// SRL returns Seigniorage rewards per luna at the epoch -func SRL(ctx sdk.Context, k Keeper, epoch int64) sdk.Dec { - return UnitLunaIndicator(ctx, k, epoch, SeigniorageRewardsForEpoch) + // Compute Seigniorage Rewards (SR) + seigniorage := k.PeekEpochSeigniorage(ctx) + seigniorageRewardsAmt := k.GetRewardWeight(ctx).MulInt(seigniorage) + seigniorageRewards := sdk.DecCoins{sdk.NewDecCoinFromDec(core.MicroLunaDenom, seigniorageRewardsAmt)} + SR := k.alignCoins(ctx, seigniorageRewards, core.MicroSDRDenom) + + k.SetSR(ctx, epoch, SR) } -// MRL returns mining rewards per luna at the epoch -func MRL(ctx sdk.Context, k Keeper, epoch int64) sdk.Dec { - return UnitLunaIndicator(ctx, k, epoch, MiningRewardForEpoch) +// TRL returns Tax Rewards per Luna for the epoch +func TRL(ctx sdk.Context, epoch int64, k Keeper) sdk.Dec { + return k.GetTR(ctx, epoch).QuoInt(k.GetTSL(ctx, epoch)) } -// UnitLunaIndicator evaluates the indicator function and divides it by the luna supply for the epoch -func UnitLunaIndicator(ctx sdk.Context, k Keeper, epoch int64, - indicatorFunction func(sdk.Context, Keeper, int64) sdk.Dec) sdk.Dec { - indicator := indicatorFunction(ctx, k, epoch) - lunaTotalBondedAmount := k.stakingKeeper.TotalBondedTokens(ctx) +// SR returns Seigniorage Rewards for the epoch +func SR(ctx sdk.Context, epoch int64, k Keeper) sdk.Dec { + return k.GetSR(ctx, epoch) +} - return indicator.QuoInt(lunaTotalBondedAmount) +// MR returns Mining Rewards = Seigniorage Rewards + Tax Rates for the epoch +func MR(ctx sdk.Context, epoch int64, k Keeper) sdk.Dec { + return k.GetTR(ctx, epoch).Add(k.GetSR(ctx, epoch)) } -// SumIndicator returns the sum of the indicator over several epochs. -// If current epoch < epochs, we return the best we can and return SumIndicator(currentEpoch) -func SumIndicator(ctx sdk.Context, k Keeper, epochs int64, - indicatorFunction func(sdk.Context, Keeper, int64) sdk.Dec) sdk.Dec { +// sumIndicator returns the sum of the indicator over several epochs. +// If current epoch < epochs, we return the best we can and return sumIndicator(currentEpoch) +func (k Keeper) sumIndicator(ctx sdk.Context, epochs int64, + indicator func(ctx sdk.Context, epoch int64, k Keeper) sdk.Dec) sdk.Dec { sum := sdk.ZeroDec() curEpoch := core.GetEpoch(ctx) for i := curEpoch; i >= 0 && i > (curEpoch-epochs); i-- { - val := indicatorFunction(ctx, k, i) + val := indicator(ctx, i, k) sum = sum.Add(val) } return sum } -// RollingAverageIndicator returns the rolling average of the indicator over several epochs. -// If current epoch < epochs, we return the best we can and return RollingAverageIndicator(currentEpoch) -func RollingAverageIndicator(ctx sdk.Context, k Keeper, epochs int64, - indicatorFunction func(sdk.Context, Keeper, int64) sdk.Dec) sdk.Dec { +// rollingAverageIndicator returns the rolling average of the indicator over several epochs. +// If current epoch < epochs, we return the best we can and return rollingAverageIndicator(currentEpoch) +func (k Keeper) rollingAverageIndicator(ctx sdk.Context, epochs int64, + indicator func(ctx sdk.Context, epoch int64, k Keeper) sdk.Dec) sdk.Dec { sum := sdk.ZeroDec() curEpoch := core.GetEpoch(ctx) var i int64 for i = curEpoch; i >= 0 && i > (curEpoch-epochs); i-- { - val := indicatorFunction(ctx, k, i) + val := indicator(ctx, i, k) sum = sum.Add(val) } diff --git a/x/treasury/internal/keeper/indicator_test.go b/x/treasury/internal/keeper/indicator_test.go index 9681846a1..34361081b 100644 --- a/x/treasury/internal/keeper/indicator_test.go +++ b/x/treasury/internal/keeper/indicator_test.go @@ -1,7 +1,6 @@ package keeper import ( - "fmt" "testing" core "github.com/terra-project/core/types" @@ -9,11 +8,10 @@ import ( "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" ) func TestFeeRewardsForEpoch(t *testing.T) { - input := CreateTestInput(t) + input, _ := setupValidators(t) taxAmount := sdk.NewInt(1000).MulRaw(core.MicroUnit) @@ -24,20 +22,23 @@ func TestFeeRewardsForEpoch(t *testing.T) { input.OracleKeeper.SetLunaPrice(input.Ctx, core.MicroCNYDenom, sdk.NewDec(1000)) // Record tax proceeds - input.TreasuryKeeper.RecordTaxProceeds(input.Ctx, sdk.Coins{ + input.TreasuryKeeper.RecordEpochTaxProceeds(input.Ctx, sdk.Coins{ sdk.NewCoin(core.MicroSDRDenom, taxAmount), sdk.NewCoin(core.MicroKRWDenom, taxAmount), sdk.NewCoin(core.MicroGBPDenom, taxAmount), sdk.NewCoin(core.MicroCNYDenom, taxAmount), }) - // Get taxes - taxProceedsInSDR := TaxRewardsForEpoch(input.Ctx, input.TreasuryKeeper, core.GetEpoch(input.Ctx)) - require.Equal(t, sdk.NewDec(1111).MulInt64(core.MicroUnit), taxProceedsInSDR) + // Update Indicators + input.TreasuryKeeper.UpdateIndicators(input.Ctx) + + // Get Tax Rawards (TR) + TR := input.TreasuryKeeper.GetTR(input.Ctx, core.GetEpoch(input.Ctx)) + require.Equal(t, sdk.NewDec(1111).MulInt64(core.MicroUnit), TR) } func TestSeigniorageRewardsForEpoch(t *testing.T) { - input := CreateTestInput(t) + input, _ := setupValidators(t) sAmt := sdk.NewInt(1000) lnasdrRate := sdk.NewDec(10) @@ -46,7 +47,7 @@ func TestSeigniorageRewardsForEpoch(t *testing.T) { supply := input.SupplyKeeper.GetSupply(input.Ctx) supply = supply.SetTotal(sdk.NewCoins(sdk.NewCoin(core.MicroLunaDenom, sAmt))) input.SupplyKeeper.SetSupply(input.Ctx, supply) - input.TreasuryKeeper.RecordHistoricalIssuance(input.Ctx) + input.TreasuryKeeper.RecordEpochInitialIssuance(input.Ctx) // Set random prices input.OracleKeeper.SetLunaPrice(input.Ctx, core.MicroSDRDenom, lnasdrRate) @@ -56,31 +57,34 @@ func TestSeigniorageRewardsForEpoch(t *testing.T) { supply = supply.SetTotal(sdk.NewCoins(sdk.NewCoin(core.MicroLunaDenom, sdk.ZeroInt()))) input.SupplyKeeper.SetSupply(input.Ctx, supply) - // Get seigniorage rewards - seigniorageProceeds := SeigniorageRewardsForEpoch(input.Ctx, input.TreasuryKeeper, core.GetEpoch(input.Ctx)) - miningRewardWeight := input.TreasuryKeeper.GetRewardWeight(input.Ctx, core.GetEpoch(input.Ctx)) - require.Equal(t, lnasdrRate.MulInt(sAmt).Mul(miningRewardWeight), seigniorageProceeds) + // Update Indicators + input.TreasuryKeeper.UpdateIndicators(input.Ctx) + + // Get seigniorage rewards (SR) + SR := input.TreasuryKeeper.GetSR(input.Ctx, core.GetEpoch(input.Ctx)) + miningRewardWeight := input.TreasuryKeeper.GetRewardWeight(input.Ctx) + require.Equal(t, lnasdrRate.MulInt(sAmt).Mul(miningRewardWeight), SR) } func TestMiningRewardsForEpoch(t *testing.T) { - input := CreateTestInput(t) + input, _ := setupValidators(t) amt := sdk.NewInt(1000).MulRaw(core.MicroUnit) supply := input.SupplyKeeper.GetSupply(input.Ctx) supply = supply.SetTotal(sdk.NewCoins(sdk.NewCoin(core.MicroLunaDenom, amt))) input.SupplyKeeper.SetSupply(input.Ctx, supply) - input.TreasuryKeeper.RecordHistoricalIssuance(input.Ctx) + input.TreasuryKeeper.RecordEpochInitialIssuance(input.Ctx) // Set random prices - input.OracleKeeper.SetLunaPrice(input.Ctx, core.MicroKRWDenom, sdk.NewDec(1)) - input.OracleKeeper.SetLunaPrice(input.Ctx, core.MicroSDRDenom, sdk.NewDec(10)) + input.OracleKeeper.SetLunaPrice(input.Ctx, core.MicroSDRDenom, sdk.NewDec(1)) + input.OracleKeeper.SetLunaPrice(input.Ctx, core.MicroKRWDenom, sdk.NewDec(10)) input.OracleKeeper.SetLunaPrice(input.Ctx, core.MicroGBPDenom, sdk.NewDec(100)) input.OracleKeeper.SetLunaPrice(input.Ctx, core.MicroCNYDenom, sdk.NewDec(1000)) input.Ctx = input.Ctx.WithBlockHeight(core.BlocksPerEpoch) // Record tax proceeds - input.TreasuryKeeper.RecordTaxProceeds(input.Ctx, sdk.Coins{ + input.TreasuryKeeper.RecordEpochTaxProceeds(input.Ctx, sdk.Coins{ sdk.NewCoin(core.MicroSDRDenom, amt), sdk.NewCoin(core.MicroKRWDenom, amt), sdk.NewCoin(core.MicroGBPDenom, amt), @@ -91,154 +95,143 @@ func TestMiningRewardsForEpoch(t *testing.T) { supply = supply.SetTotal(sdk.NewCoins(sdk.NewCoin(core.MicroLunaDenom, sdk.ZeroInt()))) input.SupplyKeeper.SetSupply(input.Ctx, supply) - tProceeds := TaxRewardsForEpoch(input.Ctx, input.TreasuryKeeper, core.GetEpoch(input.Ctx)) - sProceeds := SeigniorageRewardsForEpoch(input.Ctx, input.TreasuryKeeper, core.GetEpoch(input.Ctx)) - mProceeds := MiningRewardForEpoch(input.Ctx, input.TreasuryKeeper, core.GetEpoch(input.Ctx)) + input.TreasuryKeeper.UpdateIndicators(input.Ctx) - require.Equal(t, tProceeds.Add(sProceeds), mProceeds) -} - -func TestUnitIndicator(t *testing.T) { - input := CreateTestInput(t) - sh := staking.NewHandler(input.StakingKeeper) - - // Create Validators - amt := sdk.TokensFromConsensusPower(100) - addr, val := ValAddrs[0], PubKeys[0] - addr1, val1 := ValAddrs[1], PubKeys[1] - res := sh(input.Ctx, NewTestMsgCreateValidator(addr, val, amt)) - fmt.Println(res) - require.True(t, res.IsOK()) - res = sh(input.Ctx, NewTestMsgCreateValidator(addr1, val1, amt)) - require.True(t, res.IsOK()) - staking.EndBlocker(input.Ctx, input.StakingKeeper) - - lunaTotalBondedAmount := input.StakingKeeper.TotalBondedTokens(input.Ctx) - - // Just get an indicator to multiply the unit value by the expected rval. - // the unit indicator function obviously should return the expected rval. - actual := UnitLunaIndicator(input.Ctx, input.TreasuryKeeper, core.GetEpoch(input.Ctx), - func(_ sdk.Context, _ Keeper, _ int64) sdk.Dec { - return sdk.NewDecFromInt(lunaTotalBondedAmount.MulRaw(20)) - }) - - require.Equal(t, sdk.NewDec(20), actual) -} - -func linearFn(_ sdk.Context, _ Keeper, epoch int64) sdk.Dec { - return sdk.NewDec(epoch) -} + epoch := core.GetEpoch(input.Ctx) -func TestSumIndicator(t *testing.T) { - input := CreateTestInput(t) + tProceeds := input.TreasuryKeeper.GetTR(input.Ctx, epoch) + sProceeds := input.TreasuryKeeper.GetSR(input.Ctx, epoch) + mProceeds := tProceeds.Add(sProceeds) - // Case 1: at epoch 0 and summing over 0 epochs - rval := SumIndicator(input.Ctx, input.TreasuryKeeper, 0, linearFn) - require.Equal(t, sdk.ZeroDec(), rval) - - // Case 2: at epoch 0 and summing over negative epochs - rval = SumIndicator(input.Ctx, input.TreasuryKeeper, -1, linearFn) - require.Equal(t, sdk.ZeroDec(), rval) - - // Case 3: at epoch 3 and summing over 3, 4, 5 epochs; all should have the same rval - input.Ctx = input.Ctx.WithBlockHeight(core.BlocksPerEpoch * 3) - rval = SumIndicator(input.Ctx, input.TreasuryKeeper, 4, linearFn) - rval2 := SumIndicator(input.Ctx, input.TreasuryKeeper, 5, linearFn) - rval3 := SumIndicator(input.Ctx, input.TreasuryKeeper, 6, linearFn) - require.Equal(t, sdk.NewDec(6), rval) - require.Equal(t, rval, rval2) - require.Equal(t, rval2, rval3) - - // Case 4: at epoch 3 and summing over 0 epochs - rval = SumIndicator(input.Ctx, input.TreasuryKeeper, 0, linearFn) - require.Equal(t, sdk.ZeroDec(), rval) - - // Case 5. Sum up to 10 - input.Ctx = input.Ctx.WithBlockHeight(core.BlocksPerEpoch * 10) - rval = SumIndicator(input.Ctx, input.TreasuryKeeper, 10, linearFn) - require.Equal(t, sdk.NewDec(55), rval) + miningRewardWeight := input.TreasuryKeeper.GetRewardWeight(input.Ctx) + require.Equal(t, sdk.NewDec(1111).MulInt64(core.MicroUnit).Add(miningRewardWeight.MulInt(amt)), mProceeds) } -func TestRollingAverageIndicator(t *testing.T) { +func TestLoadIndicatorByEpoch(t *testing.T) { input := CreateTestInput(t) - sh := staking.NewHandler(input.StakingKeeper) - - // Create Validators - amt := sdk.TokensFromConsensusPower(1) - addr, val := ValAddrs[0], PubKeys[0] - addr1, val1 := ValAddrs[1], PubKeys[1] - res := sh(input.Ctx, NewTestMsgCreateValidator(addr, val, amt)) - require.True(t, res.IsOK()) - res = sh(input.Ctx, NewTestMsgCreateValidator(addr1, val1, amt)) - require.True(t, res.IsOK()) - staking.EndBlocker(input.Ctx, input.StakingKeeper) - - // Case 1: at epoch 0 and averaging over 0 epochs - rval := RollingAverageIndicator(input.Ctx, input.TreasuryKeeper, 0, linearFn) - require.Equal(t, sdk.ZeroDec(), rval) - - // Case 2: at epoch 0 and averaging over negative epochs - rval = RollingAverageIndicator(input.Ctx, input.TreasuryKeeper, -1, linearFn) - require.Equal(t, sdk.ZeroDec(), rval) - - // Case 3: at epoch 3 and averaging over 3, 4, 5 epochs; all should have the same rval - input.Ctx = input.Ctx.WithBlockHeight(core.BlocksPerEpoch * 3) - rval = RollingAverageIndicator(input.Ctx, input.TreasuryKeeper, 4, linearFn) - rval2 := RollingAverageIndicator(input.Ctx, input.TreasuryKeeper, 5, linearFn) - rval3 := RollingAverageIndicator(input.Ctx, input.TreasuryKeeper, 6, linearFn) - require.Equal(t, sdk.NewDecWithPrec(15, 1), rval) - require.Equal(t, rval, rval2) - require.Equal(t, rval2, rval3) - - // Case 4: at epoch 3 and averaging over 0 epochs - rval = RollingAverageIndicator(input.Ctx, input.TreasuryKeeper, 0, linearFn) - require.Equal(t, sdk.ZeroDec(), rval) - - // Case 5: at epoch 3 and averaging over 1 epoch - rval = RollingAverageIndicator(input.Ctx, input.TreasuryKeeper, 1, linearFn) - require.Equal(t, sdk.NewDec(3), rval) - - // Case 6: at epoch 500 and averaging over 300 epochs - input.Ctx = input.Ctx.WithBlockHeight(core.BlocksPerEpoch * 500) - rval = RollingAverageIndicator(input.Ctx, input.TreasuryKeeper, 300, linearFn) - require.Equal(t, sdk.NewDecWithPrec(3505, 1), rval) - - // Test all of our reporting functions - input.OracleKeeper.SetLunaPrice(input.Ctx, core.MicroSDRDenom, sdk.OneDec()) - - // set initial supply - input.Ctx = input.Ctx.WithBlockHeight(core.BlocksPerEpoch * 200) - supply := input.SupplyKeeper.GetSupply(input.Ctx) - supply = supply.SetTotal(sdk.NewCoins(sdk.NewCoin(core.MicroLunaDenom, sdk.NewInt(100000000*core.MicroUnit)))) - input.SupplyKeeper.SetSupply(input.Ctx, supply) - input.TreasuryKeeper.RecordHistoricalIssuance(input.Ctx) - for i := int64(201); i <= 500; i++ { - input.Ctx = input.Ctx.WithBlockHeight(core.BlocksPerEpoch * i) - input.TreasuryKeeper.RecordTaxProceeds(input.Ctx, sdk.Coins{sdk.NewCoin(core.MicroSDRDenom, sdk.NewInt(i).MulRaw(core.MicroUnit))}) - input.TreasuryKeeper.SetRewardWeight(input.Ctx, i, sdk.OneDec()) + TRArr := []sdk.Dec{ + sdk.NewDec(100), + sdk.NewDec(200), + sdk.NewDec(300), + sdk.NewDec(400), + } - supply = supply.SetTotal(supply.GetTotal().Sub(sdk.NewCoins(sdk.NewCoin(core.MicroLunaDenom, sdk.NewInt(i).MulRaw(core.MicroUnit))))) - input.SupplyKeeper.SetSupply(input.Ctx, supply) - input.TreasuryKeeper.RecordHistoricalIssuance(input.Ctx) + for epoch, TR := range TRArr { + input.TreasuryKeeper.SetTR(input.Ctx, int64(epoch), TR) } - totalBondedTokens := sdk.NewDecFromInt(input.StakingKeeper.TotalBondedTokens(input.Ctx)) - rval = RollingAverageIndicator(input.Ctx, input.TreasuryKeeper, 300, TaxRewardsForEpoch) - require.Equal(t, sdk.NewDecWithPrec(3505, 1).MulInt64(core.MicroUnit), rval) + SRArr := []sdk.Dec{ + sdk.NewDec(10), + sdk.NewDec(20), + sdk.NewDec(30), + sdk.NewDec(40), + } - rval = RollingAverageIndicator(input.Ctx, input.TreasuryKeeper, 300, SeigniorageRewardsForEpoch) - require.Equal(t, sdk.NewDecWithPrec(3505, 1).MulInt64(core.MicroUnit), rval) + for epoch, SR := range SRArr { + input.TreasuryKeeper.SetSR(input.Ctx, int64(epoch), SR) + } - rval = RollingAverageIndicator(input.Ctx, input.TreasuryKeeper, 300, MiningRewardForEpoch) - require.Equal(t, sdk.NewDecWithPrec(3505*2, 1).MulInt64(core.MicroUnit), rval) + TSLArr := []sdk.Int{ + sdk.NewInt(1000000), + sdk.NewInt(2000000), + sdk.NewInt(3000000), + sdk.NewInt(4000000), + } - rval = RollingAverageIndicator(input.Ctx, input.TreasuryKeeper, 300, TRL) - require.Equal(t, sdk.NewDecWithPrec(3505, 1).MulInt64(core.MicroUnit).Quo(totalBondedTokens).Mul(sdk.NewDec(1000000)).TruncateInt(), rval.Mul(sdk.NewDec(1000000)).TruncateInt()) + for epoch, TSL := range TSLArr { + input.TreasuryKeeper.SetTSL(input.Ctx, int64(epoch), TSL) + } - rval = RollingAverageIndicator(input.Ctx, input.TreasuryKeeper, 300, SRL) - require.Equal(t, sdk.NewDecWithPrec(3505, 1).MulInt64(core.MicroUnit).Quo(totalBondedTokens).Mul(sdk.NewDec(1000000)).TruncateInt(), rval.MulTruncate(sdk.NewDec(1000000)).TruncateInt()) + for epoch := int64(0); epoch < 4; epoch++ { + require.Equal(t, TRArr[epoch].QuoInt(TSLArr[epoch]), TRL(input.Ctx, epoch, input.TreasuryKeeper)) + require.Equal(t, SRArr[epoch], SR(input.Ctx, epoch, input.TreasuryKeeper)) + require.Equal(t, TRArr[epoch].Add(SRArr[epoch]), MR(input.Ctx, epoch, input.TreasuryKeeper)) + } +} - rval = RollingAverageIndicator(input.Ctx, input.TreasuryKeeper, 300, MRL) - require.Equal(t, sdk.NewDecWithPrec(3505*2, 1).MulInt64(core.MicroUnit).Quo(totalBondedTokens).Mul(sdk.NewDec(1000000)).TruncateInt(), rval.MulTruncate(sdk.NewDec(1000000)).TruncateInt()) +func linearFn(_ sdk.Context, _ Keeper, epoch int64) sdk.Dec { + return sdk.NewDec(epoch) } + +// func TestSumIndicator(t *testing.T) { +// input := CreateTestInput(t) + +// MRArr := []sdk.Dec{ +// sdk.NewDec(100), +// sdk.NewDec(200), +// sdk.NewDec(300), +// sdk.NewDec(400), +// sdk.NewDec(500), +// sdk.NewDec(600), +// } + +// for epoch, MR := range MRArr { +// input.TreasuryKeeper.SetMR(input.Ctx, int64(epoch), MR) +// } + +// // Case 1: at epoch 0 and summing over 0 epochs +// rval := input.TreasuryKeeper.sumIndicator(input.Ctx, 0, types.MRKey) +// require.Equal(t, sdk.ZeroDec(), rval) + +// // Case 2: at epoch 0 and summing over negative epochs +// rval = input.TreasuryKeeper.sumIndicator(input.Ctx, -1, types.MRKey) +// require.Equal(t, sdk.ZeroDec(), rval) + +// // Case 3: at epoch 3 and summing over 3, 4, 5 epochs; all should have the same rval +// input.Ctx = input.Ctx.WithBlockHeight(core.BlocksPerEpoch * 3) +// rval = input.TreasuryKeeper.sumIndicator(input.Ctx, 4, types.MRKey) +// rval2 := input.TreasuryKeeper.sumIndicator(input.Ctx, 5, types.MRKey) +// rval3 := input.TreasuryKeeper.sumIndicator(input.Ctx, 6, types.MRKey) +// require.Equal(t, sdk.NewDec(1000), rval) +// require.Equal(t, rval, rval2) +// require.Equal(t, rval2, rval3) + +// // Case 4: at epoch 3 and summing over 0 epochs +// rval = input.TreasuryKeeper.sumIndicator(input.Ctx, 0, types.MRKey) +// require.Equal(t, sdk.ZeroDec(), rval) + +// // Case 5. Sum up to 6 +// input.Ctx = input.Ctx.WithBlockHeight(core.BlocksPerEpoch * 5) +// rval = input.TreasuryKeeper.sumIndicator(input.Ctx, 6, types.MRKey) +// require.Equal(t, sdk.NewDec(2100), rval) +// } + +// func TestRollingAverageIndicator(t *testing.T) { +// input := CreateTestInput(t) +// MRArr := []sdk.Dec{ +// sdk.NewDec(100), +// sdk.NewDec(200), +// sdk.NewDec(300), +// sdk.NewDec(400), +// } + +// for epoch, MR := range MRArr { +// input.TreasuryKeeper.SetMR(input.Ctx, int64(epoch), MR) +// } + +// // Case 1: at epoch 0 and averaging over 0 epochs +// rval := input.TreasuryKeeper.rollingAverageIndicator(input.Ctx, 0, types.MRKey) +// require.Equal(t, sdk.ZeroDec(), rval) + +// // Case 2: at epoch 0 and averaging over negative epochs +// rval = input.TreasuryKeeper.rollingAverageIndicator(input.Ctx, -1, types.MRKey) +// require.Equal(t, sdk.ZeroDec(), rval) + +// // Case 3: at epoch 3 and averaging over 3, 4, 5 epochs; all should have the same rval +// input.Ctx = input.Ctx.WithBlockHeight(core.BlocksPerEpoch * 3) +// rval = input.TreasuryKeeper.rollingAverageIndicator(input.Ctx, 4, types.MRKey) +// rval2 := input.TreasuryKeeper.rollingAverageIndicator(input.Ctx, 5, types.MRKey) +// rval3 := input.TreasuryKeeper.rollingAverageIndicator(input.Ctx, 6, types.MRKey) +// require.Equal(t, sdk.NewDec(250), rval) +// require.Equal(t, rval, rval2) +// require.Equal(t, rval2, rval3) + +// // Case 4: at epoch 3 and averaging over 0 epochs +// rval = input.TreasuryKeeper.rollingAverageIndicator(input.Ctx, 0, types.MRKey) +// require.Equal(t, sdk.ZeroDec(), rval) + +// // Case 5: at epoch 3 and averaging over 1 epoch +// rval = input.TreasuryKeeper.rollingAverageIndicator(input.Ctx, 1, types.MRKey) +// require.Equal(t, sdk.NewDec(400), rval) +// } diff --git a/x/treasury/internal/keeper/keeper.go b/x/treasury/internal/keeper/keeper.go index 62893a17c..b73a225ab 100644 --- a/x/treasury/internal/keeper/keeper.go +++ b/x/treasury/internal/keeper/keeper.go @@ -62,9 +62,9 @@ func (k Keeper) Codespace() sdk.CodespaceType { } // GetTaxRate loads the tax rate -func (k Keeper) GetTaxRate(ctx sdk.Context, epoch int64) (taxRate sdk.Dec) { +func (k Keeper) GetTaxRate(ctx sdk.Context) (taxRate sdk.Dec) { store := ctx.KVStore(k.storeKey) - b := store.Get(types.GetTaxRateKey(epoch)) + b := store.Get(types.TaxRateKey) if b == nil { return types.DefaultTaxRate } @@ -74,26 +74,16 @@ func (k Keeper) GetTaxRate(ctx sdk.Context, epoch int64) (taxRate sdk.Dec) { } // SetTaxRate sets the tax rate -func (k Keeper) SetTaxRate(ctx sdk.Context, epoch int64, taxRate sdk.Dec) { +func (k Keeper) SetTaxRate(ctx sdk.Context, taxRate sdk.Dec) { store := ctx.KVStore(k.storeKey) b := k.cdc.MustMarshalBinaryLengthPrefixed(taxRate) - store.Set(types.GetTaxRateKey(epoch), b) -} - -// ClearTaxRates clears all tax rate -func (k Keeper) ClearTaxRates(ctx sdk.Context) { - store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, types.TaxRateKey) - defer iter.Close() - for ; iter.Valid(); iter.Next() { - store.Delete(iter.Key()) - } + store.Set(types.TaxRateKey, b) } // GetRewardWeight loads the reward weight -func (k Keeper) GetRewardWeight(ctx sdk.Context, epoch int64) (rewardWeight sdk.Dec) { +func (k Keeper) GetRewardWeight(ctx sdk.Context) (rewardWeight sdk.Dec) { store := ctx.KVStore(k.storeKey) - b := store.Get(types.GetRewardWeightKey(epoch)) + b := store.Get(types.RewardWeightKey) if b == nil { return types.DefaultRewardWeight } @@ -103,20 +93,10 @@ func (k Keeper) GetRewardWeight(ctx sdk.Context, epoch int64) (rewardWeight sdk. } // SetRewardWeight sets the reward weight -func (k Keeper) SetRewardWeight(ctx sdk.Context, epoch int64, rewardWeight sdk.Dec) { +func (k Keeper) SetRewardWeight(ctx sdk.Context, rewardWeight sdk.Dec) { store := ctx.KVStore(k.storeKey) b := k.cdc.MustMarshalBinaryLengthPrefixed(rewardWeight) - store.Set(types.GetRewardWeightKey(epoch), b) -} - -// ClearRewardWeights clears all reward weight -func (k Keeper) ClearRewardWeights(ctx sdk.Context) { - store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, types.RewardWeightKey) - defer iter.Close() - for ; iter.Valid(); iter.Next() { - store.Delete(iter.Key()) - } + store.Set(types.RewardWeightKey, b) } // SetTaxCap sets the tax cap denominated in integer units of the reference {denom} @@ -159,34 +139,34 @@ func (k Keeper) IterateTaxCap(ctx sdk.Context, handler func(denom string, taxCap return } -// RecordTaxProceeds adds tax proceeds that have been added this epoch -func (k Keeper) RecordTaxProceeds(ctx sdk.Context, delta sdk.Coins) { +// RecordEpochTaxProceeds adds tax proceeds that have been added this epoch +func (k Keeper) RecordEpochTaxProceeds(ctx sdk.Context, delta sdk.Coins) { if delta.Empty() || delta.IsZero() { return } - epoch := core.GetEpoch(ctx) - proceeds := k.PeekTaxProceeds(ctx, epoch) + proceeds := k.PeekEpochTaxProceeds(ctx) proceeds = proceeds.Add(delta) - k.SetTaxProceeds(ctx, epoch, proceeds) + k.SetEpochTaxProceeds(ctx, proceeds) } -// SetTaxProceeds stores tax proceeds for the given epoch -func (k Keeper) SetTaxProceeds(ctx sdk.Context, epoch int64, taxProceeds sdk.Coins) { +// SetEpochTaxProceeds stores tax proceeds for the given epoch +func (k Keeper) SetEpochTaxProceeds(ctx sdk.Context, taxProceeds sdk.Coins) { + store := ctx.KVStore(k.storeKey) + if taxProceeds.Empty() || taxProceeds.IsZero() { - return + store.Delete(types.TaxProceedsKey) + } else { + bz := k.cdc.MustMarshalBinaryLengthPrefixed(taxProceeds) + store.Set(types.TaxProceedsKey, bz) } - - store := ctx.KVStore(k.storeKey) - bz := k.cdc.MustMarshalBinaryLengthPrefixed(taxProceeds) - store.Set(types.GetTaxProceedsKey(epoch), bz) } -// PeekTaxProceeds peeks the total amount of taxes that have been collected in the given epoch. -func (k Keeper) PeekTaxProceeds(ctx sdk.Context, epoch int64) (res sdk.Coins) { +// PeekEpochTaxProceeds peeks the total amount of taxes that have been collected in the given epoch. +func (k Keeper) PeekEpochTaxProceeds(ctx sdk.Context) (res sdk.Coins) { store := ctx.KVStore(k.storeKey) - bz := store.Get(types.GetTaxProceedsKey(epoch)) + bz := store.Get(types.TaxProceedsKey) if bz == nil { res = sdk.Coins{} } else { @@ -195,76 +175,145 @@ func (k Keeper) PeekTaxProceeds(ctx sdk.Context, epoch int64) (res sdk.Coins) { return } -// ClearTaxProceeds clears all tax proceeds -func (k Keeper) ClearTaxProceeds(ctx sdk.Context) { - store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, types.TaxProceedsKey) - defer iter.Close() - for ; iter.Valid(); iter.Next() { - store.Delete(iter.Key()) - } -} - -// RecordHistoricalIssuance updates epoch issuance from supply keeper (historical) -func (k Keeper) RecordHistoricalIssuance(ctx sdk.Context) { - epoch := core.GetEpoch(ctx) +// RecordEpochInitialIssuance updates epoch initial issuance from supply keeper +func (k Keeper) RecordEpochInitialIssuance(ctx sdk.Context) { totalCoins := k.supplyKeeper.GetSupply(ctx).GetTotal() - k.SetHistoricalIssuance(ctx, epoch, totalCoins) + k.SetEpochInitialIssuance(ctx, totalCoins) } -// SetHistoricalIssuance stores epoch issuance -func (k Keeper) SetHistoricalIssuance(ctx sdk.Context, epoch int64, issuance sdk.Coins) { +// SetEpochInitialIssuance stores epoch initial issuance +func (k Keeper) SetEpochInitialIssuance(ctx sdk.Context, issuance sdk.Coins) { + store := ctx.KVStore(k.storeKey) + if issuance.Empty() || issuance.IsZero() { - return + store.Delete(types.EpochInitialIssuanceKey) + } else { + bz := k.cdc.MustMarshalBinaryLengthPrefixed(issuance) + store.Set(types.EpochInitialIssuanceKey, bz) } +} +// GetEpochInitialIssuance returns epoch initial issuance +func (k Keeper) GetEpochInitialIssuance(ctx sdk.Context) (res sdk.Coins) { store := ctx.KVStore(k.storeKey) + bz := store.Get(types.EpochInitialIssuanceKey) - bz := k.cdc.MustMarshalBinaryLengthPrefixed(issuance) - store.Set(types.GetHistoricalIssuanceKey(epoch), bz) + if bz == nil { + res = sdk.Coins{} + } else { + k.cdc.MustUnmarshalBinaryLengthPrefixed(bz, &res) + } return } -// GetHistoricalIssuance returns epoch issuance -func (k Keeper) GetHistoricalIssuance(ctx sdk.Context, epoch int64) (res sdk.Coins) { +// PeekEpochSeigniorage returns epoch seigniorage +func (k Keeper) PeekEpochSeigniorage(ctx sdk.Context) sdk.Int { + epochIssuance := k.supplyKeeper.GetSupply(ctx).GetTotal().AmountOf(core.MicroLunaDenom) + preEpochIssuance := k.GetEpochInitialIssuance(ctx).AmountOf(core.MicroLunaDenom) + epochSeigniorage := preEpochIssuance.Sub(epochIssuance) + + if epochSeigniorage.LT(sdk.ZeroInt()) { + return sdk.ZeroInt() + } + + return epochSeigniorage +} + +// GetTR returns the tax rewards for the epoch +func (k Keeper) GetTR(ctx sdk.Context, epoch int64) (res sdk.Dec) { store := ctx.KVStore(k.storeKey) - bz := store.Get(types.GetHistoricalIssuanceKey(epoch)) + bz := store.Get(types.GetTRKey(epoch)) if bz == nil { - res = sdk.Coins{} + res = sdk.ZeroDec() } else { k.cdc.MustUnmarshalBinaryLengthPrefixed(bz, &res) } + return } -// ClearHistoricalIssuance clears all historical issuance -func (k Keeper) ClearHistoricalIssuance(ctx sdk.Context) { +// SetTR stores the tax rewards for the epoch +func (k Keeper) SetTR(ctx sdk.Context, epoch int64, TR sdk.Dec) { + store := ctx.KVStore(k.storeKey) + + bz := k.cdc.MustMarshalBinaryLengthPrefixed(TR) + store.Set(types.GetTRKey(epoch), bz) +} + +// ClearTRs delete all tax rewards from the store +func (k Keeper) ClearTRs(ctx sdk.Context) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, types.HistoricalIssuanceKey) + + iter := sdk.KVStorePrefixIterator(store, types.TRKey) defer iter.Close() for ; iter.Valid(); iter.Next() { store.Delete(iter.Key()) } } -// PeekEpochSeigniorage returns epoch seigniorage -func (k Keeper) PeekEpochSeigniorage(ctx sdk.Context, epoch int64) sdk.Int { - if epoch == 0 { - return sdk.ZeroInt() +// GetSR returns the seigniorage rewards for the epoch +func (k Keeper) GetSR(ctx sdk.Context, epoch int64) (res sdk.Dec) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.GetSRKey(epoch)) + + if bz == nil { + res = sdk.ZeroDec() + } else { + k.cdc.MustUnmarshalBinaryLengthPrefixed(bz, &res) } - epochIssuance := k.GetHistoricalIssuance(ctx, epoch).AmountOf(core.MicroLunaDenom) - if epochIssuance.IsZero() { - epochIssuance = k.supplyKeeper.GetSupply(ctx).GetTotal().AmountOf(core.MicroLunaDenom) + return +} + +// SetSR stores the seigniorage rewards for the epoch +func (k Keeper) SetSR(ctx sdk.Context, epoch int64, SR sdk.Dec) { + store := ctx.KVStore(k.storeKey) + + bz := k.cdc.MustMarshalBinaryLengthPrefixed(SR) + store.Set(types.GetSRKey(epoch), bz) +} + +// ClearSRs delete all seigniorage rewards from the store +func (k Keeper) ClearSRs(ctx sdk.Context) { + store := ctx.KVStore(k.storeKey) + + iter := sdk.KVStorePrefixIterator(store, types.SRKey) + defer iter.Close() + for ; iter.Valid(); iter.Next() { + store.Delete(iter.Key()) } +} - preEpochIssuance := k.GetHistoricalIssuance(ctx, epoch-1).AmountOf(core.MicroLunaDenom) - epochSeigniorage := preEpochIssuance.Sub(epochIssuance) +// GetTSL returns the total saked luna for the epoch +func (k Keeper) GetTSL(ctx sdk.Context, epoch int64) (res sdk.Int) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.GetTSLKey(epoch)) - if epochSeigniorage.LT(sdk.ZeroInt()) { - return sdk.ZeroInt() + if bz == nil { + res = sdk.ZeroInt() + } else { + k.cdc.MustUnmarshalBinaryLengthPrefixed(bz, &res) } - return epochSeigniorage + return +} + +// SetTSL stores the total saked luna for the epoch +func (k Keeper) SetTSL(ctx sdk.Context, epoch int64, TSL sdk.Int) { + store := ctx.KVStore(k.storeKey) + + bz := k.cdc.MustMarshalBinaryLengthPrefixed(TSL) + store.Set(types.GetTSLKey(epoch), bz) +} + +// ClearTSLs delete all the total saked luna from the store +func (k Keeper) ClearTSLs(ctx sdk.Context) { + store := ctx.KVStore(k.storeKey) + + iter := sdk.KVStorePrefixIterator(store, types.TSLKey) + defer iter.Close() + for ; iter.Valid(); iter.Next() { + store.Delete(iter.Key()) + } } diff --git a/x/treasury/internal/keeper/keeper_test.go b/x/treasury/internal/keeper/keeper_test.go index e080b4811..8ae072036 100644 --- a/x/treasury/internal/keeper/keeper_test.go +++ b/x/treasury/internal/keeper/keeper_test.go @@ -17,15 +17,9 @@ func TestRewardWeight(t *testing.T) { // See that we can get and set reward weights for i := int64(0); i < 10; i++ { - input.TreasuryKeeper.SetRewardWeight(input.Ctx, i, sdk.NewDecWithPrec(i, 2)) + input.TreasuryKeeper.SetRewardWeight(input.Ctx, sdk.NewDecWithPrec(i, 2)) + require.Equal(t, sdk.NewDecWithPrec(i, 2), input.TreasuryKeeper.GetRewardWeight(input.Ctx)) } - - for i := int64(0); i < 10; i++ { - require.Equal(t, sdk.NewDecWithPrec(i, 2), input.TreasuryKeeper.GetRewardWeight(input.Ctx, i)) - } - - input.TreasuryKeeper.ClearRewardWeights(input.Ctx) - require.Equal(t, types.DefaultRewardWeight, input.TreasuryKeeper.GetRewardWeight(input.Ctx, int64(0))) } func TestTaxRate(t *testing.T) { @@ -33,15 +27,9 @@ func TestTaxRate(t *testing.T) { // See that we can get and set tax rate for i := int64(0); i < 10; i++ { - input.TreasuryKeeper.SetTaxRate(input.Ctx, i, sdk.NewDecWithPrec(i, 2)) - } - - for i := int64(0); i < 10; i++ { - require.Equal(t, sdk.NewDecWithPrec(i, 2), input.TreasuryKeeper.GetTaxRate(input.Ctx, i)) + input.TreasuryKeeper.SetTaxRate(input.Ctx, sdk.NewDecWithPrec(i, 2)) + require.Equal(t, sdk.NewDecWithPrec(i, 2), input.TreasuryKeeper.GetTaxRate(input.Ctx)) } - - input.TreasuryKeeper.ClearTaxRates(input.Ctx) - require.Equal(t, types.DefaultTaxRate, input.TreasuryKeeper.GetTaxRate(input.Ctx, int64(0))) } func TestTaxCap(t *testing.T) { @@ -82,23 +70,16 @@ func TestTaxProceeds(t *testing.T) { input := CreateTestInput(t) for i := int64(0); i < 10; i++ { - input.Ctx = input.Ctx.WithBlockHeight(i * core.BlocksPerEpoch) + proceeds := sdk.NewCoins(sdk.NewCoin(core.MicroSDRDenom, sdk.NewInt(100+i))) + input.TreasuryKeeper.RecordEpochTaxProceeds(input.Ctx, proceeds) + input.TreasuryKeeper.RecordEpochTaxProceeds(input.Ctx, proceeds) + input.TreasuryKeeper.RecordEpochTaxProceeds(input.Ctx, proceeds) - proceeds := sdk.NewCoins(sdk.NewCoin(core.MicroSDRDenom, sdk.NewInt(i))) - input.TreasuryKeeper.RecordTaxProceeds(input.Ctx, proceeds) - input.TreasuryKeeper.RecordTaxProceeds(input.Ctx, proceeds) - input.TreasuryKeeper.RecordTaxProceeds(input.Ctx, proceeds) - } + require.Equal(t, proceeds.Add(proceeds).Add(proceeds), input.TreasuryKeeper.PeekEpochTaxProceeds(input.Ctx)) - for i := int64(0); i < 10; i++ { - input.Ctx = input.Ctx.WithBlockHeight(i * core.BlocksPerEpoch) - proceeds := sdk.NewCoins(sdk.NewCoin(core.MicroSDRDenom, sdk.NewInt(i*3))) - - require.Equal(t, proceeds, input.TreasuryKeeper.PeekTaxProceeds(input.Ctx, i)) + input.TreasuryKeeper.SetEpochTaxProceeds(input.Ctx, sdk.Coins{}) + require.Equal(t, sdk.Coins{}, input.TreasuryKeeper.PeekEpochTaxProceeds(input.Ctx)) } - - input.TreasuryKeeper.ClearTaxProceeds(input.Ctx) - require.Equal(t, sdk.Coins{}, input.TreasuryKeeper.PeekTaxProceeds(input.Ctx, 0)) } func TestMicroLunaIssuance(t *testing.T) { @@ -115,17 +96,10 @@ func TestMicroLunaIssuance(t *testing.T) { supply = supply.SetTotal(sdk.NewCoins(sdk.NewCoin(core.MicroLunaDenom, sdk.NewInt(i)))) input.SupplyKeeper.SetSupply(input.Ctx, supply) - input.TreasuryKeeper.RecordHistoricalIssuance(input.Ctx) - } - - for i := int64(0); i < 10; i++ { - input.Ctx = input.Ctx.WithBlockHeight(i * blocksPerEpoch) + input.TreasuryKeeper.RecordEpochInitialIssuance(input.Ctx) - require.Equal(t, sdk.NewInt(i), input.TreasuryKeeper.GetHistoricalIssuance(input.Ctx, i).AmountOf(core.MicroLunaDenom)) + require.Equal(t, sdk.NewInt(i), input.TreasuryKeeper.GetEpochInitialIssuance(input.Ctx).AmountOf(core.MicroLunaDenom)) } - - input.TreasuryKeeper.ClearHistoricalIssuance(input.Ctx) - require.Equal(t, sdk.Coins{}, input.TreasuryKeeper.GetHistoricalIssuance(input.Ctx, 0)) } func TestPeekEpochSeigniorage(t *testing.T) { @@ -138,7 +112,7 @@ func TestPeekEpochSeigniorage(t *testing.T) { preIssuance := sdk.NewInt(rand.Int63() + 1) supply = supply.SetTotal(sdk.NewCoins(sdk.NewCoin(core.MicroLunaDenom, preIssuance))) input.SupplyKeeper.SetSupply(input.Ctx, supply) - input.TreasuryKeeper.RecordHistoricalIssuance(input.Ctx) + input.TreasuryKeeper.RecordEpochInitialIssuance(input.Ctx) nowIssuance := sdk.NewInt(rand.Int63() + 1) supply = supply.SetTotal(sdk.NewCoins(sdk.NewCoin(core.MicroLunaDenom, nowIssuance))) @@ -149,7 +123,31 @@ func TestPeekEpochSeigniorage(t *testing.T) { targetSeigniorage = sdk.ZeroInt() } - require.Equal(t, targetSeigniorage, input.TreasuryKeeper.PeekEpochSeigniorage(input.Ctx, i+1)) + require.Equal(t, targetSeigniorage, input.TreasuryKeeper.PeekEpochSeigniorage(input.Ctx)) + } +} + +func TestIndicatorGetterSetter(t *testing.T) { + input := CreateTestInput(t) + + for e := int64(0); e < 10; e++ { + randomVal := sdk.NewDec(rand.Int63() + 1) + input.TreasuryKeeper.SetTR(input.Ctx, e, randomVal) + require.Equal(t, randomVal, input.TreasuryKeeper.GetTR(input.Ctx, e)) + input.TreasuryKeeper.SetSR(input.Ctx, e, randomVal) + require.Equal(t, randomVal, input.TreasuryKeeper.GetSR(input.Ctx, e)) + input.TreasuryKeeper.SetTSL(input.Ctx, e, randomVal.TruncateInt()) + require.Equal(t, randomVal.TruncateInt(), input.TreasuryKeeper.GetTSL(input.Ctx, e)) + } + + input.TreasuryKeeper.ClearTRs(input.Ctx) + input.TreasuryKeeper.ClearSRs(input.Ctx) + input.TreasuryKeeper.ClearTSLs(input.Ctx) + + for e := int64(0); e < 10; e++ { + require.Equal(t, sdk.ZeroDec(), input.TreasuryKeeper.GetTR(input.Ctx, e)) + require.Equal(t, sdk.ZeroDec(), input.TreasuryKeeper.GetSR(input.Ctx, e)) + require.Equal(t, sdk.ZeroInt(), input.TreasuryKeeper.GetTSL(input.Ctx, e)) } } diff --git a/x/treasury/internal/keeper/policy.go b/x/treasury/internal/keeper/policy.go index 3679d189e..68af530e6 100644 --- a/x/treasury/internal/keeper/policy.go +++ b/x/treasury/internal/keeper/policy.go @@ -33,10 +33,10 @@ func (k Keeper) UpdateTaxCap(ctx sdk.Context) sdk.Coins { func (k Keeper) UpdateTaxPolicy(ctx sdk.Context) (newTaxRate sdk.Dec) { params := k.GetParams(ctx) - oldTaxRate := k.GetTaxRate(ctx, core.GetEpoch(ctx)) + oldTaxRate := k.GetTaxRate(ctx) inc := params.MiningIncrement - tlYear := RollingAverageIndicator(ctx, k, params.WindowLong, TRL) - tlMonth := RollingAverageIndicator(ctx, k, params.WindowShort, TRL) + tlYear := k.rollingAverageIndicator(ctx, params.WindowLong, TRL) + tlMonth := k.rollingAverageIndicator(ctx, params.WindowShort, TRL) // No revenues, hike as much as possible. if tlMonth.Equal(sdk.ZeroDec()) { @@ -48,7 +48,7 @@ func (k Keeper) UpdateTaxPolicy(ctx sdk.Context) (newTaxRate sdk.Dec) { newTaxRate = params.TaxPolicy.Clamp(oldTaxRate, newTaxRate) // Set the new tax rate to the store - k.SetTaxRate(ctx, core.GetEpoch(ctx)+1, newTaxRate) + k.SetTaxRate(ctx, newTaxRate) return } @@ -56,12 +56,11 @@ func (k Keeper) UpdateTaxPolicy(ctx sdk.Context) (newTaxRate sdk.Dec) { func (k Keeper) UpdateRewardPolicy(ctx sdk.Context) (newRewardWeight sdk.Dec) { params := k.GetParams(ctx) - curEpoch := core.GetEpoch(ctx) - oldWeight := k.GetRewardWeight(ctx, curEpoch) + oldWeight := k.GetRewardWeight(ctx) sbTarget := params.SeigniorageBurdenTarget - seigniorageSum := SumIndicator(ctx, k, params.WindowShort, SeigniorageRewardsForEpoch) - totalSum := SumIndicator(ctx, k, params.WindowShort, MiningRewardForEpoch) + seigniorageSum := k.sumIndicator(ctx, params.WindowShort, SR) + totalSum := k.sumIndicator(ctx, params.WindowShort, MR) // No revenues; hike as much as possible if totalSum.Equal(sdk.ZeroDec()) || seigniorageSum.Equal(sdk.ZeroDec()) { @@ -75,6 +74,6 @@ func (k Keeper) UpdateRewardPolicy(ctx sdk.Context) (newRewardWeight sdk.Dec) { newRewardWeight = params.RewardPolicy.Clamp(oldWeight, newRewardWeight) // Set the new reward weight - k.SetRewardWeight(ctx, core.GetEpoch(ctx)+1, newRewardWeight) + k.SetRewardWeight(ctx, newRewardWeight) return } diff --git a/x/treasury/internal/keeper/policy_test.go b/x/treasury/internal/keeper/policy_test.go index 8662f0a55..dc152c4b8 100644 --- a/x/treasury/internal/keeper/policy_test.go +++ b/x/treasury/internal/keeper/policy_test.go @@ -34,16 +34,18 @@ func TestUpdateTaxRate(t *testing.T) { input.Ctx = input.Ctx.WithBlockHeight(i * core.BlocksPerEpoch) taxProceeds := sdk.NewCoins(sdk.NewCoin(core.MicroSDRDenom, sdk.ZeroInt())) - input.TreasuryKeeper.RecordTaxProceeds(input.Ctx, taxProceeds) + input.TreasuryKeeper.RecordEpochTaxProceeds(input.Ctx, taxProceeds) + input.TreasuryKeeper.UpdateIndicators(input.Ctx) } input.TreasuryKeeper.UpdateTaxPolicy(input.Ctx) - taxRate := input.TreasuryKeeper.GetTaxRate(input.Ctx, core.GetEpoch(input.Ctx)+1) + taxRate := input.TreasuryKeeper.GetTaxRate(input.Ctx) require.Equal(t, types.DefaultTaxRate.Add(taxPolicy.ChangeRateMax), taxRate) } func TestUpdateRewardWeight(t *testing.T) { input := CreateTestInput(t) + input.OracleKeeper.SetLunaPrice(input.Ctx, core.MicroSDRDenom, sdk.OneDec()) sh := staking.NewHandler(input.StakingKeeper) // Create Validators @@ -56,10 +58,20 @@ func TestUpdateRewardWeight(t *testing.T) { require.True(t, res.IsOK()) staking.EndBlocker(input.Ctx, input.StakingKeeper) + input.TreasuryKeeper.UpdateIndicators(input.Ctx) + + // Case 1: zero seigniorage will increase reward weight as much as possible rewardPolicy := input.TreasuryKeeper.RewardPolicy(input.Ctx) input.TreasuryKeeper.UpdateRewardPolicy(input.Ctx) - rewardWeight := input.TreasuryKeeper.GetRewardWeight(input.Ctx, core.GetEpoch(input.Ctx)+1) + rewardWeight := input.TreasuryKeeper.GetRewardWeight(input.Ctx) require.Equal(t, types.DefaultRewardWeight.Add(rewardPolicy.ChangeRateMax), rewardWeight) + + // Case 2: huge seigniorage rewards will decrease reward weight by %types.DefaultSeigniorageBurdenTarget + input.TreasuryKeeper.SetEpochInitialIssuance(input.Ctx, sdk.NewCoins(sdk.NewCoin(core.MicroLunaDenom, sdk.NewInt(1000000000000)))) + input.TreasuryKeeper.UpdateIndicators(input.Ctx) + input.TreasuryKeeper.UpdateRewardPolicy(input.Ctx) + rewardWeight = input.TreasuryKeeper.GetRewardWeight(input.Ctx) + require.Equal(t, types.DefaultRewardWeight.Add(rewardPolicy.ChangeRateMax).Mul(types.DefaultSeigniorageBurdenTarget), rewardWeight) } func TestUpdateTaxCap(t *testing.T) { diff --git a/x/treasury/internal/keeper/querier.go b/x/treasury/internal/keeper/querier.go index f153fae24..7c8573c65 100644 --- a/x/treasury/internal/keeper/querier.go +++ b/x/treasury/internal/keeper/querier.go @@ -13,20 +13,16 @@ import ( func NewQuerier(keeper Keeper) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) (res []byte, err sdk.Error) { switch path[0] { - case types.QueryCurrentEpoch: - return queryCurrentEpoch(ctx, keeper) case types.QueryTaxRate: - return queryTaxRate(ctx, req, keeper) + return queryTaxRate(ctx, keeper) case types.QueryTaxCap: return queryTaxCap(ctx, req, keeper) case types.QueryRewardWeight: - return queryRewardWeight(ctx, req, keeper) + return queryRewardWeight(ctx, keeper) case types.QuerySeigniorageProceeds: - return querySeigniorageProceeds(ctx, req, keeper) + return querySeigniorageProceeds(ctx, keeper) case types.QueryTaxProceeds: - return queryTaxProceeds(ctx, req, keeper) - case types.QueryHistoricalIssuance: - return queryHistoricalIssuance(ctx, req, keeper) + return queryTaxProceeds(ctx, keeper) case types.QueryParameters: return queryParameters(ctx, keeper) default: @@ -44,19 +40,8 @@ func queryCurrentEpoch(ctx sdk.Context, keeper Keeper) ([]byte, sdk.Error) { return bz, nil } -func queryTaxRate(ctx sdk.Context, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { - var params types.QueryTaxRateParams - err := keeper.cdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) - } - - curEpoch := core.GetEpoch(ctx) - if 0 > params.Epoch || curEpoch < params.Epoch { - return nil, types.ErrInvalidEpoch(types.DefaultCodespace, curEpoch, params.Epoch) - } - - taxRate := keeper.GetTaxRate(ctx, params.Epoch) +func queryTaxRate(ctx sdk.Context, keeper Keeper) ([]byte, sdk.Error) { + taxRate := keeper.GetTaxRate(ctx) bz, err := codec.MarshalJSONIndent(keeper.cdc, taxRate) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err.Error())) @@ -81,19 +66,8 @@ func queryTaxCap(ctx sdk.Context, req abci.RequestQuery, keeper Keeper) ([]byte, return bz, nil } -func queryRewardWeight(ctx sdk.Context, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { - var params types.QueryRewardWeightParams - err := keeper.cdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) - } - - curEpoch := core.GetEpoch(ctx) - if 0 > params.Epoch || curEpoch < params.Epoch { - return nil, types.ErrInvalidEpoch(types.DefaultCodespace, curEpoch, params.Epoch) - } - - taxRate := keeper.GetRewardWeight(ctx, params.Epoch) +func queryRewardWeight(ctx sdk.Context, keeper Keeper) ([]byte, sdk.Error) { + taxRate := keeper.GetRewardWeight(ctx) bz, err := codec.MarshalJSONIndent(keeper.cdc, taxRate) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err.Error())) @@ -102,19 +76,8 @@ func queryRewardWeight(ctx sdk.Context, req abci.RequestQuery, keeper Keeper) ([ return bz, nil } -func querySeigniorageProceeds(ctx sdk.Context, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { - var params types.QuerySeigniorageProceedsParams - err := keeper.cdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) - } - - curEpoch := core.GetEpoch(ctx) - if 0 > params.Epoch || curEpoch < params.Epoch { - return nil, types.ErrInvalidEpoch(types.DefaultCodespace, curEpoch, params.Epoch) - } - - seigniorage := keeper.PeekEpochSeigniorage(ctx, params.Epoch) +func querySeigniorageProceeds(ctx sdk.Context, keeper Keeper) ([]byte, sdk.Error) { + seigniorage := keeper.PeekEpochSeigniorage(ctx) bz, err := codec.MarshalJSONIndent(keeper.cdc, seigniorage) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err.Error())) @@ -122,19 +85,8 @@ func querySeigniorageProceeds(ctx sdk.Context, req abci.RequestQuery, keeper Kee return bz, nil } -func queryTaxProceeds(ctx sdk.Context, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { - var params types.QueryTaxProceedsParams - err := keeper.cdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) - } - - curEpoch := core.GetEpoch(ctx) - if 0 > params.Epoch || curEpoch < params.Epoch { - return nil, types.ErrInvalidEpoch(types.DefaultCodespace, curEpoch, params.Epoch) - } - - proceeds := keeper.PeekTaxProceeds(ctx, params.Epoch) +func queryTaxProceeds(ctx sdk.Context, keeper Keeper) ([]byte, sdk.Error) { + proceeds := keeper.PeekEpochTaxProceeds(ctx) bz, err := codec.MarshalJSONIndent(keeper.cdc, proceeds) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err.Error())) @@ -142,27 +94,6 @@ func queryTaxProceeds(ctx sdk.Context, req abci.RequestQuery, keeper Keeper) ([] return bz, nil } -func queryHistoricalIssuance(ctx sdk.Context, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { - var params types.QueryHistoricalIssuanceParams - err := keeper.cdc.UnmarshalJSON(req.Data, ¶ms) - if err != nil { - return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) - } - - curEpoch := core.GetEpoch(ctx) - if 0 > params.Epoch || curEpoch < params.Epoch { - return nil, types.ErrInvalidEpoch(types.DefaultCodespace, curEpoch, params.Epoch) - } - - issuance := keeper.GetHistoricalIssuance(ctx, params.Epoch) - bz, err := codec.MarshalJSONIndent(keeper.cdc, issuance) - if err != nil { - return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err.Error())) - } - - return bz, nil -} - func queryParameters(ctx sdk.Context, keeper Keeper) ([]byte, sdk.Error) { bz, err := codec.MarshalJSONIndent(keeper.cdc, keeper.GetParams(ctx)) if err != nil { diff --git a/x/treasury/internal/keeper/querier_test.go b/x/treasury/internal/keeper/querier_test.go index ad8f072cb..579c59cee 100644 --- a/x/treasury/internal/keeper/querier_test.go +++ b/x/treasury/internal/keeper/querier_test.go @@ -17,19 +17,12 @@ import ( const custom = "custom" func getQueriedTaxRate(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, epoch int64) sdk.Dec { - params := types.QueryTaxRateParams{ - Epoch: epoch, - } - - bz, err := cdc.MarshalJSON(params) - require.NoError(t, err) - query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryTaxRate}, "/"), - Data: bz, + Data: nil, } - bz, err = querier(ctx, []string{types.QueryTaxRate}, query) + bz, err := querier(ctx, []string{types.QueryTaxRate}, query) require.Nil(t, err) require.NotNil(t, bz) @@ -65,19 +58,12 @@ func getQueriedTaxCap(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier s } func getQueriedRewardWeight(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, epoch int64) sdk.Dec { - params := types.QueryRewardWeightParams{ - Epoch: epoch, - } - - bz, err := cdc.MarshalJSON(params) - require.NoError(t, err) - query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryRewardWeight}, "/"), - Data: bz, + Data: nil, } - bz, err = querier(ctx, []string{types.QueryRewardWeight}, query) + bz, err := querier(ctx, []string{types.QueryRewardWeight}, query) require.Nil(t, err) require.NotNil(t, bz) @@ -89,19 +75,12 @@ func getQueriedRewardWeight(t *testing.T, ctx sdk.Context, cdc *codec.Codec, que } func getQueriedTaxProceeds(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, epoch int64) sdk.Coins { - params := types.QueryTaxProceedsParams{ - Epoch: epoch, - } - - bz, err := cdc.MarshalJSON(params) - require.NoError(t, err) - query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryTaxProceeds}, "/"), - Data: bz, + Data: nil, } - bz, err = querier(ctx, []string{types.QueryTaxProceeds}, query) + bz, err := querier(ctx, []string{types.QueryTaxProceeds}, query) require.Nil(t, err) require.NotNil(t, bz) @@ -113,19 +92,12 @@ func getQueriedTaxProceeds(t *testing.T, ctx sdk.Context, cdc *codec.Codec, quer } func getQueriedSeigniorageProceeds(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, epoch int64) sdk.Int { - params := types.QuerySeigniorageProceedsParams{ - Epoch: epoch, - } - - bz, err := cdc.MarshalJSON(params) - require.NoError(t, err) - query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QuerySeigniorageProceeds}, "/"), - Data: bz, + Data: nil, } - bz, err = querier(ctx, []string{types.QuerySeigniorageProceeds}, query) + bz, err := querier(ctx, []string{types.QuerySeigniorageProceeds}, query) require.Nil(t, err) require.NotNil(t, bz) @@ -136,47 +108,6 @@ func getQueriedSeigniorageProceeds(t *testing.T, ctx sdk.Context, cdc *codec.Cod return response } -func getQueriedCurrentEpoch(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier) int64 { - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryCurrentEpoch}, "/"), - Data: []byte{}, - } - - bz, err := querier(ctx, []string{types.QueryCurrentEpoch}, query) - require.Nil(t, err) - require.NotNil(t, bz) - - var response int64 - err2 := cdc.UnmarshalJSON(bz, &response) - require.Nil(t, err2) - - return response -} - -func getQueriedHistoricalIssuance(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, epoch int64) sdk.Coins { - params := types.QueryHistoricalIssuanceParams{ - Epoch: epoch, - } - - bz, err := cdc.MarshalJSON(params) - require.NoError(t, err) - - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryHistoricalIssuance}, "/"), - Data: bz, - } - - bz, err = querier(ctx, []string{types.QueryHistoricalIssuance}, query) - require.Nil(t, err) - require.NotNil(t, bz) - - var response sdk.Coins - err2 := cdc.UnmarshalJSON(bz, &response) - require.Nil(t, err2) - - return response -} - func getQueriedParameters(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier) types.Params { query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParameters}, "/"), @@ -211,7 +142,7 @@ func TestQueryRewardWeight(t *testing.T) { querier := NewQuerier(input.TreasuryKeeper) rewardWeight := sdk.NewDecWithPrec(77, 2) - input.TreasuryKeeper.SetRewardWeight(input.Ctx, core.GetEpoch(input.Ctx), rewardWeight) + input.TreasuryKeeper.SetRewardWeight(input.Ctx, rewardWeight) queriedRewardWeight := getQueriedRewardWeight(t, input.Ctx, input.Cdc, querier, core.GetEpoch(input.Ctx)) @@ -223,7 +154,7 @@ func TestQueryTaxRate(t *testing.T) { querier := NewQuerier(input.TreasuryKeeper) taxRate := sdk.NewDecWithPrec(1, 3) - input.TreasuryKeeper.SetTaxRate(input.Ctx, core.GetEpoch(input.Ctx), taxRate) + input.TreasuryKeeper.SetTaxRate(input.Ctx, taxRate) queriedTaxRate := getQueriedTaxRate(t, input.Ctx, input.Cdc, querier, core.GetEpoch(input.Ctx)) @@ -242,17 +173,6 @@ func TestQueryTaxCap(t *testing.T) { require.Equal(t, queriedTaxCap, params.TaxPolicy.Cap.Amount) } -func TestQueryCurrentEpoch(t *testing.T) { - input := CreateTestInput(t) - querier := NewQuerier(input.TreasuryKeeper) - - curEpoch := core.GetEpoch(input.Ctx) - - queriedCurEpoch := getQueriedCurrentEpoch(t, input.Ctx, input.Cdc, querier) - - require.Equal(t, queriedCurEpoch, curEpoch) -} - func TestQueryTaxProceeds(t *testing.T) { input := CreateTestInput(t) querier := NewQuerier(input.TreasuryKeeper) @@ -260,7 +180,7 @@ func TestQueryTaxProceeds(t *testing.T) { taxProceeds := sdk.Coins{ sdk.NewCoin(core.MicroSDRDenom, sdk.NewInt(1000).MulRaw(core.MicroUnit)), } - input.TreasuryKeeper.RecordTaxProceeds(input.Ctx, taxProceeds) + input.TreasuryKeeper.RecordEpochTaxProceeds(input.Ctx, taxProceeds) queriedTaxProceeds := getQueriedTaxProceeds(t, input.Ctx, input.Cdc, querier, core.GetEpoch(input.Ctx)) @@ -276,7 +196,7 @@ func TestQuerySeigniorageProceeds(t *testing.T) { supply := input.SupplyKeeper.GetSupply(input.Ctx) supply = supply.SetTotal(sdk.NewCoins(sdk.NewCoin(core.MicroLunaDenom, targetIssuance))) input.SupplyKeeper.SetSupply(input.Ctx, supply) - input.TreasuryKeeper.RecordHistoricalIssuance(input.Ctx) + input.TreasuryKeeper.RecordEpochInitialIssuance(input.Ctx) input.Ctx = input.Ctx.WithBlockHeight(core.BlocksPerEpoch) supply = supply.SetTotal(sdk.NewCoins(sdk.NewCoin(core.MicroLunaDenom, targetIssuance.Sub(targetSeigniorage)))) @@ -286,18 +206,3 @@ func TestQuerySeigniorageProceeds(t *testing.T) { require.Equal(t, targetSeigniorage, queriedSeigniorageProceeds) } - -func TestQueryHistoricalIssuance(t *testing.T) { - input := CreateTestInput(t) - querier := NewQuerier(input.TreasuryKeeper) - - targetIssuance := sdk.NewInt(1000) - supply := input.SupplyKeeper.GetSupply(input.Ctx) - supply = supply.SetTotal(sdk.NewCoins(sdk.NewCoin(core.MicroLunaDenom, targetIssuance))) - input.SupplyKeeper.SetSupply(input.Ctx, supply) - input.TreasuryKeeper.RecordHistoricalIssuance(input.Ctx) - - queriedHistoricalIssuance := getQueriedHistoricalIssuance(t, input.Ctx, input.Cdc, querier, core.GetEpoch(input.Ctx)).AmountOf(core.MicroLunaDenom) - - require.Equal(t, targetIssuance, queriedHistoricalIssuance) -} diff --git a/x/treasury/internal/keeper/seigniorage.go b/x/treasury/internal/keeper/seigniorage.go index 1474d7ddf..cc564fe2a 100644 --- a/x/treasury/internal/keeper/seigniorage.go +++ b/x/treasury/internal/keeper/seigniorage.go @@ -13,14 +13,13 @@ import ( // SettleSeigniorage computes seigniorage and distributes it to oracle and distribution(community-pool) account func (k Keeper) SettleSeigniorage(ctx sdk.Context) { // Mint seigniorage for oracle and community pool - epoch := core.GetEpoch(ctx) - seigniorageLunaAmt := k.PeekEpochSeigniorage(ctx, epoch) + seigniorageLunaAmt := k.PeekEpochSeigniorage(ctx) if seigniorageLunaAmt.LTE(sdk.ZeroInt()) { return } // Settle current epoch seigniorage - rewardWeight := k.GetRewardWeight(ctx, epoch) + rewardWeight := k.GetRewardWeight(ctx) // Align seigniorage to usdr seigniorageLunaDecCoin := sdk.NewDecCoin(core.MicroLunaDenom, seigniorageLunaAmt) diff --git a/x/treasury/internal/keeper/seigniorage_test.go b/x/treasury/internal/keeper/seigniorage_test.go index 07b19cd3d..52298200a 100644 --- a/x/treasury/internal/keeper/seigniorage_test.go +++ b/x/treasury/internal/keeper/seigniorage_test.go @@ -1,7 +1,6 @@ package keeper import ( - "fmt" "math/rand" "testing" @@ -21,22 +20,20 @@ func TestSettle(t *testing.T) { supply := input.SupplyKeeper.GetSupply(input.Ctx) supply = supply.SetTotal(sdk.NewCoins(sdk.NewCoin(core.MicroLunaDenom, issuance))) input.SupplyKeeper.SetSupply(input.Ctx, supply) - input.TreasuryKeeper.RecordHistoricalIssuance(input.Ctx) + input.TreasuryKeeper.RecordEpochInitialIssuance(input.Ctx) input.Ctx = input.Ctx.WithBlockHeight(core.BlocksPerEpoch) supply = supply.SetTotal(sdk.NewCoins(sdk.NewCoin(core.MicroLunaDenom, sdk.ZeroInt()))) input.SupplyKeeper.SetSupply(input.Ctx, supply) // check seigniorage update - require.Equal(t, issuance, input.TreasuryKeeper.PeekEpochSeigniorage(input.Ctx, 1)) + require.Equal(t, issuance, input.TreasuryKeeper.PeekEpochSeigniorage(input.Ctx)) input.TreasuryKeeper.SettleSeigniorage(input.Ctx) oracleAcc := input.SupplyKeeper.GetModuleAccount(input.Ctx, input.TreasuryKeeper.oracleModuleName) feePool := input.DistrKeeper.GetFeePool(input.Ctx) - fmt.Println(oracleAcc) - fmt.Println(feePool) - rewardWeight := input.TreasuryKeeper.GetRewardWeight(input.Ctx, 1) + rewardWeight := input.TreasuryKeeper.GetRewardWeight(input.Ctx) oracleRewardAmt := rewardWeight.MulInt(issuance).TruncateInt() leftAmt := issuance.Sub(oracleRewardAmt) diff --git a/x/treasury/internal/keeper/test_utils.go b/x/treasury/internal/keeper/test_utils.go index a880dbc3f..cd7773642 100644 --- a/x/treasury/internal/keeper/test_utils.go +++ b/x/treasury/internal/keeper/test_utils.go @@ -220,3 +220,21 @@ func NewTestMsgCreateValidator(address sdk.ValAddress, pubKey crypto.PubKey, amt staking.Description{}, commission, sdk.OneInt(), ) } + +func setupValidators(t *testing.T) (TestInput, sdk.Handler) { + input := CreateTestInput(t) + sh := staking.NewHandler(input.StakingKeeper) + + // Create Validators + amt := sdk.TokensFromConsensusPower(100) + addr, val := ValAddrs[0], PubKeys[0] + addr1, val1 := ValAddrs[1], PubKeys[1] + res := sh(input.Ctx, NewTestMsgCreateValidator(addr, val, amt)) + + require.True(t, res.IsOK()) + res = sh(input.Ctx, NewTestMsgCreateValidator(addr1, val1, amt)) + require.True(t, res.IsOK()) + staking.EndBlocker(input.Ctx, input.StakingKeeper) + + return input, sh +} diff --git a/x/treasury/internal/types/genesis.go b/x/treasury/internal/types/genesis.go index e6581a08a..9fa529290 100644 --- a/x/treasury/internal/types/genesis.go +++ b/x/treasury/internal/types/genesis.go @@ -9,57 +9,58 @@ import ( // GenesisState - all treasury state that must be provided at genesis type GenesisState struct { - Params Params `json:"params" yaml:"params"` // market params - TaxRates []sdk.Dec `json:"tax_rates" yaml:"tax_rates"` - RewardWeights []sdk.Dec `json:"reward_weights" yaml:"reward_weights"` - TaxCaps map[string]sdk.Int `json:"tax_cap" yaml:"tax_cap"` - TaxProceeds []sdk.Coins `json:"tax_proceeds" yaml:"tax_proceeds"` - HistoricalIssuances []sdk.Coins `json:"historical_issuance" yaml:"historical_issuance"` + Params Params `json:"params" yaml:"params"` // market params + TaxRate sdk.Dec `json:"tax_rate" yaml:"tax_rate"` + RewardWeight sdk.Dec `json:"reward_weight" yaml:"reward_weight"` + TaxCaps map[string]sdk.Int `json:"tax_caps" yaml:"tax_caps"` + TaxProceed sdk.Coins `json:"tax_proceed" yaml:"tax_proceed"` + EpochInitialIssuance sdk.Coins `json:"epoch_initial_issuance" yaml:"epoch_initial_issuance"` + TRs []sdk.Dec `json:"TRs" yaml:"TRs"` + SRs []sdk.Dec `json:"SRs" yaml:"SRs"` + TSLs []sdk.Int `json:"TSLs" yaml:"TSLs"` } // NewGenesisState creates a new GenesisState object -func NewGenesisState(params Params, taxRates []sdk.Dec, rewardWeights []sdk.Dec, - taxCaps map[string]sdk.Int, taxProceeds []sdk.Coins, historicalIssuances []sdk.Coins) GenesisState { +func NewGenesisState(params Params, taxRate sdk.Dec, rewardWeight sdk.Dec, + taxCaps map[string]sdk.Int, taxProceed sdk.Coins, + epochInitialIssuance sdk.Coins, TRs []sdk.Dec, SRs []sdk.Dec, TSLs []sdk.Int) GenesisState { return GenesisState{ - Params: params, - TaxRates: taxRates, - RewardWeights: rewardWeights, - TaxCaps: taxCaps, - TaxProceeds: taxProceeds, - HistoricalIssuances: historicalIssuances, + Params: params, + TaxRate: taxRate, + RewardWeight: rewardWeight, + TaxCaps: taxCaps, + TaxProceed: taxProceed, + EpochInitialIssuance: epochInitialIssuance, + TRs: TRs, + SRs: SRs, + TSLs: TSLs, } } // DefaultGenesisState gets raw genesis raw message for testing func DefaultGenesisState() GenesisState { return GenesisState{ - Params: DefaultParams(), - TaxRates: []sdk.Dec{DefaultTaxRate}, - RewardWeights: []sdk.Dec{DefaultRewardWeight}, - TaxCaps: make(map[string]sdk.Int), - TaxProceeds: []sdk.Coins{}, - HistoricalIssuances: []sdk.Coins{}, + Params: DefaultParams(), + TaxRate: DefaultTaxRate, + RewardWeight: DefaultRewardWeight, + TaxCaps: make(map[string]sdk.Int), + TaxProceed: sdk.Coins{}, + EpochInitialIssuance: sdk.Coins{}, + TRs: []sdk.Dec{}, + SRs: []sdk.Dec{}, + TSLs: []sdk.Int{}, } } // ValidateGenesis validates the provided oracle genesis state to ensure the // expected invariants holds. (i.e. params in correct bounds, no duplicate validators) func ValidateGenesis(data GenesisState) error { - if len(data.TaxRates) == 0 { - return fmt.Errorf("At lease one tax-rate shoule be exist") - } - lastTaxRate := data.TaxRates[len(data.TaxRates)-1] - if lastTaxRate.LT(data.Params.TaxPolicy.RateMin) || lastTaxRate.GT(data.Params.TaxPolicy.RateMax) { + if data.TaxRate.LT(data.Params.TaxPolicy.RateMin) || data.TaxRate.GT(data.Params.TaxPolicy.RateMax) { return fmt.Errorf("tax-rate must less than RateMax(%s) and bigger than RateMin(%s)", data.Params.TaxPolicy.RateMax, data.Params.TaxPolicy.RateMin) } - if len(data.RewardWeights) == 0 { - return fmt.Errorf("At lease one reward-weight shoule be exist") - } - - lastRewardWeight := data.RewardWeights[len(data.RewardWeights)-1] - if lastRewardWeight.LT(data.Params.RewardPolicy.RateMin) || lastRewardWeight.GT(data.Params.RewardPolicy.RateMax) { + if data.RewardWeight.LT(data.Params.RewardPolicy.RateMin) || data.RewardWeight.GT(data.Params.RewardPolicy.RateMax) { return fmt.Errorf("reward-weight must less than WeightMax(%s) and bigger than RateMin(%s)", data.Params.RewardPolicy.RateMax, data.Params.RewardPolicy.RateMin) } diff --git a/x/treasury/internal/types/genesis_test.go b/x/treasury/internal/types/genesis_test.go index c19fc3621..b13b2e731 100644 --- a/x/treasury/internal/types/genesis_test.go +++ b/x/treasury/internal/types/genesis_test.go @@ -12,24 +12,16 @@ func TestGenesisValidation(t *testing.T) { genState := DefaultGenesisState() require.NoError(t, ValidateGenesis(genState)) - // Error - at least one tax-rate should be given - genState.TaxRates = []sdk.Dec{} - require.Error(t, ValidateGenesis(genState)) - // Error - tax-rate range error - genState.TaxRates = []sdk.Dec{sdk.NewDec(-1)} + genState.TaxRate = sdk.NewDec(-1) require.Error(t, ValidateGenesis(genState)) // Valid - genState.TaxRates = []sdk.Dec{sdk.NewDecWithPrec(1, 2)} + genState.TaxRate = sdk.NewDecWithPrec(1, 2) require.NoError(t, ValidateGenesis(genState)) - // Error - at least one reward-weight should be given - genState.RewardWeights = []sdk.Dec{} - require.Error(t, ValidateGenesis(genState)) - // Error - reward-weight range error - genState.RewardWeights = []sdk.Dec{sdk.NewDec(-1)} + genState.RewardWeight = sdk.NewDec(-1) require.Error(t, ValidateGenesis(genState)) } diff --git a/x/treasury/internal/types/keys.go b/x/treasury/internal/types/keys.go index 69c88e120..616236eed 100644 --- a/x/treasury/internal/types/keys.go +++ b/x/treasury/internal/types/keys.go @@ -21,53 +21,58 @@ const ( // Keys for treasury store // Items are stored with the following key: values // -// - 0x01: sdk.Dec +// - 0x01: sdk.Dec // -// - 0x02: sdk.Dec +// - 0x02: sdk.Dec // // - 0x03: sdk.Int // -// - 0x04: sdk.Coins +// - 0x04: sdk.Coins // -// - 0x05: sdk.Coins +// - 0x05: sdk.Coins +// +// - 0x06: sdk.Dec +// +// - 0x07: sdk.Dec +// +// - 0x08: sdk.Int var ( // Keys for store prefixes - TaxRateKey = []byte{0x01} // prefix for each key to a tax-rate - RewardWeightKey = []byte{0x02} // prefix for each key to a reward-weight - TaxCapKey = []byte{0x03} // prefix for each key to a tax-cap - TaxProceedsKey = []byte{0x04} // prefix for each key to a tax-proceeds - HistoricalIssuanceKey = []byte{0x05} // prefix for each key to a historical issuance + TaxRateKey = []byte{0x01} // a key for a tax-rate + RewardWeightKey = []byte{0x02} // a key for a reward-weight + TaxCapKey = []byte{0x03} // prefix for each key to a tax-cap + TaxProceedsKey = []byte{0x04} // a key for a tax-proceeds + EpochInitialIssuanceKey = []byte{0x05} // a key for a initial epoch issuance + + // Keys for store prefixes of internal purpose variables + TRKey = []byte{0x06} // prefix for each key to a TR + SRKey = []byte{0x07} // prefix for each key to a SR + TSLKey = []byte{0x08} // prefix for each key to a TSL ) -// GetTaxRateKey - stored by *epoch* -func GetTaxRateKey(epoch int64) []byte { - b := make([]byte, 8) - binary.LittleEndian.PutUint64(b, uint64(epoch)) - return append(TaxRateKey, b...) +// GetTaxCapKey - stored by *denom* +func GetTaxCapKey(denom string) []byte { + return append(TaxCapKey, []byte(denom)...) } -// GetRewardWeightKey - stored by *epoch* -func GetRewardWeightKey(epoch int64) []byte { - b := make([]byte, 8) - binary.LittleEndian.PutUint64(b, uint64(epoch)) - return append(RewardWeightKey, b...) +// GetTRKey - stored by *epoch* +func GetTRKey(epoch int64) []byte { + return GetSubkeyByEpoch(TRKey, epoch) } -// GetTaxCapKey - stored by *denom* -func GetTaxCapKey(denom string) []byte { - return append(TaxCapKey, []byte(denom)...) +// GetSRKey - stored by *epoch* +func GetSRKey(epoch int64) []byte { + return GetSubkeyByEpoch(SRKey, epoch) } -// GetTaxProceedsKey - stored by *epoch* -func GetTaxProceedsKey(epoch int64) []byte { - b := make([]byte, 8) - binary.LittleEndian.PutUint64(b, uint64(epoch)) - return append(TaxProceedsKey, b...) +// GetTSLKey - stored by *epoch* +func GetTSLKey(epoch int64) []byte { + return GetSubkeyByEpoch(TSLKey, epoch) } -// GetHistoricalIssuanceKey - stored by *epoch* -func GetHistoricalIssuanceKey(epoch int64) []byte { +// GetSubkeyByEpoch - stored by *epoch* +func GetSubkeyByEpoch(prefix []byte, epoch int64) []byte { b := make([]byte, 8) binary.LittleEndian.PutUint64(b, uint64(epoch)) - return append(HistoricalIssuanceKey, b...) + return append(prefix, b...) } diff --git a/x/treasury/internal/types/querier.go b/x/treasury/internal/types/querier.go index 7649f91cf..294eb7418 100644 --- a/x/treasury/internal/types/querier.go +++ b/x/treasury/internal/types/querier.go @@ -2,14 +2,12 @@ package types // query endpoints supported by the auth Querier const ( - QueryCurrentEpoch = "currentEpoch" QueryTaxRate = "taxRate" QueryTaxCap = "taxCap" QueryRewardWeight = "rewardWeight" QuerySeigniorageProceeds = "seigniorageProceeds" QueryTaxProceeds = "taxProceeds" QueryParameters = "parameters" - QueryHistoricalIssuance = "historicalIssuance" ) // QueryTaxCapParams for query @@ -24,68 +22,3 @@ func NewQueryTaxCapParams(denom string) QueryTaxCapParams { Denom: denom, } } - -// QueryTaxRateParams for query -// - 'custom/treasury/taxRate -type QueryTaxRateParams struct { - Epoch int64 -} - -// NewQueryTaxRateParams returns new QueryTaxRateParams instance -func NewQueryTaxRateParams(epoch int64) QueryTaxRateParams { - return QueryTaxRateParams{ - Epoch: epoch, - } -} - -// QueryRewardWeightParams for query -// - 'custom/treasury/rewardWeight -type QueryRewardWeightParams struct { - Epoch int64 -} - -// NewQueryRewardWeightParams returns new QueryRewardWeightParams instance -func NewQueryRewardWeightParams(epoch int64) QueryRewardWeightParams { - return QueryRewardWeightParams{ - Epoch: epoch, - } -} - -// QuerySeigniorageProceedsParams for query -// - 'custom/treasury/seigniorageProceeds -type QuerySeigniorageProceedsParams struct { - Epoch int64 -} - -// NewQuerySeigniorageParams returns new QuerySeigniorageProceedsParams instance -func NewQuerySeigniorageParams(epoch int64) QuerySeigniorageProceedsParams { - return QuerySeigniorageProceedsParams{ - Epoch: epoch, - } -} - -// QueryTaxProceedsParams for query -// - 'custom/treasury/taxProceeds -type QueryTaxProceedsParams struct { - Epoch int64 -} - -// NewQueryTaxProceedsParams returns new QueryTaxProceedsParams instance -func NewQueryTaxProceedsParams(epoch int64) QueryTaxProceedsParams { - return QueryTaxProceedsParams{ - Epoch: epoch, - } -} - -// QueryHistoricalIssuanceParams for query -// - 'custom/treasury/microLunaIssuance -type QueryHistoricalIssuanceParams struct { - Epoch int64 -} - -// NewQueryHistoricalIssuanceParams returns new QueryHistoricalIssuanceParams instance -func NewQueryHistoricalIssuanceParams(epoch int64) QueryHistoricalIssuanceParams { - return QueryHistoricalIssuanceParams{ - Epoch: epoch, - } -} diff --git a/x/treasury/proposal_handler_test.go b/x/treasury/proposal_handler_test.go index e4775de73..c95fca480 100644 --- a/x/treasury/proposal_handler_test.go +++ b/x/treasury/proposal_handler_test.go @@ -6,7 +6,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - core "github.com/terra-project/core/types" "github.com/terra-project/core/x/treasury/internal/keeper" "github.com/terra-project/core/x/treasury/internal/types" ) @@ -34,7 +33,7 @@ func TestTaxRateUpdateProposalHandler(t *testing.T) { tp := testTaxRateUpdateProposal(taxRate) hdlr := NewTreasuryPolicyUpdateHandler(input.TreasuryKeeper) require.NoError(t, hdlr(input.Ctx, tp)) - require.Equal(t, taxRate, input.TreasuryKeeper.GetTaxRate(input.Ctx, core.GetEpoch(input.Ctx))) + require.Equal(t, taxRate, input.TreasuryKeeper.GetTaxRate(input.Ctx)) } func TestRewardWeightUpdateProposalHandler(t *testing.T) { @@ -44,5 +43,5 @@ func TestRewardWeightUpdateProposalHandler(t *testing.T) { tp := testRewardWeightUpdateProposal(rewardWeight) hdlr := NewTreasuryPolicyUpdateHandler(input.TreasuryKeeper) require.NoError(t, hdlr(input.Ctx, tp)) - require.Equal(t, rewardWeight, input.TreasuryKeeper.GetRewardWeight(input.Ctx, core.GetEpoch(input.Ctx))) + require.Equal(t, rewardWeight, input.TreasuryKeeper.GetRewardWeight(input.Ctx)) }