From 115a52b4ad0ea273df2978215b1c51d1bc783872 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Fri, 29 Mar 2019 20:30:47 +0800 Subject: [PATCH] [R4R] Add deposit address and do some refactor (#101) * add address for deposits * refactor * refactor * revert change * refactor * refactor * change proposals to publish * update deposit address --- cmd/gaia/app/app.go | 2 +- cmd/gaia/app/app_test.go | 2 +- x/gov/endblocker_test.go | 24 +++++++--- x/gov/genesis.go | 28 ++++++------ x/gov/handler.go | 20 +++++---- x/gov/keeper.go | 71 ++++++++++++++---------------- x/gov/keeper_test.go | 4 ++ x/gov/{procedures.go => params.go} | 12 ++--- x/gov/simulation/msgs.go | 1 - x/gov/simulation/sim_test.go | 2 +- x/gov/tally.go | 32 +++++++------- x/stake/keeper/test_common.go | 4 +- 12 files changed, 109 insertions(+), 93 deletions(-) rename x/gov/{procedures.go => params.go} (62%) diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 9f7739d2f..0b7642d75 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -138,7 +138,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio app.govKeeper = gov.NewKeeper( app.cdc, app.keyGov, - app.paramsKeeper, app.paramsKeeper.Subspace(gov.DefaultParamspace), app.bankKeeper, app.stakeKeeper, + app.paramsKeeper, app.paramsKeeper.Subspace(gov.DefaultParamSpace), app.bankKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace), app.Pool, ) diff --git a/cmd/gaia/app/app_test.go b/cmd/gaia/app/app_test.go index e348de906..26d165576 100644 --- a/cmd/gaia/app/app_test.go +++ b/cmd/gaia/app/app_test.go @@ -94,7 +94,7 @@ func NewMockGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppO app.govKeeper = gov.NewKeeper( app.cdc, app.keyGov, - app.paramsKeeper, app.paramsKeeper.Subspace(gov.DefaultParamspace), app.bankKeeper, app.stakeKeeper, + app.paramsKeeper, app.paramsKeeper.Subspace(gov.DefaultParamSpace), app.bankKeeper, app.stakeKeeper, app.RegisterCodespace(gov.DefaultCodespace), app.Pool, ) diff --git a/x/gov/endblocker_test.go b/x/gov/endblocker_test.go index 2dc7da6d3..a2fc8f786 100644 --- a/x/gov/endblocker_test.go +++ b/x/gov/endblocker_test.go @@ -37,6 +37,7 @@ func TestTickExpiredDepositPeriod(t *testing.T) { gov.EndBlocker(ctx, keeper) require.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) require.False(t, gov.ShouldPopInactiveProposalQueue(ctx, keeper)) + require.Equal(t, sdk.Coins{sdk.NewCoin(gov.DefaultDepositDenom, 1000e8)}, ck.GetCoins(ctx, gov.DepositedCoinsAccAddr)) newHeader := ctx.BlockHeader() newHeader.Time = ctx.BlockHeader().Time.Add(time.Duration(1) * time.Second) @@ -47,7 +48,7 @@ func TestTickExpiredDepositPeriod(t *testing.T) { require.False(t, gov.ShouldPopInactiveProposalQueue(ctx, keeper)) newHeader = ctx.BlockHeader() - newHeader.Time = ctx.BlockHeader().Time.Add(keeper.GetDepositProcedure(ctx).MaxDepositPeriod) + newHeader.Time = ctx.BlockHeader().Time.Add(keeper.GetDepositParams(ctx).MaxDepositPeriod) ctx = ctx.WithBlockHeader(newHeader) require.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) @@ -57,13 +58,14 @@ func TestTickExpiredDepositPeriod(t *testing.T) { validatorCoins := ck.GetCoins(ctx, addrs[0]) // check distribute deposits to proposer require.Equal(t, validatorCoins, sdk.Coins{sdk.NewCoin(gov.DefaultDepositDenom, 6000e8)}) + require.Equal(t, sdk.Coins(nil), ck.GetCoins(ctx, gov.DepositedCoinsAccAddr)) require.Nil(t, keeper.InactiveProposalQueuePeek(ctx)) require.False(t, gov.ShouldPopInactiveProposalQueue(ctx, keeper)) } func TestTickMultipleExpiredDepositPeriod(t *testing.T) { - mapp, _, keeper, stakeKeeper, addrs, pubKeys, _ := getMockApp(t, 10) + mapp, ck, keeper, stakeKeeper, addrs, pubKeys, _ := getMockApp(t, 10) validator := stake.NewValidator(sdk.ValAddress(addrs[0]), pubKeys[0], stake.Description{}) mapp.BeginBlock(abci.RequestBeginBlock{}) @@ -86,6 +88,7 @@ func TestTickMultipleExpiredDepositPeriod(t *testing.T) { gov.EndBlocker(ctx, keeper) require.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) require.False(t, gov.ShouldPopInactiveProposalQueue(ctx, keeper)) + require.Equal(t, sdk.Coins{sdk.NewCoin(gov.DefaultDepositDenom, 1000e8)}, ck.GetCoins(ctx, gov.DepositedCoinsAccAddr)) newHeader := ctx.BlockHeader() newHeader.Time = ctx.BlockHeader().Time.Add(time.Duration(2) * time.Second) @@ -100,7 +103,7 @@ func TestTickMultipleExpiredDepositPeriod(t *testing.T) { require.True(t, res.IsOK()) newHeader = ctx.BlockHeader() - newHeader.Time = ctx.BlockHeader().Time.Add(keeper.GetDepositProcedure(ctx).MaxDepositPeriod).Add(time.Duration(-1) * time.Second) + newHeader.Time = ctx.BlockHeader().Time.Add(keeper.GetDepositParams(ctx).MaxDepositPeriod).Add(time.Duration(-1) * time.Second) ctx = ctx.WithBlockHeader(newHeader) require.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) @@ -108,6 +111,7 @@ func TestTickMultipleExpiredDepositPeriod(t *testing.T) { gov.EndBlocker(ctx, keeper) require.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) require.False(t, gov.ShouldPopInactiveProposalQueue(ctx, keeper)) + require.Equal(t, sdk.Coins{sdk.NewCoin(gov.DefaultDepositDenom, 5)}, ck.GetCoins(ctx, gov.DepositedCoinsAccAddr)) newHeader = ctx.BlockHeader() newHeader.Time = ctx.BlockHeader().Time.Add(time.Duration(5) * time.Second) @@ -118,10 +122,11 @@ func TestTickMultipleExpiredDepositPeriod(t *testing.T) { gov.EndBlocker(ctx, keeper) require.Nil(t, keeper.InactiveProposalQueuePeek(ctx)) require.False(t, gov.ShouldPopInactiveProposalQueue(ctx, keeper)) + require.Equal(t, sdk.Coins(nil), ck.GetCoins(ctx, gov.DepositedCoinsAccAddr)) } func TestTickPassedDepositPeriod(t *testing.T) { - mapp, _, keeper, _, addrs, _, _ := getMockApp(t, 10) + mapp, ck, keeper, _, addrs, _, _ := getMockApp(t, 10) mapp.BeginBlock(abci.RequestBeginBlock{}) ctx := mapp.BaseApp.NewContext(sdk.RunTxModeDeliver, abci.Header{}) govHandler := gov.NewHandler(keeper) @@ -141,6 +146,7 @@ func TestTickPassedDepositPeriod(t *testing.T) { gov.EndBlocker(ctx, keeper) require.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) require.False(t, gov.ShouldPopInactiveProposalQueue(ctx, keeper)) + require.Equal(t, sdk.Coins{sdk.NewCoin(gov.DefaultDepositDenom, 1000e8)}, ck.GetCoins(ctx, gov.DepositedCoinsAccAddr)) newHeader := ctx.BlockHeader() newHeader.Time = ctx.BlockHeader().Time.Add(time.Duration(1) * time.Second) @@ -157,6 +163,7 @@ func TestTickPassedDepositPeriod(t *testing.T) { require.NotNil(t, keeper.InactiveProposalQueuePeek(ctx)) require.True(t, gov.ShouldPopInactiveProposalQueue(ctx, keeper)) require.NotNil(t, keeper.ActiveProposalQueuePeek(ctx)) + require.Equal(t, sdk.Coins{sdk.NewCoin(gov.DefaultDepositDenom, 2000e8)}, ck.GetCoins(ctx, gov.DepositedCoinsAccAddr)) gov.EndBlocker(ctx, keeper) @@ -164,7 +171,6 @@ func TestTickPassedDepositPeriod(t *testing.T) { require.False(t, gov.ShouldPopInactiveProposalQueue(ctx, keeper)) require.NotNil(t, keeper.ActiveProposalQueuePeek(ctx)) require.False(t, gov.ShouldPopActiveProposalQueue(ctx, keeper)) - } func TestTickPassedVotingPeriodRejected(t *testing.T) { @@ -210,6 +216,8 @@ func TestTickPassedVotingPeriodRejected(t *testing.T) { newVoteMsg := gov.NewMsgVote(addrs[0], int64(proposalID), gov.OptionNo) res = govHandler(ctx, newVoteMsg) require.True(t, res.IsOK()) + require.Equal(t, sdk.Coins{sdk.NewCoin(gov.DefaultDepositDenom, 2000e8)}, ck.GetCoins(ctx, gov.DepositedCoinsAccAddr)) + gov.EndBlocker(ctx, keeper) // pass voting period @@ -234,6 +242,7 @@ func TestTickPassedVotingPeriodRejected(t *testing.T) { // check distribute deposits to proposer validatorCoins := ck.GetCoins(ctx, addrs[0]) require.Equal(t, validatorCoins, sdk.Coins{sdk.NewCoin(gov.DefaultDepositDenom, 6000e8)}) + require.Equal(t, sdk.Coins(nil), ck.GetCoins(ctx, gov.DepositedCoinsAccAddr)) } func TestTickPassedVotingPeriodPassed(t *testing.T) { @@ -273,6 +282,7 @@ func TestTickPassedVotingPeriodPassed(t *testing.T) { newDepositMsg := gov.NewMsgDeposit(addrs[1], int64(proposalID), sdk.Coins{sdk.NewCoin(gov.DefaultDepositDenom, 1000e8)}) res = govHandler(ctx, newDepositMsg) require.True(t, res.IsOK()) + require.Equal(t, sdk.Coins{sdk.NewCoin(gov.DefaultDepositDenom, 2000e8)}, ck.GetCoins(ctx, gov.DepositedCoinsAccAddr)) gov.EndBlocker(ctx, keeper) newHeader = ctx.BlockHeader() @@ -305,6 +315,7 @@ func TestTickPassedVotingPeriodPassed(t *testing.T) { // check refund deposits validatorCoins := ck.GetCoins(ctx, addrs[0]) require.Equal(t, validatorCoins, sdk.Coins{sdk.NewCoin(gov.DefaultDepositDenom, 5000e8)}) + require.Equal(t, sdk.Coins(nil), ck.GetCoins(ctx, gov.DepositedCoinsAccAddr)) } func TestTickPassedVotingPeriodUnreachedQuorum(t *testing.T) { @@ -357,6 +368,8 @@ func TestTickPassedVotingPeriodUnreachedQuorum(t *testing.T) { newVoteMsg := gov.NewMsgVote(addrs[0], int64(proposalID), gov.OptionYes) res = govHandler(ctx, newVoteMsg) require.True(t, res.IsOK()) + require.Equal(t, sdk.Coins{sdk.NewCoin(gov.DefaultDepositDenom, 2000e8)}, ck.GetCoins(ctx, gov.DepositedCoinsAccAddr)) + gov.EndBlocker(ctx, keeper) // pass voting period @@ -381,6 +394,7 @@ func TestTickPassedVotingPeriodUnreachedQuorum(t *testing.T) { // check refund deposits validatorCoins := ck.GetCoins(ctx, addrs[0]) require.Equal(t, validatorCoins, sdk.Coins{sdk.NewCoin(gov.DefaultDepositDenom, 5000e8)}) + require.Equal(t, sdk.Coins(nil), ck.GetCoins(ctx, gov.DepositedCoinsAccAddr)) } func TestTickPassedVotingPeriodAllAbstain(t *testing.T) { diff --git a/x/gov/genesis.go b/x/gov/genesis.go index 56620b2d1..0dfee258d 100644 --- a/x/gov/genesis.go +++ b/x/gov/genesis.go @@ -12,16 +12,16 @@ const ( // GenesisState - all staking state that must be provided at genesis type GenesisState struct { - StartingProposalID int64 `json:"starting_proposalID"` - DepositProcedure DepositProcedure `json:"deposit_period"` - TallyingProcedure TallyingProcedure `json:"tallying_procedure"` + StartingProposalID int64 `json:"starting_proposalID"` + DepositParams DepositParams `json:"deposit_params"` + TallyParams TallyParams `json:"tally_params"` } -func NewGenesisState(startingProposalID int64, dp DepositProcedure, tp TallyingProcedure) GenesisState { +func NewGenesisState(startingProposalID int64, dp DepositParams, tp TallyParams) GenesisState { return GenesisState{ StartingProposalID: startingProposalID, - DepositProcedure: dp, - TallyingProcedure: tp, + DepositParams: dp, + TallyParams: tp, } } @@ -29,11 +29,11 @@ func NewGenesisState(startingProposalID int64, dp DepositProcedure, tp TallyingP func DefaultGenesisState() GenesisState { return GenesisState{ StartingProposalID: 1, - DepositProcedure: DepositProcedure{ + DepositParams: DepositParams{ MinDeposit: sdk.Coins{sdk.NewCoin(DefaultDepositDenom, 2000e8)}, MaxDepositPeriod: time.Duration(2*24) * time.Hour, // 2 days }, - TallyingProcedure: TallyingProcedure{ + TallyParams: TallyParams{ Quorum: sdk.NewDecWithPrec(5, 1), Threshold: sdk.NewDecWithPrec(5, 1), Veto: sdk.NewDecWithPrec(334, 3), @@ -48,19 +48,19 @@ func InitGenesis(ctx sdk.Context, k Keeper, data GenesisState) { // TODO: Handle this with #870 panic(err) } - k.setDepositProcedure(ctx, data.DepositProcedure) - k.setTallyingProcedure(ctx, data.TallyingProcedure) + k.setDepositParams(ctx, data.DepositParams) + k.setTallyParams(ctx, data.TallyParams) } // WriteGenesis - output genesis parameters func WriteGenesis(ctx sdk.Context, k Keeper) GenesisState { startingProposalID, _ := k.getNewProposalID(ctx) - depositProcedure := k.GetDepositProcedure(ctx) - tallyingProcedure := k.GetTallyingProcedure(ctx) + depositParams := k.GetDepositParams(ctx) + tallyingParams := k.GetTallyParams(ctx) return GenesisState{ StartingProposalID: startingProposalID, - DepositProcedure: depositProcedure, - TallyingProcedure: tallyingProcedure, + DepositParams: depositParams, + TallyParams: tallyingParams, } } diff --git a/x/gov/handler.go b/x/gov/handler.go index 19119d833..574653017 100644 --- a/x/gov/handler.go +++ b/x/gov/handler.go @@ -111,13 +111,13 @@ func handleMsgVote(ctx sdk.Context, keeper Keeper, msg MsgVote) sdk.Result { } // Called every block, process inflation, update validator set -func EndBlocker(ctx sdk.Context, keeper Keeper) (resTags sdk.Tags, passedProposals, failedProposals []int64) { +func EndBlocker(ctx sdk.Context, keeper Keeper) (resTags sdk.Tags, refundProposals, notRefundProposals []int64) { logger := ctx.Logger().With("module", "x/gov") resTags = sdk.NewTags() - passedProposals = make([]int64, 0) - failedProposals = make([]int64, 0) + refundProposals = make([]int64, 0) + notRefundProposals = make([]int64, 0) // Delete proposals that haven't met minDeposit for ShouldPopInactiveProposalQueue(ctx, keeper) { @@ -132,6 +132,9 @@ func EndBlocker(ctx sdk.Context, keeper Keeper) (resTags sdk.Tags, passedProposa keeper.DistributeDeposits(ctx, inactiveProposal.GetProposalID()) keeper.DeleteProposal(ctx, inactiveProposal) + + notRefundProposals = append(notRefundProposals, inactiveProposal.GetProposalID()) + resTags.AppendTag(tags.Action, tags.ActionProposalDropped) resTags.AppendTag(tags.ProposalID, proposalIDBytes) @@ -139,7 +142,7 @@ func EndBlocker(ctx sdk.Context, keeper Keeper) (resTags sdk.Tags, passedProposa fmt.Sprintf("proposal %d (%s) didn't meet minimum deposit of %v (had only %v); distribute to validator", inactiveProposal.GetProposalID(), inactiveProposal.GetTitle(), - keeper.GetDepositProcedure(ctx).MinDeposit, + keeper.GetDepositParams(ctx).MinDeposit, inactiveProposal.GetTotalDeposit(), ), ) @@ -164,7 +167,7 @@ func EndBlocker(ctx sdk.Context, keeper Keeper) (resTags sdk.Tags, passedProposa // refund deposits keeper.RefundDeposits(ctx, activeProposal.GetProposalID()) - passedProposals = append(passedProposals, activeProposal.GetProposalID()) + refundProposals = append(refundProposals, activeProposal.GetProposalID()) } else { activeProposal.SetStatus(StatusRejected) action = tags.ActionProposalRejected @@ -172,10 +175,11 @@ func EndBlocker(ctx sdk.Context, keeper Keeper) (resTags sdk.Tags, passedProposa // if votes reached quorum and not all votes are abstain, distribute deposits to validator, else refund deposits if refundDeposits { keeper.RefundDeposits(ctx, activeProposal.GetProposalID()) + refundProposals = append(refundProposals, activeProposal.GetProposalID()) } else { keeper.DistributeDeposits(ctx, activeProposal.GetProposalID()) + notRefundProposals = append(notRefundProposals, activeProposal.GetProposalID()) } - failedProposals = append(failedProposals, activeProposal.GetProposalID()) } activeProposal.SetTallyResult(tallyResults) @@ -192,14 +196,14 @@ func EndBlocker(ctx sdk.Context, keeper Keeper) (resTags sdk.Tags, passedProposa } func ShouldPopInactiveProposalQueue(ctx sdk.Context, keeper Keeper) bool { - depositProcedure := keeper.GetDepositProcedure(ctx) + depositParams := keeper.GetDepositParams(ctx) peekProposal := keeper.InactiveProposalQueuePeek(ctx) if peekProposal == nil { return false } else if peekProposal.GetStatus() != StatusDepositPeriod { return true - } else if !ctx.BlockHeader().Time.Before(peekProposal.GetSubmitTime().Add(depositProcedure.MaxDepositPeriod)) { + } else if !ctx.BlockHeader().Time.Before(peekProposal.GetSubmitTime().Add(depositParams.MaxDepositPeriod)) { return true } return false diff --git a/x/gov/keeper.go b/x/gov/keeper.go index ff7f72ed9..1cb0206c2 100644 --- a/x/gov/keeper.go +++ b/x/gov/keeper.go @@ -4,6 +4,8 @@ import ( "fmt" "time" + "github.com/tendermint/tendermint/crypto" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/bank" @@ -12,20 +14,22 @@ import ( // Parameter store default namestore const ( - DefaultParamspace = "gov" + DefaultParamSpace = "gov" ) // Parameter store key var ( - ParamStoreKeyDepositProcedure = []byte("depositprocedure") - ParamStoreKeyTallyingProcedure = []byte("tallyingprocedure") + ParamStoreKeyDepositParams = []byte("depositparams") + ParamStoreKeyTallyParams = []byte("tallyparams") + + DepositedCoinsAccAddr = sdk.AccAddress(crypto.AddressHash([]byte("BinanceChainDepositedCoins"))) ) // Type declaration for parameters func ParamTypeTable() params.TypeTable { return params.NewTypeTable( - ParamStoreKeyDepositProcedure, DepositProcedure{}, - ParamStoreKeyTallyingProcedure, TallyingProcedure{}, + ParamStoreKeyDepositParams, DepositParams{}, + ParamStoreKeyTallyParams, TallyParams{}, ) } @@ -269,32 +273,32 @@ func (keeper Keeper) ActivateVotingPeriod(ctx sdk.Context, proposal Proposal) { } // ===================================================== -// Procedures +// Params -// Returns the current Deposit Procedure from the global param store +// Returns the current Deposit Params from the global param store // nolint: errcheck -func (keeper Keeper) GetDepositProcedure(ctx sdk.Context) DepositProcedure { - var depositProcedure DepositProcedure - keeper.paramSpace.Get(ctx, ParamStoreKeyDepositProcedure, &depositProcedure) - return depositProcedure +func (keeper Keeper) GetDepositParams(ctx sdk.Context) DepositParams { + var depositParams DepositParams + keeper.paramSpace.Get(ctx, ParamStoreKeyDepositParams, &depositParams) + return depositParams } -// Returns the current Tallying Procedure from the global param store +// Returns the current Tally Params from the global param store // nolint: errcheck -func (keeper Keeper) GetTallyingProcedure(ctx sdk.Context) TallyingProcedure { - var tallyingProcedure TallyingProcedure - keeper.paramSpace.Get(ctx, ParamStoreKeyTallyingProcedure, &tallyingProcedure) - return tallyingProcedure +func (keeper Keeper) GetTallyParams(ctx sdk.Context) TallyParams { + var tallyParams TallyParams + keeper.paramSpace.Get(ctx, ParamStoreKeyTallyParams, &tallyParams) + return tallyParams } // nolint: errcheck -func (keeper Keeper) setDepositProcedure(ctx sdk.Context, depositProcedure DepositProcedure) { - keeper.paramSpace.Set(ctx, ParamStoreKeyDepositProcedure, &depositProcedure) +func (keeper Keeper) setDepositParams(ctx sdk.Context, depositParams DepositParams) { + keeper.paramSpace.Set(ctx, ParamStoreKeyDepositParams, &depositParams) } // nolint: errcheck -func (keeper Keeper) setTallyingProcedure(ctx sdk.Context, tallyingProcedure TallyingProcedure) { - keeper.paramSpace.Set(ctx, ParamStoreKeyTallyingProcedure, &tallyingProcedure) +func (keeper Keeper) setTallyParams(ctx sdk.Context, tallyParams TallyParams) { + keeper.paramSpace.Set(ctx, ParamStoreKeyTallyParams, &tallyParams) } // ===================================================== @@ -388,13 +392,14 @@ func (keeper Keeper) AddDeposit(ctx sdk.Context, proposalID int64, depositerAddr return ErrAlreadyFinishedProposal(keeper.codespace, proposalID), false } - // Subtract coins from depositer's account - _, _, err := keeper.ck.SubtractCoins(ctx, depositerAddr, depositAmount) + // Send coins from depositor's account to DepositedCoinsAccAddr account + _, err := keeper.ck.SendCoins(ctx, depositerAddr, DepositedCoinsAccAddr, depositAmount) if err != nil { return err, false } + if ctx.IsDeliverTx() { - keeper.pool.AddAddrs([]sdk.AccAddress{depositerAddr}) + keeper.pool.AddAddrs([]sdk.AccAddress{depositerAddr, DepositedCoinsAccAddr}) } // Update Proposal @@ -404,7 +409,7 @@ func (keeper Keeper) AddDeposit(ctx sdk.Context, proposalID int64, depositerAddr // Check if deposit tipped proposal into voting period // Active voting period if so activatedVotingPeriod := false - if proposal.GetStatus() == StatusDepositPeriod && proposal.GetTotalDeposit().IsGTE(keeper.GetDepositProcedure(ctx).MinDeposit) { + if proposal.GetStatus() == StatusDepositPeriod && proposal.GetTotalDeposit().IsGTE(keeper.GetDepositParams(ctx).MinDeposit) { keeper.ActivateVotingPeriod(ctx, proposal) activatedVotingPeriod = true } @@ -437,22 +442,12 @@ func (keeper Keeper) RefundDeposits(ctx sdk.Context, proposalID int64) { deposit := &Deposit{} keeper.cdc.MustUnmarshalBinaryLengthPrefixed(depositsIterator.Value(), deposit) - _, _, err := keeper.ck.AddCoins(ctx, deposit.Depositer, deposit.Amount) + _, err := keeper.ck.SendCoins(ctx, DepositedCoinsAccAddr, deposit.Depositer, deposit.Amount) if err != nil { panic(fmt.Sprintf("refund error(%s) should not happen", err.Error())) } - keeper.pool.AddAddrs([]sdk.AccAddress{deposit.Depositer}) - store.Delete(depositsIterator.Key()) - } -} - -// Deletes all the deposits on a specific proposal without refunding them -func (keeper Keeper) DeleteDeposits(ctx sdk.Context, proposalID int64) { - store := ctx.KVStore(keeper.storeKey) - depositsIterator := keeper.GetDeposits(ctx, proposalID) - defer depositsIterator.Close() - for ; depositsIterator.Valid(); depositsIterator.Next() { + keeper.pool.AddAddrs([]sdk.AccAddress{deposit.Depositer, DepositedCoinsAccAddr}) store.Delete(depositsIterator.Key()) } } @@ -480,11 +475,11 @@ func (keeper Keeper) DistributeDeposits(ctx sdk.Context, proposalID int64) { ctx.Logger().Info("distribute empty deposits") } - _, _, err := keeper.ck.AddCoins(ctx, sdk.AccAddress(proposerAccAddr), depositCoins) + _, err := keeper.ck.SendCoins(ctx, DepositedCoinsAccAddr, sdk.AccAddress(proposerAccAddr), depositCoins) if err != nil { panic(fmt.Sprintf("distribute deposits error(%s) should not happen", err.Error())) } - keeper.pool.AddAddrs([]sdk.AccAddress{sdk.AccAddress(proposerAccAddr)}) + keeper.pool.AddAddrs([]sdk.AccAddress{sdk.AccAddress(proposerAccAddr), DepositedCoinsAccAddr}) } // ===================================================== diff --git a/x/gov/keeper_test.go b/x/gov/keeper_test.go index 1dd0515f7..ef216533d 100644 --- a/x/gov/keeper_test.go +++ b/x/gov/keeper_test.go @@ -158,6 +158,7 @@ func TestDeposits(t *testing.T) { require.Equal(t, addrs[0], deposit.Depositer) require.Equal(t, fiveHundredSteak, keeper.GetProposal(ctx, proposalID).GetTotalDeposit()) require.Equal(t, addr0Initial.Minus(fiveHundredSteak), ck.GetCoins(ctx, addrs[0])) + require.Equal(t, fiveHundredSteak, ck.GetCoins(ctx, gov.DepositedCoinsAccAddr)) // Check a second deposit from same address err, votingStarted = keeper.AddDeposit(ctx, proposalID, addrs[0], oneThousandSteak) @@ -169,6 +170,7 @@ func TestDeposits(t *testing.T) { require.Equal(t, addrs[0], deposit.Depositer) require.Equal(t, fiveHundredSteak.Plus(oneThousandSteak), keeper.GetProposal(ctx, proposalID).GetTotalDeposit()) require.Equal(t, addr0Initial.Minus(fiveHundredSteak).Minus(oneThousandSteak), ck.GetCoins(ctx, addrs[0])) + require.Equal(t, fiveHundredSteak.Plus(oneThousandSteak), ck.GetCoins(ctx, gov.DepositedCoinsAccAddr)) // Check third deposit from a new address err, votingStarted = keeper.AddDeposit(ctx, proposalID, addrs[1], fiveHundredSteak) @@ -180,6 +182,7 @@ func TestDeposits(t *testing.T) { require.Equal(t, fiveHundredSteak, deposit.Amount) require.Equal(t, fiveHundredSteak.Plus(oneThousandSteak).Plus(fiveHundredSteak), keeper.GetProposal(ctx, proposalID).GetTotalDeposit()) require.Equal(t, addr1Initial.Minus(fiveHundredSteak), ck.GetCoins(ctx, addrs[1])) + require.Equal(t, sdk.Coins{sdk.NewCoin(gov.DefaultDepositDenom, 2000e8)}, ck.GetCoins(ctx, gov.DepositedCoinsAccAddr)) // Check that proposal moved to voting period require.True(t, keeper.GetProposal(ctx, proposalID).GetVotingStartTime().Equal(ctx.BlockHeader().Time)) @@ -209,6 +212,7 @@ func TestDeposits(t *testing.T) { require.False(t, found) require.Equal(t, addr0Initial, ck.GetCoins(ctx, addrs[0])) require.Equal(t, addr1Initial, ck.GetCoins(ctx, addrs[1])) + require.Equal(t, sdk.Coins(nil), ck.GetCoins(ctx, gov.DepositedCoinsAccAddr)) } func TestVotes(t *testing.T) { diff --git a/x/gov/procedures.go b/x/gov/params.go similarity index 62% rename from x/gov/procedures.go rename to x/gov/params.go index 0d4777154..e483be969 100644 --- a/x/gov/procedures.go +++ b/x/gov/params.go @@ -6,15 +6,15 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// Procedure around Deposits for governance -type DepositProcedure struct { +// Param around Deposits for governance +type DepositParams struct { MinDeposit sdk.Coins `json:"min_deposit"` // Minimum deposit for a proposal to enter voting period. MaxDepositPeriod time.Duration `json:"max_deposit_period"` // Maximum period for Atom holders to deposit on a proposal. Initial value: 2 months } -// Procedure around Tallying votes in governance -type TallyingProcedure struct { - Quorum sdk.Dec `json:"quorum"` // Minimum percentage of total stake needed to vote for a result to be considered valid - Threshold sdk.Dec `json:"threshold"` // Minimum propotion of Yes votes for proposal to pass. Initial value: 0.5 +// Param around Tally votes in governance +type TallyParams struct { + Quorum sdk.Dec `json:"quorum"` // Minimum percentage of total stake needed to vote for a result to be considered valid. Initial value: 0.5 + Threshold sdk.Dec `json:"threshold"` // Minimum proportion of Yes votes for proposal to pass. Initial value: 0.5 Veto sdk.Dec `json:"veto"` // Minimum value of Veto votes to Total votes ratio for proposal to be vetoed. Initial value: 1/3 } diff --git a/x/gov/simulation/msgs.go b/x/gov/simulation/msgs.go index 714ea0b6c..9715a7084 100644 --- a/x/gov/simulation/msgs.go +++ b/x/gov/simulation/msgs.go @@ -64,7 +64,6 @@ func SimulateSubmittingVotingAndSlashingForProposal(k gov.Keeper, sk stake.Keepe whoVotes := r.Perm(len(accs)) // didntVote := whoVotes[numVotes:] whoVotes = whoVotes[:numVotes] - //votingPeriod := k.GetVotingProcedure(ctx).VotingPeriod fops := make([]simulation.FutureOperation, numVotes+1) for i := 0; i < numVotes; i++ { whenVote := ctx.BlockHeader().Time.Add(time.Duration(r.Int63n(int64(msg.VotingPeriod))) * time.Second) diff --git a/x/gov/simulation/sim_test.go b/x/gov/simulation/sim_test.go index 2dc20ded0..f19b16482 100644 --- a/x/gov/simulation/sim_test.go +++ b/x/gov/simulation/sim_test.go @@ -32,7 +32,7 @@ func TestGovWithRandomMessages(t *testing.T) { paramKeeper := params.NewKeeper(mapp.Cdc, paramKey, paramTKey) stakeKeeper := stake.NewKeeper(mapp.Cdc, stakeKey, stakeTKey, bankKeeper, paramKeeper.Subspace(stake.DefaultParamspace), stake.DefaultCodespace) govKey := sdk.NewKVStoreKey("gov") - govKeeper := gov.NewKeeper(mapp.Cdc, govKey, paramKeeper, paramKeeper.Subspace(gov.DefaultParamspace), bankKeeper, stakeKeeper, gov.DefaultCodespace, &sdk.Pool{}) + govKeeper := gov.NewKeeper(mapp.Cdc, govKey, paramKeeper, paramKeeper.Subspace(gov.DefaultParamSpace), bankKeeper, stakeKeeper, gov.DefaultCodespace, &sdk.Pool{}) mapp.Router().AddRoute("gov", gov.NewHandler(govKeeper)) mapp.SetEndBlocker(func(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { gov.EndBlocker(ctx, govKeeper) diff --git a/x/gov/tally.go b/x/gov/tally.go index 1ac3c93ea..685c70770 100644 --- a/x/gov/tally.go +++ b/x/gov/tally.go @@ -6,11 +6,11 @@ import ( // validatorGovInfo used for tallying type validatorGovInfo struct { - Address sdk.ValAddress // address of the validator operator - Power sdk.Dec // Power of a Validator - DelegatorShares sdk.Dec // Total outstanding delegator shares - Minus sdk.Dec // Minus of validator, used to compute validator's voting power - Vote VoteOption // Vote of the validator + Address sdk.ValAddress // address of the validator operator + Power sdk.Dec // Power of a Validator + DelegatorShares sdk.Dec // Total outstanding delegator shares + DelegatorDeductions sdk.Dec // Delegator deductions from validator's delegators voting independently + Vote VoteOption // Vote of the validator } func Tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, refundDeposits bool, tallyResults TallyResult) { @@ -25,11 +25,11 @@ func Tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, refu keeper.vs.IterateValidatorsBonded(ctx, func(index int64, validator sdk.Validator) (stop bool) { currValidators[validator.GetOperator().String()] = validatorGovInfo{ - Address: validator.GetOperator(), - Power: validator.GetPower(), - DelegatorShares: validator.GetDelegatorShares(), - Minus: sdk.ZeroDec(), - Vote: OptionEmpty, + Address: validator.GetOperator(), + Power: validator.GetPower(), + DelegatorShares: validator.GetDelegatorShares(), + DelegatorDeductions: sdk.ZeroDec(), + Vote: OptionEmpty, } return false }) @@ -53,7 +53,7 @@ func Tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, refu valAddrStr := delegation.GetValidatorAddr().String() if val, ok := currValidators[valAddrStr]; ok { - val.Minus = val.Minus.Add(delegation.GetShares()) + val.DelegatorDeductions = val.DelegatorDeductions.Add(delegation.GetShares()) currValidators[valAddrStr] = val delegatorShare := delegation.GetShares().Quo(val.DelegatorShares) @@ -76,7 +76,7 @@ func Tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, refu continue } - sharesAfterMinus := val.DelegatorShares.Sub(val.Minus) + sharesAfterMinus := val.DelegatorShares.Sub(val.DelegatorDeductions) percentAfterMinus := sharesAfterMinus.Quo(val.DelegatorShares) votingPower := val.Power.Mul(percentAfterMinus) @@ -84,7 +84,7 @@ func Tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, refu totalVotingPower = totalVotingPower.Add(votingPower) } - tallyingProcedure := keeper.GetTallyingProcedure(ctx) + tallyingParams := keeper.GetTallyParams(ctx) totalPower := keeper.vs.TotalPower(ctx) tallyResults = TallyResult{ Yes: results[OptionYes], @@ -100,7 +100,7 @@ func Tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, refu } // If there is not enough quorum of votes, the proposal fails percentVoting := totalVotingPower.Quo(totalPower) - if percentVoting.LT(tallyingProcedure.Quorum) { + if percentVoting.LT(tallyingParams.Quorum) { return false, true, tallyResults } // If no one votes, proposal fails @@ -108,11 +108,11 @@ func Tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, refu return false, true, tallyResults } // If more than 1/3 of voters veto, proposal fails - if results[OptionNoWithVeto].Quo(totalVotingPower).GT(tallyingProcedure.Veto) { + if results[OptionNoWithVeto].Quo(totalVotingPower).GT(tallyingParams.Veto) { return false, false, tallyResults } // If more than 1/2 of non-abstaining voters vote Yes, proposal passes - if results[OptionYes].Quo(totalVotingPower.Sub(results[OptionAbstain])).GT(tallyingProcedure.Threshold) { + if results[OptionYes].Quo(totalVotingPower.Sub(results[OptionAbstain])).GT(tallyingParams.Threshold) { return true, true, tallyResults } // If more than 1/2 of non-abstaining voters vote No, proposal fails diff --git a/x/stake/keeper/test_common.go b/x/stake/keeper/test_common.go index 5c67f5428..462c07b42 100644 --- a/x/stake/keeper/test_common.go +++ b/x/stake/keeper/test_common.go @@ -137,7 +137,7 @@ func CreateTestInput(t *testing.T, isCheckTx bool, initCoins int64) (sdk.Context } // hodgepodge of all sorts of input required for testing -func CreateTestInputWithGov(t *testing.T, isCheckTx bool, initCoins int64) (sdk.Context, auth.AccountKeeper, Keeper, gov.Keeper, *codec.Codec ) { +func CreateTestInputWithGov(t *testing.T, isCheckTx bool, initCoins int64) (sdk.Context, auth.AccountKeeper, Keeper, gov.Keeper, *codec.Codec) { keyStake := sdk.NewKVStoreKey("stake") tkeyStake := sdk.NewTransientStoreKey("transient_stake") @@ -179,7 +179,7 @@ func CreateTestInputWithGov(t *testing.T, isCheckTx bool, initCoins int64) (sdk. pk := params.NewKeeper(cdc, keyParams, tkeyParams) keeper := NewKeeper(cdc, keyStake, tkeyStake, ck, pk.Subspace(DefaultParamspace), types.DefaultCodespace) - govKeeper := gov.NewKeeper(cdc, govKey, pk, pk.Subspace(gov.DefaultParamspace), ck, keeper, gov.DefaultCodespace, &sdk.Pool{}) + govKeeper := gov.NewKeeper(cdc, govKey, pk, pk.Subspace(gov.DefaultParamSpace), ck, keeper, gov.DefaultCodespace, &sdk.Pool{}) keeper.SetPool(ctx, types.InitialPool()) keeper.SetParams(ctx, types.DefaultParams())