diff --git a/PENDING.md b/PENDING.md index 27cf631d65..8c08d2b8f3 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 6d2eecdea5..5f8e4bc6f5 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) { @@ -555,11 +554,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) @@ -571,33 +569,53 @@ 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) delegatorDels = getDelegatorDelegations(t, port, addr) - require.Len(t, delegatorDels, 0) + require.Len(t, delegatorDels, 1) + require.Equal(t, "30.0000000000", delegatorDels[0].GetShares().String()) delegatorUbds := getDelegatorUnbondingDelegations(t, port, addr) require.Len(t, delegatorUbds, 1) - require.Equal(t, "60", delegatorUbds[0].Balance.Amount.String()) + require.Equal(t, "30", delegatorUbds[0].Balance.Amount.String()) + + delegatorReds := getDelegatorRedelegations(t, port, addr) + require.Len(t, delegatorReds, 1) + require.Equal(t, "30", delegatorReds[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) - delegatorReds := getDelegatorRedelegations(t, port, addr) - require.Len(t, delegatorReds, 0) - // 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) { @@ -972,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 getDelegatorDelegations(t *testing.T, port string, delegatorAddr sdk.AccAddress) []stake.Delegation { @@ -1074,9 +1092,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", @@ -1113,9 +1129,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", @@ -1136,7 +1150,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() @@ -1147,16 +1161,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", @@ -1164,7 +1176,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) @@ -1198,6 +1210,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 8fba41f600..f8d2bb410d 100644 --- a/cmd/gaia/app/app.go +++ b/cmd/gaia/app/app.go @@ -56,7 +56,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 @@ -91,15 +91,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, @@ -159,7 +159,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) @@ -231,8 +231,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 @@ -299,7 +299,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 e24919e102..19a1c4fe5c 100644 --- a/cmd/gaia/app/sim_test.go +++ b/cmd/gaia/app/sim_test.go @@ -106,23 +106,23 @@ func appStateFn(r *rand.Rand, accs []simulation.Account) json.RawMessage { func testAndRunTxs(app *GaiaApp) []simulation.WeightedOperation { return []simulation.WeightedOperation{ - {100, banksim.SingleInputSendMsg(app.accountMapper, app.bankKeeper)}, + {100, banksim.SingleInputSendMsg(app.accountKeeper, app.bankKeeper)}, {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), + banksim.NonnegativeBalanceInvariant(app.accountKeeper), govsim.AllInvariants(), - stakesim.AllInvariants(app.bankKeeper, app.stakeKeeper, app.accountMapper), + stakesim.AllInvariants(app.bankKeeper, app.stakeKeeper, app.accountKeeper), slashingsim.AllInvariants(), } } diff --git a/cmd/gaia/cmd/gaiadebug/hack.go b/cmd/gaia/cmd/gaiadebug/hack.go index db22da0b52..734a83df30 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 595a3694fa..2462e3e66a 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 9a101c2816..453970c1af 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 e4fa515ee2..6d45c40315 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 905982f621..70e826c60a 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 aed6de85ef..546eb7d875 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/examples/basecoin/app/app.go b/examples/basecoin/app/app.go index 3d9ac81736..286afd003e 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 da544f4803..c49d5d4768 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 04d3e371ef..41b4377180 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 97dcf4e358..12f5d8d294 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 fc00651b8f..5b3be00e12 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 35a656cebc..01cb73ef17 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 fef93b954d..f805ca880b 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 e3af7790e4..1eb40dfb29 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 6e6f07f770..5009b7ec54 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 8166ddfc53..ce398b7c28 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 dbd974c4d0..86ccbc8c01 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 68f28bd91b..c3876cf4ad 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 e9623995f0..c981f6dca6 100644 --- a/types/decimal.go +++ b/types/decimal.go @@ -248,29 +248,33 @@ func (d Dec) QuoInt(i Int) Dec { } 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) } // ____ @@ -407,17 +411,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 @@ -431,7 +431,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 a6ec0740e8..07329c7dc7 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 3fd183a0ca..9d5bc50597 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 bacb3013f9..d29b0bf50d 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 40fb177858..28d159c972 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 20d6c2d143..dd127c7312 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 e3b737ea3c..326f83dcca 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/bank/app_test.go b/x/bank/app_test.go index 7c320a9bd0..906573eae2 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 a29a25b999..bff99da996 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 8200563b0e..c72ed6fcb9 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 2da4eedc8b..ac7a484d5e 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 c48410c154..26c1446d27 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 20aa9570bf..f0cd5ba63c 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 0a253235e1..f33c5e0c99 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 ce3877a620..5141562281 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 59b615ec8a..95303b16ba 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()) @@ -139,7 +139,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/gov/keeper.go b/x/gov/keeper.go index 4b7ec26b5c..d061f12062 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 a7d4e40d05..a222c19a52 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 b33f580841..82ae30358b 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 6806d9779e..9b360c7c24 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 c8e7492be7..6cd89fded4 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 1fe411fbc5..627434a513 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 d48a6ba14d..6835d50b13 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 caaca6c9a5..4e60478fa4 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 c0ed10747c..6529609ba0 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 a648bfe850..55a6fda18f 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 faafb6664f..9a38d2d170 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 e9a894a5b6..935c0229f6 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" @@ -79,6 +78,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", @@ -213,33 +224,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 477432032a..bb986c3147 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 d0ac4a2825..2303d3c750 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) @@ -119,7 +119,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 1aef2e2d18..d3d15bc8f6 100644 --- a/x/stake/querier/queryable.go +++ b/x/stake/querier/queryable.go @@ -15,6 +15,9 @@ const ( QueryDelegatorDelegations = "delegatorDelegations" QueryDelegatorUnbondingDelegations = "delegatorUnbondingDelegations" QueryDelegatorRedelegations = "delegatorRedelegations" + QueryValidatorUnbondingDelegations = "validatorUnbondingDelegations" + QueryValidatorRedelegations = "validatorRedelegations" + QueryDelegator = "delegator" QueryDelegation = "delegation" QueryUnbondingDelegation = "unbondingDelegation" QueryDelegatorValidators = "delegatorValidators" @@ -31,16 +34,20 @@ 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 QueryDelegation: + return queryDelegation(ctx, cdc, req, k) + case QueryUnbondingDelegation: + return queryUnbondingDelegation(ctx, cdc, req, k) case QueryDelegatorDelegations: return queryDelegatorDelegations(ctx, cdc, req, k) case QueryDelegatorUnbondingDelegations: return queryDelegatorUnbondingDelegations(ctx, cdc, req, k) case QueryDelegatorRedelegations: return queryDelegatorRedelegations(ctx, cdc, req, k) - case QueryDelegation: - return queryDelegation(ctx, cdc, req, k) - case QueryUnbondingDelegation: - return queryUnbondingDelegation(ctx, cdc, req, k) case QueryDelegatorValidators: return queryDelegatorValidators(ctx, cdc, req, k) case QueryDelegatorValidator: @@ -67,6 +74,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 } @@ -111,6 +120,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 queryDelegatorDelegations(ctx sdk.Context, cdc *codec.Codec, req abci.RequestQuery, k keep.Keeper) (res []byte, err sdk.Error) { var params QueryDelegatorParams diff --git a/x/stake/querier/queryable_test.go b/x/stake/querier/queryable_test.go index 649f5ff59c..6bc4417ce0 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 2866f6292f..661e46cc49 100644 --- a/x/stake/simulation/invariants.go +++ b/x/stake/simulation/invariants.go @@ -14,7 +14,7 @@ import ( // AllInvariants runs all invariants of the stake module. // Currently: total supply, positive power -func AllInvariants(ck bank.Keeper, k stake.Keeper, am auth.AccountMapper) simulation.Invariant { +func AllInvariants(ck bank.Keeper, k stake.Keeper, am auth.AccountKeeper) simulation.Invariant { return func(app *baseapp.BaseApp) error { err := SupplyInvariants(ck, k, am)(app) if err != nil { @@ -31,7 +31,7 @@ func AllInvariants(ck bank.Keeper, k stake.Keeper, am auth.AccountMapper) simula // 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, am auth.AccountMapper) simulation.Invariant { +func SupplyInvariants(ck bank.Keeper, k stake.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 f2224c865b..8684126e30 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 6aa7801139..648c092849 100644 --- a/x/stake/simulation/sim_test.go +++ b/x/stake/simulation/sim_test.go @@ -20,7 +20,7 @@ func TestStakeWithRandomMessages(t *testing.T) { mapp := mock.NewApp() bank.RegisterCodec(mapp.Cdc) - mapper := mapp.AccountMapper + mapper := mapp.AccountKeeper bankKeeper := bank.NewBaseKeeper(mapper) stakeKey := sdk.NewKVStoreKey("stake") stakeTKey := sdk.NewTransientStoreKey("transient_stake") @@ -58,7 +58,7 @@ func TestStakeWithRandomMessages(t *testing.T) { }, []simulation.RandSetup{ Setup(mapp, stakeKeeper), }, []simulation.Invariant{ - AllInvariants(bankKeeper, stakeKeeper, mapp.AccountMapper), + AllInvariants(bankKeeper, stakeKeeper, mapp.AccountKeeper), }, 10, 100, false, )