diff --git a/.gitignore b/.gitignore index dec322b7b..cbc5e5e22 100644 --- a/.gitignore +++ b/.gitignore @@ -39,3 +39,8 @@ vagrant # Graphviz dependency-graph.png + +# Latex +*.aux +*.out +*.synctex.gz diff --git a/PENDING.md b/PENDING.md index 804b1b318..2078f8cf0 100644 --- a/PENDING.md +++ b/PENDING.md @@ -82,9 +82,11 @@ BREAKING CHANGES * [x/stake] \#2412 Added an unbonding validator queue to EndBlock to automatically update validator.Status when finished Unbonding * [x/stake] \#2500 Block conflicting redelegations until we add an index * [x/params] Global Paramstore refactored + * [types] \#2506 sdk.Dec MarshalJSON now marshals as a normal Decimal, with 10 digits of decimal precision * [x/stake] \#2508 Utilize Tendermint power for validator power key * [x/stake] \#2531 Remove all inflation logic * [x/mint] \#2531 Add minting module and inflation logic + * [x/auth] [\#2540](https://github.com/cosmos/cosmos-sdk/issues/2540) Rename `AccountMapper` to `AccountKeeper`. * Tendermint * Update tendermint version from v0.23.0 to v0.25.0, notable changes @@ -108,6 +110,7 @@ FEATURES * [gaia-lite] [\#1954](https://github.com/cosmos/cosmos-sdk/issues/1954) Add /broadcast endpoint to broadcast transactions signed by the /sign endpoint. * [gaia-lite] [\#2113](https://github.com/cosmos/cosmos-sdk/issues/2113) Rename `/accounts/{address}/send` to `/bank/accounts/{address}/transfers`, rename `/accounts/{address}` to `/auth/accounts/{address}` * [gaia-lite] [\#2478](https://github.com/cosmos/cosmos-sdk/issues/2478) Add query gov proposal's deposits endpoint + * [gaia-lite] [\#2477](https://github.com/cosmos/cosmos-sdk/issues/2477) Add query validator's outgoing redelegations and unbonding delegations endpoints * Gaia CLI (`gaiacli`) * [cli] Cmds to query staking pool and params @@ -202,6 +205,7 @@ BUG FIXES * Gaia CLI (`gaiacli`) * [cli] [\#1997](https://github.com/cosmos/cosmos-sdk/issues/1997) Handle panics gracefully when `gaiacli stake {delegation,unbond}` fail to unmarshal delegation. * [cli] [\#2265](https://github.com/cosmos/cosmos-sdk/issues/2265) Fix JSON formatting of the `gaiacli send` command. + * [cli] [\#2547](https://github.com/cosmos/cosmos-sdk/issues/2547) Mark --to and --amount as required flags for `gaiacli tx send`. * Gaia * [x/stake] Return correct Tendermint validator update set on `EndBlocker` by not diff --git a/client/lcd/lcd_test.go b/client/lcd/lcd_test.go index d4d038016..a173ac0e2 100644 --- a/client/lcd/lcd_test.go +++ b/client/lcd/lcd_test.go @@ -11,7 +11,6 @@ import ( "time" "github.com/spf13/viper" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" p2p "github.com/tendermint/tendermint/p2p" @@ -77,7 +76,7 @@ func TestKeys(t *testing.T) { // test if created account is the correct account expectedInfo, _ := GetKeyBase(t).CreateKey(newName, seed, newPassword) expectedAccount := sdk.AccAddress(expectedInfo.GetPubKey().Address().Bytes()) - assert.Equal(t, expectedAccount.String(), addr2Bech32) + require.Equal(t, expectedAccount.String(), addr2Bech32) // existing keys res, body = Request(t, port, "GET", "/keys", nil) @@ -511,7 +510,7 @@ func TestValidatorQuery(t *testing.T) { require.Equal(t, 1, len(operAddrs)) validator := getValidator(t, port, operAddrs[0]) - assert.Equal(t, validator.OperatorAddr, operAddrs[0], "The returned validator does not hold the correct data") + require.Equal(t, validator.OperatorAddr, operAddrs[0], "The returned validator does not hold the correct data") } func TestBonding(t *testing.T) { @@ -557,11 +556,10 @@ func TestBonding(t *testing.T) { bondedValidator := getDelegatorValidator(t, port, addr, operAddrs[0]) require.Equal(t, operAddrs[0], bondedValidator.OperatorAddr) - ////////////////////// // testing unbonding // create unbond TX - resultTx = doBeginUnbonding(t, port, seed, name, password, addr, operAddrs[0], 60) + resultTx = doBeginUnbonding(t, port, seed, name, password, addr, operAddrs[0], 30) tests.WaitForHeight(resultTx.Height+1, port) require.Equal(t, uint32(0), resultTx.CheckTx.Code) @@ -573,33 +571,51 @@ func TestBonding(t *testing.T) { require.Equal(t, int64(40), coins.AmountOf("steak").Int64()) unbonding := getUndelegation(t, port, addr, operAddrs[0]) - require.Equal(t, "60", unbonding.Balance.Amount.String()) + require.Equal(t, "30", unbonding.Balance.Amount.String()) + + // test redelegation + resultTx = doBeginRedelegation(t, port, seed, name, password, addr, operAddrs[0], operAddrs[1], 30) + tests.WaitForHeight(resultTx.Height+1, port) + + require.Equal(t, uint32(0), resultTx.CheckTx.Code) + require.Equal(t, uint32(0), resultTx.DeliverTx.Code) summary = getDelegationSummary(t, port, addr) - require.Len(t, summary.Delegations, 0, "Delegation summary holds all delegations") + require.Len(t, summary.Delegations, 1, "Delegation summary holds all delegations") require.Len(t, summary.UnbondingDelegations, 1, "Delegation summary holds all unbonding-delegations") - require.Equal(t, "60", summary.UnbondingDelegations[0].Balance.Amount.String()) + require.Len(t, summary.Redelegations, 1, "Delegation summary holds all redelegations") + + require.Equal(t, "30.0000000000", summary.Delegations[0].GetShares().String()) + require.Equal(t, "30", summary.UnbondingDelegations[0].Balance.Amount.String()) + require.Equal(t, "30", summary.Redelegations[0].Balance.Amount.String()) + + validatorUbds := getValidatorUnbondingDelegations(t, port, operAddrs[0]) + require.Len(t, validatorUbds, 1) + require.Equal(t, "30", validatorUbds[0].Balance.Amount.String()) + + validatorReds := getValidatorRedelegations(t, port, operAddrs[0]) + require.Len(t, validatorReds, 1) + require.Equal(t, "30", validatorReds[0].Balance.Amount.String()) bondedValidators = getDelegatorValidators(t, port, addr) - require.Len(t, bondedValidators, 0, "There's no delegation as the user withdraw all funds") + require.Len(t, bondedValidators, 1, "There's a delegation as the user only withdraw half of the funds") // TODO Undonding status not currently implemented // require.Equal(t, sdk.Unbonding, bondedValidators[0].Status) - // TODO add redelegation, need more complex capabilities such to mock context and - // TODO check summary for redelegation - // assert.Len(t, summary.Redelegations, 1, "Delegation summary holds all redelegations") - // query txs txs := getBondingTxs(t, port, addr, "") - assert.Len(t, txs, 2, "All Txs found") + require.Len(t, txs, 3, "All Txs found") txs = getBondingTxs(t, port, addr, "bond") - assert.Len(t, txs, 1, "All bonding txs found") + require.Len(t, txs, 1, "All bonding txs found") txs = getBondingTxs(t, port, addr, "unbond") - assert.Len(t, txs, 1, "All unbonding txs found") + require.Len(t, txs, 1, "All unbonding txs found") + + txs = getBondingTxs(t, port, addr, "redelegate") + require.Len(t, txs, 1, "All redelegation txs found") } func TestSubmitProposal(t *testing.T) { @@ -974,11 +990,11 @@ func getUndelegation(t *testing.T, port string, delegatorAddr sdk.AccAddress, va res, body := Request(t, port, "GET", fmt.Sprintf("/stake/delegators/%s/unbonding_delegations/%s", delegatorAddr, validatorAddr), nil) require.Equal(t, http.StatusOK, res.StatusCode, body) - var unbondings stake.UnbondingDelegation - err := cdc.UnmarshalJSON([]byte(body), &unbondings) + var unbond stake.UnbondingDelegation + err := cdc.UnmarshalJSON([]byte(body), &unbond) require.Nil(t, err) - return unbondings + return unbond } func getDelegationSummary(t *testing.T, port string, delegatorAddr sdk.AccAddress) stake.DelegationSummary { @@ -1052,9 +1068,7 @@ func doDelegate(t *testing.T, port, seed, name, password string, } ], "begin_unbondings": [], - "complete_unbondings": [], "begin_redelegates": [], - "complete_redelegates": [], "base_req": { "name": "%s", "password": "%s", @@ -1091,9 +1105,7 @@ func doBeginUnbonding(t *testing.T, port, seed, name, password string, "shares": "%d" } ], - "complete_unbondings": [], "begin_redelegates": [], - "complete_redelegates": [], "base_req": { "name": "%s", "password": "%s", @@ -1114,7 +1126,7 @@ func doBeginUnbonding(t *testing.T, port, seed, name, password string, } func doBeginRedelegation(t *testing.T, port, seed, name, password string, - delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) (resultTx ctypes.ResultBroadcastTxCommit) { + delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress, amount int64) (resultTx ctypes.ResultBroadcastTxCommit) { acc := getAccount(t, port, delAddr) accnum := acc.GetAccountNumber() @@ -1125,16 +1137,14 @@ func doBeginRedelegation(t *testing.T, port, seed, name, password string, jsonStr := []byte(fmt.Sprintf(`{ "delegations": [], "begin_unbondings": [], - "complete_unbondings": [], "begin_redelegates": [ { "delegator_addr": "%s", "validator_src_addr": "%s", "validator_dst_addr": "%s", - "shares": "30" + "shares": "%d" } ], - "complete_redelegates": [], "base_req": { "name": "%s", "password": "%s", @@ -1142,7 +1152,7 @@ func doBeginRedelegation(t *testing.T, port, seed, name, password string, "account_number":"%d", "sequence":"%d" } - }`, delAddr, valSrcAddr, valDstAddr, name, password, chainID, accnum, sequence)) + }`, delAddr, valSrcAddr, valDstAddr, amount, name, password, chainID, accnum, sequence)) res, body := Request(t, port, "POST", fmt.Sprintf("/stake/delegators/%s/delegations", delAddr), jsonStr) require.Equal(t, http.StatusOK, res.StatusCode, body) @@ -1176,6 +1186,28 @@ func getValidator(t *testing.T, port string, validatorAddr sdk.ValAddress) stake return validator } +func getValidatorUnbondingDelegations(t *testing.T, port string, validatorAddr sdk.ValAddress) []stake.UnbondingDelegation { + res, body := Request(t, port, "GET", fmt.Sprintf("/stake/validators/%s/unbonding_delegations", validatorAddr.String()), nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + + var ubds []stake.UnbondingDelegation + err := cdc.UnmarshalJSON([]byte(body), &ubds) + require.Nil(t, err) + + return ubds +} + +func getValidatorRedelegations(t *testing.T, port string, validatorAddr sdk.ValAddress) []stake.Redelegation { + res, body := Request(t, port, "GET", fmt.Sprintf("/stake/validators/%s/redelegations", validatorAddr.String()), nil) + require.Equal(t, http.StatusOK, res.StatusCode, body) + + var reds []stake.Redelegation + err := cdc.UnmarshalJSON([]byte(body), &reds) + require.Nil(t, err) + + return reds +} + // ============= Governance Module ================ func getProposal(t *testing.T, port string, proposalID int64) gov.Proposal { diff --git a/cmd/gaia/app/app.go b/cmd/gaia/app/app.go index 0d0fd0636..33c606105 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -57,7 +57,7 @@ type GaiaApp struct { tkeyParams *sdk.TransientStoreKey // Manage getting and setting accounts - accountMapper auth.AccountMapper + accountKeeper auth.AccountKeeper feeCollectionKeeper auth.FeeCollectionKeeper bankKeeper bank.Keeper stakeKeeper stake.Keeper @@ -92,15 +92,15 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio tkeyParams: sdk.NewTransientStoreKey("transient_params"), } - // define the accountMapper - app.accountMapper = auth.NewAccountMapper( + // define the accountKeeper + app.accountKeeper = auth.NewAccountKeeper( app.cdc, app.keyAccount, // target store auth.ProtoBaseAccount, // prototype ) // add handlers - app.bankKeeper = bank.NewBaseKeeper(app.accountMapper) + app.bankKeeper = bank.NewBaseKeeper(app.accountKeeper) app.feeCollectionKeeper = auth.NewFeeCollectionKeeper( app.cdc, app.keyFeeCollection, @@ -160,7 +160,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptio app.keySlashing, app.keyGov, app.keyFeeCollection, app.keyParams) app.SetInitChainer(app.initChainer) app.SetBeginBlocker(app.BeginBlocker) - app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) + app.SetAnteHandler(auth.NewAnteHandler(app.accountKeeper, app.feeCollectionKeeper)) app.MountStoresTransient(app.tkeyParams, app.tkeyStake, app.tkeyDistr) app.SetEndBlocker(app.EndBlocker) @@ -232,8 +232,8 @@ func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci // load the accounts for _, gacc := range genesisState.Accounts { acc := gacc.ToAccount() - acc.AccountNumber = app.accountMapper.GetNextAccountNumber(ctx) - app.accountMapper.SetAccount(ctx, acc) + acc.AccountNumber = app.accountKeeper.GetNextAccountNumber(ctx) + app.accountKeeper.SetAccount(ctx, acc) } // load the initial stake information @@ -300,7 +300,7 @@ func (app *GaiaApp) ExportAppStateAndValidators() (appState json.RawMessage, val accounts = append(accounts, account) return false } - app.accountMapper.IterateAccounts(ctx, appendAccount) + app.accountKeeper.IterateAccounts(ctx, appendAccount) genState := NewGenesisState( accounts, stake.WriteGenesis(ctx, app.stakeKeeper), diff --git a/cmd/gaia/app/sim_test.go b/cmd/gaia/app/sim_test.go index 630165cd0..e76dbc1aa 100644 --- a/cmd/gaia/app/sim_test.go +++ b/cmd/gaia/app/sim_test.go @@ -104,29 +104,29 @@ func appStateFn(r *rand.Rand, accs []simulation.Account) json.RawMessage { func testAndRunTxs(app *GaiaApp) []simulation.WeightedOperation { return []simulation.WeightedOperation{ - {5, authsim.SimulateDeductFee(app.accountMapper, app.feeCollectionKeeper)}, - {100, banksim.SingleInputSendMsg(app.accountMapper, app.bankKeeper)}, - {50, distributionsim.SimulateMsgSetWithdrawAddress(app.accountMapper, app.distrKeeper)}, - {50, distributionsim.SimulateMsgWithdrawDelegatorRewardsAll(app.accountMapper, app.distrKeeper)}, - {50, distributionsim.SimulateMsgWithdrawDelegatorReward(app.accountMapper, app.distrKeeper)}, - {50, distributionsim.SimulateMsgWithdrawValidatorRewardsAll(app.accountMapper, app.distrKeeper)}, + {5, authsim.SimulateDeductFee(app.accountKeeper, app.feeCollectionKeeper)}, + {100, banksim.SingleInputSendMsg(app.accountKeeper, app.bankKeeper)}, + {50, distributionsim.SimulateMsgSetWithdrawAddress(app.accountKeeper, app.distrKeeper)}, + {50, distributionsim.SimulateMsgWithdrawDelegatorRewardsAll(app.accountKeeper, app.distrKeeper)}, + {50, distributionsim.SimulateMsgWithdrawDelegatorReward(app.accountKeeper, app.distrKeeper)}, + {50, distributionsim.SimulateMsgWithdrawValidatorRewardsAll(app.accountKeeper, app.distrKeeper)}, {5, govsim.SimulateSubmittingVotingAndSlashingForProposal(app.govKeeper, app.stakeKeeper)}, {100, govsim.SimulateMsgDeposit(app.govKeeper, app.stakeKeeper)}, - {100, stakesim.SimulateMsgCreateValidator(app.accountMapper, app.stakeKeeper)}, + {100, stakesim.SimulateMsgCreateValidator(app.accountKeeper, app.stakeKeeper)}, {5, stakesim.SimulateMsgEditValidator(app.stakeKeeper)}, - {100, stakesim.SimulateMsgDelegate(app.accountMapper, app.stakeKeeper)}, - {100, stakesim.SimulateMsgBeginUnbonding(app.accountMapper, app.stakeKeeper)}, - {100, stakesim.SimulateMsgBeginRedelegate(app.accountMapper, app.stakeKeeper)}, + {100, stakesim.SimulateMsgDelegate(app.accountKeeper, app.stakeKeeper)}, + {100, stakesim.SimulateMsgBeginUnbonding(app.accountKeeper, app.stakeKeeper)}, + {100, stakesim.SimulateMsgBeginRedelegate(app.accountKeeper, app.stakeKeeper)}, {100, slashingsim.SimulateMsgUnjail(app.slashingKeeper)}, } } func invariants(app *GaiaApp) []simulation.Invariant { return []simulation.Invariant{ - banksim.NonnegativeBalanceInvariant(app.accountMapper), - distributionsim.AllInvariants(app.bankKeeper, app.distrKeeper, app.accountMapper), + banksim.NonnegativeBalanceInvariant(app.accountKeeper), + distributionsim.AllInvariants(app.bankKeeper, app.distrKeeper, app.accountKeeper), govsim.AllInvariants(), - stakesim.AllInvariants(app.bankKeeper, app.stakeKeeper, app.feeCollectionKeeper, app.distrKeeper, app.accountMapper), + stakesim.AllInvariants(app.bankKeeper, app.stakeKeeper, app.feeCollectionKeeper, app.distrKeeper, app.accountKeeper), slashingsim.AllInvariants(), } } diff --git a/cmd/gaia/cmd/gaiadebug/hack.go b/cmd/gaia/cmd/gaiadebug/hack.go index db22da0b5..734a83df3 100644 --- a/cmd/gaia/cmd/gaiadebug/hack.go +++ b/cmd/gaia/cmd/gaiadebug/hack.go @@ -138,7 +138,7 @@ type GaiaApp struct { tkeyParams *sdk.TransientStoreKey // Manage getting and setting accounts - accountMapper auth.AccountMapper + accountKeeper auth.AccountKeeper feeCollectionKeeper auth.FeeCollectionKeeper bankKeeper bank.Keeper stakeKeeper stake.Keeper @@ -165,15 +165,15 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, baseAppOptions ...func(*bam.BaseAp tkeyParams: sdk.NewTransientStoreKey("transient_params"), } - // define the accountMapper - app.accountMapper = auth.NewAccountMapper( + // define the accountKeeper + app.accountKeeper = auth.NewAccountKeeper( app.cdc, app.keyAccount, // target store auth.ProtoBaseAccount, // prototype ) // add handlers - app.bankKeeper = bank.NewBaseKeeper(app.accountMapper) + app.bankKeeper = bank.NewBaseKeeper(app.accountKeeper) app.paramsKeeper = params.NewKeeper(app.cdc, app.keyParams, app.tkeyParams) app.stakeKeeper = stake.NewKeeper(app.cdc, app.keyStake, app.tkeyStake, app.bankKeeper, app.paramsKeeper.Subspace(stake.DefaultParamspace), app.RegisterCodespace(stake.DefaultCodespace)) app.slashingKeeper = slashing.NewKeeper(app.cdc, app.keySlashing, app.stakeKeeper, app.paramsKeeper.Subspace(slashing.DefaultParamspace), app.RegisterCodespace(slashing.DefaultCodespace)) @@ -187,7 +187,7 @@ func NewGaiaApp(logger log.Logger, db dbm.DB, baseAppOptions ...func(*bam.BaseAp app.SetInitChainer(app.initChainer) app.SetBeginBlocker(app.BeginBlocker) app.SetEndBlocker(app.EndBlocker) - app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) + app.SetAnteHandler(auth.NewAnteHandler(app.accountKeeper, app.feeCollectionKeeper)) app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyStake, app.keySlashing, app.keyParams) app.MountStore(app.tkeyParams, sdk.StoreTypeTransient) err := app.LoadLatestVersion(app.keyMain) @@ -246,7 +246,7 @@ func (app *GaiaApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) abci // load the accounts for _, gacc := range genesisState.Accounts { acc := gacc.ToAccount() - app.accountMapper.SetAccount(ctx, acc) + app.accountKeeper.SetAccount(ctx, acc) } // load the initial stake information diff --git a/docs/sdk/core/app3.md b/docs/sdk/core/app3.md index 595a3694f..2462e3e66 100644 --- a/docs/sdk/core/app3.md +++ b/docs/sdk/core/app3.md @@ -86,7 +86,7 @@ type BaseAccount struct { It simply contains a field for each of the methods. -### AccountMapper +### AccountKeeper In previous apps using our `appAccount`, we handled marshaling/unmarshaling the account from the store ourselves, by performing @@ -95,36 +95,36 @@ to work with in our applications. In the SDK, we use the term `Mapper` to refer to an abstaction over a KVStore that handles marshalling and unmarshalling a particular data type to and from the underlying store. -The `x/auth` module provides an `AccountMapper` that allows us to get and +The `x/auth` module provides an `AccountKeeper` that allows us to get and set `Account` types to the store. Note the benefit of using the `Account` interface here - developers can implement their own account type that extends the `BaseAccount` to store additional data without requiring another lookup from the store. -Creating an AccountMapper is easy - we just need to specify a codec, a +Creating an AccountKeeper is easy - we just need to specify a codec, a capability key, and a prototype of the object being encoded ```go -accountMapper := auth.NewAccountMapper(cdc, keyAccount, auth.ProtoBaseAccount) +accountKeeper := auth.NewAccountKeeper(cdc, keyAccount, auth.ProtoBaseAccount) ``` Then we can get, modify, and set accounts. For instance, we could double the amount of coins in an account: ```go -acc := accountMapper.GetAccount(ctx, addr) +acc := accountKeeper.GetAccount(ctx, addr) acc.SetCoins(acc.Coins.Plus(acc.Coins)) -accountMapper.SetAccount(ctx, addr) +accountKeeper.SetAccount(ctx, addr) ``` -Note that the `AccountMapper` takes a `Context` as the first argument, and will +Note that the `AccountKeeper` takes a `Context` as the first argument, and will load the KVStore from there using the capability key it was granted on creation. Also note that you must explicitly call `SetAccount` after mutating an account for the change to persist! -See the [AccountMapper API -docs](https://godoc.org/github.com/cosmos/cosmos-sdk/x/auth#AccountMapper) for more information. +See the [AccountKeeper API +docs](https://godoc.org/github.com/cosmos/cosmos-sdk/x/auth#AccountKeeper) for more information. ## StdTx @@ -224,10 +224,10 @@ all the relevant information. As we saw in `App2`, we can use an `AnteHandler` to authenticate transactions before we handle any of their internal messages. While previously we implemented our own simple `AnteHandler`, the `x/auth` module provides a much more advanced -one that uses `AccountMapper` and works with `StdTx`: +one that uses `AccountKeeper` and works with `StdTx`: ```go -app.SetAnteHandler(auth.NewAnteHandler(accountMapper, feeKeeper)) +app.SetAnteHandler(auth.NewAnteHandler(accountKeeper, feeKeeper)) ``` The AnteHandler provided by `x/auth` enforces the following rules: @@ -263,7 +263,7 @@ The fee is paid by the first address returned by `msg.GetSigners()` for the firs ## CoinKeeper -Now that we've seen the `auth.AccountMapper` and how its used to build a +Now that we've seen the `auth.AccountKeeper` and how its used to build a complete AnteHandler, it's time to look at how to build higher-level abstractions for taking action on accounts. @@ -274,26 +274,26 @@ which expose only limitted functionality on the underlying types stored by the ` For instance, the `x/bank` module defines the canonical versions of `MsgSend` and `MsgIssue` for the SDK, as well as a `Handler` for processing them. However, -rather than passing a `KVStore` or even an `AccountMapper` directly to the handler, +rather than passing a `KVStore` or even an `AccountKeeper` directly to the handler, we introduce a `bank.Keeper`, which can only be used to transfer coins in and out of accounts. This allows us to determine up front that the only effect the bank module's `Handler` can have on the store is to change the amount of coins in an account - it can't increment sequence numbers, change PubKeys, or otherwise. -A `bank.Keeper` is easily instantiated from an `AccountMapper`: +A `bank.Keeper` is easily instantiated from an `AccountKeeper`: ```go -bankKeeper = bank.NewBaseKeeper(accountMapper) +bankKeeper = bank.NewBaseKeeper(accountKeeper) ``` We can then use it within a handler, instead of working directly with the -`AccountMapper`. For instance, to add coins to an account: +`AccountKeeper`. For instance, to add coins to an account: ```go -// Finds account with addr in AccountMapper. +// Finds account with addr in AccountKeeper. // Adds coins to account's coin array. -// Sets updated account in AccountMapper +// Sets updated account in AccountKeeper app.bankKeeper.AddCoins(ctx, addr, coins) ``` @@ -311,12 +311,12 @@ accounts. We use this `Keeper` paradigm extensively in the SDK as the way to define what kind of functionality each module gets access to. In particular, we try to follow the *principle of least authority*. -Rather than providing full blown access to the `KVStore` or the `AccountMapper`, +Rather than providing full blown access to the `KVStore` or the `AccountKeeper`, we restrict access to a small number of functions that do very specific things. ## App3 -With the `auth.AccountMapper` and `bank.Keeper` in hand, +With the `auth.AccountKeeper` and `bank.Keeper` in hand, we're now ready to build `App3`. The `x/auth` and `x/bank` modules do all the heavy lifting: @@ -334,11 +334,11 @@ func NewApp3(logger log.Logger, db dbm.DB) *bapp.BaseApp { keyFees := sdk.NewKVStoreKey("fee") // TODO // Set various mappers/keepers to interact easily with underlying stores - accountMapper := auth.NewAccountMapper(cdc, keyAccount, auth.ProtoBaseAccount) - bankKeeper := bank.NewBaseKeeper(accountMapper) + accountKeeper := auth.NewAccountKeeper(cdc, keyAccount, auth.ProtoBaseAccount) + bankKeeper := bank.NewBaseKeeper(accountKeeper) feeKeeper := auth.NewFeeCollectionKeeper(cdc, keyFees) - app.SetAnteHandler(auth.NewAnteHandler(accountMapper, feeKeeper)) + app.SetAnteHandler(auth.NewAnteHandler(accountKeeper, feeKeeper)) // Register message routes. // Note the handler gets access to diff --git a/docs/sdk/core/examples/app3.go b/docs/sdk/core/examples/app3.go index 9a101c281..453970c1a 100644 --- a/docs/sdk/core/examples/app3.go +++ b/docs/sdk/core/examples/app3.go @@ -30,11 +30,11 @@ func NewApp3(logger log.Logger, db dbm.DB) *bapp.BaseApp { keyFees := sdk.NewKVStoreKey("fee") // TODO // Set various mappers/keepers to interact easily with underlying stores - accountMapper := auth.NewAccountMapper(cdc, keyAccount, auth.ProtoBaseAccount) - bankKeeper := bank.NewBaseKeeper(accountMapper) + accountKeeper := auth.NewAccountKeeper(cdc, keyAccount, auth.ProtoBaseAccount) + bankKeeper := bank.NewBaseKeeper(accountKeeper) feeKeeper := auth.NewFeeCollectionKeeper(cdc, keyFees) - app.SetAnteHandler(auth.NewAnteHandler(accountMapper, feeKeeper)) + app.SetAnteHandler(auth.NewAnteHandler(accountKeeper, feeKeeper)) // Register message routes. // Note the handler gets access to diff --git a/docs/sdk/core/examples/app4.go b/docs/sdk/core/examples/app4.go index e4fa515ee..6d45c4031 100644 --- a/docs/sdk/core/examples/app4.go +++ b/docs/sdk/core/examples/app4.go @@ -28,17 +28,17 @@ func NewApp4(logger log.Logger, db dbm.DB) *bapp.BaseApp { keyAccount := sdk.NewKVStoreKey("acc") // Set various mappers/keepers to interact easily with underlying stores - accountMapper := auth.NewAccountMapper(cdc, keyAccount, auth.ProtoBaseAccount) - bankKeeper := bank.NewBaseKeeper(accountMapper) + accountKeeper := auth.NewAccountKeeper(cdc, keyAccount, auth.ProtoBaseAccount) + bankKeeper := bank.NewBaseKeeper(accountKeeper) // TODO keyFees := sdk.NewKVStoreKey("fee") feeKeeper := auth.NewFeeCollectionKeeper(cdc, keyFees) - app.SetAnteHandler(auth.NewAnteHandler(accountMapper, feeKeeper)) + app.SetAnteHandler(auth.NewAnteHandler(accountKeeper, feeKeeper)) // Set InitChainer - app.SetInitChainer(NewInitChainer(cdc, accountMapper)) + app.SetInitChainer(NewInitChainer(cdc, accountKeeper)) // Register message routes. // Note the handler gets access to the account store. @@ -76,7 +76,7 @@ func (ga *GenesisAccount) ToAccount() (acc *auth.BaseAccount, err error) { // InitChainer will set initial balances for accounts as well as initial coin metadata // MsgIssue can no longer be used to create new coin -func NewInitChainer(cdc *codec.Codec, accountMapper auth.AccountMapper) sdk.InitChainer { +func NewInitChainer(cdc *codec.Codec, accountKeeper auth.AccountKeeper) sdk.InitChainer { return func(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { stateJSON := req.AppStateBytes @@ -91,8 +91,8 @@ func NewInitChainer(cdc *codec.Codec, accountMapper auth.AccountMapper) sdk.Init if err != nil { panic(err) } - acc.AccountNumber = accountMapper.GetNextAccountNumber(ctx) - accountMapper.SetAccount(ctx, acc) + acc.AccountNumber = accountKeeper.GetNextAccountNumber(ctx) + accountKeeper.SetAccount(ctx, acc) } return abci.ResponseInitChain{} diff --git a/docs/sdk/overview.md b/docs/sdk/overview.md index 905982f62..70e826c60 100644 --- a/docs/sdk/overview.md +++ b/docs/sdk/overview.md @@ -127,7 +127,7 @@ func (app *BasecoinApp) initRouterHandlers() { // All handlers must be added here. // The order matters. - app.router.AddRoute("bank", bank.NewHandler(app.accountMapper)) + app.router.AddRoute("bank", bank.NewHandler(app.accountKeeper)) app.router.AddRoute("sketchy", sketchy.NewHandler()) } ``` diff --git a/docs/sdk/sdk-by-examples/simple-governance/bridging-it-all.md b/docs/sdk/sdk-by-examples/simple-governance/bridging-it-all.md index aed6de85e..546eb7d87 100644 --- a/docs/sdk/sdk-by-examples/simple-governance/bridging-it-all.md +++ b/docs/sdk/sdk-by-examples/simple-governance/bridging-it-all.md @@ -45,7 +45,7 @@ type SimpleGovApp struct { simpleGovKeeper simpleGov.Keeper // Manage getting and setting accounts - accountMapper auth.AccountMapper + accountKeeper auth.AccountKeeper } ``` @@ -206,7 +206,7 @@ var cdc = MakeCodec() - Instantiate the keepers. Note that keepers generally need access to other module's keepers. In this case, make sure you only pass an instance of the keeper for the functionality that is needed. If a keeper only needs to read in another module's store, a read-only keeper should be passed to it. ```go -app.bankKeeper = bank.NewBaseKeeper(app.accountMapper) +app.bankKeeper = bank.NewBaseKeeper(app.accountKeeper) app.stakeKeeper = simplestake.NewKeeper(app.capKeyStakingStore, app.bankKeeper,app.RegisterCodespace(simplestake.DefaultCodespace)) app.simpleGovKeeper = simpleGov.NewKeeper(app.capKeySimpleGovStore, app.bankKeeper, app.stakeKeeper, app.RegisterCodespace(simpleGov.DefaultCodespace)) ``` @@ -225,7 +225,7 @@ app.Router(). ```go // Initialize BaseApp. app.MountStoresIAVL(app.capKeyMainStore, app.capKeyAccountStore, app.capKeySimpleGovStore, app.capKeyStakingStore) - app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) + app.SetAnteHandler(auth.NewAnteHandler(app.accountKeeper, app.feeCollectionKeeper)) err := app.LoadLatestVersion(app.capKeyMainStore) if err != nil { cmn.Exit(err.Error()) diff --git a/docs/spec-proposals/f1-fee-distribution/f1_fee_distr.pdf b/docs/spec-proposals/f1-fee-distribution/f1_fee_distr.pdf new file mode 100644 index 000000000..12e7d5906 Binary files /dev/null and b/docs/spec-proposals/f1-fee-distribution/f1_fee_distr.pdf differ diff --git a/docs/spec-proposals/f1-fee-distribution/f1_fee_distr.tex b/docs/spec-proposals/f1-fee-distribution/f1_fee_distr.tex new file mode 100644 index 000000000..969e77ec9 --- /dev/null +++ b/docs/spec-proposals/f1-fee-distribution/f1_fee_distr.tex @@ -0,0 +1,135 @@ +\documentclass[]{article} +\usepackage{hyperref} + +%opening +\title{F1 Fee Distribution Draft-00} +\author{Dev Ojha} + +\begin{document} + +\maketitle + +\begin{abstract} + In a proof of stake blockchain, validators need to split the rewards gained from transaction fees each block. Furthermore, these fees must be fairly distributed to each of a validator's constituent delegators. They accrue this reward throughout the entire time they are delegated, and they have a special operation to withdraw accrued rewards. + + The F1 fee distribution scheme works for any algorithm to split funds between validators each block, with minimal iteration, and the only approximations being due to finite decimal precision. Per block there is a single iteration over the validator set, which enables only rewarding validators who signed a given block. No iteration is required to delegate, and withdrawing only requires iterating over all of that validators slashes since delegation it began. State usage is minimal as well, one state update per validator per block, and one state record per delegator. +\end{abstract} + +\section{F1 Fee Distribution} + +In a proof of stake model, each validator has an associated stake, with delegators each contributing some amount to a validator's stake. +The validator is rewarded transaction fees every block for the service they are providing the network. +In the F1 distribution, each validator is permitted to take a commission from the fees they receive, and the remaining fees should be evenly distributed across the validator's delegators, such that every delegator the percentage of the validator's stake that came from the delegator is the proportion of that validator's remaining tx fees which they are getting. +Iterating over all delegators for every validator each block is too expensive for a blockchain environment. +Instead there is an explicit withdraw fees action which a delegator can take, which will give the delegator the same total amount of fees as though they were receiving it every block. + +Suppose a delegator delegates $x$ stake to a validator at block $h$. +Let the amount of stake the validator has at block $i$ be $s_i$ and the amount of fees they receive at this height be $f_i$. +Then if a delegator contributing $x$ stake decides to withdraw at block $n$, the rewards they receive is +$$\sum_{i = h}^{n} \frac{x}{s_i}f_i = x \sum_{i = h}^{n} \frac{f_i}{s_i}$$ + +However $s_i$ will not change every block. +It only changes if the validator gets slashed, or if someone new has bonded or unbonded. +Handling slashes is relegated to \autoref{ssec:slashing}. +Define a period as the set of blocks between two changes in a given validator's total stake. +A new period begins every time that validator's total stake changes. +The above iteration will be converted to iteration over periods. +Let the total amount of stake for the validator in period $p$ be $n_p$. +Let $T_p$ be the total fees this validator accrued within this period. +Let $h$ be the start of period $p_{init}$, and height $n$ be the end of $p_{final}$. +It follows that +$$x \sum_{i = h}^{n} \frac{f_i}{s_i} = x \sum_{p = p_{init}}^{p_{final}} \frac{T_p}{n_p}$$ + +Let $p_0$ represent the period from when the validator first bonded until the first change to the validators stake. +The central idea to the F1 model is that at the end of the $k$th period, the following is stored at a state location indexable by $k$: $\sum_{i=0}^{k}\frac{T_i}{n_i}$. +When a delegator wants to delegate or withdraw their reward, they first create a new entry in state to end the current period. Let the index of the current period be $f$. +Then this entry is created using the previous entry as follows: $$\sum_{i=0}^{f}\frac{T_i}{n_i} = \sum_{i=0}^{f-1}\frac{T_i}{n_i} + \frac{T_f}{n_f} = entry_{f-1} + \frac{T_f}{n_f}$$ +Where $T_f$ is the fees the validator has accrued in period $f$, and $n_f$ is the validators total amount of stake in period $f$. + +The withdrawer's delegation object has the index $k$ for the period which they started accruing fees for. +Thus the reward they should receive when withdrawing is: + +$$x\left(entry_f - entry_k\right) = x\left(\left(\sum_{i=0}^{f}\frac{T_i}{n_i}\right) - \left(\sum_{i=0}^{k}\frac{T_i}{n_i}\right)\right) = x \sum_{i = k}^{f} \frac{T_i}{n_i}$$ + +The first summation is the state entry for $f$, and the second sum is the state entry at $k$. +It is clear from the equations that this payout mechanism maintains correctness, and required no iterations. + +$T_f$ is a separate variable in state for the amount of fees this validator has accrued since the last update to its power. +This variable is incremented at every block by however much fees this validator received that block. +On the update to the validators power, this variable is used to create the entry in state at $f$. + +This fee distribution proposal is agnostic to how all of the blocks fees are divied up between validators. +This creates many nice properties, for example only rewarding validators who signed that block. + +\section{Additional add-ons} +\subsection{Commission Rates} +Commission rates are the idea that a validator can take a fixed $x\%$ cut of all of their received fees, before redistributing evenly to the constituent delegators. +This can easily be done as follows: + +In block $h$ a validator receives $f_h$ fees. +Instead of incrementing that validators ``total accrued fees this period variable" by $f_h$, it is instead incremented by $(1 - commission\_rate) * f_p$. +Then $commission\_rate * f_p$ is deposited directly to the validator. +This scheme allow for updates to a validator's commission rate every block if desired. + +\subsection{Slashing} +\label{ssec:slashing} +Slashing is distinct from withdrawals, since not only does it lower the validators total amount of stake, but it also lowers each of its delegator's stake by a fixed percentage. +Since noone is charged gas for slashes, a slash cannot iterate over all delegators. +Thus we can no longer just multiply by $x$ over the difference in stake. +The solution here is to instead store each period created by a slash in the validators state. +Then when withdrawing, you must iterate over all slashes between when you started and ended. +Suppose you delegated at period $0$, a y\% slash occured at period $2$, and your withdrawal is period $4$. +Then you receive funds from $0$ to $2$ as normal. +The equations for funds you receive for $2$ to $4$ now uses $(1 - y)x$ for your stake instead of just $x$ stake. +When there are multiple slashes, you just account for the accumulated slash factor. + +In practice this will not really be an efficiency hit, as we can expect most validators to have no slashes. +Validators that get slashed a lot will naturally lose their delegators. +A malicious validator that gets itself slashed many times would increase the gas to withdraw linearly, but the economic loss of funds due to the slashes should far out-weigh the extra overhead the withdrawer must pay for due to the gas. + +\subsection{Inflation} +Inflation is the idea that we want every staked coin to grow in value as time progresses. Each block, every staked token should each be rewarded $x$ staking tokens as inflation, where $x$ is calculated from function which takes state and the block information as input. This also allows for many seemless upgrade's to $x$'s algorithm. This can be added efficiently into the fee distribution model as follows: + +Make each block have an inflation number, by which every staked token should produce $x$ additional staking tokens. In state there is a variable for the sum of all such inflation numbers. Then each period will store this total inflation sum in addition to $\sum_{i=0}^{end}\frac{T_i}{n_i}$. When withdrawing perform a subtraction on the inflation sums at the end and at the start to see how many new staking tokens to produce per staked token. + +This works great in the model where the inflation rate should be dynamic each block, but apply the same to each validator. Inflation creation can trivially be epoched as long as inflation isn't required within the epoch, through changes to the $x$ function. + +Note that this process is extremely efficient. + +The above can be trivially amended if we want inflation to proceed differently for different validators each block. (e.g. depending on who was offline) It can also be made to be easily adapted in a live chain. It is unclear if either of these two are more desirable settings. + +\subsection{Delegation updates} +Updating your delegation amount is equivalent to withdrawing earned rewards and a fully independent new delegation occuring in the same block. + +\subsection{Jailing / being kicked out of the validator set} +This basically requires no change. In each block you only iterate over the currently bonded validators. So you simply don't update the "total accrued fees this period" variable for jailed / non-bonded validators. Withdrawing requires \textit{no} special casing here! + +\section{State pruning} +You will notice that in the main scheme there was no note for pruning entries from state. +We can in fact prune quite effectively. +Suppose for the sake of exposition that there is at most one delegation / withdrawal to a particular validator in any given block. +Then each delegation is responsible for one addition to state. +Only the next period, and this delegator's withdrawal could depend on this entry. Thus once this delegator withdraws, this state entry can be pruned. +For the entry created by the delegator's withdrawal, that is only required by the creation of the next period. Thus once the next period is created, that withdrawal's period can be deleted. + +This can be easily adapted to the case where there are multiple delegations / withdrawals per block. Keep a counter per state entry for how many delegations need to be cleared. (So 1 for each delegation in that block which created that period, 0 for each withdrawal) When creating a new period, check that the previous period (which had to be read anyway) doesn't have a count of 0. If it does have a count of 0, delete it. When withdrawing, decrement the period which created this delegation's counter by 1. If that counter is now 0, delete that period. + +The slash entries for a validator can only be pruned when all of that validator's delegators have their bonding period starting after the slash. This seems ineffective to keep track of, thus it is not worth it. Each slash should instead remain in state until the validator unbonds and all delegators have their fees withdrawn. + +\section{Implementers Considerations} + +This is an extremely simple scheme with many nice benefits. +\begin{itemize} + \item The overhead per block is a simple iteration over the bonded validator set, which occurs anyway. (Thus it can be implemented ``for-free" with an optimized code-base) + \item Withdrawing earned fees only requires iterating over slashes since when you bonded. (Which is a negligible iteration) + \item There are no approximations in any of the calculations. (modulo minor errata resulting from fixed precision decimals used in divisions) + \item Supports arbitrary inflation models. (Thus could even vary upon block signers) + \item Supports arbitrary fee distribution amongst the validator set. (Thus can account for things like only online validators get fees, which has important incentivization impacts) + \item The above two can change on a live chain with no issues. + \item Validator commission rates can be changed every block + \item The simplicity of this scheme lends itself well to implementation +\end{itemize} + +Thus this scheme has efficiency improvements, simplicity improvements, and expressiveness improvements over the currently proposed schemes. With a correct fee distribution amongst the validator set, this solves the existing problem where one could withhold their signature for risk-free gain. + +\end{document} diff --git a/examples/basecoin/app/app.go b/examples/basecoin/app/app.go index 3d9ac8173..286afd003 100644 --- a/examples/basecoin/app/app.go +++ b/examples/basecoin/app/app.go @@ -42,7 +42,7 @@ type BasecoinApp struct { keyIBC *sdk.KVStoreKey // manage getting and setting accounts - accountMapper auth.AccountMapper + accountKeeper auth.AccountKeeper feeCollectionKeeper auth.FeeCollectionKeeper bankKeeper bank.Keeper ibcMapper ibc.Mapper @@ -67,14 +67,14 @@ func NewBasecoinApp(logger log.Logger, db dbm.DB, baseAppOptions ...func(*bam.Ba } // define and attach the mappers and keepers - app.accountMapper = auth.NewAccountMapper( + app.accountKeeper = auth.NewAccountKeeper( cdc, app.keyAccount, // target store func() auth.Account { return &types.AppAccount{} }, ) - app.bankKeeper = bank.NewBaseKeeper(app.accountMapper) + app.bankKeeper = bank.NewBaseKeeper(app.accountKeeper) app.ibcMapper = ibc.NewMapper(app.cdc, app.keyIBC, app.RegisterCodespace(ibc.DefaultCodespace)) // register message routes @@ -86,7 +86,7 @@ func NewBasecoinApp(logger log.Logger, db dbm.DB, baseAppOptions ...func(*bam.Ba app.SetInitChainer(app.initChainer) app.SetBeginBlocker(app.BeginBlocker) app.SetEndBlocker(app.EndBlocker) - app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) + app.SetAnteHandler(auth.NewAnteHandler(app.accountKeeper, app.feeCollectionKeeper)) // mount the multistore and load the latest state app.MountStoresIAVL(app.keyMain, app.keyAccount, app.keyIBC) @@ -153,8 +153,8 @@ func (app *BasecoinApp) initChainer(ctx sdk.Context, req abci.RequestInitChain) panic(err) } - acc.AccountNumber = app.accountMapper.GetNextAccountNumber(ctx) - app.accountMapper.SetAccount(ctx, acc) + acc.AccountNumber = app.accountKeeper.GetNextAccountNumber(ctx) + app.accountKeeper.SetAccount(ctx, acc) } return abci.ResponseInitChain{} @@ -177,7 +177,7 @@ func (app *BasecoinApp) ExportAppStateAndValidators() (appState json.RawMessage, return false } - app.accountMapper.IterateAccounts(ctx, appendAccountsFn) + app.accountKeeper.IterateAccounts(ctx, appendAccountsFn) genState := types.GenesisState{Accounts: accounts} appState, err = codec.MarshalJSONIndent(app.cdc, genState) diff --git a/examples/basecoin/app/app_test.go b/examples/basecoin/app/app_test.go index da544f480..c49d5d476 100644 --- a/examples/basecoin/app/app_test.go +++ b/examples/basecoin/app/app_test.go @@ -61,7 +61,7 @@ func TestGenesis(t *testing.T) { // create a context for the BaseApp ctx := baseApp.BaseApp.NewContext(true, abci.Header{}) - res := baseApp.accountMapper.GetAccount(ctx, baseAcct.Address) + res := baseApp.accountKeeper.GetAccount(ctx, baseAcct.Address) require.Equal(t, appAcct, res) // reload app and ensure the account is still there @@ -76,6 +76,6 @@ func TestGenesis(t *testing.T) { }) ctx = baseApp.BaseApp.NewContext(true, abci.Header{}) - res = baseApp.accountMapper.GetAccount(ctx, baseAcct.Address) + res = baseApp.accountKeeper.GetAccount(ctx, baseAcct.Address) require.Equal(t, appAcct, res) } diff --git a/examples/basecoin/types/account.go b/examples/basecoin/types/account.go index 04d3e371e..41b437718 100644 --- a/examples/basecoin/types/account.go +++ b/examples/basecoin/types/account.go @@ -10,7 +10,7 @@ var _ auth.Account = (*AppAccount)(nil) // AppAccount is a custom extension for this application. It is an example of // extending auth.BaseAccount with custom fields. It is compatible with the -// stock auth.AccountMapper, since auth.AccountMapper uses the flexible go-amino +// stock auth.AccountKeeper, since auth.AccountKeeper uses the flexible go-amino // library. type AppAccount struct { auth.BaseAccount diff --git a/examples/democoin/app/app.go b/examples/democoin/app/app.go index 97dcf4e35..12f5d8d29 100644 --- a/examples/democoin/app/app.go +++ b/examples/democoin/app/app.go @@ -55,7 +55,7 @@ type DemocoinApp struct { stakeKeeper simplestake.Keeper // Manage getting and setting accounts - accountMapper auth.AccountMapper + accountKeeper auth.AccountKeeper } func NewDemocoinApp(logger log.Logger, db dbm.DB) *DemocoinApp { @@ -74,15 +74,15 @@ func NewDemocoinApp(logger log.Logger, db dbm.DB) *DemocoinApp { capKeyStakingStore: sdk.NewKVStoreKey("stake"), } - // Define the accountMapper. - app.accountMapper = auth.NewAccountMapper( + // Define the accountKeeper. + app.accountKeeper = auth.NewAccountKeeper( cdc, app.capKeyAccountStore, // target store types.ProtoAppAccount, // prototype ) // Add handlers. - app.bankKeeper = bank.NewBaseKeeper(app.accountMapper) + app.bankKeeper = bank.NewBaseKeeper(app.accountKeeper) app.coolKeeper = cool.NewKeeper(app.capKeyMainStore, app.bankKeeper, app.RegisterCodespace(cool.DefaultCodespace)) app.powKeeper = pow.NewKeeper(app.capKeyPowStore, pow.NewConfig("pow", int64(1)), app.bankKeeper, app.RegisterCodespace(pow.DefaultCodespace)) app.ibcMapper = ibc.NewMapper(app.cdc, app.capKeyIBCStore, app.RegisterCodespace(ibc.DefaultCodespace)) @@ -98,7 +98,7 @@ func NewDemocoinApp(logger log.Logger, db dbm.DB) *DemocoinApp { // Initialize BaseApp. app.SetInitChainer(app.initChainerFn(app.coolKeeper, app.powKeeper)) app.MountStoresIAVL(app.capKeyMainStore, app.capKeyAccountStore, app.capKeyPowStore, app.capKeyIBCStore, app.capKeyStakingStore) - app.SetAnteHandler(auth.NewAnteHandler(app.accountMapper, app.feeCollectionKeeper)) + app.SetAnteHandler(auth.NewAnteHandler(app.accountKeeper, app.feeCollectionKeeper)) err := app.LoadLatestVersion(app.capKeyMainStore) if err != nil { cmn.Exit(err.Error()) @@ -148,7 +148,7 @@ func (app *DemocoinApp) initChainerFn(coolKeeper cool.Keeper, powKeeper pow.Keep panic(err) // TODO https://github.com/cosmos/cosmos-sdk/issues/468 // return sdk.ErrGenesisParse("").TraceCause(err, "") } - app.accountMapper.SetAccount(ctx, acc) + app.accountKeeper.SetAccount(ctx, acc) } // Application specific genesis handling @@ -182,7 +182,7 @@ func (app *DemocoinApp) ExportAppStateAndValidators() (appState json.RawMessage, accounts = append(accounts, account) return false } - app.accountMapper.IterateAccounts(ctx, appendAccount) + app.accountKeeper.IterateAccounts(ctx, appendAccount) genState := types.GenesisState{ Accounts: accounts, diff --git a/examples/democoin/app/app_test.go b/examples/democoin/app/app_test.go index fc00651b8..5b3be00e1 100644 --- a/examples/democoin/app/app_test.go +++ b/examples/democoin/app/app_test.go @@ -60,13 +60,13 @@ func TestGenesis(t *testing.T) { require.Nil(t, err) // A checkTx context ctx := bapp.BaseApp.NewContext(true, abci.Header{}) - res1 := bapp.accountMapper.GetAccount(ctx, baseAcc.Address) + res1 := bapp.accountKeeper.GetAccount(ctx, baseAcc.Address) require.Equal(t, acc, res1) // reload app and ensure the account is still there bapp = NewDemocoinApp(logger, db) bapp.InitChain(abci.RequestInitChain{AppStateBytes: []byte("{}")}) ctx = bapp.BaseApp.NewContext(true, abci.Header{}) - res1 = bapp.accountMapper.GetAccount(ctx, baseAcc.Address) + res1 = bapp.accountKeeper.GetAccount(ctx, baseAcc.Address) require.Equal(t, acc, res1) } diff --git a/examples/democoin/x/cool/app_test.go b/examples/democoin/x/cool/app_test.go index 35a656ceb..01cb73ef1 100644 --- a/examples/democoin/x/cool/app_test.go +++ b/examples/democoin/x/cool/app_test.go @@ -49,7 +49,7 @@ func getMockApp(t *testing.T) *mock.App { RegisterCodec(mapp.Cdc) keyCool := sdk.NewKVStoreKey("cool") - bankKeeper := bank.NewBaseKeeper(mapp.AccountMapper) + bankKeeper := bank.NewBaseKeeper(mapp.AccountKeeper) keeper := NewKeeper(keyCool, bankKeeper, mapp.RegisterCodespace(DefaultCodespace)) mapp.Router().AddRoute("cool", NewHandler(keeper)) @@ -84,7 +84,7 @@ func TestMsgQuiz(t *testing.T) { // A checkTx context (true) ctxCheck := mapp.BaseApp.NewContext(true, abci.Header{}) - res1 := mapp.AccountMapper.GetAccount(ctxCheck, addr1) + res1 := mapp.AccountKeeper.GetAccount(ctxCheck, addr1) require.Equal(t, acc1, res1) // Set the trend, submit a really cool quiz and check for reward diff --git a/examples/democoin/x/cool/keeper.go b/examples/democoin/x/cool/keeper.go index fef93b954..f805ca880 100644 --- a/examples/democoin/x/cool/keeper.go +++ b/examples/democoin/x/cool/keeper.go @@ -29,7 +29,7 @@ func (k Keeper) GetTrend(ctx sdk.Context) string { return string(bz) } -// Implements sdk.AccountMapper. +// Implements sdk.AccountKeeper. func (k Keeper) setTrend(ctx sdk.Context, newTrend string) { store := ctx.KVStore(k.storeKey) store.Set(trendKey, []byte(newTrend)) diff --git a/examples/democoin/x/cool/keeper_test.go b/examples/democoin/x/cool/keeper_test.go index e3af7790e..1eb40dfb2 100644 --- a/examples/democoin/x/cool/keeper_test.go +++ b/examples/democoin/x/cool/keeper_test.go @@ -29,7 +29,7 @@ func TestCoolKeeper(t *testing.T) { cdc := codec.New() auth.RegisterBaseAccount(cdc) - am := auth.NewAccountMapper(cdc, capKey, auth.ProtoBaseAccount) + am := auth.NewAccountKeeper(cdc, capKey, auth.ProtoBaseAccount) ctx := sdk.NewContext(ms, abci.Header{}, false, nil) ck := bank.NewBaseKeeper(am) keeper := NewKeeper(capKey, ck, DefaultCodespace) diff --git a/examples/democoin/x/pow/app_test.go b/examples/democoin/x/pow/app_test.go index 6e6f07f77..5009b7ec5 100644 --- a/examples/democoin/x/pow/app_test.go +++ b/examples/democoin/x/pow/app_test.go @@ -25,7 +25,7 @@ func getMockApp(t *testing.T) *mock.App { RegisterCodec(mapp.Cdc) keyPOW := sdk.NewKVStoreKey("pow") - bankKeeper := bank.NewBaseKeeper(mapp.AccountMapper) + bankKeeper := bank.NewBaseKeeper(mapp.AccountKeeper) config := Config{"pow", 1} keeper := NewKeeper(keyPOW, config, bankKeeper, mapp.RegisterCodespace(DefaultCodespace)) mapp.Router().AddRoute("pow", keeper.Handler) @@ -69,7 +69,7 @@ func TestMsgMine(t *testing.T) { // A checkTx context (true) ctxCheck := mapp.BaseApp.NewContext(true, abci.Header{}) - res1 := mapp.AccountMapper.GetAccount(ctxCheck, addr1) + res1 := mapp.AccountKeeper.GetAccount(ctxCheck, addr1) require.Equal(t, acc1, res1) // Mine and check for reward diff --git a/examples/democoin/x/pow/handler_test.go b/examples/democoin/x/pow/handler_test.go index 8166ddfc5..ce398b7c2 100644 --- a/examples/democoin/x/pow/handler_test.go +++ b/examples/democoin/x/pow/handler_test.go @@ -19,7 +19,7 @@ func TestPowHandler(t *testing.T) { cdc := codec.New() auth.RegisterBaseAccount(cdc) - am := auth.NewAccountMapper(cdc, capKey, auth.ProtoBaseAccount) + am := auth.NewAccountKeeper(cdc, capKey, auth.ProtoBaseAccount) ctx := sdk.NewContext(ms, abci.Header{}, false, log.NewNopLogger()) config := NewConfig("pow", int64(1)) ck := bank.NewBaseKeeper(am) diff --git a/examples/democoin/x/pow/keeper_test.go b/examples/democoin/x/pow/keeper_test.go index dbd974c4d..86ccbc8c0 100644 --- a/examples/democoin/x/pow/keeper_test.go +++ b/examples/democoin/x/pow/keeper_test.go @@ -32,7 +32,7 @@ func TestPowKeeperGetSet(t *testing.T) { cdc := codec.New() auth.RegisterBaseAccount(cdc) - am := auth.NewAccountMapper(cdc, capKey, auth.ProtoBaseAccount) + am := auth.NewAccountKeeper(cdc, capKey, auth.ProtoBaseAccount) ctx := sdk.NewContext(ms, abci.Header{}, false, log.NewNopLogger()) config := NewConfig("pow", int64(1)) ck := bank.NewBaseKeeper(am) diff --git a/examples/democoin/x/simplestake/keeper_test.go b/examples/democoin/x/simplestake/keeper_test.go index 68f28bd91..c3876cf4a 100644 --- a/examples/democoin/x/simplestake/keeper_test.go +++ b/examples/democoin/x/simplestake/keeper_test.go @@ -35,8 +35,8 @@ func TestKeeperGetSet(t *testing.T) { cdc := codec.New() auth.RegisterBaseAccount(cdc) - accountMapper := auth.NewAccountMapper(cdc, authKey, auth.ProtoBaseAccount) - stakeKeeper := NewKeeper(capKey, bank.NewBaseKeeper(accountMapper), DefaultCodespace) + accountKeeper := auth.NewAccountKeeper(cdc, authKey, auth.ProtoBaseAccount) + stakeKeeper := NewKeeper(capKey, bank.NewBaseKeeper(accountKeeper), DefaultCodespace) ctx := sdk.NewContext(ms, abci.Header{}, false, log.NewNopLogger()) addr := sdk.AccAddress([]byte("some-address")) @@ -65,8 +65,8 @@ func TestBonding(t *testing.T) { ctx := sdk.NewContext(ms, abci.Header{}, false, log.NewNopLogger()) - accountMapper := auth.NewAccountMapper(cdc, authKey, auth.ProtoBaseAccount) - bankKeeper := bank.NewBaseKeeper(accountMapper) + accountKeeper := auth.NewAccountKeeper(cdc, authKey, auth.ProtoBaseAccount) + bankKeeper := bank.NewBaseKeeper(accountKeeper) stakeKeeper := NewKeeper(capKey, bankKeeper, DefaultCodespace) addr := sdk.AccAddress([]byte("some-address")) privKey := ed25519.GenPrivKey() diff --git a/types/decimal.go b/types/decimal.go index 05dd97795..1514c2a22 100644 --- a/types/decimal.go +++ b/types/decimal.go @@ -253,29 +253,33 @@ func (d Dec) IsInteger() bool { } func (d Dec) String() string { - str := d.ToLeftPaddedWithDecimals(Precision) - placement := len(str) - Precision - if placement < 0 { - panic("too few decimal digits") + bz, err := d.Int.MarshalText() + if err != nil { + return "" } - return str[:placement] + "." + str[placement:] -} - -// TODO panic if negative or if totalDigits < len(initStr)??? -// evaluate as an integer and return left padded string -func (d Dec) ToLeftPaddedWithDecimals(totalDigits int8) string { - intStr := d.Int.String() - fcode := `%0` + strconv.Itoa(int(totalDigits)) + `s` - return fmt.Sprintf(fcode, intStr) -} - -// TODO panic if negative or if totalDigits < len(initStr)??? -// evaluate as an integer and return left padded string -func (d Dec) ToLeftPadded(totalDigits int8) string { - chopped := chopPrecisionAndRoundNonMutative(d.Int) - intStr := chopped.String() - fcode := `%0` + strconv.Itoa(int(totalDigits)) + `s` - return fmt.Sprintf(fcode, intStr) + var bzWDec []byte + inputSize := len(bz) + // TODO: Remove trailing zeros + // case 1, purely decimal + if inputSize <= 10 { + bzWDec = make([]byte, 12) + // 0. prefix + bzWDec[0] = byte('0') + bzWDec[1] = byte('.') + // set relevant digits to 0 + for i := 0; i < 10-inputSize; i++ { + bzWDec[i+2] = byte('0') + } + // set last few digits + copy(bzWDec[2+(10-inputSize):], bz) + } else { + // inputSize + 1 to account for the decimal point that is being added + bzWDec = make([]byte, inputSize+1) + copy(bzWDec, bz[:inputSize-10]) + bzWDec[inputSize-10] = byte('.') + copy(bzWDec[inputSize-9:], bz[inputSize-10:]) + } + return string(bzWDec) } // ____ @@ -412,17 +416,13 @@ func (d *Dec) UnmarshalAmino(text string) (err error) { return nil } -// MarshalJSON defines custom encoding scheme +// MarshalJSON marshals the decimal func (d Dec) MarshalJSON() ([]byte, error) { if d.Int == nil { return nilJSON, nil } - bz, err := d.Int.MarshalText() - if err != nil { - return nil, err - } - return json.Marshal(string(bz)) + return json.Marshal(d.String()) } // UnmarshalJSON defines custom decoding scheme @@ -436,7 +436,13 @@ func (d *Dec) UnmarshalJSON(bz []byte) error { if err != nil { return err } - return d.Int.UnmarshalText([]byte(text)) + // TODO: Reuse dec allocation + newDec, err := NewDecFromStr(text) + if err != nil { + return err + } + d.Int = newDec.Int + return nil } //___________________________________________________________________________________ diff --git a/types/decimal_test.go b/types/decimal_test.go index a6ec0740e..07329c7dc 100644 --- a/types/decimal_test.go +++ b/types/decimal_test.go @@ -4,6 +4,8 @@ import ( "math/big" "testing" + "github.com/stretchr/testify/assert" + "github.com/cosmos/cosmos-sdk/codec" "github.com/stretchr/testify/require" ) @@ -228,26 +230,46 @@ func TestTruncate(t *testing.T) { } } -func TestToLeftPadded(t *testing.T) { - tests := []struct { - dec Dec - digits int8 - exp string - }{ - {mustNewDecFromStr(t, "33.3"), 8, "00000033"}, - {mustNewDecFromStr(t, "50"), 8, "00000050"}, - {mustNewDecFromStr(t, "333"), 8, "00000333"}, - {mustNewDecFromStr(t, "333"), 12, "000000000333"}, - {mustNewDecFromStr(t, "0.3333"), 8, "00000000"}, +var cdc = codec.New() + +func TestDecMarshalJSON(t *testing.T) { + decimal := func(i int64) Dec { + d := NewDec(0) + d.Int = new(big.Int).SetInt64(i) + return d } - for tcIndex, tc := range tests { - res := tc.dec.ToLeftPadded(tc.digits) - require.Equal(t, tc.exp, res, "incorrect left padding, tc %d", tcIndex) + tests := []struct { + name string + d Dec + want string + wantErr bool // if wantErr = false, will also attempt unmarshaling + }{ + {"zero", decimal(0), "\"0.0000000000\"", false}, + {"one", decimal(1), "\"0.0000000001\"", false}, + {"ten", decimal(10), "\"0.0000000010\"", false}, + {"12340", decimal(12340), "\"0.0000012340\"", false}, + {"zeroInt", NewDec(0), "\"0.0000000000\"", false}, + {"oneInt", NewDec(1), "\"1.0000000000\"", false}, + {"tenInt", NewDec(10), "\"10.0000000000\"", false}, + {"12340Int", NewDec(12340), "\"12340.0000000000\"", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := tt.d.MarshalJSON() + if (err != nil) != tt.wantErr { + t.Errorf("Dec.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !tt.wantErr { + assert.Equal(t, tt.want, string(got), "incorrect marshalled value") + unmarshalledDec := NewDec(0) + unmarshalledDec.UnmarshalJSON(got) + assert.Equal(t, tt.d, unmarshalledDec, "incorrect unmarshalled value") + } + }) } } -var cdc = codec.New() - func TestZeroDeserializationJSON(t *testing.T) { d := Dec{new(big.Int)} err := cdc.UnmarshalJSON([]byte(`"0"`), &d) diff --git a/x/auth/ante.go b/x/auth/ante.go index 3fd183a0c..9d5bc5059 100644 --- a/x/auth/ante.go +++ b/x/auth/ante.go @@ -22,7 +22,7 @@ const ( // NewAnteHandler returns an AnteHandler that checks // and increments sequence numbers, checks signatures & account numbers, // and deducts fees from the first signer. -func NewAnteHandler(am AccountMapper, fck FeeCollectionKeeper) sdk.AnteHandler { +func NewAnteHandler(am AccountKeeper, fck FeeCollectionKeeper) sdk.AnteHandler { return func( ctx sdk.Context, tx sdk.Tx, simulate bool, ) (newCtx sdk.Context, res sdk.Result, abort bool) { @@ -137,7 +137,7 @@ func validateBasic(tx StdTx) (err sdk.Error) { return nil } -func getSignerAccs(ctx sdk.Context, am AccountMapper, addrs []sdk.AccAddress) (accs []Account, res sdk.Result) { +func getSignerAccs(ctx sdk.Context, am AccountKeeper, addrs []sdk.AccAddress) (accs []Account, res sdk.Result) { accs = make([]Account, len(addrs)) for i := 0; i < len(accs); i++ { accs[i] = am.GetAccount(ctx, addrs[i]) @@ -257,7 +257,7 @@ func adjustFeesByGas(fees sdk.Coins, gas int64) sdk.Coins { } // Deduct the fee from the account. -// We could use the CoinKeeper (in addition to the AccountMapper, +// We could use the CoinKeeper (in addition to the AccountKeeper, // because the CoinKeeper doesn't give us accounts), but it seems easier to do this. func deductFees(acc Account, fee StdFee) (Account, sdk.Result) { coins := acc.GetCoins() diff --git a/x/auth/ante_test.go b/x/auth/ante_test.go index bacb3013f..d29b0bf50 100644 --- a/x/auth/ante_test.go +++ b/x/auth/ante_test.go @@ -112,7 +112,7 @@ func TestAnteHandlerSigErrors(t *testing.T) { ms, capKey, capKey2 := setupMultiStore() cdc := codec.New() RegisterBaseAccount(cdc) - mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) + mapper := NewAccountKeeper(cdc, capKey, ProtoBaseAccount) feeCollector := NewFeeCollectionKeeper(cdc, capKey2) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) @@ -165,7 +165,7 @@ func TestAnteHandlerAccountNumbers(t *testing.T) { ms, capKey, capKey2 := setupMultiStore() cdc := codec.New() RegisterBaseAccount(cdc) - mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) + mapper := NewAccountKeeper(cdc, capKey, ProtoBaseAccount) feeCollector := NewFeeCollectionKeeper(cdc, capKey2) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) @@ -225,7 +225,7 @@ func TestAnteHandlerAccountNumbersAtBlockHeightZero(t *testing.T) { ms, capKey, capKey2 := setupMultiStore() cdc := codec.New() RegisterBaseAccount(cdc) - mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) + mapper := NewAccountKeeper(cdc, capKey, ProtoBaseAccount) feeCollector := NewFeeCollectionKeeper(cdc, capKey2) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) @@ -285,7 +285,7 @@ func TestAnteHandlerSequences(t *testing.T) { ms, capKey, capKey2 := setupMultiStore() cdc := codec.New() RegisterBaseAccount(cdc) - mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) + mapper := NewAccountKeeper(cdc, capKey, ProtoBaseAccount) feeCollector := NewFeeCollectionKeeper(cdc, capKey2) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) @@ -364,7 +364,7 @@ func TestAnteHandlerFees(t *testing.T) { ms, capKey, capKey2 := setupMultiStore() cdc := codec.New() RegisterBaseAccount(cdc) - mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) + mapper := NewAccountKeeper(cdc, capKey, ProtoBaseAccount) feeCollector := NewFeeCollectionKeeper(cdc, capKey2) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) @@ -406,7 +406,7 @@ func TestAnteHandlerMemoGas(t *testing.T) { ms, capKey, capKey2 := setupMultiStore() cdc := codec.New() RegisterBaseAccount(cdc) - mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) + mapper := NewAccountKeeper(cdc, capKey, ProtoBaseAccount) feeCollector := NewFeeCollectionKeeper(cdc, capKey2) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) @@ -450,7 +450,7 @@ func TestAnteHandlerMultiSigner(t *testing.T) { ms, capKey, capKey2 := setupMultiStore() cdc := codec.New() RegisterBaseAccount(cdc) - mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) + mapper := NewAccountKeeper(cdc, capKey, ProtoBaseAccount) feeCollector := NewFeeCollectionKeeper(cdc, capKey2) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) @@ -502,7 +502,7 @@ func TestAnteHandlerBadSignBytes(t *testing.T) { ms, capKey, capKey2 := setupMultiStore() cdc := codec.New() RegisterBaseAccount(cdc) - mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) + mapper := NewAccountKeeper(cdc, capKey, ProtoBaseAccount) feeCollector := NewFeeCollectionKeeper(cdc, capKey2) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) @@ -584,7 +584,7 @@ func TestAnteHandlerSetPubKey(t *testing.T) { ms, capKey, capKey2 := setupMultiStore() cdc := codec.New() RegisterBaseAccount(cdc) - mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) + mapper := NewAccountKeeper(cdc, capKey, ProtoBaseAccount) feeCollector := NewFeeCollectionKeeper(cdc, capKey2) anteHandler := NewAnteHandler(mapper, feeCollector) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) @@ -638,7 +638,7 @@ func TestProcessPubKey(t *testing.T) { ms, capKey, _ := setupMultiStore() cdc := codec.New() RegisterBaseAccount(cdc) - mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) + mapper := NewAccountKeeper(cdc, capKey, ProtoBaseAccount) ctx := sdk.NewContext(ms, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) // keys _, addr1 := privAndAddr() diff --git a/x/auth/context.go b/x/auth/context.go index 40fb17785..28d159c97 100644 --- a/x/auth/context.go +++ b/x/auth/context.go @@ -8,7 +8,7 @@ import ( Usage: -var accounts types.AccountMapper +var accounts types.AccountKeeper // Fetch all signer accounts. addrs := tx.GetSigners() diff --git a/x/auth/mapper.go b/x/auth/mapper.go index 20d6c2d14..dd127c731 100644 --- a/x/auth/mapper.go +++ b/x/auth/mapper.go @@ -8,9 +8,9 @@ import ( var globalAccountNumberKey = []byte("globalAccountNumber") -// This AccountMapper encodes/decodes accounts using the +// This AccountKeeper encodes/decodes accounts using the // go-amino (binary) encoding/decoding library. -type AccountMapper struct { +type AccountKeeper struct { // The (unexposed) key used to access the store from the Context. key sdk.StoreKey @@ -22,19 +22,19 @@ type AccountMapper struct { cdc *codec.Codec } -// NewAccountMapper returns a new sdk.AccountMapper that +// NewAccountKeeper returns a new sdk.AccountKeeper that // uses go-amino to (binary) encode and decode concrete sdk.Accounts. // nolint -func NewAccountMapper(cdc *codec.Codec, key sdk.StoreKey, proto func() Account) AccountMapper { - return AccountMapper{ +func NewAccountKeeper(cdc *codec.Codec, key sdk.StoreKey, proto func() Account) AccountKeeper { + return AccountKeeper{ key: key, proto: proto, cdc: cdc, } } -// Implaements sdk.AccountMapper. -func (am AccountMapper) NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) Account { +// Implaements sdk.AccountKeeper. +func (am AccountKeeper) NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) Account { acc := am.proto() err := acc.SetAddress(addr) if err != nil { @@ -50,7 +50,7 @@ func (am AccountMapper) NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddre } // New Account -func (am AccountMapper) NewAccount(ctx sdk.Context, acc Account) Account { +func (am AccountKeeper) NewAccount(ctx sdk.Context, acc Account) Account { err := acc.SetAccountNumber(am.GetNextAccountNumber(ctx)) if err != nil { // TODO: Handle with #870 @@ -64,8 +64,8 @@ func AddressStoreKey(addr sdk.AccAddress) []byte { return append([]byte("account:"), addr.Bytes()...) } -// Implements sdk.AccountMapper. -func (am AccountMapper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) Account { +// Implements sdk.AccountKeeper. +func (am AccountKeeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) Account { store := ctx.KVStore(am.key) bz := store.Get(AddressStoreKey(addr)) if bz == nil { @@ -75,8 +75,8 @@ func (am AccountMapper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) Account return acc } -// Implements sdk.AccountMapper. -func (am AccountMapper) SetAccount(ctx sdk.Context, acc Account) { +// Implements sdk.AccountKeeper. +func (am AccountKeeper) SetAccount(ctx sdk.Context, acc Account) { addr := acc.GetAddress() store := ctx.KVStore(am.key) bz := am.encodeAccount(acc) @@ -84,14 +84,14 @@ func (am AccountMapper) SetAccount(ctx sdk.Context, acc Account) { } // RemoveAccount removes an account for the account mapper store. -func (am AccountMapper) RemoveAccount(ctx sdk.Context, acc Account) { +func (am AccountKeeper) RemoveAccount(ctx sdk.Context, acc Account) { addr := acc.GetAddress() store := ctx.KVStore(am.key) store.Delete(AddressStoreKey(addr)) } -// Implements sdk.AccountMapper. -func (am AccountMapper) IterateAccounts(ctx sdk.Context, process func(Account) (stop bool)) { +// Implements sdk.AccountKeeper. +func (am AccountKeeper) IterateAccounts(ctx sdk.Context, process func(Account) (stop bool)) { store := ctx.KVStore(am.key) iter := sdk.KVStorePrefixIterator(store, []byte("account:")) defer iter.Close() @@ -109,7 +109,7 @@ func (am AccountMapper) IterateAccounts(ctx sdk.Context, process func(Account) ( } // Returns the PubKey of the account at address -func (am AccountMapper) GetPubKey(ctx sdk.Context, addr sdk.AccAddress) (crypto.PubKey, sdk.Error) { +func (am AccountKeeper) GetPubKey(ctx sdk.Context, addr sdk.AccAddress) (crypto.PubKey, sdk.Error) { acc := am.GetAccount(ctx, addr) if acc == nil { return nil, sdk.ErrUnknownAddress(addr.String()) @@ -118,7 +118,7 @@ func (am AccountMapper) GetPubKey(ctx sdk.Context, addr sdk.AccAddress) (crypto. } // Returns the Sequence of the account at address -func (am AccountMapper) GetSequence(ctx sdk.Context, addr sdk.AccAddress) (int64, sdk.Error) { +func (am AccountKeeper) GetSequence(ctx sdk.Context, addr sdk.AccAddress) (int64, sdk.Error) { acc := am.GetAccount(ctx, addr) if acc == nil { return 0, sdk.ErrUnknownAddress(addr.String()) @@ -126,7 +126,7 @@ func (am AccountMapper) GetSequence(ctx sdk.Context, addr sdk.AccAddress) (int64 return acc.GetSequence(), nil } -func (am AccountMapper) setSequence(ctx sdk.Context, addr sdk.AccAddress, newSequence int64) sdk.Error { +func (am AccountKeeper) setSequence(ctx sdk.Context, addr sdk.AccAddress, newSequence int64) sdk.Error { acc := am.GetAccount(ctx, addr) if acc == nil { return sdk.ErrUnknownAddress(addr.String()) @@ -141,7 +141,7 @@ func (am AccountMapper) setSequence(ctx sdk.Context, addr sdk.AccAddress, newSeq } // Returns and increments the global account number counter -func (am AccountMapper) GetNextAccountNumber(ctx sdk.Context) int64 { +func (am AccountKeeper) GetNextAccountNumber(ctx sdk.Context) int64 { var accNumber int64 store := ctx.KVStore(am.key) bz := store.Get(globalAccountNumberKey) @@ -163,7 +163,7 @@ func (am AccountMapper) GetNextAccountNumber(ctx sdk.Context) int64 { //---------------------------------------- // misc. -func (am AccountMapper) encodeAccount(acc Account) []byte { +func (am AccountKeeper) encodeAccount(acc Account) []byte { bz, err := am.cdc.MarshalBinaryBare(acc) if err != nil { panic(err) @@ -171,7 +171,7 @@ func (am AccountMapper) encodeAccount(acc Account) []byte { return bz } -func (am AccountMapper) decodeAccount(bz []byte) (acc Account) { +func (am AccountKeeper) decodeAccount(bz []byte) (acc Account) { err := am.cdc.UnmarshalBinaryBare(bz, &acc) if err != nil { panic(err) diff --git a/x/auth/mapper_test.go b/x/auth/mapper_test.go index e3b737ea3..326f83dcc 100644 --- a/x/auth/mapper_test.go +++ b/x/auth/mapper_test.go @@ -32,7 +32,7 @@ func TestAccountMapperGetSet(t *testing.T) { // make context and mapper ctx := sdk.NewContext(ms, abci.Header{}, false, log.NewNopLogger()) - mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) + mapper := NewAccountKeeper(cdc, capKey, ProtoBaseAccount) addr := sdk.AccAddress([]byte("some-address")) @@ -68,7 +68,7 @@ func TestAccountMapperRemoveAccount(t *testing.T) { // make context and mapper ctx := sdk.NewContext(ms, abci.Header{}, false, log.NewNopLogger()) - mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) + mapper := NewAccountKeeper(cdc, capKey, ProtoBaseAccount) addr1 := sdk.AccAddress([]byte("addr1")) addr2 := sdk.AccAddress([]byte("addr2")) @@ -106,7 +106,7 @@ func BenchmarkAccountMapperGetAccountFound(b *testing.B) { // make context and mapper ctx := sdk.NewContext(ms, abci.Header{}, false, log.NewNopLogger()) - mapper := NewAccountMapper(cdc, capKey, ProtoBaseAccount) + mapper := NewAccountKeeper(cdc, capKey, ProtoBaseAccount) // assumes b.N < 2**24 for i := 0; i < b.N; i++ { diff --git a/x/auth/simulation/fake.go b/x/auth/simulation/fake.go index e89e70842..222b747ec 100644 --- a/x/auth/simulation/fake.go +++ b/x/auth/simulation/fake.go @@ -13,7 +13,7 @@ import ( ) // SimulateDeductFee -func SimulateDeductFee(m auth.AccountMapper, f auth.FeeCollectionKeeper) simulation.Operation { +func SimulateDeductFee(m auth.AccountKeeper, f auth.FeeCollectionKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) ( action string, fOp []simulation.FutureOperation, err error) { diff --git a/x/bank/app_test.go b/x/bank/app_test.go index 7c320a9bd..906573eae 100644 --- a/x/bank/app_test.go +++ b/x/bank/app_test.go @@ -102,7 +102,7 @@ func TestMsgSendWithAccounts(t *testing.T) { ctxCheck := mapp.BaseApp.NewContext(true, abci.Header{}) - res1 := mapp.AccountMapper.GetAccount(ctxCheck, addr1) + res1 := mapp.AccountKeeper.GetAccount(ctxCheck, addr1) require.NotNil(t, res1) require.Equal(t, acc, res1.(*auth.BaseAccount)) diff --git a/x/bank/bench_test.go b/x/bank/bench_test.go index a29a25b99..bff99da99 100644 --- a/x/bank/bench_test.go +++ b/x/bank/bench_test.go @@ -16,7 +16,7 @@ func getBenchmarkMockApp() (*mock.App, error) { mapp := mock.NewApp() RegisterCodec(mapp.Cdc) - bankKeeper := NewBaseKeeper(mapp.AccountMapper) + bankKeeper := NewBaseKeeper(mapp.AccountKeeper) mapp.Router().AddRoute("bank", NewHandler(bankKeeper)) err := mapp.CompleteSetup() diff --git a/x/bank/client/cli/sendtx.go b/x/bank/client/cli/sendtx.go index 8200563b0..c72ed6fcb 100644 --- a/x/bank/client/cli/sendtx.go +++ b/x/bank/client/cli/sendtx.go @@ -75,6 +75,8 @@ func SendTxCmd(cdc *codec.Codec) *cobra.Command { cmd.Flags().String(flagTo, "", "Address to send coins") cmd.Flags().String(flagAmount, "", "Amount of coins to send") + cmd.MarkFlagRequired(flagTo) + cmd.MarkFlagRequired(flagAmount) return cmd } diff --git a/x/bank/keeper.go b/x/bank/keeper.go index 2da4eedc8..ac7a484d5 100644 --- a/x/bank/keeper.go +++ b/x/bank/keeper.go @@ -29,11 +29,11 @@ var _ Keeper = (*BaseKeeper)(nil) // BaseKeeper manages transfers between accounts. It implements the Keeper // interface. type BaseKeeper struct { - am auth.AccountMapper + am auth.AccountKeeper } // NewBaseKeeper returns a new BaseKeeper -func NewBaseKeeper(am auth.AccountMapper) BaseKeeper { +func NewBaseKeeper(am auth.AccountKeeper) BaseKeeper { return BaseKeeper{am: am} } @@ -96,11 +96,11 @@ var _ SendKeeper = (*BaseSendKeeper)(nil) // SendKeeper only allows transfers between accounts without the possibility of // creating coins. It implements the SendKeeper interface. type BaseSendKeeper struct { - am auth.AccountMapper + am auth.AccountKeeper } // NewBaseSendKeeper returns a new BaseSendKeeper. -func NewBaseSendKeeper(am auth.AccountMapper) BaseSendKeeper { +func NewBaseSendKeeper(am auth.AccountKeeper) BaseSendKeeper { return BaseSendKeeper{am: am} } @@ -143,11 +143,11 @@ var _ ViewKeeper = (*BaseViewKeeper)(nil) // BaseViewKeeper implements a read only keeper implementation of ViewKeeper. type BaseViewKeeper struct { - am auth.AccountMapper + am auth.AccountKeeper } // NewBaseViewKeeper returns a new BaseViewKeeper. -func NewBaseViewKeeper(am auth.AccountMapper) BaseViewKeeper { +func NewBaseViewKeeper(am auth.AccountKeeper) BaseViewKeeper { return BaseViewKeeper{am: am} } @@ -163,7 +163,7 @@ func (keeper BaseViewKeeper) HasCoins(ctx sdk.Context, addr sdk.AccAddress, amt //______________________________________________________________________________________________ -func getCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.AccAddress) sdk.Coins { +func getCoins(ctx sdk.Context, am auth.AccountKeeper, addr sdk.AccAddress) sdk.Coins { ctx.GasMeter().ConsumeGas(costGetCoins, "getCoins") acc := am.GetAccount(ctx, addr) if acc == nil { @@ -172,7 +172,7 @@ func getCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.AccAddress) sdk.C return acc.GetCoins() } -func setCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.AccAddress, amt sdk.Coins) sdk.Error { +func setCoins(ctx sdk.Context, am auth.AccountKeeper, addr sdk.AccAddress, amt sdk.Coins) sdk.Error { ctx.GasMeter().ConsumeGas(costSetCoins, "setCoins") acc := am.GetAccount(ctx, addr) if acc == nil { @@ -188,13 +188,13 @@ func setCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.AccAddress, amt s } // HasCoins returns whether or not an account has at least amt coins. -func hasCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.AccAddress, amt sdk.Coins) bool { +func hasCoins(ctx sdk.Context, am auth.AccountKeeper, addr sdk.AccAddress, amt sdk.Coins) bool { ctx.GasMeter().ConsumeGas(costHasCoins, "hasCoins") return getCoins(ctx, am, addr).IsGTE(amt) } // SubtractCoins subtracts amt from the coins at the addr. -func subtractCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) { +func subtractCoins(ctx sdk.Context, am auth.AccountKeeper, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) { ctx.GasMeter().ConsumeGas(costSubtractCoins, "subtractCoins") oldCoins := getCoins(ctx, am, addr) newCoins := oldCoins.Minus(amt) @@ -207,7 +207,7 @@ func subtractCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.AccAddress, } // AddCoins adds amt to the coins at the addr. -func addCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) { +func addCoins(ctx sdk.Context, am auth.AccountKeeper, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, sdk.Tags, sdk.Error) { ctx.GasMeter().ConsumeGas(costAddCoins, "addCoins") oldCoins := getCoins(ctx, am, addr) newCoins := oldCoins.Plus(amt) @@ -221,7 +221,7 @@ func addCoins(ctx sdk.Context, am auth.AccountMapper, addr sdk.AccAddress, amt s // SendCoins moves coins from one account to another // NOTE: Make sure to revert state changes from tx on error -func sendCoins(ctx sdk.Context, am auth.AccountMapper, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) (sdk.Tags, sdk.Error) { +func sendCoins(ctx sdk.Context, am auth.AccountKeeper, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) (sdk.Tags, sdk.Error) { _, subTags, err := subtractCoins(ctx, am, fromAddr, amt) if err != nil { return nil, err @@ -237,7 +237,7 @@ func sendCoins(ctx sdk.Context, am auth.AccountMapper, fromAddr sdk.AccAddress, // InputOutputCoins handles a list of inputs and outputs // NOTE: Make sure to revert state changes from tx on error -func inputOutputCoins(ctx sdk.Context, am auth.AccountMapper, inputs []Input, outputs []Output) (sdk.Tags, sdk.Error) { +func inputOutputCoins(ctx sdk.Context, am auth.AccountKeeper, inputs []Input, outputs []Output) (sdk.Tags, sdk.Error) { allTags := sdk.EmptyTags() for _, in := range inputs { diff --git a/x/bank/keeper_test.go b/x/bank/keeper_test.go index c48410c15..26c1446d2 100644 --- a/x/bank/keeper_test.go +++ b/x/bank/keeper_test.go @@ -33,16 +33,16 @@ func TestKeeper(t *testing.T) { auth.RegisterBaseAccount(cdc) ctx := sdk.NewContext(ms, abci.Header{}, false, log.NewNopLogger()) - accountMapper := auth.NewAccountMapper(cdc, authKey, auth.ProtoBaseAccount) - bankKeeper := NewBaseKeeper(accountMapper) + accountKeeper := auth.NewAccountKeeper(cdc, authKey, auth.ProtoBaseAccount) + bankKeeper := NewBaseKeeper(accountKeeper) addr := sdk.AccAddress([]byte("addr1")) addr2 := sdk.AccAddress([]byte("addr2")) addr3 := sdk.AccAddress([]byte("addr3")) - acc := accountMapper.NewAccountWithAddress(ctx, addr) + acc := accountKeeper.NewAccountWithAddress(ctx, addr) // Test GetCoins/SetCoins - accountMapper.SetAccount(ctx, acc) + accountKeeper.SetAccount(ctx, acc) require.True(t, bankKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{})) bankKeeper.SetCoins(ctx, addr, sdk.Coins{sdk.NewInt64Coin("foocoin", 10)}) @@ -118,17 +118,17 @@ func TestSendKeeper(t *testing.T) { auth.RegisterBaseAccount(cdc) ctx := sdk.NewContext(ms, abci.Header{}, false, log.NewNopLogger()) - accountMapper := auth.NewAccountMapper(cdc, authKey, auth.ProtoBaseAccount) - bankKeeper := NewBaseKeeper(accountMapper) - sendKeeper := NewBaseSendKeeper(accountMapper) + accountKeeper := auth.NewAccountKeeper(cdc, authKey, auth.ProtoBaseAccount) + bankKeeper := NewBaseKeeper(accountKeeper) + sendKeeper := NewBaseSendKeeper(accountKeeper) addr := sdk.AccAddress([]byte("addr1")) addr2 := sdk.AccAddress([]byte("addr2")) addr3 := sdk.AccAddress([]byte("addr3")) - acc := accountMapper.NewAccountWithAddress(ctx, addr) + acc := accountKeeper.NewAccountWithAddress(ctx, addr) // Test GetCoins/SetCoins - accountMapper.SetAccount(ctx, acc) + accountKeeper.SetAccount(ctx, acc) require.True(t, sendKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{})) bankKeeper.SetCoins(ctx, addr, sdk.Coins{sdk.NewInt64Coin("foocoin", 10)}) @@ -187,15 +187,15 @@ func TestViewKeeper(t *testing.T) { auth.RegisterBaseAccount(cdc) ctx := sdk.NewContext(ms, abci.Header{}, false, log.NewNopLogger()) - accountMapper := auth.NewAccountMapper(cdc, authKey, auth.ProtoBaseAccount) - bankKeeper := NewBaseKeeper(accountMapper) - viewKeeper := NewBaseViewKeeper(accountMapper) + accountKeeper := auth.NewAccountKeeper(cdc, authKey, auth.ProtoBaseAccount) + bankKeeper := NewBaseKeeper(accountKeeper) + viewKeeper := NewBaseViewKeeper(accountKeeper) addr := sdk.AccAddress([]byte("addr1")) - acc := accountMapper.NewAccountWithAddress(ctx, addr) + acc := accountKeeper.NewAccountWithAddress(ctx, addr) // Test GetCoins/SetCoins - accountMapper.SetAccount(ctx, acc) + accountKeeper.SetAccount(ctx, acc) require.True(t, viewKeeper.GetCoins(ctx, addr).IsEqual(sdk.Coins{})) bankKeeper.SetCoins(ctx, addr, sdk.Coins{sdk.NewInt64Coin("foocoin", 10)}) diff --git a/x/bank/simulation/invariants.go b/x/bank/simulation/invariants.go index 20aa9570b..f0cd5ba63 100644 --- a/x/bank/simulation/invariants.go +++ b/x/bank/simulation/invariants.go @@ -13,7 +13,7 @@ import ( ) // NonnegativeBalanceInvariant checks that all accounts in the application have non-negative balances -func NonnegativeBalanceInvariant(mapper auth.AccountMapper) simulation.Invariant { +func NonnegativeBalanceInvariant(mapper auth.AccountKeeper) simulation.Invariant { return func(app *baseapp.BaseApp) error { ctx := app.NewContext(false, abci.Header{}) accts := mock.GetAllAccounts(mapper, ctx) @@ -31,7 +31,7 @@ func NonnegativeBalanceInvariant(mapper auth.AccountMapper) simulation.Invariant // TotalCoinsInvariant checks that the sum of the coins across all accounts // is what is expected -func TotalCoinsInvariant(mapper auth.AccountMapper, totalSupplyFn func() sdk.Coins) simulation.Invariant { +func TotalCoinsInvariant(mapper auth.AccountKeeper, totalSupplyFn func() sdk.Coins) simulation.Invariant { return func(app *baseapp.BaseApp) error { ctx := app.NewContext(false, abci.Header{}) totalCoins := sdk.Coins{} diff --git a/x/bank/simulation/msgs.go b/x/bank/simulation/msgs.go index 0a253235e..f33c5e0c9 100644 --- a/x/bank/simulation/msgs.go +++ b/x/bank/simulation/msgs.go @@ -17,7 +17,7 @@ import ( // SingleInputSendTx tests and runs a single msg send w/ auth, with one input and one output, where both // accounts already exist. -func SingleInputSendTx(mapper auth.AccountMapper) simulation.Operation { +func SingleInputSendTx(mapper auth.AccountKeeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) (action string, fOps []simulation.FutureOperation, err error) { fromAcc, action, msg, abort := createSingleInputSendMsg(r, ctx, accs, mapper) if abort { @@ -35,7 +35,7 @@ func SingleInputSendTx(mapper auth.AccountMapper) simulation.Operation { // SingleInputSendMsg tests and runs a single msg send, with one input and one output, where both // accounts already exist. -func SingleInputSendMsg(mapper auth.AccountMapper, bk bank.Keeper) simulation.Operation { +func SingleInputSendMsg(mapper auth.AccountKeeper, bk bank.Keeper) simulation.Operation { handler := bank.NewHandler(bk) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) (action string, fOps []simulation.FutureOperation, err error) { fromAcc, action, msg, abort := createSingleInputSendMsg(r, ctx, accs, mapper) @@ -52,7 +52,7 @@ func SingleInputSendMsg(mapper auth.AccountMapper, bk bank.Keeper) simulation.Op } } -func createSingleInputSendMsg(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, mapper auth.AccountMapper) (fromAcc simulation.Account, action string, msg bank.MsgSend, abort bool) { +func createSingleInputSendMsg(r *rand.Rand, ctx sdk.Context, accs []simulation.Account, mapper auth.AccountKeeper) (fromAcc simulation.Account, action string, msg bank.MsgSend, abort bool) { fromAcc = simulation.RandomAcc(r, accs) toAcc := simulation.RandomAcc(r, accs) // Disallow sending money to yourself @@ -92,7 +92,7 @@ func createSingleInputSendMsg(r *rand.Rand, ctx sdk.Context, accs []simulation.A // Sends and verifies the transition of a msg send. This fails if there are repeated inputs or outputs // pass in handler as nil to handle txs, otherwise handle msgs -func sendAndVerifyMsgSend(app *baseapp.BaseApp, mapper auth.AccountMapper, msg bank.MsgSend, ctx sdk.Context, privkeys []crypto.PrivKey, handler sdk.Handler) error { +func sendAndVerifyMsgSend(app *baseapp.BaseApp, mapper auth.AccountKeeper, msg bank.MsgSend, ctx sdk.Context, privkeys []crypto.PrivKey, handler sdk.Handler) error { initialInputAddrCoins := make([]sdk.Coins, len(msg.Inputs)) initialOutputAddrCoins := make([]sdk.Coins, len(msg.Outputs)) AccountNumbers := make([]int64, len(msg.Inputs)) diff --git a/x/bank/simulation/sim_test.go b/x/bank/simulation/sim_test.go index ce3877a62..514156228 100644 --- a/x/bank/simulation/sim_test.go +++ b/x/bank/simulation/sim_test.go @@ -15,7 +15,7 @@ func TestBankWithRandomMessages(t *testing.T) { mapp := mock.NewApp() bank.RegisterCodec(mapp.Cdc) - mapper := mapp.AccountMapper + mapper := mapp.AccountKeeper bankKeeper := bank.NewBaseKeeper(mapper) mapp.Router().AddRoute("bank", bank.NewHandler(bankKeeper)) diff --git a/x/distribution/keeper/test_common.go b/x/distribution/keeper/test_common.go index 42f3861fb..58658ab8e 100644 --- a/x/distribution/keeper/test_common.go +++ b/x/distribution/keeper/test_common.go @@ -72,7 +72,7 @@ func MakeTestCodec() *codec.Codec { // test input with default values func CreateTestInputDefault(t *testing.T, isCheckTx bool, initCoins int64) ( - sdk.Context, auth.AccountMapper, Keeper, stake.Keeper, DummyFeeCollectionKeeper) { + sdk.Context, auth.AccountKeeper, Keeper, stake.Keeper, DummyFeeCollectionKeeper) { communityTax := sdk.NewDecWithPrec(2, 2) return CreateTestInputAdvanced(t, isCheckTx, initCoins, communityTax) @@ -81,7 +81,7 @@ func CreateTestInputDefault(t *testing.T, isCheckTx bool, initCoins int64) ( // hogpodge of all sorts of input required for testing func CreateTestInputAdvanced(t *testing.T, isCheckTx bool, initCoins int64, communityTax sdk.Dec) ( - sdk.Context, auth.AccountMapper, Keeper, stake.Keeper, DummyFeeCollectionKeeper) { + sdk.Context, auth.AccountKeeper, Keeper, stake.Keeper, DummyFeeCollectionKeeper) { keyDistr := sdk.NewKVStoreKey("distr") keyStake := sdk.NewKVStoreKey("stake") @@ -109,8 +109,8 @@ func CreateTestInputAdvanced(t *testing.T, isCheckTx bool, initCoins int64, pk := params.NewKeeper(cdc, keyParams, tkeyParams) ctx := sdk.NewContext(ms, abci.Header{ChainID: "foochainid"}, isCheckTx, log.NewNopLogger()) - accountMapper := auth.NewAccountMapper(cdc, keyAcc, auth.ProtoBaseAccount) - ck := bank.NewBaseKeeper(accountMapper) + accountKeeper := auth.NewAccountKeeper(cdc, keyAcc, auth.ProtoBaseAccount) + ck := bank.NewBaseKeeper(accountKeeper) sk := stake.NewKeeper(cdc, keyStake, tkeyStake, ck, pk.Subspace(stake.DefaultParamspace), stake.DefaultCodespace) sk.SetPool(ctx, stake.InitialPool()) sk.SetParams(ctx, stake.DefaultParams()) @@ -138,7 +138,7 @@ func CreateTestInputAdvanced(t *testing.T, isCheckTx bool, initCoins int64, keeper.SetBaseProposerReward(ctx, sdk.NewDecWithPrec(1, 2)) keeper.SetBonusProposerReward(ctx, sdk.NewDecWithPrec(4, 2)) - return ctx, accountMapper, keeper, sk, fck + return ctx, accountKeeper, keeper, sk, fck } //__________________________________________________________________________________ diff --git a/x/distribution/simulation/invariants.go b/x/distribution/simulation/invariants.go index 7036be46f..3a3a1fcd1 100644 --- a/x/distribution/simulation/invariants.go +++ b/x/distribution/simulation/invariants.go @@ -10,7 +10,7 @@ import ( // AllInvariants runs all invariants of the distribution module. // Currently: total supply, positive power -func AllInvariants(ck bank.Keeper, k distribution.Keeper, am auth.AccountMapper) simulation.Invariant { +func AllInvariants(ck bank.Keeper, k distribution.Keeper, am auth.AccountKeeper) simulation.Invariant { return func(app *baseapp.BaseApp) error { return nil } diff --git a/x/distribution/simulation/msgs.go b/x/distribution/simulation/msgs.go index 241dccdab..6c1bfea77 100644 --- a/x/distribution/simulation/msgs.go +++ b/x/distribution/simulation/msgs.go @@ -13,7 +13,7 @@ import ( ) // SimulateMsgSetWithdrawAddress -func SimulateMsgSetWithdrawAddress(m auth.AccountMapper, k distribution.Keeper) simulation.Operation { +func SimulateMsgSetWithdrawAddress(m auth.AccountKeeper, k distribution.Keeper) simulation.Operation { handler := distribution.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) ( @@ -41,7 +41,7 @@ func SimulateMsgSetWithdrawAddress(m auth.AccountMapper, k distribution.Keeper) } // SimulateMsgWithdrawDelegatorRewardsAll -func SimulateMsgWithdrawDelegatorRewardsAll(m auth.AccountMapper, k distribution.Keeper) simulation.Operation { +func SimulateMsgWithdrawDelegatorRewardsAll(m auth.AccountKeeper, k distribution.Keeper) simulation.Operation { handler := distribution.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) ( @@ -68,7 +68,7 @@ func SimulateMsgWithdrawDelegatorRewardsAll(m auth.AccountMapper, k distribution } // SimulateMsgWithdrawDelegatorReward -func SimulateMsgWithdrawDelegatorReward(m auth.AccountMapper, k distribution.Keeper) simulation.Operation { +func SimulateMsgWithdrawDelegatorReward(m auth.AccountKeeper, k distribution.Keeper) simulation.Operation { handler := distribution.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) ( @@ -96,7 +96,7 @@ func SimulateMsgWithdrawDelegatorReward(m auth.AccountMapper, k distribution.Kee } // SimulateMsgWithdrawValidatorRewardsAll -func SimulateMsgWithdrawValidatorRewardsAll(m auth.AccountMapper, k distribution.Keeper) simulation.Operation { +func SimulateMsgWithdrawValidatorRewardsAll(m auth.AccountKeeper, k distribution.Keeper) simulation.Operation { handler := distribution.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) ( diff --git a/x/distribution/types/fee_pool.go b/x/distribution/types/fee_pool.go index 2861ad986..ae1d72cc0 100644 --- a/x/distribution/types/fee_pool.go +++ b/x/distribution/types/fee_pool.go @@ -29,18 +29,6 @@ func (ta TotalAccum) UpdateForNewHeight(height int64, accumCreatedPerBlock sdk.D return ta } -// update total validator accumulation factor for the new height -// CONTRACT: height should be greater than the old height -func (ta TotalAccum) UpdateForNewHeight_DEBUG(height int64, accumCreatedPerBlock sdk.Dec) TotalAccum { - blocks := height - ta.UpdateHeight - if blocks < 0 { - panic("reverse updated for new height") - } - ta.Accum = ta.Accum.Add(accumCreatedPerBlock.MulInt(sdk.NewInt(blocks))) - ta.UpdateHeight = height - return ta -} - //___________________________________________________________________________________________ // global fee pool for distribution @@ -53,7 +41,7 @@ type FeePool struct { // update total validator accumulation factor // NOTE: Do not call this except from ValidatorDistInfo.TakeFeePoolRewards(). func (f FeePool) UpdateTotalValAccum(height int64, totalBondedTokens sdk.Dec) FeePool { - f.TotalValAccum = f.TotalValAccum.UpdateForNewHeight_DEBUG(height, totalBondedTokens) + f.TotalValAccum = f.TotalValAccum.UpdateForNewHeight(height, totalBondedTokens) return f } diff --git a/x/gov/keeper.go b/x/gov/keeper.go index 4b7ec26b5..d061f1206 100644 --- a/x/gov/keeper.go +++ b/x/gov/keeper.go @@ -111,14 +111,14 @@ func (keeper Keeper) GetProposal(ctx sdk.Context, proposalID int64) Proposal { return proposal } -// Implements sdk.AccountMapper. +// Implements sdk.AccountKeeper. func (keeper Keeper) SetProposal(ctx sdk.Context, proposal Proposal) { store := ctx.KVStore(keeper.storeKey) bz := keeper.cdc.MustMarshalBinary(proposal) store.Set(KeyProposal(proposal.GetProposalID()), bz) } -// Implements sdk.AccountMapper. +// Implements sdk.AccountKeeper. func (keeper Keeper) DeleteProposal(ctx sdk.Context, proposal Proposal) { store := ctx.KVStore(keeper.storeKey) store.Delete(KeyProposal(proposal.GetProposalID())) diff --git a/x/gov/simulation/sim_test.go b/x/gov/simulation/sim_test.go index a7d4e40d0..a222c19a5 100644 --- a/x/gov/simulation/sim_test.go +++ b/x/gov/simulation/sim_test.go @@ -22,7 +22,7 @@ func TestGovWithRandomMessages(t *testing.T) { bank.RegisterCodec(mapp.Cdc) gov.RegisterCodec(mapp.Cdc) - mapper := mapp.AccountMapper + mapper := mapp.AccountKeeper bankKeeper := bank.NewBaseKeeper(mapper) stakeKey := sdk.NewKVStoreKey("stake") diff --git a/x/gov/test_common.go b/x/gov/test_common.go index b33f58084..82ae30358 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -33,7 +33,7 @@ func getMockApp(t *testing.T, numGenAccs int) (*mock.App, Keeper, stake.Keeper, keyGov := sdk.NewKVStoreKey("gov") pk := params.NewKeeper(mapp.Cdc, keyGlobalParams, tkeyGlobalParams) - ck := bank.NewBaseKeeper(mapp.AccountMapper) + ck := bank.NewBaseKeeper(mapp.AccountKeeper) sk := stake.NewKeeper(mapp.Cdc, keyStake, tkeyStake, ck, pk.Subspace(stake.DefaultParamspace), mapp.RegisterCodespace(stake.DefaultCodespace)) keeper := NewKeeper(mapp.Cdc, keyGov, pk, pk.Subspace("testgov"), ck, sk, DefaultCodespace) diff --git a/x/ibc/app_test.go b/x/ibc/app_test.go index 6806d9779..9b360c7c2 100644 --- a/x/ibc/app_test.go +++ b/x/ibc/app_test.go @@ -21,7 +21,7 @@ func getMockApp(t *testing.T) *mock.App { RegisterCodec(mapp.Cdc) keyIBC := sdk.NewKVStoreKey("ibc") ibcMapper := NewMapper(mapp.Cdc, keyIBC, mapp.RegisterCodespace(DefaultCodespace)) - bankKeeper := bank.NewBaseKeeper(mapp.AccountMapper) + bankKeeper := bank.NewBaseKeeper(mapp.AccountKeeper) mapp.Router().AddRoute("ibc", NewHandler(ibcMapper, bankKeeper)) require.NoError(t, mapp.CompleteSetup(keyIBC)) @@ -49,7 +49,7 @@ func TestIBCMsgs(t *testing.T) { // A checkTx context (true) ctxCheck := mapp.BaseApp.NewContext(true, abci.Header{}) - res1 := mapp.AccountMapper.GetAccount(ctxCheck, addr1) + res1 := mapp.AccountKeeper.GetAccount(ctxCheck, addr1) require.Equal(t, acc, res1) packet := IBCPacket{ diff --git a/x/ibc/ibc_test.go b/x/ibc/ibc_test.go index c8e7492be..6cd89fded 100644 --- a/x/ibc/ibc_test.go +++ b/x/ibc/ibc_test.go @@ -17,7 +17,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/bank" ) -// AccountMapper(/Keeper) and IBCMapper should use different StoreKey later +// AccountKeeper(/Keeper) and IBCMapper should use different StoreKey later func defaultContext(key sdk.StoreKey) sdk.Context { db := dbm.NewMemDB() @@ -64,7 +64,7 @@ func TestIBC(t *testing.T) { key := sdk.NewKVStoreKey("ibc") ctx := defaultContext(key) - am := auth.NewAccountMapper(cdc, key, auth.ProtoBaseAccount) + am := auth.NewAccountKeeper(cdc, key, auth.ProtoBaseAccount) ck := bank.NewBaseKeeper(am) src := newAddress() diff --git a/x/mock/app.go b/x/mock/app.go index 1fe411fbc..627434a51 100644 --- a/x/mock/app.go +++ b/x/mock/app.go @@ -29,7 +29,7 @@ type App struct { KeyAccount *sdk.KVStoreKey // TODO: Abstract this out from not needing to be auth specifically - AccountMapper auth.AccountMapper + AccountKeeper auth.AccountKeeper FeeCollectionKeeper auth.FeeCollectionKeeper GenesisAccounts []auth.Account @@ -57,8 +57,8 @@ func NewApp() *App { TotalCoinsSupply: sdk.Coins{}, } - // Define the accountMapper - app.AccountMapper = auth.NewAccountMapper( + // Define the accountKeeper + app.AccountKeeper = auth.NewAccountKeeper( app.Cdc, app.KeyAccount, auth.ProtoBaseAccount, @@ -67,7 +67,7 @@ func NewApp() *App { // Initialize the app. The chainers and blockers can be overwritten before // calling complete setup. app.SetInitChainer(app.InitChainer) - app.SetAnteHandler(auth.NewAnteHandler(app.AccountMapper, app.FeeCollectionKeeper)) + app.SetAnteHandler(auth.NewAnteHandler(app.AccountKeeper, app.FeeCollectionKeeper)) // Not sealing for custom extension @@ -101,9 +101,9 @@ func (app *App) CompleteSetup(newKeys ...sdk.StoreKey) error { func (app *App) InitChainer(ctx sdk.Context, _ abci.RequestInitChain) abci.ResponseInitChain { // Load the genesis accounts for _, genacc := range app.GenesisAccounts { - acc := app.AccountMapper.NewAccountWithAddress(ctx, genacc.GetAddress()) + acc := app.AccountKeeper.NewAccountWithAddress(ctx, genacc.GetAddress()) acc.SetCoins(genacc.GetCoins()) - app.AccountMapper.SetAccount(ctx, acc) + app.AccountKeeper.SetAccount(ctx, acc) } return abci.ResponseInitChain{} @@ -247,8 +247,8 @@ func RandomSetGenesis(r *rand.Rand, app *App, addrs []sdk.AccAddress, denoms []s app.GenesisAccounts = accts } -// GetAllAccounts returns all accounts in the accountMapper. -func GetAllAccounts(mapper auth.AccountMapper, ctx sdk.Context) []auth.Account { +// GetAllAccounts returns all accounts in the accountKeeper. +func GetAllAccounts(mapper auth.AccountKeeper, ctx sdk.Context) []auth.Account { accounts := []auth.Account{} appendAccount := func(acc auth.Account) (stop bool) { accounts = append(accounts, acc) diff --git a/x/mock/app_test.go b/x/mock/app_test.go index d48a6ba14..6835d50b1 100644 --- a/x/mock/app_test.go +++ b/x/mock/app_test.go @@ -56,7 +56,7 @@ func TestCheckAndDeliverGenTx(t *testing.T) { msg := testMsg{signers: []sdk.AccAddress{addrs[0]}, positiveNum: 1} - acct := mApp.AccountMapper.GetAccount(ctxCheck, addrs[0]) + acct := mApp.AccountKeeper.GetAccount(ctxCheck, addrs[0]) require.Equal(t, accs[0], acct.(*auth.BaseAccount)) SignCheckDeliver( diff --git a/x/mock/test_utils.go b/x/mock/test_utils.go index caaca6c9a..4e60478fa 100644 --- a/x/mock/test_utils.go +++ b/x/mock/test_utils.go @@ -41,7 +41,7 @@ func RandFromBigInterval(r *rand.Rand, intervals []BigInterval) sdk.Int { // CheckBalance checks the balance of an account. func CheckBalance(t *testing.T, app *App, addr sdk.AccAddress, exp sdk.Coins) { ctxCheck := app.BaseApp.NewContext(true, abci.Header{}) - res := app.AccountMapper.GetAccount(ctxCheck, addr) + res := app.AccountKeeper.GetAccount(ctxCheck, addr) require.Equal(t, exp, res.GetCoins()) } diff --git a/x/slashing/app_test.go b/x/slashing/app_test.go index c0ed10747..6529609ba 100644 --- a/x/slashing/app_test.go +++ b/x/slashing/app_test.go @@ -31,7 +31,7 @@ func getMockApp(t *testing.T) (*mock.App, stake.Keeper, Keeper) { keyParams := sdk.NewKVStoreKey("params") tkeyParams := sdk.NewTransientStoreKey("transient_params") - bankKeeper := bank.NewBaseKeeper(mapp.AccountMapper) + bankKeeper := bank.NewBaseKeeper(mapp.AccountKeeper) paramsKeeper := params.NewKeeper(mapp.Cdc, keyParams, tkeyParams) stakeKeeper := stake.NewKeeper(mapp.Cdc, keyStake, tkeyStake, bankKeeper, paramsKeeper.Subspace(stake.DefaultParamspace), mapp.RegisterCodespace(stake.DefaultCodespace)) diff --git a/x/slashing/test_common.go b/x/slashing/test_common.go index a648bfe85..55a6fda18 100644 --- a/x/slashing/test_common.go +++ b/x/slashing/test_common.go @@ -68,9 +68,9 @@ func createTestInput(t *testing.T, defaults Params) (sdk.Context, bank.Keeper, s require.Nil(t, err) ctx := sdk.NewContext(ms, abci.Header{Time: time.Unix(0, 0)}, false, log.NewTMLogger(os.Stdout)) cdc := createTestCodec() - accountMapper := auth.NewAccountMapper(cdc, keyAcc, auth.ProtoBaseAccount) + accountKeeper := auth.NewAccountKeeper(cdc, keyAcc, auth.ProtoBaseAccount) - ck := bank.NewBaseKeeper(accountMapper) + ck := bank.NewBaseKeeper(accountKeeper) paramsKeeper := params.NewKeeper(cdc, keyParams, tkeyParams) sk := stake.NewKeeper(cdc, keyStake, tkeyStake, ck, paramsKeeper.Subspace(stake.DefaultParamspace), stake.DefaultCodespace) genesis := stake.DefaultGenesisState() diff --git a/x/stake/app_test.go b/x/stake/app_test.go index faafb6664..9a38d2d17 100644 --- a/x/stake/app_test.go +++ b/x/stake/app_test.go @@ -24,7 +24,7 @@ func getMockApp(t *testing.T) (*mock.App, Keeper) { keyParams := sdk.NewKVStoreKey("params") tkeyParams := sdk.NewTransientStoreKey("transient_params") - bankKeeper := bank.NewBaseKeeper(mApp.AccountMapper) + bankKeeper := bank.NewBaseKeeper(mApp.AccountKeeper) pk := params.NewKeeper(mApp.Cdc, keyParams, tkeyParams) keeper := NewKeeper(mApp.Cdc, keyStake, tkeyStake, bankKeeper, pk.Subspace(DefaultParamspace), mApp.RegisterCodespace(DefaultCodespace)) diff --git a/x/stake/client/rest/query.go b/x/stake/client/rest/query.go index 0398119d8..14de0b8e8 100644 --- a/x/stake/client/rest/query.go +++ b/x/stake/client/rest/query.go @@ -9,7 +9,6 @@ import ( "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/stake" "github.com/cosmos/cosmos-sdk/x/stake/tags" "github.com/gorilla/mux" @@ -67,6 +66,18 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Co validatorHandlerFn(cliCtx, cdc), ).Methods("GET") + // Get all unbonding delegations from a validator + r.HandleFunc( + "/stake/validators/{validatorAddr}/unbonding_delegations", + validatorUnbondingDelegationsHandlerFn(cliCtx, cdc), + ).Methods("GET") + + // Get all outgoing redelegations from a validator + r.HandleFunc( + "/stake/validators/{validatorAddr}/redelegations", + validatorRedelegationsHandlerFn(cliCtx, cdc), + ).Methods("GET") + // Get the current state of the staking pool r.HandleFunc( "/stake/pool", @@ -191,33 +202,17 @@ func validatorsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Handl // HTTP request handler to query the validator information from a given validator address func validatorHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - bech32validatorAddr := vars["validatorAddr"] + return queryValidator(cliCtx, cdc, "custom/stake/validator") +} - validatorAddr, err := sdk.ValAddressFromBech32(bech32validatorAddr) - if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } +// HTTP request handler to query all unbonding delegations from a validator +func validatorUnbondingDelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { + return queryValidator(cliCtx, cdc, "custom/stake/validatorUnbondingDelegations") +} - params := stake.QueryValidatorParams{ - ValidatorAddr: validatorAddr, - } - - bz, err := cdc.MarshalJSON(params) - if err != nil { - utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - res, err := cliCtx.QueryWithData("custom/stake/validator", bz) - if err != nil { - utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - utils.PostProcessResponse(w, cdc, res, cliCtx.Indent) - } +// HTTP request handler to query all redelegations from a source validator +func validatorRedelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { + return queryValidator(cliCtx, cdc, "custom/stake/validatorRedelegations") } // HTTP request handler to query the pool information diff --git a/x/stake/client/rest/utils.go b/x/stake/client/rest/utils.go index 477432032..bb986c314 100644 --- a/x/stake/client/rest/utils.go +++ b/x/stake/client/rest/utils.go @@ -111,3 +111,33 @@ func queryDelegator(cliCtx context.CLIContext, cdc *codec.Codec, endpoint string utils.PostProcessResponse(w, cdc, res, cliCtx.Indent) } } + +func queryValidator(cliCtx context.CLIContext, cdc *codec.Codec, endpoint string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + bech32validatorAddr := vars["validatorAddr"] + + validatorAddr, err := sdk.ValAddressFromBech32(bech32validatorAddr) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + params := stake.QueryValidatorParams{ + ValidatorAddr: validatorAddr, + } + + bz, err := cdc.MarshalJSON(params) + if err != nil { + utils.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + res, err := cliCtx.QueryWithData(endpoint, bz) + if err != nil { + utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + utils.PostProcessResponse(w, cdc, res, cliCtx.Indent) + } +} diff --git a/x/stake/keeper/test_common.go b/x/stake/keeper/test_common.go index 13e2ca2c5..7978f17e9 100644 --- a/x/stake/keeper/test_common.go +++ b/x/stake/keeper/test_common.go @@ -74,7 +74,7 @@ func MakeTestCodec() *codec.Codec { } // hogpodge of all sorts of input required for testing -func CreateTestInput(t *testing.T, isCheckTx bool, initCoins int64) (sdk.Context, auth.AccountMapper, Keeper) { +func CreateTestInput(t *testing.T, isCheckTx bool, initCoins int64) (sdk.Context, auth.AccountKeeper, Keeper) { keyStake := sdk.NewKVStoreKey("stake") tkeyStake := sdk.NewTransientStoreKey("transient_stake") @@ -94,13 +94,13 @@ func CreateTestInput(t *testing.T, isCheckTx bool, initCoins int64) (sdk.Context ctx := sdk.NewContext(ms, abci.Header{ChainID: "foochainid"}, isCheckTx, log.NewNopLogger()) cdc := MakeTestCodec() - accountMapper := auth.NewAccountMapper( + accountKeeper := auth.NewAccountKeeper( cdc, // amino codec keyAcc, // target store auth.ProtoBaseAccount, // prototype ) - ck := bank.NewBaseKeeper(accountMapper) + ck := bank.NewBaseKeeper(accountKeeper) pk := params.NewKeeper(cdc, keyParams, tkeyParams) keeper := NewKeeper(cdc, keyStake, tkeyStake, ck, pk.Subspace(DefaultParamspace), types.DefaultCodespace) @@ -118,7 +118,7 @@ func CreateTestInput(t *testing.T, isCheckTx bool, initCoins int64) (sdk.Context keeper.SetPool(ctx, pool) } - return ctx, accountMapper, keeper + return ctx, accountKeeper, keeper } func NewPubKey(pk string) (res crypto.PubKey) { diff --git a/x/stake/querier/queryable.go b/x/stake/querier/queryable.go index 7cf01d0d3..ace001fce 100644 --- a/x/stake/querier/queryable.go +++ b/x/stake/querier/queryable.go @@ -10,15 +10,17 @@ import ( // query endpoints supported by the staking Querier const ( - QueryValidators = "validators" - QueryValidator = "validator" - QueryDelegator = "delegator" - QueryDelegation = "delegation" - QueryUnbondingDelegation = "unbondingDelegation" - QueryDelegatorValidators = "delegatorValidators" - QueryDelegatorValidator = "delegatorValidator" - QueryPool = "pool" - QueryParameters = "parameters" + QueryValidators = "validators" + QueryValidator = "validator" + QueryValidatorUnbondingDelegations = "validatorUnbondingDelegations" + QueryValidatorRedelegations = "validatorRedelegations" + QueryDelegator = "delegator" + QueryDelegation = "delegation" + QueryUnbondingDelegation = "unbondingDelegation" + QueryDelegatorValidators = "delegatorValidators" + QueryDelegatorValidator = "delegatorValidator" + QueryPool = "pool" + QueryParameters = "parameters" ) // creates a querier for staking REST endpoints @@ -29,6 +31,10 @@ func NewQuerier(k keep.Keeper, cdc *codec.Codec) sdk.Querier { return queryValidators(ctx, cdc, k) case QueryValidator: return queryValidator(ctx, cdc, req, k) + case QueryValidatorUnbondingDelegations: + return queryValidatorUnbondingDelegations(ctx, cdc, req, k) + case QueryValidatorRedelegations: + return queryValidatorRedelegations(ctx, cdc, req, k) case QueryDelegator: return queryDelegator(ctx, cdc, req, k) case QueryDelegation: @@ -58,6 +64,8 @@ type QueryDelegatorParams struct { // defines the params for the following queries: // - 'custom/stake/validator' +// - 'custom/stake/validatorUnbondingDelegations' +// - 'custom/stake/validatorRedelegations' type QueryValidatorParams struct { ValidatorAddr sdk.ValAddress } @@ -102,6 +110,40 @@ func queryValidator(ctx sdk.Context, cdc *codec.Codec, req abci.RequestQuery, k return res, nil } +func queryValidatorUnbondingDelegations(ctx sdk.Context, cdc *codec.Codec, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { + var params QueryValidatorParams + + errRes := cdc.UnmarshalJSON(req.Data, ¶ms) + if errRes != nil { + return []byte{}, sdk.ErrUnknownAddress("") + } + + unbonds := k.GetUnbondingDelegationsFromValidator(ctx, params.ValidatorAddr) + + res, errRes = codec.MarshalJSONIndent(cdc, unbonds) + if errRes != nil { + return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", errRes.Error())) + } + return res, nil +} + +func queryValidatorRedelegations(ctx sdk.Context, cdc *codec.Codec, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { + var params QueryValidatorParams + + errRes := cdc.UnmarshalJSON(req.Data, ¶ms) + if errRes != nil { + return []byte{}, sdk.ErrUnknownAddress("") + } + + redelegations := k.GetRedelegationsFromValidator(ctx, params.ValidatorAddr) + + res, errRes = codec.MarshalJSONIndent(cdc, redelegations) + if errRes != nil { + return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", errRes.Error())) + } + return res, nil +} + func queryDelegator(ctx sdk.Context, cdc *codec.Codec, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { var params QueryDelegatorParams errRes := cdc.UnmarshalJSON(req.Data, ¶ms) diff --git a/x/stake/querier/queryable_test.go b/x/stake/querier/queryable_test.go index 1d76da90d..2a8608417 100644 --- a/x/stake/querier/queryable_test.go +++ b/x/stake/querier/queryable_test.go @@ -81,6 +81,12 @@ func TestNewQuerier(t *testing.T) { _, err = querier(ctx, []string{"validator"}, query) require.Nil(t, err) + + _, err = querier(ctx, []string{"validatorUnbondingDelegations"}, query) + require.Nil(t, err) + + _, err = querier(ctx, []string{"validatorRedelegations"}, query) + require.Nil(t, err) } func TestQueryParametersPool(t *testing.T) { diff --git a/x/stake/simulation/invariants.go b/x/stake/simulation/invariants.go index e249bac9f..f8d9a5227 100644 --- a/x/stake/simulation/invariants.go +++ b/x/stake/simulation/invariants.go @@ -15,7 +15,7 @@ import ( // AllInvariants runs all invariants of the stake module. // Currently: total supply, positive power -func AllInvariants(ck bank.Keeper, k stake.Keeper, f auth.FeeCollectionKeeper, d distribution.Keeper, am auth.AccountMapper) simulation.Invariant { +func AllInvariants(ck bank.Keeper, k stake.Keeper, f auth.FeeCollectionKeeper, d distribution.Keeper, am auth.AccountKeeper) simulation.Invariant { return func(app *baseapp.BaseApp) error { err := SupplyInvariants(ck, k, f, d, am)(app) if err != nil { @@ -32,7 +32,7 @@ func AllInvariants(ck bank.Keeper, k stake.Keeper, f auth.FeeCollectionKeeper, d // SupplyInvariants checks that the total supply reflects all held loose tokens, bonded tokens, and unbonding delegations // nolint: unparam -func SupplyInvariants(ck bank.Keeper, k stake.Keeper, f auth.FeeCollectionKeeper, d distribution.Keeper, am auth.AccountMapper) simulation.Invariant { +func SupplyInvariants(ck bank.Keeper, k stake.Keeper, f auth.FeeCollectionKeeper, d distribution.Keeper, am auth.AccountKeeper) simulation.Invariant { return func(app *baseapp.BaseApp) error { ctx := app.NewContext(false, abci.Header{}) pool := k.GetPool(ctx) diff --git a/x/stake/simulation/msgs.go b/x/stake/simulation/msgs.go index f2224c865..8684126e3 100644 --- a/x/stake/simulation/msgs.go +++ b/x/stake/simulation/msgs.go @@ -14,7 +14,7 @@ import ( ) // SimulateMsgCreateValidator -func SimulateMsgCreateValidator(m auth.AccountMapper, k stake.Keeper) simulation.Operation { +func SimulateMsgCreateValidator(m auth.AccountKeeper, k stake.Keeper) simulation.Operation { handler := stake.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) ( @@ -111,7 +111,7 @@ func SimulateMsgEditValidator(k stake.Keeper) simulation.Operation { } // SimulateMsgDelegate -func SimulateMsgDelegate(m auth.AccountMapper, k stake.Keeper) simulation.Operation { +func SimulateMsgDelegate(m auth.AccountKeeper, k stake.Keeper) simulation.Operation { handler := stake.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) ( @@ -149,7 +149,7 @@ func SimulateMsgDelegate(m auth.AccountMapper, k stake.Keeper) simulation.Operat } // SimulateMsgBeginUnbonding -func SimulateMsgBeginUnbonding(m auth.AccountMapper, k stake.Keeper) simulation.Operation { +func SimulateMsgBeginUnbonding(m auth.AccountKeeper, k stake.Keeper) simulation.Operation { handler := stake.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) ( @@ -187,7 +187,7 @@ func SimulateMsgBeginUnbonding(m auth.AccountMapper, k stake.Keeper) simulation. } // SimulateMsgBeginRedelegate -func SimulateMsgBeginRedelegate(m auth.AccountMapper, k stake.Keeper) simulation.Operation { +func SimulateMsgBeginRedelegate(m auth.AccountKeeper, k stake.Keeper) simulation.Operation { handler := stake.NewHandler(k) return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account, event func(string)) ( @@ -238,10 +238,10 @@ func Setup(mapp *mock.App, k stake.Keeper) simulation.RandSetup { params := k.GetParams(ctx) denom := params.BondDenom loose := sdk.ZeroInt() - mapp.AccountMapper.IterateAccounts(ctx, func(acc auth.Account) bool { + mapp.AccountKeeper.IterateAccounts(ctx, func(acc auth.Account) bool { balance := simulation.RandomAmount(r, sdk.NewInt(1000000)) acc.SetCoins(acc.GetCoins().Plus(sdk.Coins{sdk.NewCoin(denom, balance)})) - mapp.AccountMapper.SetAccount(ctx, acc) + mapp.AccountKeeper.SetAccount(ctx, acc) loose = loose.Add(balance) return false }) diff --git a/x/stake/simulation/sim_test.go b/x/stake/simulation/sim_test.go index 2ce9fa00d..51f633eb1 100644 --- a/x/stake/simulation/sim_test.go +++ b/x/stake/simulation/sim_test.go @@ -22,7 +22,7 @@ func TestStakeWithRandomMessages(t *testing.T) { mapp := mock.NewApp() bank.RegisterCodec(mapp.Cdc) - mapper := mapp.AccountMapper + mapper := mapp.AccountKeeper bankKeeper := bank.NewBaseKeeper(mapper) feeKey := sdk.NewKVStoreKey("fee") stakeKey := sdk.NewKVStoreKey("stake") @@ -64,7 +64,7 @@ func TestStakeWithRandomMessages(t *testing.T) { }, []simulation.RandSetup{ Setup(mapp, stakeKeeper), }, []simulation.Invariant{ - AllInvariants(bankKeeper, stakeKeeper, feeCollectionKeeper, distrKeeper, mapp.AccountMapper), + AllInvariants(bankKeeper, stakeKeeper, feeCollectionKeeper, distrKeeper, mapp.AccountKeeper), }, 10, 100, false, )