From 65ab2530cc654fd9e252b124ed24cbaa18023b2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juli=C3=A1n=20Toledano?= Date: Tue, 19 Mar 2024 10:20:42 +0100 Subject: [PATCH] refactor(x/staking)!: removes the use of Accounts String() method (#19742) --- CHANGELOG.md | 3 + UPGRADING.md | 10 + simapp/sim_bench_test.go | 2 +- simapp/sim_test.go | 10 +- .../evidence/keeper/infraction_test.go | 12 +- .../slashing/keeper/keeper_test.go | 20 +- tests/sims/gov/operations_test.go | 5 +- testutil/sims/simulation_helpers.go | 10 +- testutil/sims/state_helpers.go | 34 +-- types/module/simulation.go | 3 + types/simulation/types.go | 4 +- x/auth/simulation/genesis_test.go | 19 +- x/auth/simulation/proposals.go | 5 +- x/auth/simulation/proposals_test.go | 4 +- x/authz/client/cli/tx.go | 6 +- x/authz/msgs_test.go | 5 +- x/authz/simulation/genesis_test.go | 16 +- x/bank/simulation/genesis_test.go | 20 +- x/bank/simulation/proposals.go | 5 +- x/bank/simulation/proposals_test.go | 4 +- x/distribution/simulation/genesis_test.go | 18 +- x/distribution/simulation/proposals.go | 5 +- x/distribution/simulation/proposals_test.go | 4 +- x/evidence/simulation/genesis_test.go | 19 +- x/feegrant/simulation/genesis_test.go | 18 +- x/gov/simulation/genesis_test.go | 20 +- x/gov/simulation/operations.go | 5 +- x/gov/simulation/proposals.go | 5 +- x/gov/simulation/proposals_test.go | 4 +- x/group/simulation/genesis_test.go | 17 +- x/mint/simulation/genesis_test.go | 21 +- x/mint/simulation/proposals.go | 5 +- x/mint/simulation/proposals_test.go | 4 +- x/nft/simulation/genesis_test.go | 19 +- x/protocolpool/simulation/proposals.go | 5 +- x/protocolpool/simulation/proposals_test.go | 4 +- x/slashing/simulation/genesis_test.go | 18 +- x/slashing/simulation/proposals.go | 5 +- x/slashing/simulation/proposals_test.go | 4 +- x/staking/CHANGELOG.md | 1 + x/staking/keeper/alias_functions.go | 6 +- x/staking/keeper/cons_pubkey_test.go | 23 +- x/staking/keeper/delegation_test.go | 96 ++++---- x/staking/keeper/keeper_test.go | 45 ++-- x/staking/keeper/msg_server_test.go | 226 +++++++++--------- x/staking/keeper/validator_test.go | 8 +- x/staking/migrations/v5/migrations_test.go | 12 +- x/staking/simulation/genesis.go | 12 +- x/staking/simulation/genesis_test.go | 20 +- x/staking/simulation/operations.go | 28 ++- x/staking/simulation/proposals.go | 12 +- x/staking/simulation/proposals_test.go | 11 +- x/staking/testutil/helpers.go | 20 +- x/staking/testutil/validator.go | 5 +- x/staking/types/authz.go | 31 ++- x/staking/types/authz_test.go | 86 ++++--- x/staking/types/delegation_test.go | 50 +++- x/staking/types/msg_test.go | 6 +- x/staking/types/validator_test.go | 12 +- 59 files changed, 680 insertions(+), 427 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b543d29b8a7e..20e5795ef952 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -101,6 +101,9 @@ Every module contains its own CHANGELOG.md. Please refer to the module you are i ### API Breaking Changes +* (types) [#19742](https://github.com/cosmos/cosmos-sdk/pull/19742) Removes the use of `Accounts.String` + * `MsgSimulatorFn` now takes an `address.Codec` as argument and also returns an error. + * `SimulationState` now has address and validator codecs as fields. * (types) [#19447](https://github.com/cosmos/cosmos-sdk/pull/19447) `module.testutil.MakeTestEncodingConfig` now takes `CodecOptions` as argument. * (types) [#19512](https://github.com/cosmos/cosmos-sdk/pull/19512) Remove basic manager and all related functions (`module.BasicManager`, `module.NewBasicManager`, `module.NewBasicManagerFromManager`, `NewGenesisOnlyAppModule`). * The module manager now can do everything that the basic manager was doing. diff --git a/UPGRADING.md b/UPGRADING.md index cdc28d55457f..a1a6bc8ce2be 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -145,6 +145,16 @@ If you were depending on `cosmossdk.io/api/tendermint`, please use the buf gener #### `**all**` +##### Simulation + +As an effort to remove the use of the global config, `sdk.Address.String` method must be removed. As a consequence, `MsgSimulatorFn` has been updated to return an error and use an `address.Codec` to set +`staking.MsgUpdateParams.Authority`. + +```diff +-type MsgSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []Account) sdk.Msg ++type MsgSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []Account, cdc address.Codec) (sdk.Msg, error) +``` + ##### Core API Core API has been introduced for modules since v0.47. With the deprecation of `sdk.Context`, we strongly recommend to use the `cosmossdk.io/core/appmodule` interfaces for the modules. This will allow the modules to work out of the box with server/v2 and baseapp, as well as limit their dependencies on the SDK. diff --git a/simapp/sim_bench_test.go b/simapp/sim_bench_test.go index aa53674b3bd9..ab3538c7af07 100644 --- a/simapp/sim_bench_test.go +++ b/simapp/sim_bench_test.go @@ -66,7 +66,7 @@ func BenchmarkFullAppSimulation(b *testing.B) { b, os.Stdout, app.BaseApp, - simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()), + simtestutil.AppStateFn(app.AppCodec(), app.AuthKeeper.AddressCodec(), app.StakingKeeper.ValidatorAddressCodec(), app.SimulationManager(), app.DefaultGenesis()), simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 simtestutil.SimulationOperations(app, app.AppCodec(), config), BlockedAddresses(), diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 960490f168bd..1ff1daa615b5 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -86,7 +86,7 @@ func TestFullAppSimulation(t *testing.T) { t, os.Stdout, app.BaseApp, - simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()), + simtestutil.AppStateFn(app.AppCodec(), app.AuthKeeper.AddressCodec(), app.StakingKeeper.ValidatorAddressCodec(), app.SimulationManager(), app.DefaultGenesis()), simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 simtestutil.SimulationOperations(app, app.AppCodec(), config), BlockedAddresses(), @@ -134,7 +134,7 @@ func TestAppImportExport(t *testing.T) { t, os.Stdout, app.BaseApp, - simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()), + simtestutil.AppStateFn(app.AppCodec(), app.AuthKeeper.AddressCodec(), app.StakingKeeper.ValidatorAddressCodec(), app.SimulationManager(), app.DefaultGenesis()), simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 simtestutil.SimulationOperations(app, app.AppCodec(), config), BlockedAddresses(), @@ -255,7 +255,7 @@ func TestAppSimulationAfterImport(t *testing.T) { t, os.Stdout, app.BaseApp, - simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()), + simtestutil.AppStateFn(app.AppCodec(), app.AuthKeeper.AddressCodec(), app.StakingKeeper.ValidatorAddressCodec(), app.SimulationManager(), app.DefaultGenesis()), simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 simtestutil.SimulationOperations(app, app.AppCodec(), config), BlockedAddresses(), @@ -307,7 +307,7 @@ func TestAppSimulationAfterImport(t *testing.T) { t, os.Stdout, newApp.BaseApp, - simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()), + simtestutil.AppStateFn(app.AppCodec(), app.AuthKeeper.AddressCodec(), app.StakingKeeper.ValidatorAddressCodec(), app.SimulationManager(), app.DefaultGenesis()), simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 simtestutil.SimulationOperations(newApp, newApp.AppCodec(), config), BlockedAddresses(), @@ -386,7 +386,7 @@ func TestAppStateDeterminism(t *testing.T) { t, os.Stdout, app.BaseApp, - simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()), + simtestutil.AppStateFn(app.AppCodec(), app.AuthKeeper.AddressCodec(), app.StakingKeeper.ValidatorAddressCodec(), app.SimulationManager(), app.DefaultGenesis()), simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 simtestutil.SimulationOperations(app, app.AppCodec(), config), BlockedAddresses(), diff --git a/tests/integration/evidence/keeper/infraction_test.go b/tests/integration/evidence/keeper/infraction_test.go index 4dcc9b3e8298..87d5a52c9fa4 100644 --- a/tests/integration/evidence/keeper/infraction_test.go +++ b/tests/integration/evidence/keeper/infraction_test.go @@ -261,7 +261,11 @@ func TestHandleDoubleSign(t *testing.T) { totalBond := validator.TokensFromShares(del.GetShares()).TruncateInt() tstaking.Ctx = ctx tstaking.Denom = stakingParams.BondDenom - tstaking.Undelegate(sdk.AccAddress(operatorAddr), operatorAddr, totalBond, true) + accAddr, err := f.accountKeeper.AddressCodec().BytesToString(operatorAddr) + assert.NilError(t, err) + opAddr, err := f.stakingKeeper.ValidatorAddressCodec().BytesToString(operatorAddr) + assert.NilError(t, err) + tstaking.Undelegate(accAddr, opAddr, totalBond, true) // query evidence from store iter, err := f.evidenceKeeper.Evidences.Iterate(ctx, nil) @@ -424,7 +428,11 @@ func TestHandleDoubleSignAfterRotation(t *testing.T) { totalBond := validator.TokensFromShares(del.GetShares()).TruncateInt() tstaking.Ctx = ctx tstaking.Denom = stakingParams.BondDenom - tstaking.Undelegate(sdk.AccAddress(operatorAddr), operatorAddr, totalBond, true) + accAddr, err := f.accountKeeper.AddressCodec().BytesToString(operatorAddr) + assert.NilError(t, err) + opAddr, err := f.stakingKeeper.ValidatorAddressCodec().BytesToString(operatorAddr) + assert.NilError(t, err) + tstaking.Undelegate(accAddr, opAddr, totalBond, true) // query evidence from store var evidences []exported.Evidence diff --git a/tests/integration/slashing/keeper/keeper_test.go b/tests/integration/slashing/keeper/keeper_test.go index a74665167221..dc14c0284836 100644 --- a/tests/integration/slashing/keeper/keeper_test.go +++ b/tests/integration/slashing/keeper/keeper_test.go @@ -195,7 +195,11 @@ func TestUnJailNotBonded(t *testing.T) { // unbond below minimum self-delegation assert.Equal(t, p.BondDenom, tstaking.Denom) - tstaking.Undelegate(sdk.AccAddress(addr), addr, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 1), true) + accAddr, err := f.accountKeeper.AddressCodec().BytesToString(addr) + assert.NilError(t, err) + valAddr, err := f.stakingKeeper.ValidatorAddressCodec().BytesToString(addr) + require.NoError(t, err) + tstaking.Undelegate(accAddr, valAddr, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 1), true) _, err = f.stakingKeeper.EndBlocker(f.ctx) assert.NilError(t, err) @@ -220,8 +224,12 @@ func TestUnJailNotBonded(t *testing.T) { assert.NilError(t, err) newHeight = f.ctx.BlockHeight() + 1 f.ctx = f.ctx.WithBlockHeight(newHeight).WithHeaderInfo(coreheader.Info{Height: newHeight}) - // bond to meet minimum self-delegation - tstaking.DelegateWithPower(sdk.AccAddress(addr), addr, 1) + // bond to meet minimum self-delegationa + accAddr, err = f.accountKeeper.AddressCodec().BytesToString(addr) + assert.NilError(t, err) + valAddr, err = f.stakingKeeper.ValidatorAddressCodec().BytesToString(addr) + assert.NilError(t, err) + tstaking.DelegateWithPower(accAddr, valAddr, 1) _, err = f.stakingKeeper.EndBlocker(f.ctx) assert.NilError(t, err) @@ -430,7 +438,11 @@ func TestValidatorDippingInAndOut(t *testing.T) { f.ctx = f.ctx.WithBlockHeight(height).WithHeaderInfo(coreheader.Info{Height: height}) // validator added back in - tstaking.DelegateWithPower(sdk.AccAddress(pks[2].Address()), valAddr, 50) + accAddr, err := f.accountKeeper.AddressCodec().BytesToString(sdk.AccAddress(pks[2].Address())) + assert.NilError(t, err) + vAddr, err := f.stakingKeeper.ValidatorAddressCodec().BytesToString(valAddr) + assert.NilError(t, err) + tstaking.DelegateWithPower(accAddr, vAddr, 50) validatorUpdates, err = f.stakingKeeper.EndBlocker(f.ctx) require.NoError(t, err) diff --git a/tests/sims/gov/operations_test.go b/tests/sims/gov/operations_test.go index d5469829c827..972aedec6055 100644 --- a/tests/sims/gov/operations_test.go +++ b/tests/sims/gov/operations_test.go @@ -9,6 +9,7 @@ import ( "github.com/cosmos/gogoproto/proto" "github.com/stretchr/testify/require" + "cosmossdk.io/core/address" "cosmossdk.io/core/header" "cosmossdk.io/depinject" "cosmossdk.io/log" @@ -55,8 +56,8 @@ func (m MockWeightedProposals) DefaultWeight() int { } func (m MockWeightedProposals) MsgSimulatorFn() simtypes.MsgSimulatorFn { - return func(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) sdk.Msg { - return nil + return func(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, _ address.Codec) (sdk.Msg, error) { + return nil, nil } } diff --git a/testutil/sims/simulation_helpers.go b/testutil/sims/simulation_helpers.go index ac2d5b871cf7..2c5fa7af259e 100644 --- a/testutil/sims/simulation_helpers.go +++ b/testutil/sims/simulation_helpers.go @@ -54,10 +54,12 @@ func SetupSimulation(config simtypes.Config, dirPrefix, dbName string, verbose, func SimulationOperations(app runtime.AppSimI, cdc codec.Codec, config simtypes.Config) []simtypes.WeightedOperation { signingCtx := cdc.InterfaceRegistry().SigningContext() simState := module.SimulationState{ - AppParams: make(simtypes.AppParams), - Cdc: cdc, - TxConfig: authtx.NewTxConfig(cdc, signingCtx.AddressCodec(), signingCtx.ValidatorAddressCodec(), authtx.DefaultSignModes), // TODO(tip): we should extract this from app - BondDenom: sdk.DefaultBondDenom, + AppParams: make(simtypes.AppParams), + Cdc: cdc, + AddressCodec: signingCtx.AddressCodec(), + ValidatorCodec: signingCtx.ValidatorAddressCodec(), + TxConfig: authtx.NewTxConfig(cdc, signingCtx.AddressCodec(), signingCtx.ValidatorAddressCodec(), authtx.DefaultSignModes), // TODO(tip): we should extract this from app + BondDenom: sdk.DefaultBondDenom, } if config.ParamsFile != "" { diff --git a/testutil/sims/state_helpers.go b/testutil/sims/state_helpers.go index 031a6125ca1b..68885c52568d 100644 --- a/testutil/sims/state_helpers.go +++ b/testutil/sims/state_helpers.go @@ -12,6 +12,7 @@ import ( "github.com/cosmos/gogoproto/proto" + "cosmossdk.io/core/address" "cosmossdk.io/math" authtypes "cosmossdk.io/x/auth/types" banktypes "cosmossdk.io/x/bank/types" @@ -36,19 +37,20 @@ const ( // AppStateFn returns the initial application state using a genesis or the simulation parameters. // It calls AppStateFnWithExtendedCb with nil rawStateCb. -func AppStateFn(cdc codec.JSONCodec, simManager *module.SimulationManager, genesisState map[string]json.RawMessage) simtypes.AppStateFn { - return AppStateFnWithExtendedCb(cdc, simManager, genesisState, nil) +func AppStateFn(cdc codec.JSONCodec, addresCodec, validatorCodec address.Codec, simManager *module.SimulationManager, genesisState map[string]json.RawMessage) simtypes.AppStateFn { + return AppStateFnWithExtendedCb(cdc, addresCodec, validatorCodec, simManager, genesisState, nil) } // AppStateFnWithExtendedCb returns the initial application state using a genesis or the simulation parameters. // It calls AppStateFnWithExtendedCbs with nil moduleStateCb. func AppStateFnWithExtendedCb( cdc codec.JSONCodec, + addresCodec, validatorCodec address.Codec, simManager *module.SimulationManager, genesisState map[string]json.RawMessage, rawStateCb func(rawState map[string]json.RawMessage), ) simtypes.AppStateFn { - return AppStateFnWithExtendedCbs(cdc, simManager, genesisState, nil, rawStateCb) + return AppStateFnWithExtendedCbs(cdc, addresCodec, validatorCodec, simManager, genesisState, nil, rawStateCb) } // AppStateFnWithExtendedCbs returns the initial application state using a genesis or the simulation parameters. @@ -59,6 +61,7 @@ func AppStateFnWithExtendedCb( // rawStateCb is the callback function to extend rawState. func AppStateFnWithExtendedCbs( cdc codec.JSONCodec, + addressCodec, validatorCodec address.Codec, simManager *module.SimulationManager, genesisState map[string]json.RawMessage, moduleStateCb func(moduleName string, genesisState interface{}), @@ -103,11 +106,11 @@ func AppStateFnWithExtendedCbs( if err != nil { panic(err) } - appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams, genesisState) + appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams, genesisState, addressCodec, validatorCodec) default: appParams := make(simtypes.AppParams) - appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams, genesisState) + appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams, genesisState, addressCodec, validatorCodec) } rawState := make(map[string]json.RawMessage) @@ -195,6 +198,7 @@ func AppStateRandomizedFn( genesisTimestamp time.Time, appParams simtypes.AppParams, genesisState map[string]json.RawMessage, + addressCodec, validatorCodec address.Codec, ) (json.RawMessage, []simtypes.Account) { numAccs := int64(len(accs)) // generate a random amount of initial stake coins and a random initial @@ -226,15 +230,17 @@ func AppStateRandomizedFn( ) simState := &module.SimulationState{ - AppParams: appParams, - Cdc: cdc, - Rand: r, - GenState: genesisState, - Accounts: accs, - InitialStake: initialStake, - NumBonded: numInitiallyBonded, - BondDenom: sdk.DefaultBondDenom, - GenTimestamp: genesisTimestamp, + AppParams: appParams, + Cdc: cdc, + AddressCodec: addressCodec, + ValidatorCodec: validatorCodec, + Rand: r, + GenState: genesisState, + Accounts: accs, + InitialStake: initialStake, + NumBonded: numInitiallyBonded, + BondDenom: sdk.DefaultBondDenom, + GenTimestamp: genesisTimestamp, } simManager.GenerateGenesisStates(simState) diff --git a/types/module/simulation.go b/types/module/simulation.go index 32e8f7da8ed4..20bb46ba1976 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -6,6 +6,7 @@ import ( "sort" "time" + "cosmossdk.io/core/address" "cosmossdk.io/core/appmodule" sdkmath "cosmossdk.io/math" @@ -145,6 +146,8 @@ func (sm *SimulationManager) WeightedOperations(simState SimulationState) []simu type SimulationState struct { AppParams simulation.AppParams Cdc codec.JSONCodec // application codec + AddressCodec address.Codec // address codec + ValidatorCodec address.Codec // validator address codec TxConfig client.TxConfig // Shared TxConfig; this is expensive to create and stateless, so create it once up front. Rand *rand.Rand // random number GenState map[string]json.RawMessage // genesis state diff --git a/types/simulation/types.go b/types/simulation/types.go index 32bcd54520e6..15bcb2bef155 100644 --- a/types/simulation/types.go +++ b/types/simulation/types.go @@ -8,6 +8,8 @@ import ( "github.com/cosmos/gogoproto/proto" + "cosmossdk.io/core/address" + "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/kv" @@ -39,7 +41,7 @@ type WeightedProposalMsg interface { MsgSimulatorFn() MsgSimulatorFn // msg simulator function } -type MsgSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []Account) sdk.Msg +type MsgSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []Account, cdc address.Codec) (sdk.Msg, error) type SimValFn func(r *rand.Rand) string diff --git a/x/auth/simulation/genesis_test.go b/x/auth/simulation/genesis_test.go index 94d2621a2af9..2d6a63e4882c 100644 --- a/x/auth/simulation/genesis_test.go +++ b/x/auth/simulation/genesis_test.go @@ -12,6 +12,7 @@ import ( "cosmossdk.io/x/auth/types" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/testutil" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -23,18 +24,20 @@ func TestRandomizedGenState(t *testing.T) { registry := codectypes.NewInterfaceRegistry() types.RegisterInterfaces(registry) cdc := codec.NewProtoCodec(registry) - + cdcOpts := testutil.CodecOptions{} s := rand.NewSource(1) r := rand.New(s) simState := module.SimulationState{ - AppParams: make(simtypes.AppParams), - Cdc: cdc, - Rand: r, - NumBonded: 3, - Accounts: simtypes.RandomAccounts(r, 3), - InitialStake: sdkmath.NewInt(1000), - GenState: make(map[string]json.RawMessage), + AppParams: make(simtypes.AppParams), + Cdc: cdc, + AddressCodec: cdcOpts.GetAddressCodec(), + ValidatorCodec: cdcOpts.GetValidatorCodec(), + Rand: r, + NumBonded: 3, + Accounts: simtypes.RandomAccounts(r, 3), + InitialStake: sdkmath.NewInt(1000), + GenState: make(map[string]json.RawMessage), } simulation.RandomizedGenState(&simState, simulation.RandomGenesisAccounts) diff --git a/x/auth/simulation/proposals.go b/x/auth/simulation/proposals.go index 809bbcb32826..148753163ad0 100644 --- a/x/auth/simulation/proposals.go +++ b/x/auth/simulation/proposals.go @@ -3,6 +3,7 @@ package simulation import ( "math/rand" + coreaddress "cosmossdk.io/core/address" "cosmossdk.io/x/auth/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -30,7 +31,7 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { } // SimulateMsgUpdateParams returns a random MsgUpdateParams -func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) sdk.Msg { +func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, _ coreaddress.Codec) (sdk.Msg, error) { // use the default gov module account address as authority var authority sdk.AccAddress = address.Module("gov") @@ -44,5 +45,5 @@ func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) return &types.MsgUpdateParams{ Authority: authority.String(), Params: params, - } + }, nil } diff --git a/x/auth/simulation/proposals_test.go b/x/auth/simulation/proposals_test.go index 1168a0b892b8..6a1168afd593 100644 --- a/x/auth/simulation/proposals_test.go +++ b/x/auth/simulation/proposals_test.go @@ -9,6 +9,7 @@ import ( "cosmossdk.io/x/auth/simulation" "cosmossdk.io/x/auth/types" + codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/address" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -32,7 +33,8 @@ func TestProposalMsgs(t *testing.T) { assert.Equal(t, simulation.OpWeightMsgUpdateParams, w0.AppParamsKey()) assert.Equal(t, simulation.DefaultWeightMsgUpdateParams, w0.DefaultWeight()) - msg := w0.MsgSimulatorFn()(r, ctx, accounts) + msg, err := w0.MsgSimulatorFn()(r, ctx, accounts, codectestutil.CodecOptions{}.GetAddressCodec()) + assert.NilError(t, err) msgUpdateParams, ok := msg.(*types.MsgUpdateParams) assert.Assert(t, ok) diff --git a/x/authz/client/cli/tx.go b/x/authz/client/cli/tx.go index e666d4bcbfb3..6227785b067a 100644 --- a/x/authz/client/cli/tx.go +++ b/x/authz/client/cli/tx.go @@ -211,11 +211,11 @@ Examples: switch args[1] { case delegate: - authorization, err = staking.NewStakeAuthorization(allowed, denied, staking.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, delegateLimit) + authorization, err = staking.NewStakeAuthorization(allowed, denied, staking.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, delegateLimit, clientCtx.ValidatorAddressCodec) case unbond: - authorization, err = staking.NewStakeAuthorization(allowed, denied, staking.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE, delegateLimit) + authorization, err = staking.NewStakeAuthorization(allowed, denied, staking.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE, delegateLimit, clientCtx.ValidatorAddressCodec) default: - authorization, err = staking.NewStakeAuthorization(allowed, denied, staking.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE, delegateLimit) + authorization, err = staking.NewStakeAuthorization(allowed, denied, staking.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE, delegateLimit, clientCtx.ValidatorAddressCodec) } if err != nil { return err diff --git a/x/authz/msgs_test.go b/x/authz/msgs_test.go index c05601502921..bd0a230be281 100644 --- a/x/authz/msgs_test.go +++ b/x/authz/msgs_test.go @@ -20,6 +20,7 @@ import ( "cosmossdk.io/x/tx/signing/aminojson" "github.com/cosmos/cosmos-sdk/codec" + codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -54,7 +55,7 @@ func TestAminoJSON(t *testing.T) { banktypes.RegisterLegacyAminoCodec(legacyAmino) stakingtypes.RegisterLegacyAminoCodec(legacyAmino) legacytx.RegressionTestingAminoCodec = legacyAmino - + valAddressCodec := codectestutil.CodecOptions{}.GetValidatorCodec() aminoHandler := aminojson.NewSignModeHandler(aminojson.SignModeHandlerOptions{ FileResolver: proto.HybridResolver, }) @@ -73,7 +74,7 @@ func TestAminoJSON(t *testing.T) { require.NoError(t, err) valAddr, err := sdk.ValAddressFromBech32("cosmosvaloper1xcy3els9ua75kdm783c3qu0rfa2eples6eavqq") require.NoError(t, err) - stakingAuth, err := stakingtypes.NewStakeAuthorization([]sdk.ValAddress{valAddr}, nil, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, &sdk.Coin{Denom: "stake", Amount: sdkmath.NewInt(1000)}) + stakingAuth, err := stakingtypes.NewStakeAuthorization([]sdk.ValAddress{valAddr}, nil, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, &sdk.Coin{Denom: "stake", Amount: sdkmath.NewInt(1000)}, valAddressCodec) require.NoError(t, err) delegateGrant, err := authz.NewGrant(blockTime, stakingAuth, nil) require.NoError(t, err) diff --git a/x/authz/simulation/genesis_test.go b/x/authz/simulation/genesis_test.go index 6578c21644f3..4237084127c2 100644 --- a/x/authz/simulation/genesis_test.go +++ b/x/authz/simulation/genesis_test.go @@ -27,13 +27,15 @@ func TestRandomizedGenState(t *testing.T) { r := rand.New(s) simState := module.SimulationState{ - AppParams: make(simtypes.AppParams), - Cdc: encCfg.Codec, - Rand: r, - NumBonded: 3, - Accounts: simtypes.RandomAccounts(r, 3), - InitialStake: sdkmath.NewInt(1000), - GenState: make(map[string]json.RawMessage), + AppParams: make(simtypes.AppParams), + Cdc: encCfg.Codec, + AddressCodec: encCfg.TxConfig.SigningContext().AddressCodec(), + ValidatorCodec: encCfg.TxConfig.SigningContext().ValidatorAddressCodec(), + Rand: r, + NumBonded: 3, + Accounts: simtypes.RandomAccounts(r, 3), + InitialStake: sdkmath.NewInt(1000), + GenState: make(map[string]json.RawMessage), } simulation.RandomizedGenState(&simState) diff --git a/x/bank/simulation/genesis_test.go b/x/bank/simulation/genesis_test.go index b293fc0609fc..19556a2b7665 100644 --- a/x/bank/simulation/genesis_test.go +++ b/x/bank/simulation/genesis_test.go @@ -13,6 +13,7 @@ import ( "cosmossdk.io/x/bank/types" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/testutil" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -24,18 +25,21 @@ import ( func TestRandomizedGenState(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) + cdcOpts := testutil.CodecOptions{} s := rand.NewSource(1) r := rand.New(s) simState := module.SimulationState{ - AppParams: make(simtypes.AppParams), - Cdc: cdc, - Rand: r, - NumBonded: 3, - BondDenom: sdk.DefaultBondDenom, - Accounts: simtypes.RandomAccounts(r, 3), - InitialStake: sdkmath.NewInt(1000), - GenState: make(map[string]json.RawMessage), + AppParams: make(simtypes.AppParams), + Cdc: cdc, + AddressCodec: cdcOpts.GetAddressCodec(), + ValidatorCodec: cdcOpts.GetValidatorCodec(), + Rand: r, + NumBonded: 3, + BondDenom: sdk.DefaultBondDenom, + Accounts: simtypes.RandomAccounts(r, 3), + InitialStake: sdkmath.NewInt(1000), + GenState: make(map[string]json.RawMessage), } simulation.RandomizedGenState(&simState) diff --git a/x/bank/simulation/proposals.go b/x/bank/simulation/proposals.go index 475c83604a38..18340ded35af 100644 --- a/x/bank/simulation/proposals.go +++ b/x/bank/simulation/proposals.go @@ -3,6 +3,7 @@ package simulation import ( "math/rand" + coreaddress "cosmossdk.io/core/address" "cosmossdk.io/x/bank/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -30,7 +31,7 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { } // SimulateMsgUpdateParams returns a random MsgUpdateParams -func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) sdk.Msg { +func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, _ coreaddress.Codec) (sdk.Msg, error) { // use the default gov module account address as authority var authority sdk.AccAddress = address.Module("gov") @@ -40,5 +41,5 @@ func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) return &types.MsgUpdateParams{ Authority: authority.String(), Params: params, - } + }, nil } diff --git a/x/bank/simulation/proposals_test.go b/x/bank/simulation/proposals_test.go index 089f237709b4..479d55488e48 100644 --- a/x/bank/simulation/proposals_test.go +++ b/x/bank/simulation/proposals_test.go @@ -9,6 +9,7 @@ import ( "cosmossdk.io/x/bank/simulation" "cosmossdk.io/x/bank/types" + codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/address" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -32,7 +33,8 @@ func TestProposalMsgs(t *testing.T) { assert.Equal(t, simulation.OpWeightMsgUpdateParams, w0.AppParamsKey()) assert.Equal(t, simulation.DefaultWeightMsgUpdateParams, w0.DefaultWeight()) - msg := w0.MsgSimulatorFn()(r, ctx, accounts) + msg, err := w0.MsgSimulatorFn()(r, ctx, accounts, codectestutil.CodecOptions{}.GetAddressCodec()) + assert.NilError(t, err) msgUpdateParams, ok := msg.(*types.MsgUpdateParams) assert.Assert(t, ok) diff --git a/x/distribution/simulation/genesis_test.go b/x/distribution/simulation/genesis_test.go index e64b3fe021ec..0448d66909a7 100644 --- a/x/distribution/simulation/genesis_test.go +++ b/x/distribution/simulation/genesis_test.go @@ -12,6 +12,7 @@ import ( "cosmossdk.io/x/distribution/types" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/testutil" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -22,17 +23,20 @@ import ( func TestRandomizedGenState(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) + cdcOpts := testutil.CodecOptions{} s := rand.NewSource(1) r := rand.New(s) simState := module.SimulationState{ - AppParams: make(simtypes.AppParams), - Cdc: cdc, - Rand: r, - NumBonded: 3, - Accounts: simtypes.RandomAccounts(r, 3), - InitialStake: sdkmath.NewInt(1000), - GenState: make(map[string]json.RawMessage), + AppParams: make(simtypes.AppParams), + Cdc: cdc, + AddressCodec: cdcOpts.GetAddressCodec(), + ValidatorCodec: cdcOpts.GetValidatorCodec(), + Rand: r, + NumBonded: 3, + Accounts: simtypes.RandomAccounts(r, 3), + InitialStake: sdkmath.NewInt(1000), + GenState: make(map[string]json.RawMessage), } simulation.RandomizedGenState(&simState) diff --git a/x/distribution/simulation/proposals.go b/x/distribution/simulation/proposals.go index 0fa3ccc6f250..fadbf3bb93ef 100644 --- a/x/distribution/simulation/proposals.go +++ b/x/distribution/simulation/proposals.go @@ -3,6 +3,7 @@ package simulation import ( "math/rand" + coreaddress "cosmossdk.io/core/address" sdkmath "cosmossdk.io/math" "cosmossdk.io/x/distribution/types" @@ -31,7 +32,7 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { } // SimulateMsgUpdateParams returns a random MsgUpdateParams -func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) sdk.Msg { +func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, _ coreaddress.Codec) (sdk.Msg, error) { // use the default gov module account address as authority var authority sdk.AccAddress = address.Module("gov") @@ -42,5 +43,5 @@ func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) return &types.MsgUpdateParams{ Authority: authority.String(), Params: params, - } + }, nil } diff --git a/x/distribution/simulation/proposals_test.go b/x/distribution/simulation/proposals_test.go index 1d3d6d059c97..cd9a4b81b35a 100644 --- a/x/distribution/simulation/proposals_test.go +++ b/x/distribution/simulation/proposals_test.go @@ -10,6 +10,7 @@ import ( "cosmossdk.io/x/distribution/simulation" "cosmossdk.io/x/distribution/types" + codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/address" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -33,7 +34,8 @@ func TestProposalMsgs(t *testing.T) { assert.Equal(t, simulation.OpWeightMsgUpdateParams, w0.AppParamsKey()) assert.Equal(t, simulation.DefaultWeightMsgUpdateParams, w0.DefaultWeight()) - msg := w0.MsgSimulatorFn()(r, ctx, accounts) + msg, err := w0.MsgSimulatorFn()(r, ctx, accounts, codectestutil.CodecOptions{}.GetAddressCodec()) + assert.NilError(t, err) msgUpdateParams, ok := msg.(*types.MsgUpdateParams) assert.Assert(t, ok) diff --git a/x/evidence/simulation/genesis_test.go b/x/evidence/simulation/genesis_test.go index 5d7851ea002d..d44fb7afdb63 100644 --- a/x/evidence/simulation/genesis_test.go +++ b/x/evidence/simulation/genesis_test.go @@ -12,6 +12,7 @@ import ( "cosmossdk.io/x/evidence/types" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/testutil" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -22,18 +23,20 @@ import ( func TestRandomizedGenState(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) - + cdcOpts := testutil.CodecOptions{} s := rand.NewSource(1) r := rand.New(s) simState := module.SimulationState{ - AppParams: make(simtypes.AppParams), - Cdc: cdc, - Rand: r, - NumBonded: 3, - Accounts: simtypes.RandomAccounts(r, 3), - InitialStake: math.NewInt(1000), - GenState: make(map[string]json.RawMessage), + AppParams: make(simtypes.AppParams), + Cdc: cdc, + AddressCodec: cdcOpts.GetAddressCodec(), + ValidatorCodec: cdcOpts.GetValidatorCodec(), + Rand: r, + NumBonded: 3, + Accounts: simtypes.RandomAccounts(r, 3), + InitialStake: math.NewInt(1000), + GenState: make(map[string]json.RawMessage), } simulation.RandomizedGenState(&simState) diff --git a/x/feegrant/simulation/genesis_test.go b/x/feegrant/simulation/genesis_test.go index 7bdd29c2e38f..8dacce757d30 100644 --- a/x/feegrant/simulation/genesis_test.go +++ b/x/feegrant/simulation/genesis_test.go @@ -22,17 +22,19 @@ func TestRandomizedGenState(t *testing.T) { encCfg := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}, module.AppModule{}) s := rand.NewSource(1) r := rand.New(s) - + cdcOpts := codectestutil.CodecOptions{} accounts := simtypes.RandomAccounts(r, 3) simState := moduletypes.SimulationState{ - AppParams: make(simtypes.AppParams), - Cdc: encCfg.Codec, - Rand: r, - NumBonded: 3, - Accounts: accounts, - InitialStake: math.NewInt(1000), - GenState: make(map[string]json.RawMessage), + AppParams: make(simtypes.AppParams), + Cdc: encCfg.Codec, + AddressCodec: cdcOpts.GetAddressCodec(), + ValidatorCodec: cdcOpts.GetValidatorCodec(), + Rand: r, + NumBonded: 3, + Accounts: accounts, + InitialStake: math.NewInt(1000), + GenState: make(map[string]json.RawMessage), } simulation.RandomizedGenState(&simState) diff --git a/x/gov/simulation/genesis_test.go b/x/gov/simulation/genesis_test.go index 702350a40978..ce0a2c45acfb 100644 --- a/x/gov/simulation/genesis_test.go +++ b/x/gov/simulation/genesis_test.go @@ -13,6 +13,7 @@ import ( v1 "cosmossdk.io/x/gov/types/v1" "github.com/cosmos/cosmos-sdk/codec" + codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" @@ -24,19 +25,22 @@ import ( func TestRandomizedGenState(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) + cdcOpts := codectestutil.CodecOptions{} s := rand.NewSource(1) r := rand.New(s) simState := module.SimulationState{ - AppParams: make(simtypes.AppParams), - Cdc: cdc, - Rand: r, - NumBonded: 3, - BondDenom: sdk.DefaultBondDenom, - Accounts: simtypes.RandomAccounts(r, 3), - InitialStake: sdkmath.NewInt(1000), - GenState: make(map[string]json.RawMessage), + AppParams: make(simtypes.AppParams), + Cdc: cdc, + AddressCodec: cdcOpts.GetAddressCodec(), + ValidatorCodec: cdcOpts.GetValidatorCodec(), + Rand: r, + NumBonded: 3, + BondDenom: sdk.DefaultBondDenom, + Accounts: simtypes.RandomAccounts(r, 3), + InitialStake: sdkmath.NewInt(1000), + GenState: make(map[string]json.RawMessage), } simulation.RandomizedGenState(&simState) diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 26969d3365d3..352ce952021c 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -155,7 +155,10 @@ func SimulateMsgSubmitProposal( return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { msgs := []sdk.Msg{} - proposalMsg := msgSim(r, ctx, accs) + proposalMsg, err := msgSim(r, ctx, accs, ak.AddressCodec()) + if err != nil { + return simtypes.OperationMsg{}, nil, err + } if proposalMsg != nil { msgs = append(msgs, proposalMsg) } diff --git a/x/gov/simulation/proposals.go b/x/gov/simulation/proposals.go index 3a5a3050fccd..91b5d67e7b85 100644 --- a/x/gov/simulation/proposals.go +++ b/x/gov/simulation/proposals.go @@ -3,6 +3,7 @@ package simulation import ( "math/rand" + coreaddress "cosmossdk.io/core/address" "cosmossdk.io/x/gov/types/v1beta1" sdk "github.com/cosmos/cosmos-sdk/types" @@ -26,8 +27,8 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { // SimulateTextProposal returns a random text proposal content. // A text proposal is a proposal that contains no msgs. -func SimulateTextProposal(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) sdk.Msg { - return nil +func SimulateTextProposal(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, _ coreaddress.Codec) (sdk.Msg, error) { + return nil, nil } // ProposalContents defines the module weighted proposals' contents diff --git a/x/gov/simulation/proposals_test.go b/x/gov/simulation/proposals_test.go index e8f4a7879603..42ef52a7db9d 100644 --- a/x/gov/simulation/proposals_test.go +++ b/x/gov/simulation/proposals_test.go @@ -8,6 +8,7 @@ import ( "cosmossdk.io/x/gov/simulation" + codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" sdk "github.com/cosmos/cosmos-sdk/types" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" ) @@ -30,7 +31,8 @@ func TestProposalMsgs(t *testing.T) { assert.Equal(t, simulation.OpWeightSubmitTextProposal, w0.AppParamsKey()) assert.Equal(t, simulation.DefaultWeightTextProposal, w0.DefaultWeight()) - msg := w0.MsgSimulatorFn()(r, ctx, accounts) + msg, err := w0.MsgSimulatorFn()(r, ctx, accounts, codectestutil.CodecOptions{}.GetAddressCodec()) + assert.NilError(t, err) assert.Assert(t, msg == nil) } diff --git a/x/group/simulation/genesis_test.go b/x/group/simulation/genesis_test.go index 9d129fca7af7..ccdf37efff01 100644 --- a/x/group/simulation/genesis_test.go +++ b/x/group/simulation/genesis_test.go @@ -22,18 +22,21 @@ import ( func TestRandomizedGenState(t *testing.T) { encodingConfig := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}, groupmodule.AppModule{}, bank.AppModule{}) cdc := encodingConfig.Codec + cdcOpts := codectestutil.CodecOptions{} s := rand.NewSource(1) r := rand.New(s) simState := module.SimulationState{ - AppParams: make(simtypes.AppParams), - Cdc: cdc, - Rand: r, - NumBonded: 3, - Accounts: simtypes.RandomAccounts(r, 3), - InitialStake: sdkmath.NewInt(1000), - GenState: make(map[string]json.RawMessage), + AppParams: make(simtypes.AppParams), + Cdc: cdc, + AddressCodec: cdcOpts.GetAddressCodec(), + ValidatorCodec: cdcOpts.GetValidatorCodec(), + Rand: r, + NumBonded: 3, + Accounts: simtypes.RandomAccounts(r, 3), + InitialStake: sdkmath.NewInt(1000), + GenState: make(map[string]json.RawMessage), } simulation.RandomizedGenState(&simState) diff --git a/x/mint/simulation/genesis_test.go b/x/mint/simulation/genesis_test.go index 8a3858e3d293..784f910e326c 100644 --- a/x/mint/simulation/genesis_test.go +++ b/x/mint/simulation/genesis_test.go @@ -22,20 +22,23 @@ import ( // TestRandomizedGenState tests the normal scenario of applying RandomizedGenState. // Abonormal scenarios are not tested here. func TestRandomizedGenState(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}, mint.AppModule{}) + cdcOpts := codectestutil.CodecOptions{} + encCfg := moduletestutil.MakeTestEncodingConfig(cdcOpts, mint.AppModule{}) s := rand.NewSource(1) r := rand.New(s) simState := module.SimulationState{ - AppParams: make(simtypes.AppParams), - Cdc: encCfg.Codec, - Rand: r, - NumBonded: 3, - BondDenom: sdk.DefaultBondDenom, - Accounts: simtypes.RandomAccounts(r, 3), - InitialStake: math.NewInt(1000), - GenState: make(map[string]json.RawMessage), + AppParams: make(simtypes.AppParams), + Cdc: encCfg.Codec, + AddressCodec: cdcOpts.GetAddressCodec(), + ValidatorCodec: cdcOpts.GetValidatorCodec(), + Rand: r, + NumBonded: 3, + BondDenom: sdk.DefaultBondDenom, + Accounts: simtypes.RandomAccounts(r, 3), + InitialStake: math.NewInt(1000), + GenState: make(map[string]json.RawMessage), } simulation.RandomizedGenState(&simState) diff --git a/x/mint/simulation/proposals.go b/x/mint/simulation/proposals.go index 594413d94886..9ba75b4a6615 100644 --- a/x/mint/simulation/proposals.go +++ b/x/mint/simulation/proposals.go @@ -3,6 +3,7 @@ package simulation import ( "math/rand" + coreaddress "cosmossdk.io/core/address" sdkmath "cosmossdk.io/math" "cosmossdk.io/x/mint/types" @@ -31,7 +32,7 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { } // SimulateMsgUpdateParams returns a random MsgUpdateParams -func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) sdk.Msg { +func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, _ coreaddress.Codec) (sdk.Msg, error) { // use the default gov module account address as authority var authority sdk.AccAddress = address.Module("gov") @@ -46,5 +47,5 @@ func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) return &types.MsgUpdateParams{ Authority: authority.String(), Params: params, - } + }, nil } diff --git a/x/mint/simulation/proposals_test.go b/x/mint/simulation/proposals_test.go index d9d313f5d4fc..42d604b3e005 100644 --- a/x/mint/simulation/proposals_test.go +++ b/x/mint/simulation/proposals_test.go @@ -10,6 +10,7 @@ import ( "cosmossdk.io/x/mint/simulation" "cosmossdk.io/x/mint/types" + codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/address" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -33,7 +34,8 @@ func TestProposalMsgs(t *testing.T) { assert.Equal(t, simulation.OpWeightMsgUpdateParams, w0.AppParamsKey()) assert.Equal(t, simulation.DefaultWeightMsgUpdateParams, w0.DefaultWeight()) - msg := w0.MsgSimulatorFn()(r, ctx, accounts) + msg, err := w0.MsgSimulatorFn()(r, ctx, accounts, codectestutil.CodecOptions{}.GetAddressCodec()) + assert.NilError(t, err) msgUpdateParams, ok := msg.(*types.MsgUpdateParams) assert.Assert(t, ok) diff --git a/x/nft/simulation/genesis_test.go b/x/nft/simulation/genesis_test.go index 3aa6928943c0..bf93143a3b23 100644 --- a/x/nft/simulation/genesis_test.go +++ b/x/nft/simulation/genesis_test.go @@ -20,19 +20,22 @@ import ( ) func TestRandomizedGenState(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}, nftmodule.AppModule{}) + cdcOpts := codectestutil.CodecOptions{} + encCfg := moduletestutil.MakeTestEncodingConfig(cdcOpts, nftmodule.AppModule{}) s := rand.NewSource(1) r := rand.New(s) simState := module.SimulationState{ - AppParams: make(simtypes.AppParams), - Cdc: encCfg.Codec, - Rand: r, - NumBonded: 3, - Accounts: simtypes.RandomAccounts(r, 3), - InitialStake: sdkmath.NewInt(1000), - GenState: make(map[string]json.RawMessage), + AppParams: make(simtypes.AppParams), + Cdc: encCfg.Codec, + AddressCodec: cdcOpts.GetAddressCodec(), + ValidatorCodec: cdcOpts.GetValidatorCodec(), + Rand: r, + NumBonded: 3, + Accounts: simtypes.RandomAccounts(r, 3), + InitialStake: sdkmath.NewInt(1000), + GenState: make(map[string]json.RawMessage), } simulation.RandomizedGenState(&simState, addresscodec.NewBech32Codec("cosmos")) diff --git a/x/protocolpool/simulation/proposals.go b/x/protocolpool/simulation/proposals.go index bfeac7e0f382..224a9f8fb535 100644 --- a/x/protocolpool/simulation/proposals.go +++ b/x/protocolpool/simulation/proposals.go @@ -3,6 +3,7 @@ package simulation import ( "math/rand" + coreaddress "cosmossdk.io/core/address" pooltypes "cosmossdk.io/x/protocolpool/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -27,7 +28,7 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { } } -func SimulateMsgCommunityPoolSpend(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) sdk.Msg { +func SimulateMsgCommunityPoolSpend(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, _ coreaddress.Codec) (sdk.Msg, error) { // use the default gov module account address as authority var authority sdk.AccAddress = address.Module("gov") @@ -43,5 +44,5 @@ func SimulateMsgCommunityPoolSpend(r *rand.Rand, _ sdk.Context, _ []simtypes.Acc Authority: authority.String(), Recipient: acc.Address.String(), Amount: coins, - } + }, nil } diff --git a/x/protocolpool/simulation/proposals_test.go b/x/protocolpool/simulation/proposals_test.go index ac7361e2d903..4cef1da31bdc 100644 --- a/x/protocolpool/simulation/proposals_test.go +++ b/x/protocolpool/simulation/proposals_test.go @@ -9,6 +9,7 @@ import ( "cosmossdk.io/x/protocolpool/simulation" pooltypes "cosmossdk.io/x/protocolpool/types" + codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/address" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -32,7 +33,8 @@ func TestProposalMsgs(t *testing.T) { assert.Equal(t, simulation.OpWeightMsgCommunityPoolSpend, w0.AppParamsKey()) assert.Equal(t, simulation.DefaultWeightMsgCommunityPoolSpend, w0.DefaultWeight()) - msg := w0.MsgSimulatorFn()(r, ctx, accounts) + msg, err := w0.MsgSimulatorFn()(r, ctx, accounts, codectestutil.CodecOptions{}.GetAddressCodec()) + assert.NilError(t, err) msgCommunityPoolSpend, ok := msg.(*pooltypes.MsgCommunityPoolSpend) assert.Assert(t, ok) diff --git a/x/slashing/simulation/genesis_test.go b/x/slashing/simulation/genesis_test.go index 55de836d4552..b1bed6f6f803 100644 --- a/x/slashing/simulation/genesis_test.go +++ b/x/slashing/simulation/genesis_test.go @@ -13,6 +13,7 @@ import ( "cosmossdk.io/x/slashing/types" "github.com/cosmos/cosmos-sdk/codec" + codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -23,18 +24,21 @@ import ( func TestRandomizedGenState(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) + cdcOpts := codectestutil.CodecOptions{} s := rand.NewSource(1) r := rand.New(s) simState := module.SimulationState{ - AppParams: make(simtypes.AppParams), - Cdc: cdc, - Rand: r, - NumBonded: 3, - Accounts: simtypes.RandomAccounts(r, 3), - InitialStake: sdkmath.NewInt(1000), - GenState: make(map[string]json.RawMessage), + AppParams: make(simtypes.AppParams), + Cdc: cdc, + AddressCodec: cdcOpts.GetAddressCodec(), + ValidatorCodec: cdcOpts.GetValidatorCodec(), + Rand: r, + NumBonded: 3, + Accounts: simtypes.RandomAccounts(r, 3), + InitialStake: sdkmath.NewInt(1000), + GenState: make(map[string]json.RawMessage), } simulation.RandomizedGenState(&simState) diff --git a/x/slashing/simulation/proposals.go b/x/slashing/simulation/proposals.go index 7cad19e47d70..1a6e60f012ea 100644 --- a/x/slashing/simulation/proposals.go +++ b/x/slashing/simulation/proposals.go @@ -4,6 +4,7 @@ import ( "math/rand" "time" + coreaddress "cosmossdk.io/core/address" sdkmath "cosmossdk.io/math" "cosmossdk.io/x/slashing/types" @@ -32,7 +33,7 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { } // SimulateMsgUpdateParams returns a random MsgUpdateParams -func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) sdk.Msg { +func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, _ coreaddress.Codec) (sdk.Msg, error) { // use the default gov module account address as authority var authority sdk.AccAddress = address.Module("gov") @@ -46,5 +47,5 @@ func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) return &types.MsgUpdateParams{ Authority: authority.String(), Params: params, - } + }, nil } diff --git a/x/slashing/simulation/proposals_test.go b/x/slashing/simulation/proposals_test.go index 4ac72eb63717..eb63a817ac6d 100644 --- a/x/slashing/simulation/proposals_test.go +++ b/x/slashing/simulation/proposals_test.go @@ -11,6 +11,7 @@ import ( "cosmossdk.io/x/slashing/simulation" "cosmossdk.io/x/slashing/types" + codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/address" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -34,7 +35,8 @@ func TestProposalMsgs(t *testing.T) { assert.Equal(t, simulation.OpWeightMsgUpdateParams, w0.AppParamsKey()) assert.Equal(t, simulation.DefaultWeightMsgUpdateParams, w0.DefaultWeight()) - msg := w0.MsgSimulatorFn()(r, ctx, accounts) + msg, err := w0.MsgSimulatorFn()(r, ctx, accounts, codectestutil.CodecOptions{}.GetAddressCodec()) + assert.NilError(t, err) msgUpdateParams, ok := msg.(*types.MsgUpdateParams) assert.Assert(t, ok) diff --git a/x/staking/CHANGELOG.md b/x/staking/CHANGELOG.md index 1cf49509062e..a9280795ded6 100644 --- a/x/staking/CHANGELOG.md +++ b/x/staking/CHANGELOG.md @@ -41,6 +41,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### API Breaking Changes +* [#19742](https://github.com/cosmos/cosmos-sdk/pull/19742) `NewStakeAuthorization` now takes `address.Codec` as argument. * [#19735](https://github.com/cosmos/cosmos-sdk/pull/19735) Update genesis api to match new `appmodule.HasGenesis` interface. * [#18198](https://github.com/cosmos/cosmos-sdk/pull/18198) `Validator` and `Delegator` interfaces were moved to `github.com/cosmos/cosmos-sdk/types` to avoid interface dependency on staking in other modules. * [#17778](https://github.com/cosmos/cosmos-sdk/pull/17778) Use collections for `Params` diff --git a/x/staking/keeper/alias_functions.go b/x/staking/keeper/alias_functions.go index 9aa826982a6c..b4633943c7b4 100644 --- a/x/staking/keeper/alias_functions.go +++ b/x/staking/keeper/alias_functions.go @@ -59,7 +59,11 @@ func (k Keeper) IterateBondedValidatorsByPower(ctx context.Context, fn func(inde address := iterator.Value() validator, err := k.GetValidator(ctx, address) if err != nil { - return fmt.Errorf("validator record not found for address: %s", sdk.ValAddress(address).String()) + addr, err := k.validatorAddressCodec.BytesToString(address) + if err != nil { + return fmt.Errorf("validator record not found for address: %s", address) + } + return fmt.Errorf("validator record not found for address: %s", addr) } if validator.IsBonded() { stop := fn(i, validator) // XXX is this safe will the validator unexposed fields be able to get written to? diff --git a/x/staking/keeper/cons_pubkey_test.go b/x/staking/keeper/cons_pubkey_test.go index 1431a06ff3b2..6404f3edccae 100644 --- a/x/staking/keeper/cons_pubkey_test.go +++ b/x/staking/keeper/cons_pubkey_test.go @@ -29,10 +29,11 @@ func (s *KeeperTestSuite) TestConsPubKeyRotationHistory() { s.bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), types.NotBondedPoolName, types.BondedPoolName, gomock.Any()) _ = stakingkeeper.TestingUpdateValidator(stakingKeeper, ctx, val, true) - val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) - selfDelegation := types.NewDelegation(val0AccAddr.String(), addrVals[0].String(), issuedShares) + val0AccAddr, err := s.accountKeeper.AddressCodec().BytesToString(addrVals[0]) + s.Require().NoError(err) + selfDelegation := types.NewDelegation(val0AccAddr, s.valAddressToString(addrVals[0]), issuedShares) - err := stakingKeeper.SetDelegation(ctx, selfDelegation) + err = stakingKeeper.SetDelegation(ctx, selfDelegation) s.Require().NoError(err) validators, err := stakingKeeper.GetAllValidators(ctx) @@ -40,7 +41,7 @@ func (s *KeeperTestSuite) TestConsPubKeyRotationHistory() { s.Require().Len(validators, 1) validator := validators[0] - valAddr, err := sdk.ValAddressFromBech32(validator.OperatorAddress) + valAddr, err := s.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator.OperatorAddress) s.Require().NoError(err) historyObjects, err := stakingKeeper.GetValidatorConsPubKeyRotationHistory(ctx, valAddr) @@ -57,7 +58,7 @@ func (s *KeeperTestSuite) TestConsPubKeyRotationHistory() { s.Require().NoError(err) height := uint64(ctx.BlockHeight()) - err = stakingKeeper.RotationHistory.Set(ctx, collections.Join(valAddr.Bytes(), height), types.ConsPubKeyRotationHistory{ + err = stakingKeeper.RotationHistory.Set(ctx, collections.Join(valAddr, height), types.ConsPubKeyRotationHistory{ OperatorAddress: valAddr, OldConsPubkey: validator.ConsensusPubkey, NewConsPubkey: newConsPub, @@ -74,7 +75,7 @@ func (s *KeeperTestSuite) TestConsPubKeyRotationHistory() { s.Require().NoError(err) s.Require().Len(historyObjects, 1) - err = stakingKeeper.RotationHistory.Set(ctx, collections.Join(valAddr.Bytes(), height+1), types.ConsPubKeyRotationHistory{ + err = stakingKeeper.RotationHistory.Set(ctx, collections.Join(valAddr, height+1), types.ConsPubKeyRotationHistory{ OperatorAddress: valAddr, OldConsPubkey: newConsPub, NewConsPubkey: newConsPub2, @@ -157,6 +158,9 @@ func (s *KeeperTestSuite) setValidators(n int) { _, addrVals := createValAddrs(n) for i := 0; i < n; i++ { + addr, err := s.stakingKeeper.ValidatorAddressCodec().BytesToString(addrVals[i]) + s.Require().NoError(err) + val := testutil.NewValidator(s.T(), addrVals[i], PKs[i]) valTokens := stakingKeeper.TokensFromConsensusPower(ctx, 10) val, issuedShares := val.AddTokensFromDel(valTokens) @@ -164,9 +168,10 @@ func (s *KeeperTestSuite) setValidators(n int) { s.bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), types.NotBondedPoolName, types.BondedPoolName, gomock.Any()) _ = stakingkeeper.TestingUpdateValidator(stakingKeeper, ctx, val, true) - val0AccAddr := sdk.AccAddress(addrVals[i].Bytes()) - selfDelegation := types.NewDelegation(val0AccAddr.String(), addrVals[i].String(), issuedShares) - err := stakingKeeper.SetDelegation(ctx, selfDelegation) + accAddr, err := s.accountKeeper.AddressCodec().BytesToString(addrVals[i]) + s.Require().NoError(err) + selfDelegation := types.NewDelegation(accAddr, addr, issuedShares) + err = stakingKeeper.SetDelegation(ctx, selfDelegation) s.Require().NoError(err) err = stakingKeeper.SetValidatorByConsAddr(ctx, val) diff --git a/x/staking/keeper/delegation_test.go b/x/staking/keeper/delegation_test.go index 883073748965..0768485815b4 100644 --- a/x/staking/keeper/delegation_test.go +++ b/x/staking/keeper/delegation_test.go @@ -44,7 +44,7 @@ func (s *KeeperTestSuite) TestDelegation() { } // first add a validators[0] to delegate too - bond1to1 := stakingtypes.NewDelegation(addrDels[0].String(), valAddrs[0].String(), math.LegacyNewDec(9)) + bond1to1 := stakingtypes.NewDelegation(s.addressToString(addrDels[0]), s.valAddressToString(valAddrs[0]), math.LegacyNewDec(9)) // check the empty keeper first _, err := keeper.Delegations.Get(ctx, collections.Join(addrDels[0], valAddrs[0])) @@ -64,11 +64,11 @@ func (s *KeeperTestSuite) TestDelegation() { require.Equal(bond1to1, resBond) // add some more records - bond1to2 := stakingtypes.NewDelegation(addrDels[0].String(), valAddrs[1].String(), math.LegacyNewDec(9)) - bond1to3 := stakingtypes.NewDelegation(addrDels[0].String(), valAddrs[2].String(), math.LegacyNewDec(9)) - bond2to1 := stakingtypes.NewDelegation(addrDels[1].String(), valAddrs[0].String(), math.LegacyNewDec(9)) - bond2to2 := stakingtypes.NewDelegation(addrDels[1].String(), valAddrs[1].String(), math.LegacyNewDec(9)) - bond2to3 := stakingtypes.NewDelegation(addrDels[1].String(), valAddrs[2].String(), math.LegacyNewDec(9)) + bond1to2 := stakingtypes.NewDelegation(s.addressToString(addrDels[0]), s.valAddressToString(valAddrs[1]), math.LegacyNewDec(9)) + bond1to3 := stakingtypes.NewDelegation(s.addressToString(addrDels[0]), s.valAddressToString(valAddrs[2]), math.LegacyNewDec(9)) + bond2to1 := stakingtypes.NewDelegation(s.addressToString(addrDels[1]), s.valAddressToString(valAddrs[0]), math.LegacyNewDec(9)) + bond2to2 := stakingtypes.NewDelegation(s.addressToString(addrDels[1]), s.valAddressToString(valAddrs[1]), math.LegacyNewDec(9)) + bond2to3 := stakingtypes.NewDelegation(s.addressToString(addrDels[1]), s.valAddressToString(valAddrs[2]), math.LegacyNewDec(9)) require.NoError(keeper.SetDelegation(ctx, bond1to2)) require.NoError(keeper.SetDelegation(ctx, bond1to3)) require.NoError(keeper.SetDelegation(ctx, bond2to1)) @@ -114,11 +114,11 @@ func (s *KeeperTestSuite) TestDelegation() { for i := 0; i < 3; i++ { resVal, err := keeper.GetDelegatorValidator(ctx, addrDels[0], valAddrs[i]) require.Nil(err) - require.Equal(valAddrs[i].String(), resVal.GetOperator()) + require.Equal(s.valAddressToString(valAddrs[i]), resVal.GetOperator()) resVal, err = keeper.GetDelegatorValidator(ctx, addrDels[1], valAddrs[i]) require.Nil(err) - require.Equal(valAddrs[i].String(), resVal.GetOperator()) + require.Equal(s.valAddressToString(valAddrs[i]), resVal.GetOperator()) resDels, err := keeper.GetValidatorDelegations(ctx, valAddrs[i]) require.NoError(err) @@ -181,7 +181,7 @@ func (s *KeeperTestSuite) TestDelegationsByValIndex() { // delegate 2 tokens // // total delegations after delegating: del1 -> 2stake - _, err := s.msgServer.Delegate(ctx, stakingtypes.NewMsgDelegate(addrDels[0].String(), valAddrs[0].String(), sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(2)))) + _, err := s.msgServer.Delegate(ctx, stakingtypes.NewMsgDelegate(s.addressToString(addrDels[0]), s.valAddressToString(valAddrs[0]), sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(2)))) require.NoError(err) dels, err := s.stakingKeeper.GetValidatorDelegations(ctx, valAddrs[0]) @@ -191,7 +191,7 @@ func (s *KeeperTestSuite) TestDelegationsByValIndex() { // delegate 4 tokens // // total delegations after delegating: del1 -> 2stake, del2 -> 4stake - _, err = s.msgServer.Delegate(ctx, stakingtypes.NewMsgDelegate(addrDels[1].String(), valAddrs[0].String(), sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(4)))) + _, err = s.msgServer.Delegate(ctx, stakingtypes.NewMsgDelegate(s.addressToString(addrDels[1]), s.valAddressToString(valAddrs[0]), sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(4)))) require.NoError(err) dels, err = s.stakingKeeper.GetValidatorDelegations(ctx, valAddrs[0]) @@ -201,7 +201,7 @@ func (s *KeeperTestSuite) TestDelegationsByValIndex() { // undelegate 1 token from del1 // // total delegations after undelegating: del1 -> 1stake, del2 -> 4stake - _, err = s.msgServer.Undelegate(ctx, stakingtypes.NewMsgUndelegate(addrDels[0].String(), valAddrs[0].String(), sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(1)))) + _, err = s.msgServer.Undelegate(ctx, stakingtypes.NewMsgUndelegate(s.addressToString(addrDels[0]), s.valAddressToString(valAddrs[0]), sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(1)))) require.NoError(err) dels, err = s.stakingKeeper.GetValidatorDelegations(ctx, valAddrs[0]) @@ -211,7 +211,7 @@ func (s *KeeperTestSuite) TestDelegationsByValIndex() { // undelegate 1 token from del1 // // total delegations after undelegating: del2 -> 4stake - _, err = s.msgServer.Undelegate(ctx, stakingtypes.NewMsgUndelegate(addrDels[0].String(), valAddrs[0].String(), sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(1)))) + _, err = s.msgServer.Undelegate(ctx, stakingtypes.NewMsgUndelegate(s.addressToString(addrDels[0]), s.valAddressToString(valAddrs[0]), sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(1)))) require.NoError(err) dels, err = s.stakingKeeper.GetValidatorDelegations(ctx, valAddrs[0]) @@ -221,7 +221,7 @@ func (s *KeeperTestSuite) TestDelegationsByValIndex() { // undelegate 2 tokens from del2 // // total delegations after undelegating: del2 -> 2stake - _, err = s.msgServer.Undelegate(ctx, stakingtypes.NewMsgUndelegate(addrDels[1].String(), valAddrs[0].String(), sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(2)))) + _, err = s.msgServer.Undelegate(ctx, stakingtypes.NewMsgUndelegate(s.addressToString(addrDels[1]), s.valAddressToString(valAddrs[0]), sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(2)))) require.NoError(err) dels, err = s.stakingKeeper.GetValidatorDelegations(ctx, valAddrs[0]) @@ -231,7 +231,7 @@ func (s *KeeperTestSuite) TestDelegationsByValIndex() { // undelegate 2 tokens from del2 // // total delegations after undelegating: [] - _, err = s.msgServer.Undelegate(ctx, stakingtypes.NewMsgUndelegate(addrDels[1].String(), valAddrs[0].String(), sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(2)))) + _, err = s.msgServer.Undelegate(ctx, stakingtypes.NewMsgUndelegate(s.addressToString(addrDels[1]), s.valAddressToString(valAddrs[0]), sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(2)))) require.NoError(err) dels, err = s.stakingKeeper.GetValidatorDelegations(ctx, valAddrs[0]) @@ -379,7 +379,7 @@ func (s *KeeperTestSuite) TestUnbondDelegation() { s.bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), stakingtypes.NotBondedPoolName, stakingtypes.BondedPoolName, gomock.Any()) _ = stakingkeeper.TestingUpdateValidator(keeper, ctx, validator, true) - delegation := stakingtypes.NewDelegation(delAddrs[0].String(), valAddrs[0].String(), issuedShares) + delegation := stakingtypes.NewDelegation(s.addressToString(delAddrs[0]), s.valAddressToString(valAddrs[0]), issuedShares) require.NoError(keeper.SetDelegation(ctx, delegation)) bondTokens := keeper.TokensFromConsensusPower(ctx, 6) @@ -404,11 +404,11 @@ func (s *KeeperTestSuite) TestUndelegateSelfDelegationBelowMinSelfDelegation() { ctx, keeper := s.ctx, s.stakingKeeper require := s.Require() - addrDels, addrVals := createValAddrs(1) + addrDels, valAddrs := createValAddrs(1) delTokens := keeper.TokensFromConsensusPower(ctx, 10) // create a validator with a self-delegation - validator := testutil.NewValidator(s.T(), addrVals[0], PKs[0]) + validator := testutil.NewValidator(s.T(), valAddrs[0], PKs[0]) validator.MinSelfDelegation = delTokens validator, issuedShares := validator.AddTokensFromDel(delTokens) @@ -419,7 +419,7 @@ func (s *KeeperTestSuite) TestUndelegateSelfDelegationBelowMinSelfDelegation() { require.NoError(keeper.SetValidatorByConsAddr(ctx, validator)) require.True(validator.IsBonded()) - selfDelegation := stakingtypes.NewDelegation(sdk.AccAddress(addrVals[0].Bytes()).String(), addrVals[0].String(), issuedShares) + selfDelegation := stakingtypes.NewDelegation(s.addressToString(valAddrs[0]), s.valAddressToString(valAddrs[0]), issuedShares) require.NoError(keeper.SetDelegation(ctx, selfDelegation)) // create a second delegation to this validator @@ -429,19 +429,19 @@ func (s *KeeperTestSuite) TestUndelegateSelfDelegationBelowMinSelfDelegation() { require.Equal(delTokens, issuedShares.RoundInt()) validator = stakingkeeper.TestingUpdateValidator(keeper, ctx, validator, true) - delegation := stakingtypes.NewDelegation(addrDels[0].String(), addrVals[0].String(), issuedShares) + delegation := stakingtypes.NewDelegation(s.addressToString(addrDels[0]), s.valAddressToString(valAddrs[0]), issuedShares) require.NoError(keeper.SetDelegation(ctx, delegation)) - val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) + val0AccAddr := sdk.AccAddress(valAddrs[0].Bytes()) s.bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, gomock.Any()) - _, _, err := keeper.Undelegate(ctx, val0AccAddr, addrVals[0], math.LegacyNewDecFromInt(keeper.TokensFromConsensusPower(ctx, 6))) + _, _, err := keeper.Undelegate(ctx, val0AccAddr, valAddrs[0], math.LegacyNewDecFromInt(keeper.TokensFromConsensusPower(ctx, 6))) require.NoError(err) // end block s.bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, gomock.Any()) s.applyValidatorSetUpdates(ctx, keeper, 1) - validator, err = keeper.GetValidator(ctx, addrVals[0]) + validator, err = keeper.GetValidator(ctx, valAddrs[0]) require.NoError(err) require.Equal(keeper.TokensFromConsensusPower(ctx, 14), validator.Tokens) require.Equal(stakingtypes.Unbonding, validator.Status) @@ -466,7 +466,7 @@ func (s *KeeperTestSuite) TestUndelegateFromUnbondingValidator() { validator = stakingkeeper.TestingUpdateValidator(keeper, ctx, validator, true) require.True(validator.IsBonded()) - selfDelegation := stakingtypes.NewDelegation(addrDels[0].String(), addrVals[0].String(), issuedShares) + selfDelegation := stakingtypes.NewDelegation(s.addressToString(addrDels[0]), s.valAddressToString(addrVals[0]), issuedShares) require.NoError(keeper.SetDelegation(ctx, selfDelegation)) // create a second delegation to this validator @@ -476,7 +476,7 @@ func (s *KeeperTestSuite) TestUndelegateFromUnbondingValidator() { require.Equal(delTokens, issuedShares.RoundInt()) stakingkeeper.TestingUpdateValidator(keeper, ctx, validator, true) - delegation := stakingtypes.NewDelegation(addrDels[1].String(), addrVals[0].String(), issuedShares) + delegation := stakingtypes.NewDelegation(s.addressToString(addrDels[1]), s.valAddressToString(addrVals[0]), issuedShares) require.NoError(keeper.SetDelegation(ctx, delegation)) header := ctx.HeaderInfo() @@ -547,7 +547,7 @@ func (s *KeeperTestSuite) TestUndelegateFromUnbondedValidator() { require.True(validator.IsBonded()) val0AccAddr := sdk.AccAddress(addrVals[0]) - selfDelegation := stakingtypes.NewDelegation(val0AccAddr.String(), addrVals[0].String(), issuedShares) + selfDelegation := stakingtypes.NewDelegation(s.addressToString(val0AccAddr), s.valAddressToString(addrVals[0]), issuedShares) require.NoError(keeper.SetDelegation(ctx, selfDelegation)) // create a second delegation to this validator @@ -556,7 +556,7 @@ func (s *KeeperTestSuite) TestUndelegateFromUnbondedValidator() { require.Equal(delTokens, issuedShares.RoundInt()) validator = stakingkeeper.TestingUpdateValidator(keeper, ctx, validator, true) require.True(validator.IsBonded()) - delegation := stakingtypes.NewDelegation(addrDels[1].String(), addrVals[0].String(), issuedShares) + delegation := stakingtypes.NewDelegation(s.addressToString(addrDels[1]), s.valAddressToString(addrVals[0]), issuedShares) require.NoError(keeper.SetDelegation(ctx, delegation)) ctx = ctx.WithBlockHeight(10) @@ -629,7 +629,7 @@ func (s *KeeperTestSuite) TestUnbondingAllDelegationFromValidator() { require.True(validator.IsBonded()) val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) - selfDelegation := stakingtypes.NewDelegation(val0AccAddr.String(), addrVals[0].String(), issuedShares) + selfDelegation := stakingtypes.NewDelegation(s.addressToString(val0AccAddr), s.valAddressToString(addrVals[0]), issuedShares) require.NoError(keeper.SetDelegation(ctx, selfDelegation)) // create a second delegation to this validator @@ -640,7 +640,7 @@ func (s *KeeperTestSuite) TestUnbondingAllDelegationFromValidator() { validator = stakingkeeper.TestingUpdateValidator(keeper, ctx, validator, true) require.True(validator.IsBonded()) - delegation := stakingtypes.NewDelegation(addrDels[1].String(), addrVals[0].String(), issuedShares) + delegation := stakingtypes.NewDelegation(s.addressToString(addrDels[1]), s.valAddressToString(addrVals[0]), issuedShares) require.NoError(keeper.SetDelegation(ctx, delegation)) ctx = ctx.WithHeaderInfo(coreheader.Info{Height: 10, Time: time.Unix(333, 0)}) @@ -799,7 +799,7 @@ func (s *KeeperTestSuite) TestRedelegateToSameValidator() { val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) - selfDelegation := stakingtypes.NewDelegation(val0AccAddr.String(), addrVals[0].String(), issuedShares) + selfDelegation := stakingtypes.NewDelegation(s.addressToString(val0AccAddr), s.valAddressToString(addrVals[0]), issuedShares) require.NoError(keeper.SetDelegation(ctx, selfDelegation)) _, err := keeper.BeginRedelegation(ctx, val0AccAddr, addrVals[0], addrVals[0], math.LegacyNewDec(5)) @@ -821,7 +821,7 @@ func (s *KeeperTestSuite) TestRedelegationMaxEntries() { s.bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), stakingtypes.NotBondedPoolName, stakingtypes.BondedPoolName, gomock.Any()) _ = stakingkeeper.TestingUpdateValidator(keeper, ctx, validator, true) val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) - selfDelegation := stakingtypes.NewDelegation(val0AccAddr.String(), addrVals[0].String(), issuedShares) + selfDelegation := stakingtypes.NewDelegation(s.addressToString(val0AccAddr), s.valAddressToString(addrVals[0]), issuedShares) require.NoError(keeper.SetDelegation(ctx, selfDelegation)) // create a second validator @@ -876,7 +876,7 @@ func (s *KeeperTestSuite) TestRedelegateSelfDelegation() { validator = stakingkeeper.TestingUpdateValidator(keeper, ctx, validator, true) val0AccAddr := sdk.AccAddress(addrVals[0]) - selfDelegation := stakingtypes.NewDelegation(val0AccAddr.String(), addrVals[0].String(), issuedShares) + selfDelegation := stakingtypes.NewDelegation(s.addressToString(val0AccAddr), s.valAddressToString(addrVals[0]), issuedShares) require.NoError(keeper.SetDelegation(ctx, selfDelegation)) // create a second validator @@ -893,7 +893,7 @@ func (s *KeeperTestSuite) TestRedelegateSelfDelegation() { require.Equal(delTokens, issuedShares.RoundInt()) stakingkeeper.TestingUpdateValidator(keeper, ctx, validator, true) - delegation := stakingtypes.NewDelegation(addrDels[0].String(), addrVals[0].String(), issuedShares) + delegation := stakingtypes.NewDelegation(s.addressToString(addrDels[0]), s.valAddressToString(addrVals[0]), issuedShares) require.NoError(keeper.SetDelegation(ctx, delegation)) _, err := keeper.BeginRedelegation(ctx, val0AccAddr, addrVals[0], addrVals[1], math.LegacyNewDecFromInt(delTokens)) @@ -925,7 +925,7 @@ func (s *KeeperTestSuite) TestRedelegateFromUnbondingValidator() { s.bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), stakingtypes.NotBondedPoolName, stakingtypes.BondedPoolName, gomock.Any()) validator = stakingkeeper.TestingUpdateValidator(keeper, ctx, validator, true) val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) - selfDelegation := stakingtypes.NewDelegation(val0AccAddr.String(), addrVals[0].String(), issuedShares) + selfDelegation := stakingtypes.NewDelegation(s.addressToString(val0AccAddr), s.valAddressToString(addrVals[0]), issuedShares) require.NoError(keeper.SetDelegation(ctx, selfDelegation)) // create a second delegation to this validator @@ -934,7 +934,7 @@ func (s *KeeperTestSuite) TestRedelegateFromUnbondingValidator() { validator, issuedShares = validator.AddTokensFromDel(delTokens) require.Equal(delTokens, issuedShares.RoundInt()) stakingkeeper.TestingUpdateValidator(keeper, ctx, validator, true) - delegation := stakingtypes.NewDelegation(addrDels[1].String(), addrVals[0].String(), issuedShares) + delegation := stakingtypes.NewDelegation(s.addressToString(addrDels[1]), s.valAddressToString(addrVals[0]), issuedShares) require.NoError(keeper.SetDelegation(ctx, delegation)) // create a second validator @@ -994,10 +994,10 @@ func (s *KeeperTestSuite) TestRedelegateFromUnbondedValidator() { ctx, keeper := s.ctx, s.stakingKeeper require := s.Require() - addrDels, addrVals := createValAddrs(2) + addrDels, valAddrs := createValAddrs(2) // create a validator with a self-delegation - validator := testutil.NewValidator(s.T(), addrVals[0], PKs[0]) + validator := testutil.NewValidator(s.T(), valAddrs[0], PKs[0]) require.NoError(keeper.SetValidatorByConsAddr(ctx, validator)) valTokens := keeper.TokensFromConsensusPower(ctx, 10) @@ -1005,8 +1005,8 @@ func (s *KeeperTestSuite) TestRedelegateFromUnbondedValidator() { require.Equal(valTokens, issuedShares.RoundInt()) s.bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), stakingtypes.NotBondedPoolName, stakingtypes.BondedPoolName, gomock.Any()) validator = stakingkeeper.TestingUpdateValidator(keeper, ctx, validator, true) - val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) - selfDelegation := stakingtypes.NewDelegation(val0AccAddr.String(), addrVals[0].String(), issuedShares) + val0AccAddr := sdk.AccAddress(valAddrs[0].Bytes()) + selfDelegation := stakingtypes.NewDelegation(s.addressToString(val0AccAddr), s.valAddressToString(valAddrs[0]), issuedShares) require.NoError(keeper.SetDelegation(ctx, selfDelegation)) // create a second delegation to this validator @@ -1015,11 +1015,11 @@ func (s *KeeperTestSuite) TestRedelegateFromUnbondedValidator() { validator, issuedShares = validator.AddTokensFromDel(delTokens) require.Equal(delTokens, issuedShares.RoundInt()) stakingkeeper.TestingUpdateValidator(keeper, ctx, validator, true) - delegation := stakingtypes.NewDelegation(addrDels[1].String(), addrVals[0].String(), issuedShares) + delegation := stakingtypes.NewDelegation(s.addressToString(addrDels[1]), s.valAddressToString(valAddrs[0]), issuedShares) require.NoError(keeper.SetDelegation(ctx, delegation)) // create a second validator - validator2 := testutil.NewValidator(s.T(), addrVals[1], PKs[1]) + validator2 := testutil.NewValidator(s.T(), valAddrs[1], PKs[1]) validator2, issuedShares = validator2.AddTokensFromDel(valTokens) require.Equal(valTokens, issuedShares.RoundInt()) s.bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), stakingtypes.NotBondedPoolName, stakingtypes.BondedPoolName, gomock.Any()) @@ -1031,7 +1031,7 @@ func (s *KeeperTestSuite) TestRedelegateFromUnbondedValidator() { // unbond the all self-delegation to put validator in unbonding state s.bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, gomock.Any()) - _, amount, err := keeper.Undelegate(ctx, val0AccAddr, addrVals[0], math.LegacyNewDecFromInt(delTokens)) + _, amount, err := keeper.Undelegate(ctx, val0AccAddr, valAddrs[0], math.LegacyNewDecFromInt(delTokens)) require.NoError(err) require.Equal(amount, delTokens) @@ -1039,7 +1039,7 @@ func (s *KeeperTestSuite) TestRedelegateFromUnbondedValidator() { s.bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, gomock.Any()) s.applyValidatorSetUpdates(ctx, keeper, 1) - validator, err = keeper.GetValidator(ctx, addrVals[0]) + validator, err = keeper.GetValidator(ctx, valAddrs[0]) require.NoError(err) require.Equal(ctx.HeaderInfo().Height, validator.UnbondingHeight) params, err := keeper.Params.Get(ctx) @@ -1053,11 +1053,11 @@ func (s *KeeperTestSuite) TestRedelegateFromUnbondedValidator() { // redelegate some of the delegation's shares redelegationTokens := keeper.TokensFromConsensusPower(ctx, 6) s.bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), stakingtypes.NotBondedPoolName, stakingtypes.BondedPoolName, gomock.Any()) - _, err = keeper.BeginRedelegation(ctx, addrDels[1], addrVals[0], addrVals[1], math.LegacyNewDecFromInt(redelegationTokens)) + _, err = keeper.BeginRedelegation(ctx, addrDels[1], valAddrs[0], valAddrs[1], math.LegacyNewDecFromInt(redelegationTokens)) require.NoError(err) // no red should have been found - red, err := keeper.Redelegations.Get(ctx, collections.Join3(addrDels[0].Bytes(), addrVals[0].Bytes(), addrVals[1].Bytes())) + red, err := keeper.Redelegations.Get(ctx, collections.Join3(addrDels[0].Bytes(), valAddrs[0].Bytes(), valAddrs[1].Bytes())) require.ErrorIs(err, collections.ErrNotFound, "%v", red) } @@ -1193,14 +1193,14 @@ func (s *KeeperTestSuite) TestUndelegateWithDustShare() { validator = stakingkeeper.TestingUpdateValidator(keeper, ctx, validator, true) // first add a validators[0] to delegate too - bond1to1 := stakingtypes.NewDelegation(addrDels[0].String(), valAddrs[0].String(), math.LegacyNewDec(100)) + bond1to1 := stakingtypes.NewDelegation(s.addressToString(addrDels[0]), s.valAddressToString(valAddrs[0]), math.LegacyNewDec(100)) require.NoError(keeper.SetDelegation(ctx, bond1to1)) resBond, err := keeper.Delegations.Get(ctx, collections.Join(addrDels[0], valAddrs[0])) require.NoError(err) require.Equal(bond1to1, resBond) // second delegators[1] add a validators[0] to delegate - bond2to1 := stakingtypes.NewDelegation(addrDels[1].String(), valAddrs[0].String(), math.LegacyNewDec(1)) + bond2to1 := stakingtypes.NewDelegation(s.addressToString(addrDels[1]), s.valAddressToString(valAddrs[0]), math.LegacyNewDec(1)) validator, delegatorShare := validator.AddTokensFromDel(math.NewInt(1)) bond2to1.Shares = delegatorShare _ = stakingkeeper.TestingUpdateValidator(keeper, ctx, validator, true) @@ -1215,12 +1215,12 @@ func (s *KeeperTestSuite) TestUndelegateWithDustShare() { require.Equal(2, len(delegations)) // undelegate all delegator[0]'s delegate - _, err = s.msgServer.Undelegate(ctx, stakingtypes.NewMsgUndelegate(addrDels[0].String(), valAddrs[0].String(), sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(99)))) + _, err = s.msgServer.Undelegate(ctx, stakingtypes.NewMsgUndelegate(s.addressToString(addrDels[0]), s.valAddressToString(valAddrs[0]), sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(99)))) require.NoError(err) // remain only delegator[1]'s delegate delegations, err = keeper.GetValidatorDelegations(ctx, valAddrs[0]) require.NoError(err) require.Equal(1, len(delegations)) - require.Equal(delegations[0].DelegatorAddress, addrDels[1].String()) + require.Equal(delegations[0].DelegatorAddress, s.addressToString(addrDels[1])) } diff --git a/x/staking/keeper/keeper_test.go b/x/staking/keeper/keeper_test.go index de6cfe138b5f..4039aa0c3aba 100644 --- a/x/staking/keeper/keeper_test.go +++ b/x/staking/keeper/keeper_test.go @@ -69,13 +69,14 @@ func (s *KeeperTestSuite) SetupTest() { accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec("cosmos")).AnyTimes() bankKeeper := stakingtestutil.NewMockBankKeeper(ctrl) - + authority, err := accountKeeper.AddressCodec().BytesToString(authtypes.NewModuleAddress(stakingtypes.GovModuleName)) + s.Require().NoError(err) keeper := stakingkeeper.NewKeeper( encCfg.Codec, env, accountKeeper, bankKeeper, - authtypes.NewModuleAddress(stakingtypes.GovModuleName).String(), + authority, address.NewBech32Codec("cosmosvaloper"), address.NewBech32Codec("cosmosvalcons"), ) @@ -93,6 +94,18 @@ func (s *KeeperTestSuite) SetupTest() { s.msgServer = stakingkeeper.NewMsgServerImpl(keeper) } +func (s *KeeperTestSuite) addressToString(addr []byte) string { + r, err := s.accountKeeper.AddressCodec().BytesToString(addr) + s.Require().NoError(err) + return r +} + +func (s *KeeperTestSuite) valAddressToString(addr []byte) string { + r, err := s.stakingKeeper.ValidatorAddressCodec().BytesToString(addr) + s.Require().NoError(err) + return r +} + func (s *KeeperTestSuite) TestParams() { ctx, keeper := s.ctx, s.stakingKeeper require := s.Require() @@ -348,8 +361,8 @@ func (s *KeeperTestSuite) TestUnbondingDelegationsMigrationToColls() { 100, func(i int64) { ubd := stakingtypes.UnbondingDelegation{ - DelegatorAddress: delAddrs[i].String(), - ValidatorAddress: valAddrs[i].String(), + DelegatorAddress: s.addressToString(delAddrs[i]), + ValidatorAddress: s.valAddressToString(valAddrs[i]), Entries: []stakingtypes.UnbondingDelegationEntry{ { CreationHeight: i, @@ -373,8 +386,8 @@ func (s *KeeperTestSuite) TestUnbondingDelegationsMigrationToColls() { 100, func(i int64) { ubd := stakingtypes.UnbondingDelegation{ - DelegatorAddress: delAddrs[i].String(), - ValidatorAddress: valAddrs[i].String(), + DelegatorAddress: s.addressToString(delAddrs[i]), + ValidatorAddress: s.valAddressToString(valAddrs[i]), Entries: []stakingtypes.UnbondingDelegationEntry{ { CreationHeight: i, @@ -435,7 +448,7 @@ func (s *KeeperTestSuite) TestValidatorsMigrationToColls() { 100, func(i int64) { val := stakingtypes.Validator{ - OperatorAddress: valAddrs[i].String(), + OperatorAddress: s.valAddressToString(valAddrs[i]), ConsensusPubkey: pkAny, Jailed: false, Status: stakingtypes.Bonded, @@ -461,7 +474,7 @@ func (s *KeeperTestSuite) TestValidatorsMigrationToColls() { 100, func(i int64) { val := stakingtypes.Validator{ - OperatorAddress: valAddrs[i].String(), + OperatorAddress: s.valAddressToString(valAddrs[i]), ConsensusPubkey: pkAny, Jailed: false, Status: stakingtypes.Bonded, @@ -493,7 +506,7 @@ func (s *KeeperTestSuite) TestValidatorQueueMigrationToColls() { 100, func(i int64) { var addrs []string - addrs = append(addrs, valAddrs[i].String()) + addrs = append(addrs, s.valAddressToString(valAddrs[i])) bz, err := s.cdc.Marshal(&stakingtypes.ValAddresses{Addresses: addrs}) s.Require().NoError(err) @@ -510,7 +523,7 @@ func (s *KeeperTestSuite) TestValidatorQueueMigrationToColls() { 100, func(i int64) { var addrs []string - addrs = append(addrs, valAddrs[i].String()) + addrs = append(addrs, s.valAddressToString(valAddrs[i])) err := s.stakingKeeper.SetUnbondingValidatorsQueue(s.ctx, endTime, endHeight, addrs) s.Require().NoError(err) @@ -533,9 +546,9 @@ func (s *KeeperTestSuite) TestRedelegationQueueMigrationToColls() { dvvTriplets := stakingtypes.DVVTriplets{ Triplets: []stakingtypes.DVVTriplet{ { - DelegatorAddress: addrs[i].String(), - ValidatorSrcAddress: valAddrs[i].String(), - ValidatorDstAddress: valAddrs[i+1].String(), + DelegatorAddress: s.addressToString(addrs[i]), + ValidatorSrcAddress: s.valAddressToString(valAddrs[i]), + ValidatorDstAddress: s.valAddressToString(valAddrs[i+1]), }, }, } @@ -556,9 +569,9 @@ func (s *KeeperTestSuite) TestRedelegationQueueMigrationToColls() { dvvTriplets := stakingtypes.DVVTriplets{ Triplets: []stakingtypes.DVVTriplet{ { - DelegatorAddress: addrs[i].String(), - ValidatorSrcAddress: valAddrs[i].String(), - ValidatorDstAddress: valAddrs[i+1].String(), + DelegatorAddress: s.addressToString(addrs[i]), + ValidatorSrcAddress: s.valAddressToString(valAddrs[i]), + ValidatorDstAddress: s.valAddressToString(valAddrs[i+1]), }, }, } diff --git a/x/staking/keeper/msg_server_test.go b/x/staking/keeper/msg_server_test.go index c0d9785557e5..b13bbca6d40e 100644 --- a/x/staking/keeper/msg_server_test.go +++ b/x/staking/keeper/msg_server_test.go @@ -70,8 +70,8 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { MaxChangeRate: math.LegacyNewDec(0), }, MinSelfDelegation: math.NewInt(1), - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkey, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000), }, @@ -90,8 +90,8 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { MaxChangeRate: math.LegacyNewDec(0), }, MinSelfDelegation: math.NewInt(1), - DelegatorAddress: Addr.String(), - ValidatorAddress: sdk.AccAddress([]byte("invalid")).String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.addressToString([]byte("invalid")), Pubkey: pubkey, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000), }, @@ -110,8 +110,8 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { MaxChangeRate: math.LegacyNewDec(0), }, MinSelfDelegation: math.NewInt(1), - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: nil, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000), }, @@ -130,8 +130,8 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { MaxChangeRate: math.LegacyNewDec(0), }, MinSelfDelegation: math.NewInt(1), - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkeyInvalidLen, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000), }, @@ -150,8 +150,8 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { MaxChangeRate: math.LegacyNewDec(0), }, MinSelfDelegation: math.NewInt(1), - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkey, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 0), }, @@ -170,8 +170,8 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { MaxChangeRate: math.LegacyNewDec(0), }, MinSelfDelegation: math.NewInt(1), - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkey, Value: sdk.Coin{}, }, @@ -190,8 +190,8 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { MaxChangeRate: math.LegacyNewDec(0), }, MinSelfDelegation: math.NewInt(0), - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkey, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000), }, @@ -210,8 +210,8 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { MaxChangeRate: math.LegacyNewDec(0), }, MinSelfDelegation: math.NewInt(-1), - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkey, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000), }, @@ -230,8 +230,8 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { MaxChangeRate: math.LegacyNewDec(0), }, MinSelfDelegation: math.NewInt(100), - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkey, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 10), }, @@ -254,8 +254,8 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { MaxChangeRate: math.LegacyNewDec(0), }, MinSelfDelegation: math.NewInt(1), - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkey, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000), }, @@ -287,7 +287,7 @@ func (s *KeeperTestSuite) TestMsgEditValidator() { require.NotNil(pk) comm := types.NewCommissionRates(math.LegacyNewDec(0), math.LegacyNewDec(0), math.LegacyNewDec(0)) - msg, err := types.NewMsgCreateValidator(ValAddr.String(), pk, sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(10)), types.Description{Moniker: "NewVal"}, comm, math.OneInt()) + msg, err := types.NewMsgCreateValidator(s.valAddressToString(ValAddr), pk, sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(10)), types.Description{Moniker: "NewVal"}, comm, math.OneInt()) require.NoError(err) res, err := msgServer.CreateValidator(ctx, msg) @@ -316,7 +316,7 @@ func (s *KeeperTestSuite) TestMsgEditValidator() { Description: types.Description{ Moniker: "TestValidator", }, - ValidatorAddress: sdk.AccAddress([]byte("invalid")).String(), + ValidatorAddress: s.addressToString([]byte("invalid")), CommissionRate: &newRate, MinSelfDelegation: &newSelfDel, }, @@ -328,7 +328,7 @@ func (s *KeeperTestSuite) TestMsgEditValidator() { ctx: newCtx, input: &types.MsgEditValidator{ Description: types.Description{}, - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), CommissionRate: &newRate, MinSelfDelegation: &newSelfDel, }, @@ -342,7 +342,7 @@ func (s *KeeperTestSuite) TestMsgEditValidator() { Description: types.Description{ Moniker: "TestValidator", }, - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), CommissionRate: &newRate, MinSelfDelegation: &negSelfDel, }, @@ -356,7 +356,7 @@ func (s *KeeperTestSuite) TestMsgEditValidator() { Description: types.Description{ Moniker: "TestValidator", }, - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), CommissionRate: &invalidRate, MinSelfDelegation: &newSelfDel, }, @@ -370,7 +370,7 @@ func (s *KeeperTestSuite) TestMsgEditValidator() { Description: types.Description{ Moniker: "TestValidator", }, - ValidatorAddress: sdk.ValAddress([]byte("val")).String(), + ValidatorAddress: s.valAddressToString([]byte("val")), CommissionRate: &newRate, MinSelfDelegation: &newSelfDel, }, @@ -384,7 +384,7 @@ func (s *KeeperTestSuite) TestMsgEditValidator() { Description: types.Description{ Moniker: "TestValidator", }, - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), CommissionRate: &newRate, MinSelfDelegation: &newSelfDel, }, @@ -398,7 +398,7 @@ func (s *KeeperTestSuite) TestMsgEditValidator() { Description: types.Description{ Moniker: "TestValidator", }, - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), CommissionRate: &newRate, MinSelfDelegation: &lowSelfDel, }, @@ -412,7 +412,7 @@ func (s *KeeperTestSuite) TestMsgEditValidator() { Description: types.Description{ Moniker: "TestValidator", }, - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), CommissionRate: &newRate, MinSelfDelegation: &highSelfDel, }, @@ -430,7 +430,7 @@ func (s *KeeperTestSuite) TestMsgEditValidator() { SecurityContact: "abc@gmail.com", Details: "newDetails", }, - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), CommissionRate: &newRate, MinSelfDelegation: &newSelfDel, }, @@ -461,7 +461,7 @@ func (s *KeeperTestSuite) TestMsgDelegate() { comm := types.NewCommissionRates(math.LegacyNewDec(0), math.LegacyNewDec(0), math.LegacyNewDec(0)) - msg, err := types.NewMsgCreateValidator(ValAddr.String(), pk, sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(10)), types.Description{Moniker: "NewVal"}, comm, math.OneInt()) + msg, err := types.NewMsgCreateValidator(s.valAddressToString(ValAddr), pk, sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(10)), types.Description{Moniker: "NewVal"}, comm, math.OneInt()) require.NoError(err) res, err := msgServer.CreateValidator(ctx, msg) @@ -477,8 +477,8 @@ func (s *KeeperTestSuite) TestMsgDelegate() { { name: "invalid validator", input: &types.MsgDelegate{ - DelegatorAddress: Addr.String(), - ValidatorAddress: sdk.AccAddress([]byte("invalid")).String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.addressToString([]byte("invalid")), Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))}, }, expErr: true, @@ -488,7 +488,7 @@ func (s *KeeperTestSuite) TestMsgDelegate() { name: "empty delegator", input: &types.MsgDelegate{ DelegatorAddress: "", - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))}, }, expErr: true, @@ -498,7 +498,7 @@ func (s *KeeperTestSuite) TestMsgDelegate() { name: "invalid delegator", input: &types.MsgDelegate{ DelegatorAddress: "invalid", - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))}, }, expErr: true, @@ -507,8 +507,8 @@ func (s *KeeperTestSuite) TestMsgDelegate() { { name: "validator does not exist", input: &types.MsgDelegate{ - DelegatorAddress: Addr.String(), - ValidatorAddress: sdk.ValAddress([]byte("val")).String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString([]byte("val")), Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))}, }, expErr: true, @@ -517,8 +517,8 @@ func (s *KeeperTestSuite) TestMsgDelegate() { { name: "zero amount", input: &types.MsgDelegate{ - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(0))}, }, expErr: true, @@ -527,8 +527,8 @@ func (s *KeeperTestSuite) TestMsgDelegate() { { name: "negative amount", input: &types.MsgDelegate{ - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(-1))}, }, expErr: true, @@ -537,8 +537,8 @@ func (s *KeeperTestSuite) TestMsgDelegate() { { name: "invalid BondDenom", input: &types.MsgDelegate{ - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.Coin{Denom: "test", Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))}, }, expErr: true, @@ -547,8 +547,8 @@ func (s *KeeperTestSuite) TestMsgDelegate() { { name: "valid msg", input: &types.MsgDelegate{ - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))}, }, expErr: false, @@ -586,14 +586,14 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { comm := types.NewCommissionRates(math.LegacyNewDec(0), math.LegacyNewDec(0), math.LegacyNewDec(0)) amt := sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))} - msg, err := types.NewMsgCreateValidator(srcValAddr.String(), pk, amt, types.Description{Moniker: "NewVal"}, comm, math.OneInt()) + msg, err := types.NewMsgCreateValidator(s.valAddressToString(srcValAddr), pk, amt, types.Description{Moniker: "NewVal"}, comm, math.OneInt()) require.NoError(err) res, err := msgServer.CreateValidator(ctx, msg) require.NoError(err) require.NotNil(res) s.bankKeeper.EXPECT().DelegateCoinsFromAccountToModule(gomock.Any(), addr2, types.NotBondedPoolName, gomock.Any()).AnyTimes() - msg, err = types.NewMsgCreateValidator(dstValAddr.String(), dstPk, amt, types.Description{Moniker: "NewVal"}, comm, math.OneInt()) + msg, err = types.NewMsgCreateValidator(s.valAddressToString(dstValAddr), dstPk, amt, types.Description{Moniker: "NewVal"}, comm, math.OneInt()) require.NoError(err) res, err = msgServer.CreateValidator(ctx, msg) @@ -601,7 +601,7 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { require.NotNil(res) shares := math.LegacyNewDec(100) - del := types.NewDelegation(Addr.String(), srcValAddr.String(), shares) + del := types.NewDelegation(s.addressToString(Addr), s.valAddressToString(srcValAddr), shares) require.NoError(keeper.SetDelegation(ctx, del)) _, err = keeper.Delegations.Get(ctx, collections.Join(Addr, srcValAddr)) require.NoError(err) @@ -615,9 +615,9 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { { name: "invalid source validator", input: &types.MsgBeginRedelegate{ - DelegatorAddress: Addr.String(), - ValidatorSrcAddress: sdk.AccAddress([]byte("invalid")).String(), - ValidatorDstAddress: dstValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorSrcAddress: s.addressToString([]byte("invalid")), + ValidatorDstAddress: s.valAddressToString(dstValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), }, expErr: true, @@ -627,8 +627,8 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { name: "empty delegator", input: &types.MsgBeginRedelegate{ DelegatorAddress: "", - ValidatorSrcAddress: srcValAddr.String(), - ValidatorDstAddress: dstValAddr.String(), + ValidatorSrcAddress: s.valAddressToString(srcValAddr), + ValidatorDstAddress: s.valAddressToString(dstValAddr), Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))}, }, expErr: true, @@ -638,8 +638,8 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { name: "invalid delegator", input: &types.MsgBeginRedelegate{ DelegatorAddress: "invalid", - ValidatorSrcAddress: srcValAddr.String(), - ValidatorDstAddress: dstValAddr.String(), + ValidatorSrcAddress: s.valAddressToString(srcValAddr), + ValidatorDstAddress: s.valAddressToString(dstValAddr), Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))}, }, expErr: true, @@ -648,9 +648,9 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { { name: "invalid destination validator", input: &types.MsgBeginRedelegate{ - DelegatorAddress: Addr.String(), - ValidatorSrcAddress: srcValAddr.String(), - ValidatorDstAddress: sdk.AccAddress([]byte("invalid")).String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorSrcAddress: s.valAddressToString(srcValAddr), + ValidatorDstAddress: s.addressToString([]byte("invalid")), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), }, expErr: true, @@ -659,9 +659,9 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { { name: "validator does not exist", input: &types.MsgBeginRedelegate{ - DelegatorAddress: Addr.String(), - ValidatorSrcAddress: sdk.ValAddress([]byte("invalid")).String(), - ValidatorDstAddress: dstValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorSrcAddress: s.valAddressToString(sdk.ValAddress([]byte("invalid"))), + ValidatorDstAddress: s.valAddressToString(dstValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), }, expErr: true, @@ -670,9 +670,9 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { { name: "self redelegation", input: &types.MsgBeginRedelegate{ - DelegatorAddress: Addr.String(), - ValidatorSrcAddress: srcValAddr.String(), - ValidatorDstAddress: srcValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorSrcAddress: s.valAddressToString(srcValAddr), + ValidatorDstAddress: s.valAddressToString(srcValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), }, expErr: true, @@ -681,9 +681,9 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { { name: "amount greater than delegated shares amount", input: &types.MsgBeginRedelegate{ - DelegatorAddress: Addr.String(), - ValidatorSrcAddress: srcValAddr.String(), - ValidatorDstAddress: dstValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorSrcAddress: s.valAddressToString(srcValAddr), + ValidatorDstAddress: s.valAddressToString(dstValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(101)), }, expErr: true, @@ -692,9 +692,9 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { { name: "zero amount", input: &types.MsgBeginRedelegate{ - DelegatorAddress: Addr.String(), - ValidatorSrcAddress: srcValAddr.String(), - ValidatorDstAddress: dstValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorSrcAddress: s.valAddressToString(srcValAddr), + ValidatorDstAddress: s.valAddressToString(dstValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(0)), }, expErr: true, @@ -703,9 +703,9 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { { name: "invalid coin denom", input: &types.MsgBeginRedelegate{ - DelegatorAddress: Addr.String(), - ValidatorSrcAddress: srcValAddr.String(), - ValidatorDstAddress: dstValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorSrcAddress: s.valAddressToString(srcValAddr), + ValidatorDstAddress: s.valAddressToString(dstValAddr), Amount: sdk.NewCoin("test", shares.RoundInt()), }, expErr: true, @@ -714,9 +714,9 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { { name: "valid msg", input: &types.MsgBeginRedelegate{ - DelegatorAddress: Addr.String(), - ValidatorSrcAddress: srcValAddr.String(), - ValidatorDstAddress: dstValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorSrcAddress: s.valAddressToString(srcValAddr), + ValidatorDstAddress: s.valAddressToString(dstValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), }, expErr: false, @@ -748,14 +748,14 @@ func (s *KeeperTestSuite) TestMsgUndelegate() { comm := types.NewCommissionRates(math.LegacyNewDec(0), math.LegacyNewDec(0), math.LegacyNewDec(0)) amt := sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))} - msg, err := types.NewMsgCreateValidator(ValAddr.String(), pk, amt, types.Description{Moniker: "NewVal"}, comm, math.OneInt()) + msg, err := types.NewMsgCreateValidator(s.valAddressToString(ValAddr), pk, amt, types.Description{Moniker: "NewVal"}, comm, math.OneInt()) require.NoError(err) res, err := msgServer.CreateValidator(ctx, msg) require.NoError(err) require.NotNil(res) shares := math.LegacyNewDec(100) - del := types.NewDelegation(Addr.String(), ValAddr.String(), shares) + del := types.NewDelegation(s.addressToString(Addr), s.valAddressToString(ValAddr), shares) require.NoError(keeper.SetDelegation(ctx, del)) _, err = keeper.Delegations.Get(ctx, collections.Join(Addr, ValAddr)) require.NoError(err) @@ -769,8 +769,8 @@ func (s *KeeperTestSuite) TestMsgUndelegate() { { name: "invalid validator", input: &types.MsgUndelegate{ - DelegatorAddress: Addr.String(), - ValidatorAddress: sdk.AccAddress([]byte("invalid")).String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.addressToString([]byte("invalid")), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), }, expErr: true, @@ -780,7 +780,7 @@ func (s *KeeperTestSuite) TestMsgUndelegate() { name: "empty delegator", input: &types.MsgUndelegate{ DelegatorAddress: "", - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: shares.RoundInt()}, }, expErr: true, @@ -790,7 +790,7 @@ func (s *KeeperTestSuite) TestMsgUndelegate() { name: "invalid delegator", input: &types.MsgUndelegate{ DelegatorAddress: "invalid", - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: shares.RoundInt()}, }, expErr: true, @@ -799,8 +799,8 @@ func (s *KeeperTestSuite) TestMsgUndelegate() { { name: "validator does not exist", input: &types.MsgUndelegate{ - DelegatorAddress: Addr.String(), - ValidatorAddress: sdk.ValAddress([]byte("invalid")).String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString([]byte("invalid")), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), }, expErr: true, @@ -809,8 +809,8 @@ func (s *KeeperTestSuite) TestMsgUndelegate() { { name: "amount greater than delegated shares amount", input: &types.MsgUndelegate{ - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(101)), }, expErr: true, @@ -819,8 +819,8 @@ func (s *KeeperTestSuite) TestMsgUndelegate() { { name: "zero amount", input: &types.MsgUndelegate{ - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(0)), }, expErr: true, @@ -829,8 +829,8 @@ func (s *KeeperTestSuite) TestMsgUndelegate() { { name: "invalid coin denom", input: &types.MsgUndelegate{ - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin("test", shares.RoundInt()), }, expErr: true, @@ -839,8 +839,8 @@ func (s *KeeperTestSuite) TestMsgUndelegate() { { name: "valid msg", input: &types.MsgUndelegate{ - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), }, expErr: false, @@ -873,14 +873,14 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { s.bankKeeper.EXPECT().DelegateCoinsFromAccountToModule(gomock.Any(), Addr, types.NotBondedPoolName, gomock.Any()).AnyTimes() - msg, err := types.NewMsgCreateValidator(ValAddr.String(), pk, amt, types.Description{Moniker: "NewVal"}, comm, math.OneInt()) + msg, err := types.NewMsgCreateValidator(s.valAddressToString(ValAddr), pk, amt, types.Description{Moniker: "NewVal"}, comm, math.OneInt()) require.NoError(err) res, err := msgServer.CreateValidator(ctx, msg) require.NoError(err) require.NotNil(res) shares := math.LegacyNewDec(100) - del := types.NewDelegation(Addr.String(), ValAddr.String(), shares) + del := types.NewDelegation(s.addressToString(Addr), s.valAddressToString(ValAddr), shares) require.NoError(keeper.SetDelegation(ctx, del)) resDel, err := keeper.Delegations.Get(ctx, collections.Join(Addr, ValAddr)) require.NoError(err) @@ -901,8 +901,8 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { { name: "invalid validator", input: &types.MsgCancelUnbondingDelegation{ - DelegatorAddress: Addr.String(), - ValidatorAddress: sdk.AccAddress([]byte("invalid")).String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.addressToString([]byte("invalid")), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), CreationHeight: 10, }, @@ -913,7 +913,7 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { name: "empty delegator", input: &types.MsgCancelUnbondingDelegation{ DelegatorAddress: "", - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), CreationHeight: 10, }, @@ -924,7 +924,7 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { name: "invalid delegator", input: &types.MsgCancelUnbondingDelegation{ DelegatorAddress: "invalid", - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), CreationHeight: 10, }, @@ -934,8 +934,8 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { { name: "entry not found at height", input: &types.MsgCancelUnbondingDelegation{ - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), CreationHeight: 11, }, @@ -945,8 +945,8 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { { name: "invalid height", input: &types.MsgCancelUnbondingDelegation{ - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), CreationHeight: -1, }, @@ -956,8 +956,8 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { { name: "invalid coin", input: &types.MsgCancelUnbondingDelegation{ - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin("test", shares.RoundInt()), CreationHeight: 10, }, @@ -967,8 +967,8 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { { name: "validator does not exist", input: &types.MsgCancelUnbondingDelegation{ - DelegatorAddress: Addr.String(), - ValidatorAddress: sdk.ValAddress([]byte("invalid")).String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString([]byte("invalid")), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), CreationHeight: 10, }, @@ -978,8 +978,8 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { { name: "amount is greater than balance", input: &types.MsgCancelUnbondingDelegation{ - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(101)), CreationHeight: 10, }, @@ -989,8 +989,8 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { { name: "zero amount", input: &types.MsgCancelUnbondingDelegation{ - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(0)), CreationHeight: 10, }, @@ -1000,8 +1000,8 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { { name: "valid msg", input: &types.MsgCancelUnbondingDelegation{ - DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), CreationHeight: 10, }, @@ -1032,7 +1032,7 @@ func (s *KeeperTestSuite) TestMsgUpdateParams() { require.NotNil(pk) comm := types.NewCommissionRates(math.LegacyNewDec(0), math.LegacyNewDec(0), math.LegacyNewDec(0)) s.bankKeeper.EXPECT().DelegateCoinsFromAccountToModule(gomock.Any(), Addr, types.NotBondedPoolName, gomock.Any()).AnyTimes() - msg, err := types.NewMsgCreateValidator(ValAddr.String(), pk, sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(10)), types.Description{Moniker: "NewVal"}, comm, math.OneInt()) + msg, err := types.NewMsgCreateValidator(s.valAddressToString(ValAddr), pk, sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(10)), types.Description{Moniker: "NewVal"}, comm, math.OneInt()) require.NoError(err) _, err = msgServer.CreateValidator(ctx, msg) require.NoError(err) diff --git a/x/staking/keeper/validator_test.go b/x/staking/keeper/validator_test.go index 5ac1a44865bb..4b2b2099c5d9 100644 --- a/x/staking/keeper/validator_test.go +++ b/x/staking/keeper/validator_test.go @@ -436,12 +436,12 @@ func (s *KeeperTestSuite) TestUnbondingValidator() { // set unbonding validator endTime := time.Now() endHeight := ctx.HeaderInfo().Height + 10 - require.NoError(keeper.SetUnbondingValidatorsQueue(ctx, endTime, endHeight, []string{valAddr.String()})) + require.NoError(keeper.SetUnbondingValidatorsQueue(ctx, endTime, endHeight, []string{s.valAddressToString(valAddr)})) resVals, err := keeper.GetUnbondingValidators(ctx, endTime, endHeight) require.NoError(err) require.Equal(1, len(resVals)) - require.Equal(valAddr.String(), resVals[0]) + require.Equal(s.valAddressToString(valAddr), resVals[0]) // add another unbonding validator valAddr1 := sdk.ValAddress(PKs[1].Address().Bytes()) @@ -459,7 +459,7 @@ func (s *KeeperTestSuite) TestUnbondingValidator() { resVals, err = keeper.GetUnbondingValidators(ctx, endTime, endHeight) require.NoError(err) require.Equal(1, len(resVals)) - require.Equal(valAddr.String(), resVals[0]) + require.Equal(s.valAddressToString(valAddr), resVals[0]) // check unbonding mature validators ctx = ctx.WithHeaderInfo(header.Info{Height: endHeight, Time: endTime}) @@ -478,7 +478,7 @@ func (s *KeeperTestSuite) TestUnbondingValidator() { validator, err = keeper.GetValidator(ctx, valAddr) require.ErrorIs(err, stakingtypes.ErrNoValidatorFound) - require.NoError(keeper.SetUnbondingValidatorsQueue(ctx, endTime, endHeight, []string{valAddr.String()})) + require.NoError(keeper.SetUnbondingValidatorsQueue(ctx, endTime, endHeight, []string{s.valAddressToString(valAddr)})) validator = testutil.NewValidator(s.T(), valAddr, valPubKey) validator, _ = validator.AddTokensFromDel(addTokens) validator.Status = stakingtypes.Unbonding diff --git a/x/staking/migrations/v5/migrations_test.go b/x/staking/migrations/v5/migrations_test.go index 07e19b3fcb8e..66d51205e740 100644 --- a/x/staking/migrations/v5/migrations_test.go +++ b/x/staking/migrations/v5/migrations_test.go @@ -81,7 +81,8 @@ func createHistoricalInfo(height int64, chainID string) *stakingtypes.Historical } func TestDelegationsByValidatorMigrations(t *testing.T) { - cdc := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}, staking.AppModule{}).Codec + codecOpts := codectestutil.CodecOptions{} + cdc := moduletestutil.MakeTestEncodingConfig(codecOpts, staking.AppModule{}).Codec storeKey := storetypes.NewKVStoreKey(v5.ModuleName) tKey := storetypes.NewTransientStoreKey("transient_test") ctx := testutil.DefaultContext(storeKey, tKey) @@ -92,8 +93,13 @@ func TestDelegationsByValidatorMigrations(t *testing.T) { valAddrs := sims.ConvertAddrsToValAddrs(accAddrs[0:1]) var addedDels []stakingtypes.Delegation + valAddr, err := codecOpts.GetValidatorCodec().BytesToString(valAddrs[0]) + assert.NoError(t, err) + for i := 1; i < 11; i++ { - del1 := stakingtypes.NewDelegation(accAddrs[i].String(), valAddrs[0].String(), sdkmath.LegacyNewDec(100)) + accAddr, err := codecOpts.GetAddressCodec().BytesToString(accAddrs[i]) + assert.NoError(t, err) + del1 := stakingtypes.NewDelegation(accAddr, valAddr, sdkmath.LegacyNewDec(100)) store.Set(v5.GetDelegationKey(accAddrs[i], valAddrs[0]), stakingtypes.MustMarshalDelegation(cdc, del1)) addedDels = append(addedDels, del1) } @@ -102,7 +108,7 @@ func TestDelegationsByValidatorMigrations(t *testing.T) { dels := getValDelegations(ctx, cdc, storeKey, valAddrs[0]) assert.Len(t, dels, 0) - err := v5.MigrateStore(ctx, store, cdc, logger) + err = v5.MigrateStore(ctx, store, cdc, logger) assert.NoError(t, err) // after migration the state of delegations by val index should not be empty diff --git a/x/staking/simulation/genesis.go b/x/staking/simulation/genesis.go index 41b22accb205..8b97c60136b9 100644 --- a/x/staking/simulation/genesis.go +++ b/x/staking/simulation/genesis.go @@ -76,6 +76,10 @@ func RandomizedGenState(simState *module.SimulationState) { for i := 0; i < int(simState.NumBonded); i++ { valAddr := sdk.ValAddress(simState.Accounts[i].Address) + ValStrAddress, err := simState.ValidatorCodec.BytesToString(valAddr) + if err != nil { + panic(err) + } valAddrs[i] = valAddr maxCommission := sdkmath.LegacyNewDecWithPrec(int64(simulation.RandIntBetween(simState.Rand, 1, 100)), 2) @@ -85,7 +89,7 @@ func RandomizedGenState(simState *module.SimulationState) { simulation.RandomDecAmount(simState.Rand, maxCommission), ) - validator, err := types.NewValidator(valAddr.String(), simState.Accounts[i].ConsKey.PubKey(), types.Description{}) + validator, err := types.NewValidator(ValStrAddress, simState.Accounts[i].ConsKey.PubKey(), types.Description{}) if err != nil { panic(err) } @@ -93,7 +97,11 @@ func RandomizedGenState(simState *module.SimulationState) { validator.DelegatorShares = sdkmath.LegacyNewDecFromInt(simState.InitialStake) validator.Commission = commission - delegation := types.NewDelegation(simState.Accounts[i].Address.String(), valAddr.String(), sdkmath.LegacyNewDecFromInt(simState.InitialStake)) + accAddress, err := simState.AddressCodec.BytesToString(simState.Accounts[i].Address) + if err != nil { + panic(err) + } + delegation := types.NewDelegation(accAddress, ValStrAddress, sdkmath.LegacyNewDecFromInt(simState.InitialStake)) validators = append(validators, validator) delegations = append(delegations, delegation) diff --git a/x/staking/simulation/genesis_test.go b/x/staking/simulation/genesis_test.go index 3f50cb9e0d3b..c3e399a44ecb 100644 --- a/x/staking/simulation/genesis_test.go +++ b/x/staking/simulation/genesis_test.go @@ -12,6 +12,7 @@ import ( "cosmossdk.io/x/staking/types" "github.com/cosmos/cosmos-sdk/codec" + codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -25,19 +26,22 @@ func TestRandomizedGenState(t *testing.T) { interfaceRegistry := codectypes.NewInterfaceRegistry() cryptocodec.RegisterInterfaces(interfaceRegistry) cdc := codec.NewProtoCodec(interfaceRegistry) + cdcOpts := codectestutil.CodecOptions{} s := rand.NewSource(1) r := rand.New(s) simState := module.SimulationState{ - AppParams: make(simtypes.AppParams), - Cdc: cdc, - Rand: r, - NumBonded: 3, - BondDenom: sdk.DefaultBondDenom, - Accounts: simtypes.RandomAccounts(r, 3), - InitialStake: sdkmath.NewInt(1000), - GenState: make(map[string]json.RawMessage), + AppParams: make(simtypes.AppParams), + Cdc: cdc, + AddressCodec: cdcOpts.GetAddressCodec(), + ValidatorCodec: cdcOpts.GetValidatorCodec(), + Rand: r, + NumBonded: 3, + BondDenom: sdk.DefaultBondDenom, + Accounts: simtypes.RandomAccounts(r, 3), + InitialStake: sdkmath.NewInt(1000), + GenState: make(map[string]json.RawMessage), } simulation.RandomizedGenState(&simState) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 9193fd5522fe..5358c910a900 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -188,7 +188,11 @@ func SimulateMsgCreateValidator( simtypes.RandomDecAmount(r, maxCommission), ) - msg, err := types.NewMsgCreateValidator(address.String(), simAccount.ConsKey.PubKey(), selfDelegation, description, commission, math.OneInt()) + addr, err := k.ValidatorAddressCodec().BytesToString(address) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, msgType, "unable to generate validator address"), nil, err + } + msg, err := types.NewMsgCreateValidator(addr, simAccount.ConsKey.PubKey(), selfDelegation, description, commission, math.OneInt()) if err != nil { return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "unable to create CreateValidator message"), nil, err } @@ -344,7 +348,11 @@ func SimulateMsgDelegate( } } - msg := types.NewMsgDelegate(simAccount.Address.String(), val.GetOperator(), bondAmt) + accAddr, err := ak.AddressCodec().BytesToString(simAccount.Address) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, msgType, "error getting account string address"), nil, err + } + msg := types.NewMsgDelegate(accAddr, val.GetOperator(), bondAmt) txCtx := simulation.OperationInput{ R: r, @@ -553,8 +561,12 @@ func SimulateMsgCancelUnbondingDelegate( return simtypes.NoOpMsg(types.ModuleName, msgType, "bond denom not found"), nil, err } + accAddr, err := ak.AddressCodec().BytesToString(simAccount.Address) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, msgType, "error getting account string address"), nil, err + } msg := types.NewMsgCancelUnbondingDelegation( - simAccount.Address.String(), val.GetOperator(), unbondingDelegationEntry.CreationHeight, sdk.NewCoin(bondDenom, cancelBondAmt), + accAddr, val.GetOperator(), unbondingDelegationEntry.CreationHeight, sdk.NewCoin(bondDenom, cancelBondAmt), ) spendable := bk.SpendableCoins(ctx, simAccount.Address) @@ -762,9 +774,17 @@ func SimulateMsgRotateConsPubKey(txGen client.TxConfig, ak types.AccountKeeper, if err != nil { return simtypes.NoOpMsg(types.ModuleName, msgType, "cannot get conskey"), nil, err } + consAddress, err := k.ConsensusAddressCodec().BytesToString(cons) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, msgType, "error getting consensus address"), nil, err + } acc, _ := simtypes.RandomAcc(r, accs) - if sdk.ConsAddress(cons).String() == sdk.ConsAddress(acc.ConsKey.PubKey().Address()).String() { + accAddress, err := k.ConsensusAddressCodec().BytesToString(acc.ConsKey.PubKey().Address()) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, msgType, "error getting consensus address"), nil, err + } + if consAddress == accAddress { return simtypes.NoOpMsg(types.ModuleName, msgType, "new pubkey and current pubkey should be different"), nil, nil } diff --git a/x/staking/simulation/proposals.go b/x/staking/simulation/proposals.go index ec26aa3683ad..9a74e2509bd3 100644 --- a/x/staking/simulation/proposals.go +++ b/x/staking/simulation/proposals.go @@ -4,6 +4,7 @@ import ( "math/rand" "time" + coreaddress "cosmossdk.io/core/address" sdkmath "cosmossdk.io/math" "cosmossdk.io/x/staking/types" @@ -32,7 +33,7 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { } // SimulateMsgUpdateParams returns a random MsgUpdateParams -func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) sdk.Msg { +func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, addressCodec coreaddress.Codec) (sdk.Msg, error) { // use the default gov module account address as authority var authority sdk.AccAddress = address.Module("gov") @@ -44,8 +45,13 @@ func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) params.UnbondingTime = time.Duration(simtypes.RandTimestamp(r).UnixNano()) params.MinCommissionRate = simtypes.RandomDecAmount(r, sdkmath.LegacyNewDec(1)) + addr, err := addressCodec.BytesToString(authority) + if err != nil { + return nil, err + } + return &types.MsgUpdateParams{ - Authority: authority.String(), + Authority: addr, Params: params, - } + }, nil } diff --git a/x/staking/simulation/proposals_test.go b/x/staking/simulation/proposals_test.go index 88637a73383b..359a218b484e 100644 --- a/x/staking/simulation/proposals_test.go +++ b/x/staking/simulation/proposals_test.go @@ -11,6 +11,7 @@ import ( "cosmossdk.io/x/staking/simulation" "cosmossdk.io/x/staking/types" + codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/address" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -23,7 +24,7 @@ func TestProposalMsgs(t *testing.T) { ctx := sdk.NewContext(nil, true, nil) accounts := simtypes.RandomAccounts(r, 3) - + addressCodec := codectestutil.CodecOptions{}.GetAddressCodec() // execute ProposalMsgs function weightedProposalMsgs := simulation.ProposalMsgs() assert.Assert(t, len(weightedProposalMsgs) == 1) @@ -34,11 +35,15 @@ func TestProposalMsgs(t *testing.T) { assert.Equal(t, simulation.OpWeightMsgUpdateParams, w0.AppParamsKey()) assert.Equal(t, simulation.DefaultWeightMsgUpdateParams, w0.DefaultWeight()) - msg := w0.MsgSimulatorFn()(r, ctx, accounts) + msg, err := w0.MsgSimulatorFn()(r, ctx, accounts, addressCodec) + assert.NilError(t, err) msgUpdateParams, ok := msg.(*types.MsgUpdateParams) assert.Assert(t, ok) - assert.Equal(t, sdk.AccAddress(address.Module("gov")).String(), msgUpdateParams.Authority) + addr, err := addressCodec.BytesToString(address.Module("gov")) + assert.NilError(t, err) + + assert.Equal(t, addr, msgUpdateParams.Authority) assert.Equal(t, "GqiQWIXnku", msgUpdateParams.Params.BondDenom) assert.Equal(t, uint32(213), msgUpdateParams.Params.MaxEntries) assert.Equal(t, uint32(300), msgUpdateParams.Params.HistoricalEntries) diff --git a/x/staking/testutil/helpers.go b/x/staking/testutil/helpers.go index 459b17fec834..bf2a0e985f11 100644 --- a/x/staking/testutil/helpers.go +++ b/x/staking/testutil/helpers.go @@ -53,7 +53,9 @@ func (sh *Helper) CreateValidatorWithValPower(addr sdk.ValAddress, pk cryptotype // CreateValidatorMsg returns a message used to create validator in this service. func (sh *Helper) CreateValidatorMsg(addr sdk.ValAddress, pk cryptotypes.PubKey, stakeAmount math.Int) *stakingtypes.MsgCreateValidator { coin := sdk.NewCoin(sh.Denom, stakeAmount) - msg, err := stakingtypes.NewMsgCreateValidator(addr.String(), pk, coin, stakingtypes.Description{}, sh.Commission, math.OneInt()) + address, err := sh.k.ValidatorAddressCodec().BytesToString(addr) + require.NoError(sh.t, err) + msg, err := stakingtypes.NewMsgCreateValidator(address, pk, coin, stakingtypes.Description{}, sh.Commission, math.OneInt()) require.NoError(sh.t, err) return msg } @@ -64,7 +66,9 @@ func (sh *Helper) CreateValidatorWithMsg(ctx context.Context, msg *stakingtypes. } func (sh *Helper) createValidator(addr sdk.ValAddress, pk cryptotypes.PubKey, coin sdk.Coin, ok bool) { - msg, err := stakingtypes.NewMsgCreateValidator(addr.String(), pk, coin, stakingtypes.Description{Moniker: "TestValidator"}, sh.Commission, math.OneInt()) + address, err := sh.k.ValidatorAddressCodec().BytesToString(addr) + require.NoError(sh.t, err) + msg, err := stakingtypes.NewMsgCreateValidator(address, pk, coin, stakingtypes.Description{Moniker: "TestValidator"}, sh.Commission, math.OneInt()) require.NoError(sh.t, err) res, err := sh.msgSrvr.CreateValidator(sh.Ctx, msg) if ok { @@ -77,27 +81,27 @@ func (sh *Helper) createValidator(addr sdk.ValAddress, pk cryptotypes.PubKey, co } // Delegate calls staking module staking module `MsgServer/Delegate` to delegate stake for a validator -func (sh *Helper) Delegate(delegator sdk.AccAddress, val sdk.ValAddress, amount math.Int) { +func (sh *Helper) Delegate(delegator, val string, amount math.Int) { coin := sdk.NewCoin(sh.Denom, amount) - msg := stakingtypes.NewMsgDelegate(delegator.String(), val.String(), coin) + msg := stakingtypes.NewMsgDelegate(delegator, val, coin) res, err := sh.msgSrvr.Delegate(sh.Ctx, msg) require.NoError(sh.t, err) require.NotNil(sh.t, res) } // DelegateWithPower calls staking module `MsgServer/Delegate` to delegate stake for a validator -func (sh *Helper) DelegateWithPower(delegator sdk.AccAddress, val sdk.ValAddress, power int64) { +func (sh *Helper) DelegateWithPower(delegator, val string, power int64) { coin := sdk.NewCoin(sh.Denom, sh.k.TokensFromConsensusPower(sh.Ctx, power)) - msg := stakingtypes.NewMsgDelegate(delegator.String(), val.String(), coin) + msg := stakingtypes.NewMsgDelegate(delegator, val, coin) res, err := sh.msgSrvr.Delegate(sh.Ctx, msg) require.NoError(sh.t, err) require.NotNil(sh.t, res) } // Undelegate calls staking module `MsgServer/Undelegate` to unbound some stake from a validator. -func (sh *Helper) Undelegate(delegator sdk.AccAddress, val sdk.ValAddress, amount math.Int, ok bool) { +func (sh *Helper) Undelegate(delegator, val string, amount math.Int, ok bool) { unbondAmt := sdk.NewCoin(sh.Denom, amount) - msg := stakingtypes.NewMsgUndelegate(delegator.String(), val.String(), unbondAmt) + msg := stakingtypes.NewMsgUndelegate(delegator, val, unbondAmt) res, err := sh.msgSrvr.Undelegate(sh.Ctx, msg) if ok { require.NoError(sh.t, err) diff --git a/x/staking/testutil/validator.go b/x/staking/testutil/validator.go index ad155b66cc36..85173cfab0f2 100644 --- a/x/staking/testutil/validator.go +++ b/x/staking/testutil/validator.go @@ -7,6 +7,7 @@ import ( "cosmossdk.io/x/staking/types" + codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -14,7 +15,9 @@ import ( // NewValidator is a testing helper method to create validators in tests func NewValidator(tb testing.TB, operator sdk.ValAddress, pubKey cryptotypes.PubKey) types.Validator { tb.Helper() - v, err := types.NewValidator(operator.String(), pubKey, types.Description{}) + operatorAddr, err := codectestutil.CodecOptions{}.GetValidatorCodec().BytesToString(operator) + require.NoError(tb, err) + v, err := types.NewValidator(operatorAddr, pubKey, types.Description{}) require.NoError(tb, err) return v } diff --git a/x/staking/types/authz.go b/x/staking/types/authz.go index d3c7425d6ade..aa70ba70b7ef 100644 --- a/x/staking/types/authz.go +++ b/x/staking/types/authz.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "cosmossdk.io/core/address" errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" @@ -16,8 +17,8 @@ import ( const gasCostPerIteration = uint64(10) // NewStakeAuthorization creates a new StakeAuthorization object. -func NewStakeAuthorization(allowed, denied []sdk.ValAddress, authzType AuthorizationType, amount *sdk.Coin) (*StakeAuthorization, error) { - allowedValidators, deniedValidators, err := validateAllowAndDenyValidators(allowed, denied) +func NewStakeAuthorization(allowed, denied []sdk.ValAddress, authzType AuthorizationType, amount *sdk.Coin, valAddressCodec address.Codec) (*StakeAuthorization, error) { + allowedValidators, deniedValidators, err := validateAllowAndDenyValidators(allowed, denied, valAddressCodec) if err != nil { return nil, err } @@ -153,7 +154,7 @@ func (a StakeAuthorization) Accept(ctx context.Context, msg sdk.Msg) (authz.Acce }, nil } -func validateAllowAndDenyValidators(allowed, denied []sdk.ValAddress) ([]string, []string, error) { +func validateAllowAndDenyValidators(allowed, denied []sdk.ValAddress, valAddressCodec address.Codec) ([]string, []string, error) { if len(allowed) == 0 && len(denied) == 0 { return nil, nil, sdkerrors.ErrInvalidRequest.Wrap("both allowed & deny list cannot be empty") } @@ -166,11 +167,15 @@ func validateAllowAndDenyValidators(allowed, denied []sdk.ValAddress) ([]string, if len(allowed) > 0 { foundAllowedValidators := make(map[string]bool, len(allowed)) for i, validator := range allowed { - if foundAllowedValidators[validator.String()] { - return nil, nil, sdkerrors.ErrInvalidRequest.Wrapf("duplicate allowed validator address: %s", validator.String()) + valAddr, err := valAddressCodec.BytesToString(validator) + if err != nil { + return nil, nil, sdkerrors.ErrInvalidRequest.Wrap("could not convert validator address") } - foundAllowedValidators[validator.String()] = true - allowedValidators[i] = validator.String() + if foundAllowedValidators[valAddr] { + return nil, nil, sdkerrors.ErrInvalidRequest.Wrapf("duplicate allowed validator address: %s", valAddr) + } + foundAllowedValidators[valAddr] = true + allowedValidators[i] = valAddr } return allowedValidators, nil, nil } @@ -178,11 +183,15 @@ func validateAllowAndDenyValidators(allowed, denied []sdk.ValAddress) ([]string, deniedValidators := make([]string, len(denied)) foundDeniedValidators := make(map[string]bool, len(denied)) for i, validator := range denied { - if foundDeniedValidators[validator.String()] { - return nil, nil, sdkerrors.ErrInvalidRequest.Wrapf("duplicate denied validator address: %s", validator.String()) + valAddr, err := valAddressCodec.BytesToString(validator) + if err != nil { + return nil, nil, sdkerrors.ErrInvalidRequest.Wrap("could not convert validator address") + } + if foundDeniedValidators[valAddr] { + return nil, nil, sdkerrors.ErrInvalidRequest.Wrapf("duplicate denied validator address: %s", valAddr) } - foundDeniedValidators[validator.String()] = true - deniedValidators[i] = validator.String() + foundDeniedValidators[valAddr] = true + deniedValidators[i] = valAddr } return nil, deniedValidators, nil diff --git a/x/staking/types/authz_test.go b/x/staking/types/authz_test.go index fa6185293ec5..f0912a8c41e1 100644 --- a/x/staking/types/authz_test.go +++ b/x/staking/types/authz_test.go @@ -3,12 +3,14 @@ package types_test import ( "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" coreheader "cosmossdk.io/core/header" storetypes "cosmossdk.io/store/types" stakingtypes "cosmossdk.io/x/staking/types" + codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -23,46 +25,60 @@ var ( val3 = sdk.ValAddress("_____validator3_____") ) +func valAddressToString(t *testing.T, addr sdk.ValAddress) string { + t.Helper() + r, err := codectestutil.CodecOptions{}.GetValidatorCodec().BytesToString(addr) + assert.NoError(t, err) + return r +} + +func accAddressToString(t *testing.T, addr sdk.AccAddress) string { + t.Helper() + r, err := codectestutil.CodecOptions{}.GetAddressCodec().BytesToString(addr) + assert.NoError(t, err) + return r +} + func TestAuthzAuthorizations(t *testing.T) { key := storetypes.NewKVStoreKey(stakingtypes.StoreKey) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) ctx := testCtx.Ctx.WithHeaderInfo(coreheader.Info{}) - + valAddressCodec := codectestutil.CodecOptions{}.GetValidatorCodec() // verify ValidateBasic returns error for the AUTHORIZATION_TYPE_UNSPECIFIED authorization type - delAuth, err := stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val2}, []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNSPECIFIED, &coin100) + delAuth, err := stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val2}, []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNSPECIFIED, &coin100, valAddressCodec) require.NoError(t, err) require.Error(t, delAuth.ValidateBasic()) // verify MethodName - delAuth, err = stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val2}, []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, &coin100) + delAuth, err = stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val2}, []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, &coin100, valAddressCodec) require.NoError(t, err) require.Equal(t, delAuth.MsgTypeURL(), sdk.MsgTypeURL(&stakingtypes.MsgDelegate{})) // error both allow & deny list - _, err = stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val2}, []sdk.ValAddress{val1}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, &coin100) + _, err = stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val2}, []sdk.ValAddress{val1}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, &coin100, valAddressCodec) require.Error(t, err) // error duplicate allow list - _, err = stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val1}, []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, &coin100) + _, err = stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val1}, []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, &coin100, valAddressCodec) require.ErrorContains(t, err, "duplicate allowed validator address") // error duplicate denied list - _, err = stakingtypes.NewStakeAuthorization([]sdk.ValAddress{}, []sdk.ValAddress{val1, val1}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, &coin100) + _, err = stakingtypes.NewStakeAuthorization([]sdk.ValAddress{}, []sdk.ValAddress{val1, val1}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, &coin100, valAddressCodec) require.ErrorContains(t, err, "duplicate denied validator address") // verify MethodName - undelAuth, _ := stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val2}, []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE, &coin100) + undelAuth, _ := stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val2}, []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE, &coin100, valAddressCodec) require.Equal(t, undelAuth.MsgTypeURL(), sdk.MsgTypeURL(&stakingtypes.MsgUndelegate{})) // verify MethodName - beginRedelAuth, _ := stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val2}, []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE, &coin100) + beginRedelAuth, _ := stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val2}, []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE, &coin100, valAddressCodec) require.Equal(t, beginRedelAuth.MsgTypeURL(), sdk.MsgTypeURL(&stakingtypes.MsgBeginRedelegate{})) // verify MethodName for CancelUnbondingDelegation - cancelUnbondAuth, _ := stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val2}, []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_CANCEL_UNBONDING_DELEGATION, &coin100) + cancelUnbondAuth, _ := stakingtypes.NewStakeAuthorization([]sdk.ValAddress{val1, val2}, []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_CANCEL_UNBONDING_DELEGATION, &coin100, valAddressCodec) require.Equal(t, cancelUnbondAuth.MsgTypeURL(), sdk.MsgTypeURL(&stakingtypes.MsgCancelUnbondingDelegation{})) - validators1_2 := []string{val1.String(), val2.String()} + validators1_2 := []string{valAddressToString(t, val1), valAddressToString(t, val2)} testCases := []struct { msg string @@ -81,7 +97,7 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, &coin100, - stakingtypes.NewMsgDelegate(delAddr.String(), val1.String(), coin100), + stakingtypes.NewMsgDelegate(accAddressToString(t, delAddr), valAddressToString(t, val1), coin100), false, true, nil, @@ -92,7 +108,7 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, &coin100, - stakingtypes.NewMsgDelegate(delAddr.String(), val1.String(), coin150), + stakingtypes.NewMsgDelegate(accAddressToString(t, delAddr), valAddressToString(t, val1), coin150), true, false, nil, @@ -103,7 +119,7 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, &coin100, - stakingtypes.NewMsgDelegate(delAddr.String(), val1.String(), coin50), + stakingtypes.NewMsgDelegate(accAddressToString(t, delAddr), valAddressToString(t, val1), coin50), false, false, &stakingtypes.StakeAuthorization{ @@ -118,7 +134,7 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, &coin100, - stakingtypes.NewMsgDelegate(delAddr.String(), val3.String(), coin100), + stakingtypes.NewMsgDelegate(accAddressToString(t, delAddr), valAddressToString(t, val3), coin100), true, false, nil, @@ -129,7 +145,7 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, nil, - stakingtypes.NewMsgDelegate(delAddr.String(), val2.String(), coin100), + stakingtypes.NewMsgDelegate(accAddressToString(t, delAddr), valAddressToString(t, val2), coin100), false, false, &stakingtypes.StakeAuthorization{ @@ -144,7 +160,7 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{val1}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, nil, - stakingtypes.NewMsgDelegate(delAddr.String(), val1.String(), coin100), + stakingtypes.NewMsgDelegate(accAddressToString(t, delAddr), valAddressToString(t, val1), coin100), true, false, nil, @@ -155,12 +171,12 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{val1}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, nil, - stakingtypes.NewMsgDelegate(delAddr.String(), val2.String(), coin100), + stakingtypes.NewMsgDelegate(accAddressToString(t, delAddr), valAddressToString(t, val2), coin100), false, false, &stakingtypes.StakeAuthorization{ Validators: &stakingtypes.StakeAuthorization_DenyList{ - DenyList: &stakingtypes.StakeAuthorization_Validators{Address: []string{val1.String()}}, + DenyList: &stakingtypes.StakeAuthorization_Validators{Address: []string{valAddressToString(t, val1)}}, }, MaxTokens: nil, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, }, }, @@ -170,7 +186,7 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE, &coin100, - stakingtypes.NewMsgUndelegate(delAddr.String(), val1.String(), coin100), + stakingtypes.NewMsgUndelegate(accAddressToString(t, delAddr), valAddressToString(t, val1), coin100), false, true, nil, @@ -181,7 +197,7 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE, &coin100, - stakingtypes.NewMsgUndelegate(delAddr.String(), val1.String(), coin50), + stakingtypes.NewMsgUndelegate(accAddressToString(t, delAddr), valAddressToString(t, val1), coin50), false, false, &stakingtypes.StakeAuthorization{ @@ -196,7 +212,7 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE, &coin100, - stakingtypes.NewMsgUndelegate(delAddr.String(), val3.String(), coin100), + stakingtypes.NewMsgUndelegate(accAddressToString(t, delAddr), valAddressToString(t, val3), coin100), true, false, nil, @@ -207,7 +223,7 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE, nil, - stakingtypes.NewMsgUndelegate(delAddr.String(), val2.String(), coin100), + stakingtypes.NewMsgUndelegate(accAddressToString(t, delAddr), valAddressToString(t, val2), coin100), false, false, &stakingtypes.StakeAuthorization{ @@ -222,7 +238,7 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{val1}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE, &coin100, - stakingtypes.NewMsgUndelegate(delAddr.String(), val1.String(), coin100), + stakingtypes.NewMsgUndelegate(accAddressToString(t, delAddr), valAddressToString(t, val1), coin100), true, false, nil, @@ -234,7 +250,7 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE, &coin100, - stakingtypes.NewMsgUndelegate(delAddr.String(), val1.String(), coin100), + stakingtypes.NewMsgUndelegate(accAddressToString(t, delAddr), valAddressToString(t, val1), coin100), false, true, nil, @@ -245,7 +261,7 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE, &coin100, - stakingtypes.NewMsgBeginRedelegate(delAddr.String(), val1.String(), val1.String(), coin50), + stakingtypes.NewMsgBeginRedelegate(accAddressToString(t, delAddr), valAddressToString(t, val1), valAddressToString(t, val1), coin50), false, false, &stakingtypes.StakeAuthorization{ @@ -260,7 +276,7 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE, &coin100, - stakingtypes.NewMsgBeginRedelegate(delAddr.String(), val3.String(), val3.String(), coin100), + stakingtypes.NewMsgBeginRedelegate(accAddressToString(t, delAddr), valAddressToString(t, val3), valAddressToString(t, val3), coin100), true, false, nil, @@ -271,7 +287,7 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE, nil, - stakingtypes.NewMsgBeginRedelegate(delAddr.String(), val2.String(), val2.String(), coin100), + stakingtypes.NewMsgBeginRedelegate(accAddressToString(t, delAddr), valAddressToString(t, val2), valAddressToString(t, val2), coin100), false, false, &stakingtypes.StakeAuthorization{ @@ -286,7 +302,7 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{val1}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE, &coin100, - stakingtypes.NewMsgBeginRedelegate(delAddr.String(), val1.String(), val1.String(), coin100), + stakingtypes.NewMsgBeginRedelegate(accAddressToString(t, delAddr), valAddressToString(t, val1), valAddressToString(t, val1), coin100), true, false, nil, @@ -297,7 +313,7 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_CANCEL_UNBONDING_DELEGATION, &coin100, - stakingtypes.NewMsgCancelUnbondingDelegation(delAddr.String(), val1.String(), ctx.HeaderInfo().Height, coin100), + stakingtypes.NewMsgCancelUnbondingDelegation(accAddressToString(t, delAddr), valAddressToString(t, val1), ctx.HeaderInfo().Height, coin100), false, true, nil, @@ -308,12 +324,12 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_CANCEL_UNBONDING_DELEGATION, &coin100, - stakingtypes.NewMsgCancelUnbondingDelegation(delAddr.String(), val1.String(), ctx.HeaderInfo().Height, coin50), + stakingtypes.NewMsgCancelUnbondingDelegation(accAddressToString(t, delAddr), valAddressToString(t, val1), ctx.HeaderInfo().Height, coin50), false, false, &stakingtypes.StakeAuthorization{ Validators: &stakingtypes.StakeAuthorization_AllowList{ - AllowList: &stakingtypes.StakeAuthorization_Validators{Address: []string{val1.String()}}, + AllowList: &stakingtypes.StakeAuthorization_Validators{Address: []string{valAddressToString(t, val1)}}, }, MaxTokens: &coin50, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_CANCEL_UNBONDING_DELEGATION, @@ -325,7 +341,7 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_CANCEL_UNBONDING_DELEGATION, &coin100, - stakingtypes.NewMsgCancelUnbondingDelegation(delAddr.String(), val3.String(), ctx.HeaderInfo().Height, coin50), + stakingtypes.NewMsgCancelUnbondingDelegation(accAddressToString(t, delAddr), valAddressToString(t, val3), ctx.HeaderInfo().Height, coin50), true, false, nil, @@ -336,7 +352,7 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_CANCEL_UNBONDING_DELEGATION, nil, - stakingtypes.NewMsgCancelUnbondingDelegation(delAddr.String(), val2.String(), ctx.HeaderInfo().Height, coin100), + stakingtypes.NewMsgCancelUnbondingDelegation(accAddressToString(t, delAddr), valAddressToString(t, val2), ctx.HeaderInfo().Height, coin100), false, false, &stakingtypes.StakeAuthorization{ @@ -353,7 +369,7 @@ func TestAuthzAuthorizations(t *testing.T) { []sdk.ValAddress{val1}, stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_CANCEL_UNBONDING_DELEGATION, &coin100, - stakingtypes.NewMsgCancelUnbondingDelegation(delAddr.String(), val1.String(), ctx.HeaderInfo().Height, coin100), + stakingtypes.NewMsgCancelUnbondingDelegation(accAddressToString(t, delAddr), valAddressToString(t, val1), ctx.HeaderInfo().Height, coin100), true, false, nil, @@ -363,7 +379,7 @@ func TestAuthzAuthorizations(t *testing.T) { for _, tc := range testCases { tc := tc t.Run(tc.msg, func(t *testing.T) { - delAuth, err := stakingtypes.NewStakeAuthorization(tc.allowed, tc.denied, tc.msgType, tc.limit) + delAuth, err := stakingtypes.NewStakeAuthorization(tc.allowed, tc.denied, tc.msgType, tc.limit, valAddressCodec) require.NoError(t, err) resp, err := delAuth.Accept(ctx, tc.srvMsg) require.Equal(t, tc.isDelete, resp.Delete) diff --git a/x/staking/types/delegation_test.go b/x/staking/types/delegation_test.go index 1f5eaa7bfac9..3452ce51744c 100644 --- a/x/staking/types/delegation_test.go +++ b/x/staking/types/delegation_test.go @@ -13,17 +13,25 @@ import ( "github.com/cosmos/cosmos-sdk/codec" addresscodec "github.com/cosmos/cosmos-sdk/codec/address" + codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" sdk "github.com/cosmos/cosmos-sdk/types" ) func TestDelegationEqual(t *testing.T) { - d1 := types.NewDelegation(sdk.AccAddress(valAddr1).String(), valAddr2.String(), math.LegacyNewDec(100)) + codecOpts := codectestutil.CodecOptions{} + addr, err := codecOpts.GetAddressCodec().BytesToString(valAddr1) + require.NoError(t, err) + valAddr, err := codecOpts.GetValidatorCodec().BytesToString(valAddr2) + require.NoError(t, err) + d1 := types.NewDelegation(addr, valAddr, math.LegacyNewDec(100)) d2 := d1 ok := d1.String() == d2.String() require.True(t, ok) - d2.ValidatorAddress = valAddr3.String() + vAddr3, err := codecOpts.GetValidatorCodec().BytesToString(valAddr2) + require.NoError(t, err) + d2.ValidatorAddress = vAddr3 d2.Shares = math.LegacyNewDec(200) ok = d1.String() == d2.String() @@ -31,7 +39,12 @@ func TestDelegationEqual(t *testing.T) { } func TestDelegationString(t *testing.T) { - d := types.NewDelegation(sdk.AccAddress(valAddr1).String(), valAddr2.String(), math.LegacyNewDec(100)) + codecOpts := codectestutil.CodecOptions{} + addr, err := codecOpts.GetAddressCodec().BytesToString(valAddr1) + require.NoError(t, err) + valAddr, err := codecOpts.GetValidatorCodec().BytesToString(valAddr2) + require.NoError(t, err) + d := types.NewDelegation(addr, valAddr, math.LegacyNewDec(100)) require.NotEmpty(t, d.String()) } @@ -43,7 +56,9 @@ func TestUnbondingDelegationEqual(t *testing.T) { ok := ubd1.String() == ubd2.String() require.True(t, ok) - ubd2.ValidatorAddress = valAddr3.String() + vAddr3, err := codectestutil.CodecOptions{}.GetValidatorCodec().BytesToString(valAddr3) + require.NoError(t, err) + ubd2.ValidatorAddress = vAddr3 ubd2.Entries[0].CompletionTime = time.Unix(20*20*2, 0) ok = (ubd1.String() == ubd2.String()) @@ -81,9 +96,15 @@ func TestRedelegationString(t *testing.T) { func TestDelegationResponses(t *testing.T) { cdc := codec.NewLegacyAmino() - dr1 := types.NewDelegationResp(sdk.AccAddress(valAddr1).String(), valAddr2.String(), math.LegacyNewDec(5), + codecOpts := codectestutil.CodecOptions{} + addr, err := codecOpts.GetAddressCodec().BytesToString(valAddr1) + require.NoError(t, err) + valAddr, err := codecOpts.GetValidatorCodec().BytesToString(valAddr2) + require.NoError(t, err) + + dr1 := types.NewDelegationResp(addr, valAddr, math.LegacyNewDec(5), sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(5))) - dr2 := types.NewDelegationResp(sdk.AccAddress(valAddr1).String(), valAddr3.String(), math.LegacyNewDec(5), + dr2 := types.NewDelegationResp(addr, valAddr, math.LegacyNewDec(5), sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(5))) drs := types.DelegationResponses{dr1, dr2} @@ -110,12 +131,25 @@ func TestDelegationResponses(t *testing.T) { func TestRedelegationResponses(t *testing.T) { cdc := codec.NewLegacyAmino() + addressCdc := codectestutil.CodecOptions{}.GetAddressCodec() + addr1, err := addressCdc.BytesToString(valAddr1) + require.NoError(t, err) + addr2, err := addressCdc.BytesToString(valAddr2) + require.NoError(t, err) + validatorCdc := codectestutil.CodecOptions{}.GetValidatorCodec() + vAddr1, err := validatorCdc.BytesToString(valAddr1) + require.NoError(t, err) + vAddr2, err := validatorCdc.BytesToString(valAddr2) + require.NoError(t, err) + vAddr3, err := validatorCdc.BytesToString(valAddr3) + require.NoError(t, err) + entries := []types.RedelegationEntryResponse{ types.NewRedelegationEntryResponse(0, time.Unix(0, 0), math.LegacyNewDec(5), math.NewInt(5), math.NewInt(5), 0), types.NewRedelegationEntryResponse(0, time.Unix(0, 0), math.LegacyNewDec(5), math.NewInt(5), math.NewInt(5), 0), } - rdr1 := types.NewRedelegationResponse(sdk.AccAddress(valAddr1).String(), valAddr2.String(), valAddr3.String(), entries) - rdr2 := types.NewRedelegationResponse(sdk.AccAddress(valAddr2).String(), valAddr1.String(), valAddr3.String(), entries) + rdr1 := types.NewRedelegationResponse(addr1, vAddr2, vAddr3, entries) + rdr2 := types.NewRedelegationResponse(addr2, vAddr1, vAddr3, entries) rdrs := types.RedelegationResponses{rdr1, rdr2} bz1, err := json.Marshal(rdr1) diff --git a/x/staking/types/msg_test.go b/x/staking/types/msg_test.go index 8e37b5d29922..c7a072ffcdc0 100644 --- a/x/staking/types/msg_test.go +++ b/x/staking/types/msg_test.go @@ -9,6 +9,7 @@ import ( "cosmossdk.io/x/staking/types" "github.com/cosmos/cosmos-sdk/codec" + codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" @@ -34,9 +35,10 @@ func TestMsgDecode(t *testing.T) { require.True(t, pk1.Equals(pkUnmarshaled.(*ed25519.PubKey))) // now let's try to serialize the whole message - + vAddr1, err := codectestutil.CodecOptions{}.GetValidatorCodec().BytesToString(valAddr1) + require.NoError(t, err) commission1 := types.NewCommissionRates(math.LegacyZeroDec(), math.LegacyZeroDec(), math.LegacyZeroDec()) - msg, err := types.NewMsgCreateValidator(valAddr1.String(), pk1, coinPos, types.Description{}, commission1, math.OneInt()) + msg, err := types.NewMsgCreateValidator(vAddr1, pk1, coinPos, types.Description{}, commission1, math.OneInt()) require.NoError(t, err) msgSerialized, err := cdc.MarshalInterface(msg) require.NoError(t, err) diff --git a/x/staking/types/validator_test.go b/x/staking/types/validator_test.go index d181f82c2603..504562eb6e91 100644 --- a/x/staking/types/validator_test.go +++ b/x/staking/types/validator_test.go @@ -15,6 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/codec/legacy" + codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" @@ -136,8 +137,10 @@ func TestAddTokensValidatorUnbonded(t *testing.T) { // TODO refactor to make simpler like the AddToken tests above func TestRemoveDelShares(t *testing.T) { + addr1, err := codectestutil.CodecOptions{}.GetValidatorCodec().BytesToString(valAddr1) + require.NoError(t, err) valA := types.Validator{ - OperatorAddress: valAddr1.String(), + OperatorAddress: addr1, ConsensusPubkey: pk1Any, Status: types.Bonded, Tokens: math.NewInt(100), @@ -335,8 +338,9 @@ func TestBondStatus(t *testing.T) { } func mkValidator(tokens int64, shares math.LegacyDec) types.Validator { + vAddr1, _ := codectestutil.CodecOptions{}.GetValidatorCodec().BytesToString(valAddr1) return types.Validator{ - OperatorAddress: valAddr1.String(), + OperatorAddress: vAddr1, ConsensusPubkey: pk1Any, Status: types.Bonded, Tokens: math.NewInt(tokens), @@ -347,7 +351,9 @@ func mkValidator(tokens int64, shares math.LegacyDec) types.Validator { // Creates a new validators and asserts the error check. func newValidator(t *testing.T, operator sdk.ValAddress, pubKey cryptotypes.PubKey) types.Validator { t.Helper() - v, err := types.NewValidator(operator.String(), pubKey, types.Description{}) + addr, err := codectestutil.CodecOptions{}.GetValidatorCodec().BytesToString(operator) + require.NoError(t, err) + v, err := types.NewValidator(addr, pubKey, types.Description{}) require.NoError(t, err) return v }