From c2b94bc64061e9d2e12db51a92c5c31bd43325d6 Mon Sep 17 00:00:00 2001 From: Julian Toledano Date: Mon, 11 Mar 2024 17:44:04 +0100 Subject: [PATCH 01/17] del: remove ValAddress.String() --- simapp/sim_bench_test.go | 2 +- simapp/sim_test.go | 10 +- .../evidence/keeper/infraction_test.go | 12 +- .../slashing/keeper/keeper_test.go | 20 ++- testutil/sims/simulation_helpers.go | 10 +- testutil/sims/state_helpers.go | 34 +++-- types/module/simulation.go | 3 + x/auth/simulation/genesis_test.go | 19 +-- 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/distribution/simulation/genesis_test.go | 18 ++- x/evidence/simulation/genesis_test.go | 19 +-- x/feegrant/simulation/genesis_test.go | 18 +-- x/gov/simulation/genesis_test.go | 20 +-- x/group/simulation/genesis_test.go | 17 ++- x/mint/simulation/genesis_test.go | 21 +-- x/nft/simulation/genesis_test.go | 19 +-- x/slashing/simulation/genesis_test.go | 18 ++- x/staking/keeper/alias_functions.go | 6 +- x/staking/keeper/cons_pubkey_test.go | 9 +- x/staking/keeper/delegation_test.go | 94 ++++++------ x/staking/keeper/keeper_test.go | 32 +++-- x/staking/keeper/msg_server_test.go | 136 +++++++++--------- x/staking/keeper/validator_test.go | 8 +- x/staking/migrations/v5/migrations_test.go | 10 +- x/staking/simulation/genesis.go | 12 +- x/staking/simulation/genesis_test.go | 20 +-- x/staking/simulation/operations.go | 6 +- 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 +- 37 files changed, 515 insertions(+), 335 deletions(-) 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 8001d48d0749..f9eb493db7cb 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/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/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/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/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/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 5a9cbd898261..cf4eaf2f3a0b 100644 --- a/x/gov/simulation/genesis_test.go +++ b/x/gov/simulation/genesis_test.go @@ -14,6 +14,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" @@ -25,19 +26,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/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/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/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/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..2d32be54a0d4 100644 --- a/x/staking/keeper/cons_pubkey_test.go +++ b/x/staking/keeper/cons_pubkey_test.go @@ -30,7 +30,7 @@ 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) + selfDelegation := types.NewDelegation(val0AccAddr.String(), s.valAddressToString(addrVals[0]), issuedShares) err := stakingKeeper.SetDelegation(ctx, selfDelegation) s.Require().NoError(err) @@ -157,6 +157,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) @@ -165,8 +168,8 @@ 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) + selfDelegation := types.NewDelegation(val0AccAddr.String(), 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..ff8ccf8c303a 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(addrDels[1].String(), 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(addrDels[0].String(), 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(addrDels[0].String(), 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(addrDels[1].String(), 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(addrDels[1].String(), 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(delAddrs[0].String(), 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(sdk.AccAddress(valAddrs[0].Bytes()).String(), 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(addrDels[0].String(), 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(addrDels[0].String(), 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(addrDels[1].String(), 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(val0AccAddr.String(), 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(addrDels[1].String(), 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(val0AccAddr.String(), 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(addrDels[1].String(), 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(val0AccAddr.String(), 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(val0AccAddr.String(), 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(val0AccAddr.String(), 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(addrDels[0].String(), 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(val0AccAddr.String(), 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(addrDels[1].String(), 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(val0AccAddr.String(), 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(addrDels[1].String(), 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(addrDels[0].String(), 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(addrDels[1].String(), s.valAddressToString(valAddrs[0]), math.LegacyNewDec(1)) validator, delegatorShare := validator.AddTokensFromDel(math.NewInt(1)) bond2to1.Shares = delegatorShare _ = stakingkeeper.TestingUpdateValidator(keeper, ctx, validator, true) @@ -1215,7 +1215,7 @@ 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(addrDels[0].String(), s.valAddressToString(valAddrs[0]), sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(99)))) require.NoError(err) // remain only delegator[1]'s delegate diff --git a/x/staking/keeper/keeper_test.go b/x/staking/keeper/keeper_test.go index de6cfe138b5f..0016ddbec274 100644 --- a/x/staking/keeper/keeper_test.go +++ b/x/staking/keeper/keeper_test.go @@ -93,6 +93,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() @@ -349,7 +361,7 @@ func (s *KeeperTestSuite) TestUnbondingDelegationsMigrationToColls() { func(i int64) { ubd := stakingtypes.UnbondingDelegation{ DelegatorAddress: delAddrs[i].String(), - ValidatorAddress: valAddrs[i].String(), + ValidatorAddress: s.valAddressToString(valAddrs[i]), Entries: []stakingtypes.UnbondingDelegationEntry{ { CreationHeight: i, @@ -374,7 +386,7 @@ func (s *KeeperTestSuite) TestUnbondingDelegationsMigrationToColls() { func(i int64) { ubd := stakingtypes.UnbondingDelegation{ DelegatorAddress: delAddrs[i].String(), - ValidatorAddress: valAddrs[i].String(), + ValidatorAddress: s.valAddressToString(valAddrs[i]), Entries: []stakingtypes.UnbondingDelegationEntry{ { CreationHeight: i, @@ -435,7 +447,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 +473,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 +505,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 +522,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) @@ -534,8 +546,8 @@ func (s *KeeperTestSuite) TestRedelegationQueueMigrationToColls() { Triplets: []stakingtypes.DVVTriplet{ { DelegatorAddress: addrs[i].String(), - ValidatorSrcAddress: valAddrs[i].String(), - ValidatorDstAddress: valAddrs[i+1].String(), + ValidatorSrcAddress: s.valAddressToString(valAddrs[i]), + ValidatorDstAddress: s.valAddressToString(valAddrs[i+1]), }, }, } @@ -557,8 +569,8 @@ func (s *KeeperTestSuite) TestRedelegationQueueMigrationToColls() { Triplets: []stakingtypes.DVVTriplet{ { DelegatorAddress: addrs[i].String(), - ValidatorSrcAddress: valAddrs[i].String(), - ValidatorDstAddress: valAddrs[i+1].String(), + 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..2f0de367ef67 100644 --- a/x/staking/keeper/msg_server_test.go +++ b/x/staking/keeper/msg_server_test.go @@ -71,7 +71,7 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { }, MinSelfDelegation: math.NewInt(1), DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkey, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000), }, @@ -111,7 +111,7 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { }, MinSelfDelegation: math.NewInt(1), DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: nil, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000), }, @@ -131,7 +131,7 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { }, MinSelfDelegation: math.NewInt(1), DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkeyInvalidLen, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000), }, @@ -151,7 +151,7 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { }, MinSelfDelegation: math.NewInt(1), DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkey, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 0), }, @@ -171,7 +171,7 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { }, MinSelfDelegation: math.NewInt(1), DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkey, Value: sdk.Coin{}, }, @@ -191,7 +191,7 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { }, MinSelfDelegation: math.NewInt(0), DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkey, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000), }, @@ -211,7 +211,7 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { }, MinSelfDelegation: math.NewInt(-1), DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkey, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000), }, @@ -231,7 +231,7 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { }, MinSelfDelegation: math.NewInt(100), DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkey, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 10), }, @@ -255,7 +255,7 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { }, MinSelfDelegation: math.NewInt(1), DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + 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) @@ -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) @@ -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, @@ -508,7 +508,7 @@ func (s *KeeperTestSuite) TestMsgDelegate() { name: "validator does not exist", input: &types.MsgDelegate{ DelegatorAddress: Addr.String(), - ValidatorAddress: sdk.ValAddress([]byte("val")).String(), + ValidatorAddress: s.valAddressToString([]byte("val")), Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))}, }, expErr: true, @@ -518,7 +518,7 @@ func (s *KeeperTestSuite) TestMsgDelegate() { name: "zero amount", input: &types.MsgDelegate{ DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(0))}, }, expErr: true, @@ -528,7 +528,7 @@ func (s *KeeperTestSuite) TestMsgDelegate() { name: "negative amount", input: &types.MsgDelegate{ DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(-1))}, }, expErr: true, @@ -538,7 +538,7 @@ func (s *KeeperTestSuite) TestMsgDelegate() { name: "invalid BondDenom", input: &types.MsgDelegate{ DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.Coin{Denom: "test", Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))}, }, expErr: true, @@ -548,7 +548,7 @@ func (s *KeeperTestSuite) TestMsgDelegate() { name: "valid msg", input: &types.MsgDelegate{ DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + 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(Addr.String(), s.valAddressToString(srcValAddr), shares) require.NoError(keeper.SetDelegation(ctx, del)) _, err = keeper.Delegations.Get(ctx, collections.Join(Addr, srcValAddr)) require.NoError(err) @@ -617,7 +617,7 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { input: &types.MsgBeginRedelegate{ DelegatorAddress: Addr.String(), ValidatorSrcAddress: sdk.AccAddress([]byte("invalid")).String(), - ValidatorDstAddress: dstValAddr.String(), + 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, @@ -649,7 +649,7 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { name: "invalid destination validator", input: &types.MsgBeginRedelegate{ DelegatorAddress: Addr.String(), - ValidatorSrcAddress: srcValAddr.String(), + ValidatorSrcAddress: s.valAddressToString(srcValAddr), ValidatorDstAddress: sdk.AccAddress([]byte("invalid")).String(), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), }, @@ -660,8 +660,8 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { name: "validator does not exist", input: &types.MsgBeginRedelegate{ DelegatorAddress: Addr.String(), - ValidatorSrcAddress: sdk.ValAddress([]byte("invalid")).String(), - ValidatorDstAddress: dstValAddr.String(), + ValidatorSrcAddress: s.valAddressToString(sdk.ValAddress([]byte("invalid"))), + ValidatorDstAddress: s.valAddressToString(dstValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), }, expErr: true, @@ -671,8 +671,8 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { name: "self redelegation", input: &types.MsgBeginRedelegate{ DelegatorAddress: Addr.String(), - ValidatorSrcAddress: srcValAddr.String(), - ValidatorDstAddress: srcValAddr.String(), + ValidatorSrcAddress: s.valAddressToString(srcValAddr), + ValidatorDstAddress: s.valAddressToString(srcValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), }, expErr: true, @@ -682,8 +682,8 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { name: "amount greater than delegated shares amount", input: &types.MsgBeginRedelegate{ DelegatorAddress: Addr.String(), - ValidatorSrcAddress: srcValAddr.String(), - ValidatorDstAddress: dstValAddr.String(), + ValidatorSrcAddress: s.valAddressToString(srcValAddr), + ValidatorDstAddress: s.valAddressToString(dstValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(101)), }, expErr: true, @@ -693,8 +693,8 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { name: "zero amount", input: &types.MsgBeginRedelegate{ DelegatorAddress: Addr.String(), - ValidatorSrcAddress: srcValAddr.String(), - ValidatorDstAddress: dstValAddr.String(), + ValidatorSrcAddress: s.valAddressToString(srcValAddr), + ValidatorDstAddress: s.valAddressToString(dstValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(0)), }, expErr: true, @@ -704,8 +704,8 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { name: "invalid coin denom", input: &types.MsgBeginRedelegate{ DelegatorAddress: Addr.String(), - ValidatorSrcAddress: srcValAddr.String(), - ValidatorDstAddress: dstValAddr.String(), + ValidatorSrcAddress: s.valAddressToString(srcValAddr), + ValidatorDstAddress: s.valAddressToString(dstValAddr), Amount: sdk.NewCoin("test", shares.RoundInt()), }, expErr: true, @@ -715,8 +715,8 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { name: "valid msg", input: &types.MsgBeginRedelegate{ DelegatorAddress: Addr.String(), - ValidatorSrcAddress: srcValAddr.String(), - ValidatorDstAddress: dstValAddr.String(), + 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(Addr.String(), s.valAddressToString(ValAddr), shares) require.NoError(keeper.SetDelegation(ctx, del)) _, err = keeper.Delegations.Get(ctx, collections.Join(Addr, ValAddr)) require.NoError(err) @@ -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, @@ -800,7 +800,7 @@ func (s *KeeperTestSuite) TestMsgUndelegate() { name: "validator does not exist", input: &types.MsgUndelegate{ DelegatorAddress: Addr.String(), - ValidatorAddress: sdk.ValAddress([]byte("invalid")).String(), + ValidatorAddress: s.valAddressToString([]byte("invalid")), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), }, expErr: true, @@ -810,7 +810,7 @@ func (s *KeeperTestSuite) TestMsgUndelegate() { name: "amount greater than delegated shares amount", input: &types.MsgUndelegate{ DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(101)), }, expErr: true, @@ -820,7 +820,7 @@ func (s *KeeperTestSuite) TestMsgUndelegate() { name: "zero amount", input: &types.MsgUndelegate{ DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(0)), }, expErr: true, @@ -830,7 +830,7 @@ func (s *KeeperTestSuite) TestMsgUndelegate() { name: "invalid coin denom", input: &types.MsgUndelegate{ DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin("test", shares.RoundInt()), }, expErr: true, @@ -840,7 +840,7 @@ func (s *KeeperTestSuite) TestMsgUndelegate() { name: "valid msg", input: &types.MsgUndelegate{ DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + 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(Addr.String(), s.valAddressToString(ValAddr), shares) require.NoError(keeper.SetDelegation(ctx, del)) resDel, err := keeper.Delegations.Get(ctx, collections.Join(Addr, ValAddr)) require.NoError(err) @@ -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, }, @@ -935,7 +935,7 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { name: "entry not found at height", input: &types.MsgCancelUnbondingDelegation{ DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), CreationHeight: 11, }, @@ -946,7 +946,7 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { name: "invalid height", input: &types.MsgCancelUnbondingDelegation{ DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), CreationHeight: -1, }, @@ -957,7 +957,7 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { name: "invalid coin", input: &types.MsgCancelUnbondingDelegation{ DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin("test", shares.RoundInt()), CreationHeight: 10, }, @@ -968,7 +968,7 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { name: "validator does not exist", input: &types.MsgCancelUnbondingDelegation{ DelegatorAddress: Addr.String(), - ValidatorAddress: sdk.ValAddress([]byte("invalid")).String(), + ValidatorAddress: s.valAddressToString([]byte("invalid")), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), CreationHeight: 10, }, @@ -979,7 +979,7 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { name: "amount is greater than balance", input: &types.MsgCancelUnbondingDelegation{ DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(101)), CreationHeight: 10, }, @@ -990,7 +990,7 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { name: "zero amount", input: &types.MsgCancelUnbondingDelegation{ DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(0)), CreationHeight: 10, }, @@ -1001,7 +1001,7 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { name: "valid msg", input: &types.MsgCancelUnbondingDelegation{ DelegatorAddress: Addr.String(), - ValidatorAddress: ValAddr.String(), + 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..9aa2c36cbec5 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..cb8cdbc2b481 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,11 @@ 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)) + del1 := stakingtypes.NewDelegation(accAddrs[i].String(), valAddr, sdkmath.LegacyNewDec(100)) store.Set(v5.GetDelegationKey(accAddrs[i], valAddrs[0]), stakingtypes.MustMarshalDelegation(cdc, del1)) addedDels = append(addedDels, del1) } @@ -102,7 +106,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..fa557087deba 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 } 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..7680c0a9b2f6 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(valAddr2) + 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 } From 53add8cc3b7f097dfe30649857e5e4bf1a6e9798 Mon Sep 17 00:00:00 2001 From: Julian Toledano Date: Tue, 12 Mar 2024 13:22:38 +0100 Subject: [PATCH 02/17] del: remove AccAddress.String() --- tests/sims/gov/operations_test.go | 3 +- types/simulation/types.go | 4 +- x/auth/simulation/proposals.go | 3 +- x/auth/simulation/proposals_test.go | 3 +- x/bank/simulation/proposals.go | 3 +- x/bank/simulation/proposals_test.go | 3 +- x/distribution/simulation/proposals.go | 3 +- x/distribution/simulation/proposals_test.go | 3 +- x/gov/simulation/operations.go | 2 +- x/gov/simulation/proposals.go | 3 +- x/gov/simulation/proposals_test.go | 3 +- x/mint/simulation/proposals.go | 3 +- x/mint/simulation/proposals_test.go | 3 +- x/protocolpool/simulation/proposals.go | 3 +- x/protocolpool/simulation/proposals_test.go | 3 +- x/slashing/simulation/proposals.go | 3 +- x/slashing/simulation/proposals_test.go | 3 +- x/staking/keeper/cons_pubkey_test.go | 12 +-- x/staking/keeper/delegation_test.go | 52 +++++------ x/staking/keeper/keeper_test.go | 13 +-- x/staking/keeper/msg_server_test.go | 96 ++++++++++----------- x/staking/migrations/v5/migrations_test.go | 4 +- x/staking/simulation/operations.go | 12 ++- x/staking/simulation/proposals.go | 11 ++- x/staking/simulation/proposals_test.go | 10 ++- x/staking/types/delegation_test.go | 2 +- 26 files changed, 152 insertions(+), 111 deletions(-) diff --git a/tests/sims/gov/operations_test.go b/tests/sims/gov/operations_test.go index d5469829c827..94409159bfbb 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,7 +56,7 @@ func (m MockWeightedProposals) DefaultWeight() int { } func (m MockWeightedProposals) MsgSimulatorFn() simtypes.MsgSimulatorFn { - return func(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) sdk.Msg { + return func(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, _ address.Codec) sdk.Msg { return nil } } diff --git a/types/simulation/types.go b/types/simulation/types.go index 32bcd54520e6..922e16494628 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 type SimValFn func(r *rand.Rand) string diff --git a/x/auth/simulation/proposals.go b/x/auth/simulation/proposals.go index 809bbcb32826..e7980616965d 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, addressCodec coreaddress.Codec) sdk.Msg { // use the default gov module account address as authority var authority sdk.AccAddress = address.Module("gov") diff --git a/x/auth/simulation/proposals_test.go b/x/auth/simulation/proposals_test.go index 1168a0b892b8..b60b19f4e4ff 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,7 @@ 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 := w0.MsgSimulatorFn()(r, ctx, accounts, codectestutil.CodecOptions{}.GetAddressCodec()) msgUpdateParams, ok := msg.(*types.MsgUpdateParams) assert.Assert(t, ok) diff --git a/x/bank/simulation/proposals.go b/x/bank/simulation/proposals.go index 475c83604a38..64028fdaebc2 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, addressCodec coreaddress.Codec) sdk.Msg { // use the default gov module account address as authority var authority sdk.AccAddress = address.Module("gov") diff --git a/x/bank/simulation/proposals_test.go b/x/bank/simulation/proposals_test.go index 089f237709b4..1f17f7286722 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,7 @@ 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 := w0.MsgSimulatorFn()(r, ctx, accounts, codectestutil.CodecOptions{}.GetAddressCodec()) msgUpdateParams, ok := msg.(*types.MsgUpdateParams) assert.Assert(t, ok) diff --git a/x/distribution/simulation/proposals.go b/x/distribution/simulation/proposals.go index 0fa3ccc6f250..f28e63c4a933 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, addressCodec coreaddress.Codec) sdk.Msg { // use the default gov module account address as authority var authority sdk.AccAddress = address.Module("gov") diff --git a/x/distribution/simulation/proposals_test.go b/x/distribution/simulation/proposals_test.go index 1d3d6d059c97..3b8598913cd9 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,7 @@ 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 := w0.MsgSimulatorFn()(r, ctx, accounts, codectestutil.CodecOptions{}.GetAddressCodec()) msgUpdateParams, ok := msg.(*types.MsgUpdateParams) assert.Assert(t, ok) diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 26969d3365d3..0b9d76b18fe4 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -155,7 +155,7 @@ 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 := msgSim(r, ctx, accs, ak.AddressCodec()) if proposalMsg != nil { msgs = append(msgs, proposalMsg) } diff --git a/x/gov/simulation/proposals.go b/x/gov/simulation/proposals.go index 3a5a3050fccd..049c59adf0de 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,7 +27,7 @@ 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 { +func SimulateTextProposal(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, addressCodec coreaddress.Codec) sdk.Msg { return nil } diff --git a/x/gov/simulation/proposals_test.go b/x/gov/simulation/proposals_test.go index e8f4a7879603..9b81a064829e 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,7 @@ 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 := w0.MsgSimulatorFn()(r, ctx, accounts, codectestutil.CodecOptions{}.GetAddressCodec()) assert.Assert(t, msg == nil) } diff --git a/x/mint/simulation/proposals.go b/x/mint/simulation/proposals.go index 594413d94886..6026077c9499 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, addressCodec coreaddress.Codec) sdk.Msg { // use the default gov module account address as authority var authority sdk.AccAddress = address.Module("gov") diff --git a/x/mint/simulation/proposals_test.go b/x/mint/simulation/proposals_test.go index d9d313f5d4fc..111548f8aa3c 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,7 @@ 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 := w0.MsgSimulatorFn()(r, ctx, accounts, codectestutil.CodecOptions{}.GetAddressCodec()) msgUpdateParams, ok := msg.(*types.MsgUpdateParams) assert.Assert(t, ok) diff --git a/x/protocolpool/simulation/proposals.go b/x/protocolpool/simulation/proposals.go index bfeac7e0f382..928dd03e9768 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, addressCodec coreaddress.Codec) sdk.Msg { // use the default gov module account address as authority var authority sdk.AccAddress = address.Module("gov") diff --git a/x/protocolpool/simulation/proposals_test.go b/x/protocolpool/simulation/proposals_test.go index ac7361e2d903..9454b6b6eaea 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,7 @@ 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 := w0.MsgSimulatorFn()(r, ctx, accounts, codectestutil.CodecOptions{}.GetAddressCodec()) msgCommunityPoolSpend, ok := msg.(*pooltypes.MsgCommunityPoolSpend) assert.Assert(t, ok) diff --git a/x/slashing/simulation/proposals.go b/x/slashing/simulation/proposals.go index 7cad19e47d70..407f8084ccbd 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, addressCodec coreaddress.Codec) sdk.Msg { // use the default gov module account address as authority var authority sdk.AccAddress = address.Module("gov") diff --git a/x/slashing/simulation/proposals_test.go b/x/slashing/simulation/proposals_test.go index 4ac72eb63717..3d3ec3a38567 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,7 @@ 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 := w0.MsgSimulatorFn()(r, ctx, accounts, codectestutil.CodecOptions{}.GetAddressCodec()) msgUpdateParams, ok := msg.(*types.MsgUpdateParams) assert.Assert(t, ok) diff --git a/x/staking/keeper/cons_pubkey_test.go b/x/staking/keeper/cons_pubkey_test.go index 2d32be54a0d4..55b8f7a7465f 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(), s.valAddressToString(addrVals[0]), 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) @@ -167,8 +168,9 @@ 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(), addr, issuedShares) + 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) diff --git a/x/staking/keeper/delegation_test.go b/x/staking/keeper/delegation_test.go index ff8ccf8c303a..0768485815b4 100644 --- a/x/staking/keeper/delegation_test.go +++ b/x/staking/keeper/delegation_test.go @@ -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(), s.valAddressToString(valAddrs[0]), 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(), s.valAddressToString(valAddrs[0]), 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(), s.valAddressToString(valAddrs[0]), 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(), s.valAddressToString(valAddrs[0]), 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(), s.valAddressToString(valAddrs[0]), 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(), s.valAddressToString(valAddrs[0]), issuedShares) + delegation := stakingtypes.NewDelegation(s.addressToString(delAddrs[0]), s.valAddressToString(valAddrs[0]), issuedShares) require.NoError(keeper.SetDelegation(ctx, delegation)) bondTokens := keeper.TokensFromConsensusPower(ctx, 6) @@ -419,7 +419,7 @@ func (s *KeeperTestSuite) TestUndelegateSelfDelegationBelowMinSelfDelegation() { require.NoError(keeper.SetValidatorByConsAddr(ctx, validator)) require.True(validator.IsBonded()) - selfDelegation := stakingtypes.NewDelegation(sdk.AccAddress(valAddrs[0].Bytes()).String(), s.valAddressToString(valAddrs[0]), 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,7 +429,7 @@ func (s *KeeperTestSuite) TestUndelegateSelfDelegationBelowMinSelfDelegation() { require.Equal(delTokens, issuedShares.RoundInt()) validator = stakingkeeper.TestingUpdateValidator(keeper, ctx, validator, true) - delegation := stakingtypes.NewDelegation(addrDels[0].String(), s.valAddressToString(valAddrs[0]), issuedShares) + delegation := stakingtypes.NewDelegation(s.addressToString(addrDels[0]), s.valAddressToString(valAddrs[0]), issuedShares) require.NoError(keeper.SetDelegation(ctx, delegation)) val0AccAddr := sdk.AccAddress(valAddrs[0].Bytes()) @@ -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(), s.valAddressToString(addrVals[0]), 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(), s.valAddressToString(addrVals[0]), 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(), s.valAddressToString(addrVals[0]), 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(), s.valAddressToString(addrVals[0]), 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(), s.valAddressToString(addrVals[0]), 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(), s.valAddressToString(addrVals[0]), 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(), s.valAddressToString(addrVals[0]), 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(), s.valAddressToString(addrVals[0]), 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(), s.valAddressToString(addrVals[0]), 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(), s.valAddressToString(addrVals[0]), 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(), s.valAddressToString(addrVals[0]), 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(), s.valAddressToString(addrVals[0]), issuedShares) + delegation := stakingtypes.NewDelegation(s.addressToString(addrDels[1]), s.valAddressToString(addrVals[0]), issuedShares) require.NoError(keeper.SetDelegation(ctx, delegation)) // create a second validator @@ -1006,7 +1006,7 @@ func (s *KeeperTestSuite) TestRedelegateFromUnbondedValidator() { s.bankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), stakingtypes.NotBondedPoolName, stakingtypes.BondedPoolName, gomock.Any()) validator = stakingkeeper.TestingUpdateValidator(keeper, ctx, validator, true) val0AccAddr := sdk.AccAddress(valAddrs[0].Bytes()) - selfDelegation := stakingtypes.NewDelegation(val0AccAddr.String(), s.valAddressToString(valAddrs[0]), issuedShares) + 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,7 +1015,7 @@ 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(), s.valAddressToString(valAddrs[0]), issuedShares) + delegation := stakingtypes.NewDelegation(s.addressToString(addrDels[1]), s.valAddressToString(valAddrs[0]), issuedShares) require.NoError(keeper.SetDelegation(ctx, delegation)) // create a second validator @@ -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(), s.valAddressToString(valAddrs[0]), 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(), s.valAddressToString(valAddrs[0]), 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(), s.valAddressToString(valAddrs[0]), 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 0016ddbec274..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"), ) @@ -360,7 +361,7 @@ func (s *KeeperTestSuite) TestUnbondingDelegationsMigrationToColls() { 100, func(i int64) { ubd := stakingtypes.UnbondingDelegation{ - DelegatorAddress: delAddrs[i].String(), + DelegatorAddress: s.addressToString(delAddrs[i]), ValidatorAddress: s.valAddressToString(valAddrs[i]), Entries: []stakingtypes.UnbondingDelegationEntry{ { @@ -385,7 +386,7 @@ func (s *KeeperTestSuite) TestUnbondingDelegationsMigrationToColls() { 100, func(i int64) { ubd := stakingtypes.UnbondingDelegation{ - DelegatorAddress: delAddrs[i].String(), + DelegatorAddress: s.addressToString(delAddrs[i]), ValidatorAddress: s.valAddressToString(valAddrs[i]), Entries: []stakingtypes.UnbondingDelegationEntry{ { @@ -545,7 +546,7 @@ func (s *KeeperTestSuite) TestRedelegationQueueMigrationToColls() { dvvTriplets := stakingtypes.DVVTriplets{ Triplets: []stakingtypes.DVVTriplet{ { - DelegatorAddress: addrs[i].String(), + DelegatorAddress: s.addressToString(addrs[i]), ValidatorSrcAddress: s.valAddressToString(valAddrs[i]), ValidatorDstAddress: s.valAddressToString(valAddrs[i+1]), }, @@ -568,7 +569,7 @@ func (s *KeeperTestSuite) TestRedelegationQueueMigrationToColls() { dvvTriplets := stakingtypes.DVVTriplets{ Triplets: []stakingtypes.DVVTriplet{ { - DelegatorAddress: addrs[i].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 2f0de367ef67..b13bbca6d40e 100644 --- a/x/staking/keeper/msg_server_test.go +++ b/x/staking/keeper/msg_server_test.go @@ -70,7 +70,7 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { MaxChangeRate: math.LegacyNewDec(0), }, MinSelfDelegation: math.NewInt(1), - DelegatorAddress: Addr.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,7 +110,7 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { MaxChangeRate: math.LegacyNewDec(0), }, MinSelfDelegation: math.NewInt(1), - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: nil, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000), @@ -130,7 +130,7 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { MaxChangeRate: math.LegacyNewDec(0), }, MinSelfDelegation: math.NewInt(1), - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkeyInvalidLen, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000), @@ -150,7 +150,7 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { MaxChangeRate: math.LegacyNewDec(0), }, MinSelfDelegation: math.NewInt(1), - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkey, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 0), @@ -170,7 +170,7 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { MaxChangeRate: math.LegacyNewDec(0), }, MinSelfDelegation: math.NewInt(1), - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkey, Value: sdk.Coin{}, @@ -190,7 +190,7 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { MaxChangeRate: math.LegacyNewDec(0), }, MinSelfDelegation: math.NewInt(0), - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkey, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000), @@ -210,7 +210,7 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { MaxChangeRate: math.LegacyNewDec(0), }, MinSelfDelegation: math.NewInt(-1), - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkey, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000), @@ -230,7 +230,7 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { MaxChangeRate: math.LegacyNewDec(0), }, MinSelfDelegation: math.NewInt(100), - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkey, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 10), @@ -254,7 +254,7 @@ func (s *KeeperTestSuite) TestMsgCreateValidator() { MaxChangeRate: math.LegacyNewDec(0), }, MinSelfDelegation: math.NewInt(1), - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Pubkey: pubkey, Value: sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000), @@ -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, }, @@ -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, @@ -507,7 +507,7 @@ func (s *KeeperTestSuite) TestMsgDelegate() { { name: "validator does not exist", input: &types.MsgDelegate{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString([]byte("val")), Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))}, }, @@ -517,7 +517,7 @@ func (s *KeeperTestSuite) TestMsgDelegate() { { name: "zero amount", input: &types.MsgDelegate{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(0))}, }, @@ -527,7 +527,7 @@ func (s *KeeperTestSuite) TestMsgDelegate() { { name: "negative amount", input: &types.MsgDelegate{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(-1))}, }, @@ -537,7 +537,7 @@ func (s *KeeperTestSuite) TestMsgDelegate() { { name: "invalid BondDenom", input: &types.MsgDelegate{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.Coin{Denom: "test", Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))}, }, @@ -547,7 +547,7 @@ func (s *KeeperTestSuite) TestMsgDelegate() { { name: "valid msg", input: &types.MsgDelegate{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: keeper.TokensFromConsensusPower(s.ctx, int64(100))}, }, @@ -601,7 +601,7 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { require.NotNil(res) shares := math.LegacyNewDec(100) - del := types.NewDelegation(Addr.String(), s.valAddressToString(srcValAddr), 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,8 +615,8 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { { name: "invalid source validator", input: &types.MsgBeginRedelegate{ - DelegatorAddress: Addr.String(), - ValidatorSrcAddress: sdk.AccAddress([]byte("invalid")).String(), + DelegatorAddress: s.addressToString(Addr), + ValidatorSrcAddress: s.addressToString([]byte("invalid")), ValidatorDstAddress: s.valAddressToString(dstValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), }, @@ -648,9 +648,9 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { { name: "invalid destination validator", input: &types.MsgBeginRedelegate{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorSrcAddress: s.valAddressToString(srcValAddr), - ValidatorDstAddress: sdk.AccAddress([]byte("invalid")).String(), + ValidatorDstAddress: s.addressToString([]byte("invalid")), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), }, expErr: true, @@ -659,7 +659,7 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { { name: "validator does not exist", input: &types.MsgBeginRedelegate{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorSrcAddress: s.valAddressToString(sdk.ValAddress([]byte("invalid"))), ValidatorDstAddress: s.valAddressToString(dstValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), @@ -670,7 +670,7 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { { name: "self redelegation", input: &types.MsgBeginRedelegate{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorSrcAddress: s.valAddressToString(srcValAddr), ValidatorDstAddress: s.valAddressToString(srcValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), @@ -681,7 +681,7 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { { name: "amount greater than delegated shares amount", input: &types.MsgBeginRedelegate{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorSrcAddress: s.valAddressToString(srcValAddr), ValidatorDstAddress: s.valAddressToString(dstValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(101)), @@ -692,7 +692,7 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { { name: "zero amount", input: &types.MsgBeginRedelegate{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorSrcAddress: s.valAddressToString(srcValAddr), ValidatorDstAddress: s.valAddressToString(dstValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(0)), @@ -703,7 +703,7 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { { name: "invalid coin denom", input: &types.MsgBeginRedelegate{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorSrcAddress: s.valAddressToString(srcValAddr), ValidatorDstAddress: s.valAddressToString(dstValAddr), Amount: sdk.NewCoin("test", shares.RoundInt()), @@ -714,7 +714,7 @@ func (s *KeeperTestSuite) TestMsgBeginRedelegate() { { name: "valid msg", input: &types.MsgBeginRedelegate{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorSrcAddress: s.valAddressToString(srcValAddr), ValidatorDstAddress: s.valAddressToString(dstValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), @@ -755,7 +755,7 @@ func (s *KeeperTestSuite) TestMsgUndelegate() { require.NotNil(res) shares := math.LegacyNewDec(100) - del := types.NewDelegation(Addr.String(), s.valAddressToString(ValAddr), 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, @@ -799,7 +799,7 @@ func (s *KeeperTestSuite) TestMsgUndelegate() { { name: "validator does not exist", input: &types.MsgUndelegate{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString([]byte("invalid")), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), }, @@ -809,7 +809,7 @@ func (s *KeeperTestSuite) TestMsgUndelegate() { { name: "amount greater than delegated shares amount", input: &types.MsgUndelegate{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(101)), }, @@ -819,7 +819,7 @@ func (s *KeeperTestSuite) TestMsgUndelegate() { { name: "zero amount", input: &types.MsgUndelegate{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(0)), }, @@ -829,7 +829,7 @@ func (s *KeeperTestSuite) TestMsgUndelegate() { { name: "invalid coin denom", input: &types.MsgUndelegate{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin("test", shares.RoundInt()), }, @@ -839,7 +839,7 @@ func (s *KeeperTestSuite) TestMsgUndelegate() { { name: "valid msg", input: &types.MsgUndelegate{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), }, @@ -880,7 +880,7 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { require.NotNil(res) shares := math.LegacyNewDec(100) - del := types.NewDelegation(Addr.String(), s.valAddressToString(ValAddr), 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, }, @@ -934,7 +934,7 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { { name: "entry not found at height", input: &types.MsgCancelUnbondingDelegation{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), CreationHeight: 11, @@ -945,7 +945,7 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { { name: "invalid height", input: &types.MsgCancelUnbondingDelegation{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), CreationHeight: -1, @@ -956,7 +956,7 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { { name: "invalid coin", input: &types.MsgCancelUnbondingDelegation{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin("test", shares.RoundInt()), CreationHeight: 10, @@ -967,7 +967,7 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { { name: "validator does not exist", input: &types.MsgCancelUnbondingDelegation{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString([]byte("invalid")), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), CreationHeight: 10, @@ -978,7 +978,7 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { { name: "amount is greater than balance", input: &types.MsgCancelUnbondingDelegation{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(101)), CreationHeight: 10, @@ -989,7 +989,7 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { { name: "zero amount", input: &types.MsgCancelUnbondingDelegation{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(0)), CreationHeight: 10, @@ -1000,7 +1000,7 @@ func (s *KeeperTestSuite) TestMsgCancelUnbondingDelegation() { { name: "valid msg", input: &types.MsgCancelUnbondingDelegation{ - DelegatorAddress: Addr.String(), + DelegatorAddress: s.addressToString(Addr), ValidatorAddress: s.valAddressToString(ValAddr), Amount: sdk.NewCoin(sdk.DefaultBondDenom, shares.RoundInt()), CreationHeight: 10, diff --git a/x/staking/migrations/v5/migrations_test.go b/x/staking/migrations/v5/migrations_test.go index cb8cdbc2b481..66d51205e740 100644 --- a/x/staking/migrations/v5/migrations_test.go +++ b/x/staking/migrations/v5/migrations_test.go @@ -97,7 +97,9 @@ func TestDelegationsByValidatorMigrations(t *testing.T) { assert.NoError(t, err) for i := 1; i < 11; i++ { - del1 := stakingtypes.NewDelegation(accAddrs[i].String(), valAddr, 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) } diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index fa557087deba..b4c2723337b4 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -348,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, @@ -557,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) diff --git a/x/staking/simulation/proposals.go b/x/staking/simulation/proposals.go index ec26aa3683ad..98ddb464b35a 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,8 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { } // SimulateMsgUpdateParams returns a random MsgUpdateParams -func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) sdk.Msg { +// TODO: return errors +func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, addressCodec coreaddress.Codec) sdk.Msg { // use the default gov module account address as authority var authority sdk.AccAddress = address.Module("gov") @@ -44,8 +46,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 &types.MsgUpdateParams{ - Authority: authority.String(), + Authority: addr, Params: params, } } diff --git a/x/staking/simulation/proposals_test.go b/x/staking/simulation/proposals_test.go index 88637a73383b..5991e2784d29 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,14 @@ 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 := w0.MsgSimulatorFn()(r, ctx, accounts, addressCodec) 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/types/delegation_test.go b/x/staking/types/delegation_test.go index 7680c0a9b2f6..3452ce51744c 100644 --- a/x/staking/types/delegation_test.go +++ b/x/staking/types/delegation_test.go @@ -56,7 +56,7 @@ func TestUnbondingDelegationEqual(t *testing.T) { ok := ubd1.String() == ubd2.String() require.True(t, ok) - vAddr3, err := codectestutil.CodecOptions{}.GetValidatorCodec().BytesToString(valAddr2) + vAddr3, err := codectestutil.CodecOptions{}.GetValidatorCodec().BytesToString(valAddr3) require.NoError(t, err) ubd2.ValidatorAddress = vAddr3 From a43f4b1d503a067528aeb27e07d392896841349a Mon Sep 17 00:00:00 2001 From: Julian Toledano Date: Wed, 13 Mar 2024 11:07:29 +0100 Subject: [PATCH 03/17] update: MsgSimulatorFn returns error --- tests/sims/gov/operations_test.go | 4 ++-- types/simulation/types.go | 2 +- x/auth/simulation/proposals.go | 4 ++-- x/auth/simulation/proposals_test.go | 3 ++- x/bank/simulation/proposals.go | 4 ++-- x/bank/simulation/proposals_test.go | 3 ++- x/distribution/simulation/proposals.go | 4 ++-- x/distribution/simulation/proposals_test.go | 3 ++- x/gov/simulation/operations.go | 5 ++++- x/gov/simulation/proposals.go | 4 ++-- x/gov/simulation/proposals_test.go | 3 ++- x/mint/simulation/proposals.go | 4 ++-- x/mint/simulation/proposals_test.go | 3 ++- x/protocolpool/simulation/proposals.go | 4 ++-- x/protocolpool/simulation/proposals_test.go | 3 ++- x/slashing/simulation/proposals.go | 4 ++-- x/slashing/simulation/proposals_test.go | 3 ++- x/staking/simulation/proposals.go | 7 +++---- x/staking/simulation/proposals_test.go | 3 ++- 19 files changed, 40 insertions(+), 30 deletions(-) diff --git a/tests/sims/gov/operations_test.go b/tests/sims/gov/operations_test.go index 94409159bfbb..972aedec6055 100644 --- a/tests/sims/gov/operations_test.go +++ b/tests/sims/gov/operations_test.go @@ -56,8 +56,8 @@ func (m MockWeightedProposals) DefaultWeight() int { } func (m MockWeightedProposals) MsgSimulatorFn() simtypes.MsgSimulatorFn { - return func(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, _ address.Codec) sdk.Msg { - return nil + return func(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, _ address.Codec) (sdk.Msg, error) { + return nil, nil } } diff --git a/types/simulation/types.go b/types/simulation/types.go index 922e16494628..15bcb2bef155 100644 --- a/types/simulation/types.go +++ b/types/simulation/types.go @@ -41,7 +41,7 @@ type WeightedProposalMsg interface { MsgSimulatorFn() MsgSimulatorFn // msg simulator function } -type MsgSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []Account, cdc address.Codec) 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/proposals.go b/x/auth/simulation/proposals.go index e7980616965d..5a05ecc069a2 100644 --- a/x/auth/simulation/proposals.go +++ b/x/auth/simulation/proposals.go @@ -31,7 +31,7 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { } // SimulateMsgUpdateParams returns a random MsgUpdateParams -func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, addressCodec coreaddress.Codec) 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") @@ -45,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 b60b19f4e4ff..6a1168afd593 100644 --- a/x/auth/simulation/proposals_test.go +++ b/x/auth/simulation/proposals_test.go @@ -33,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, codectestutil.CodecOptions{}.GetAddressCodec()) + 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/bank/simulation/proposals.go b/x/bank/simulation/proposals.go index 64028fdaebc2..2c12a173d5b0 100644 --- a/x/bank/simulation/proposals.go +++ b/x/bank/simulation/proposals.go @@ -31,7 +31,7 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { } // SimulateMsgUpdateParams returns a random MsgUpdateParams -func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, addressCodec coreaddress.Codec) 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") @@ -41,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 1f17f7286722..479d55488e48 100644 --- a/x/bank/simulation/proposals_test.go +++ b/x/bank/simulation/proposals_test.go @@ -33,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, codectestutil.CodecOptions{}.GetAddressCodec()) + 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/proposals.go b/x/distribution/simulation/proposals.go index f28e63c4a933..61a4cc25bb41 100644 --- a/x/distribution/simulation/proposals.go +++ b/x/distribution/simulation/proposals.go @@ -32,7 +32,7 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { } // SimulateMsgUpdateParams returns a random MsgUpdateParams -func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, addressCodec coreaddress.Codec) 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") @@ -43,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 3b8598913cd9..cd9a4b81b35a 100644 --- a/x/distribution/simulation/proposals_test.go +++ b/x/distribution/simulation/proposals_test.go @@ -34,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, codectestutil.CodecOptions{}.GetAddressCodec()) + 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/gov/simulation/operations.go b/x/gov/simulation/operations.go index 0b9d76b18fe4..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, ak.AddressCodec()) + 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 049c59adf0de..0162aa3e1617 100644 --- a/x/gov/simulation/proposals.go +++ b/x/gov/simulation/proposals.go @@ -27,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, addressCodec coreaddress.Codec) sdk.Msg { - return nil +func SimulateTextProposal(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, addressCodec 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 9b81a064829e..42ef52a7db9d 100644 --- a/x/gov/simulation/proposals_test.go +++ b/x/gov/simulation/proposals_test.go @@ -31,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, codectestutil.CodecOptions{}.GetAddressCodec()) + msg, err := w0.MsgSimulatorFn()(r, ctx, accounts, codectestutil.CodecOptions{}.GetAddressCodec()) + assert.NilError(t, err) assert.Assert(t, msg == nil) } diff --git a/x/mint/simulation/proposals.go b/x/mint/simulation/proposals.go index 6026077c9499..185f24da3b93 100644 --- a/x/mint/simulation/proposals.go +++ b/x/mint/simulation/proposals.go @@ -32,7 +32,7 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { } // SimulateMsgUpdateParams returns a random MsgUpdateParams -func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, addressCodec coreaddress.Codec) 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") @@ -47,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 111548f8aa3c..42d604b3e005 100644 --- a/x/mint/simulation/proposals_test.go +++ b/x/mint/simulation/proposals_test.go @@ -34,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, codectestutil.CodecOptions{}.GetAddressCodec()) + 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/protocolpool/simulation/proposals.go b/x/protocolpool/simulation/proposals.go index 928dd03e9768..ef8ec43481de 100644 --- a/x/protocolpool/simulation/proposals.go +++ b/x/protocolpool/simulation/proposals.go @@ -28,7 +28,7 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { } } -func SimulateMsgCommunityPoolSpend(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, addressCodec coreaddress.Codec) sdk.Msg { +func SimulateMsgCommunityPoolSpend(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,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 9454b6b6eaea..4cef1da31bdc 100644 --- a/x/protocolpool/simulation/proposals_test.go +++ b/x/protocolpool/simulation/proposals_test.go @@ -33,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, codectestutil.CodecOptions{}.GetAddressCodec()) + 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/proposals.go b/x/slashing/simulation/proposals.go index 407f8084ccbd..2526b9d6f2fc 100644 --- a/x/slashing/simulation/proposals.go +++ b/x/slashing/simulation/proposals.go @@ -33,7 +33,7 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { } // SimulateMsgUpdateParams returns a random MsgUpdateParams -func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, addressCodec coreaddress.Codec) 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") @@ -47,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 3d3ec3a38567..eb63a817ac6d 100644 --- a/x/slashing/simulation/proposals_test.go +++ b/x/slashing/simulation/proposals_test.go @@ -35,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, codectestutil.CodecOptions{}.GetAddressCodec()) + 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/simulation/proposals.go b/x/staking/simulation/proposals.go index 98ddb464b35a..9a74e2509bd3 100644 --- a/x/staking/simulation/proposals.go +++ b/x/staking/simulation/proposals.go @@ -33,8 +33,7 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { } // SimulateMsgUpdateParams returns a random MsgUpdateParams -// TODO: return errors -func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, addressCodec coreaddress.Codec) 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") @@ -48,11 +47,11 @@ func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, addr, err := addressCodec.BytesToString(authority) if err != nil { - + return nil, err } return &types.MsgUpdateParams{ Authority: addr, Params: params, - } + }, nil } diff --git a/x/staking/simulation/proposals_test.go b/x/staking/simulation/proposals_test.go index 5991e2784d29..359a218b484e 100644 --- a/x/staking/simulation/proposals_test.go +++ b/x/staking/simulation/proposals_test.go @@ -35,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, addressCodec) + msg, err := w0.MsgSimulatorFn()(r, ctx, accounts, addressCodec) + assert.NilError(t, err) msgUpdateParams, ok := msg.(*types.MsgUpdateParams) assert.Assert(t, ok) From 20469b427dc952c935637380f0467ed86e6632ff Mon Sep 17 00:00:00 2001 From: Julian Toledano Date: Wed, 13 Mar 2024 11:17:50 +0100 Subject: [PATCH 04/17] del: remove ConsAddress.String() --- x/staking/simulation/operations.go | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index b4c2723337b4..5358c910a900 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -774,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 } From 45a3a3cd4fe5d3f1b2618c41c0d42a5a71a298be Mon Sep 17 00:00:00 2001 From: Julian Toledano Date: Wed, 13 Mar 2024 11:45:15 +0100 Subject: [PATCH 05/17] fix: TestUnbondingValidator --- x/staking/keeper/validator_test.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/x/staking/keeper/validator_test.go b/x/staking/keeper/validator_test.go index 9aa2c36cbec5..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{s.valAddressToString(ValAddr)})) + 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(s.valAddressToString(ValAddr), 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(s.valAddressToString(ValAddr), 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{s.valAddressToString(ValAddr)})) + 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 From 5e0c525a9d57a946cc919c2aac6b166252f9abd1 Mon Sep 17 00:00:00 2001 From: Julian Toledano Date: Wed, 13 Mar 2024 13:00:50 +0100 Subject: [PATCH 06/17] CHANGELOG --- x/staking/CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/x/staking/CHANGELOG.md b/x/staking/CHANGELOG.md index 4e635690e03c..7b7f182a0243 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. * [#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` * remove from `Keeper`: `GetParams`, `SetParams` From 6b1122588141789acfe8cb079794739b8563af3f Mon Sep 17 00:00:00 2001 From: Julian Toledano Date: Wed, 13 Mar 2024 13:01:44 +0100 Subject: [PATCH 07/17] update: SimulateMsgUpdateParams blank identifier --- x/auth/simulation/proposals.go | 2 +- x/bank/simulation/proposals.go | 2 +- x/distribution/simulation/proposals.go | 2 +- x/gov/simulation/proposals.go | 2 +- x/mint/simulation/proposals.go | 2 +- x/protocolpool/simulation/proposals.go | 2 +- x/slashing/simulation/proposals.go | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/x/auth/simulation/proposals.go b/x/auth/simulation/proposals.go index 5a05ecc069a2..148753163ad0 100644 --- a/x/auth/simulation/proposals.go +++ b/x/auth/simulation/proposals.go @@ -31,7 +31,7 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { } // SimulateMsgUpdateParams returns a random MsgUpdateParams -func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, addressCodec coreaddress.Codec) (sdk.Msg, error) { +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") diff --git a/x/bank/simulation/proposals.go b/x/bank/simulation/proposals.go index 2c12a173d5b0..18340ded35af 100644 --- a/x/bank/simulation/proposals.go +++ b/x/bank/simulation/proposals.go @@ -31,7 +31,7 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { } // SimulateMsgUpdateParams returns a random MsgUpdateParams -func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, addressCodec coreaddress.Codec) (sdk.Msg, error) { +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") diff --git a/x/distribution/simulation/proposals.go b/x/distribution/simulation/proposals.go index 61a4cc25bb41..fadbf3bb93ef 100644 --- a/x/distribution/simulation/proposals.go +++ b/x/distribution/simulation/proposals.go @@ -32,7 +32,7 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { } // SimulateMsgUpdateParams returns a random MsgUpdateParams -func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, addressCodec coreaddress.Codec) (sdk.Msg, error) { +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") diff --git a/x/gov/simulation/proposals.go b/x/gov/simulation/proposals.go index 0162aa3e1617..91b5d67e7b85 100644 --- a/x/gov/simulation/proposals.go +++ b/x/gov/simulation/proposals.go @@ -27,7 +27,7 @@ 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, addressCodec coreaddress.Codec) (sdk.Msg, error) { +func SimulateTextProposal(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, _ coreaddress.Codec) (sdk.Msg, error) { return nil, nil } diff --git a/x/mint/simulation/proposals.go b/x/mint/simulation/proposals.go index 185f24da3b93..9ba75b4a6615 100644 --- a/x/mint/simulation/proposals.go +++ b/x/mint/simulation/proposals.go @@ -32,7 +32,7 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { } // SimulateMsgUpdateParams returns a random MsgUpdateParams -func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, addressCodec coreaddress.Codec) (sdk.Msg, error) { +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") diff --git a/x/protocolpool/simulation/proposals.go b/x/protocolpool/simulation/proposals.go index ef8ec43481de..224a9f8fb535 100644 --- a/x/protocolpool/simulation/proposals.go +++ b/x/protocolpool/simulation/proposals.go @@ -28,7 +28,7 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { } } -func SimulateMsgCommunityPoolSpend(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, addressCodec coreaddress.Codec) (sdk.Msg, error) { +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") diff --git a/x/slashing/simulation/proposals.go b/x/slashing/simulation/proposals.go index 2526b9d6f2fc..1a6e60f012ea 100644 --- a/x/slashing/simulation/proposals.go +++ b/x/slashing/simulation/proposals.go @@ -33,7 +33,7 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg { } // SimulateMsgUpdateParams returns a random MsgUpdateParams -func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, addressCodec coreaddress.Codec) (sdk.Msg, error) { +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") From d10707f17d8ad6c95c3c37909186bc518ec1257e Mon Sep 17 00:00:00 2001 From: Julian Toledano Date: Wed, 13 Mar 2024 13:14:34 +0100 Subject: [PATCH 08/17] UPGRADING --- UPGRADING.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/UPGRADING.md b/UPGRADING.md index 1519b8f80efc..a797a867f73a 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -143,6 +143,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. From ec42726efbd41a9480cab028aba925bf45657d67 Mon Sep 17 00:00:00 2001 From: Julian Toledano Date: Wed, 13 Mar 2024 14:45:50 +0100 Subject: [PATCH 09/17] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c08fd6566c3..09db996a0b20 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -97,6 +97,7 @@ 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) `MsgSimulatorFn` now takes an `address.Codec`as argument and also returns an error. * (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. From ebb185cf74974d5e9f29b9bee07833598069f7cd Mon Sep 17 00:00:00 2001 From: Julian Toledano Date: Wed, 13 Mar 2024 17:08:09 +0100 Subject: [PATCH 10/17] fix: typo --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e40ea55c1fb..40c953dec9e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -99,7 +99,7 @@ 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) `MsgSimulatorFn` now takes an `address.Codec`as argument and also returns an error. +* (types) [#19742](https://github.com/cosmos/cosmos-sdk/pull/19742) `MsgSimulatorFn` now takes an `address.Codec` as argument and also returns an error. * (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. From 5b5d080a95fe3da51076ff580436624f6b2d0c57 Mon Sep 17 00:00:00 2001 From: Julian Toledano Date: Thu, 14 Mar 2024 09:37:29 +0100 Subject: [PATCH 11/17] update CHANGELOG --- CHANGELOG.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 40c953dec9e3..428465f44611 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -99,7 +99,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) `MsgSimulatorFn` now takes an `address.Codec` as argument and also returns an error. +* (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. From 7f804f282fd8e3421c438ed6eb67e0a7ef711a69 Mon Sep 17 00:00:00 2001 From: Julian Toledano Date: Fri, 15 Mar 2024 10:45:20 +0100 Subject: [PATCH 12/17] del: ValAddressFromBech32 --- x/staking/keeper/cons_pubkey_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/x/staking/keeper/cons_pubkey_test.go b/x/staking/keeper/cons_pubkey_test.go index 55b8f7a7465f..6404f3edccae 100644 --- a/x/staking/keeper/cons_pubkey_test.go +++ b/x/staking/keeper/cons_pubkey_test.go @@ -41,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) @@ -58,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, @@ -75,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, From 70b09b8fe1647c6aeaf165f52e37221ef2ec9d09 Mon Sep 17 00:00:00 2001 From: Julian Toledano Date: Fri, 15 Mar 2024 12:09:37 +0100 Subject: [PATCH 13/17] del: remove ValAddress.String --- x/authz/client/cli/tx_test.go | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/x/authz/client/cli/tx_test.go b/x/authz/client/cli/tx_test.go index a9c4d87a96f6..851bc609bcc8 100644 --- a/x/authz/client/cli/tx_test.go +++ b/x/authz/client/cli/tx_test.go @@ -182,6 +182,8 @@ func (s *CLITestSuite) msgSendExec(grantee sdk.AccAddress) { func (s *CLITestSuite) TestCLITxGrantAuthorization() { val := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) + valAddress, err := s.clientCtx.ValidatorAddressCodec.BytesToString(s.addrs[0]) + s.Require().NoError(err) grantee := s.grantee[0] @@ -271,7 +273,7 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, sdk.ValAddress(s.addrs[0]).String()), + fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, valAddress), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, true, @@ -287,7 +289,7 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", cli.FlagDenyValidators, sdk.ValAddress(s.addrs[0]).String()), + fmt.Sprintf("--%s=%s", cli.FlagDenyValidators, valAddress), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, true, @@ -303,7 +305,7 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, sdk.ValAddress(s.addrs[0]).String()), + fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, valAddress), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, true, @@ -319,7 +321,7 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, sdk.ValAddress(s.addrs[0]).String()), + fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, valAddress), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, true, @@ -335,7 +337,7 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), - fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, sdk.ValAddress(s.addrs[0]).String()), + fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, valAddress), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), }, true, From 47815f98d12d8858462e724ff664d40c31657ef6 Mon Sep 17 00:00:00 2001 From: Julian Toledano Date: Mon, 18 Mar 2024 12:24:14 +0100 Subject: [PATCH 14/17] del: remove AccAddress String --- x/authz/CHANGELOG.md | 1 + x/authz/client/cli/tx.go | 17 +++-- x/authz/client/cli/tx_test.go | 92 +++++++++++++++----------- x/authz/keeper/grpc_query_test.go | 51 +++++++++------ x/authz/keeper/keeper.go | 25 ++++++-- x/authz/keeper/keeper_test.go | 52 +++++++++------ x/authz/keeper/msg_server_test.go | 103 ++++++++++++++++++------------ x/authz/module/abci_test.go | 7 +- x/authz/msgs.go | 16 ++--- x/authz/simulation/genesis.go | 11 ++-- x/authz/simulation/operations.go | 22 ++++++- 11 files changed, 251 insertions(+), 146 deletions(-) diff --git a/x/authz/CHANGELOG.md b/x/authz/CHANGELOG.md index e6de2c18baca..2e9073e4ddc2 100644 --- a/x/authz/CHANGELOG.md +++ b/x/authz/CHANGELOG.md @@ -31,6 +31,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### API Breaking Changes +* []() `NewMsgExec`, `NewMsgGrant` and `NewMsgRevoke` now takes strings as arguments instead of `sdk.AccAddress`. * [#19637](https://github.com/cosmos/cosmos-sdk/pull/19637) `NewKeeper` doesn't take a message router anymore. Set the message router in the `appmodule.Environment` instead. * [#19490](https://github.com/cosmos/cosmos-sdk/pull/19490) `appmodule.Environment` is received on the Keeper to get access to different application services. * [#18737](https://github.com/cosmos/cosmos-sdk/pull/18737) Update the keeper method `DequeueAndDeleteExpiredGrants` to take a limit argument for the number of grants to prune. diff --git a/x/authz/client/cli/tx.go b/x/authz/client/cli/tx.go index 6227785b067a..75dbc2db03c8 100644 --- a/x/authz/client/cli/tx.go +++ b/x/authz/client/cli/tx.go @@ -67,7 +67,10 @@ func NewCmdExecAuthorization() *cobra.Command { if err != nil { return err } - grantee := clientCtx.GetFromAddress() + grantee, err := clientCtx.AddressCodec.BytesToString(clientCtx.GetFromAddress()) + if err != nil { + return err + } if offline, _ := cmd.Flags().GetBool(flags.FlagOffline); offline { return errors.New("cannot broadcast tx during offline mode") @@ -106,14 +109,14 @@ Examples: return err } - if strings.EqualFold(args[0], clientCtx.GetFromAddress().String()) { - return errors.New("grantee and granter should be different") - } - - grantee, err := clientCtx.AddressCodec.StringToBytes(args[0]) + grantee := args[0] + granter, err := clientCtx.AddressCodec.BytesToString(clientCtx.GetFromAddress()) if err != nil { return err } + if strings.EqualFold(args[0], granter) { + return errors.New("grantee and granter should be different") + } var authorization authz.Authorization switch args[1] { @@ -230,7 +233,7 @@ Examples: return err } - msg, err := authz.NewMsgGrant(clientCtx.GetFromAddress(), grantee, authorization, expire) + msg, err := authz.NewMsgGrant(granter, grantee, authorization, expire) if err != nil { return err } diff --git a/x/authz/client/cli/tx_test.go b/x/authz/client/cli/tx_test.go index 851bc609bcc8..bdb963a102a2 100644 --- a/x/authz/client/cli/tx_test.go +++ b/x/authz/client/cli/tx_test.go @@ -80,6 +80,8 @@ func (s *CLITestSuite) SetupSuite() { val := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) s.grantee = make([]sdk.AccAddress, 6) + valAddr, err := s.baseCtx.AddressCodec.BytesToString(val[0].Address) + s.Require().NoError(err) s.addrs = make([]sdk.AccAddress, 1) s.addrs[0] = s.createAccount("validator address") @@ -93,13 +95,15 @@ func (s *CLITestSuite) SetupSuite() { s.grantee[1] = s.createAccount("grantee2") // Send some funds to the new account. s.msgSendExec(s.grantee[1]) + grantee1Addr, err := s.baseCtx.AddressCodec.BytesToString(s.grantee[1]) + s.Require().NoError(err) // grant send authorization to grantee2 out, err := authzclitestutil.CreateGrant(s.clientCtx, []string{ - s.grantee[1].String(), + grantee1Addr, "send", fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=%s", flags.FlagFrom, valAddr), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(10))).String()), @@ -112,13 +116,15 @@ func (s *CLITestSuite) SetupSuite() { // Create new account in the keyring. s.grantee[2] = s.createAccount("grantee3") + grantee2Addr, err := s.baseCtx.AddressCodec.BytesToString(s.grantee[2]) + s.Require().NoError(err) // grant send authorization to grantee3 _, err = authzclitestutil.CreateGrant(s.clientCtx, []string{ - s.grantee[2].String(), + grantee2Addr, "send", fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=%s", flags.FlagFrom, valAddr), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(10))).String()), @@ -129,6 +135,8 @@ func (s *CLITestSuite) SetupSuite() { // Create new accounts in the keyring. s.grantee[3] = s.createAccount("grantee4") s.msgSendExec(s.grantee[3]) + grantee3Addr, err := s.baseCtx.AddressCodec.BytesToString(s.grantee[3]) + s.Require().NoError(err) s.grantee[4] = s.createAccount("grantee5") s.grantee[5] = s.createAccount("grantee6") @@ -136,11 +144,11 @@ func (s *CLITestSuite) SetupSuite() { // grant send authorization with allow list to grantee4 out, err = authzclitestutil.CreateGrant(s.clientCtx, []string{ - s.grantee[3].String(), + grantee3Addr, "send", fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=%s", flags.FlagFrom, valAddr), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, time.Now().Add(time.Minute*time.Duration(120)).Unix()), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), @@ -170,9 +178,13 @@ func (s *CLITestSuite) msgSendExec(grantee sdk.AccAddress) { coins := sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(200))) from := val[0].Address + fromAddr, err := s.clientCtx.AddressCodec.BytesToString(from) + s.Require().NoError(err) + granteeAddr, err := s.clientCtx.AddressCodec.BytesToString(grantee) + s.Require().NoError(err) msgSend := &banktypes.MsgSend{ - FromAddress: from.String(), - ToAddress: grantee.String(), + FromAddress: fromAddr, + ToAddress: granteeAddr, Amount: coins, } @@ -184,8 +196,12 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { val := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) valAddress, err := s.clientCtx.ValidatorAddressCodec.BytesToString(s.addrs[0]) s.Require().NoError(err) + fromAddr, err := s.baseCtx.AddressCodec.BytesToString(val[0].Address) + s.Require().NoError(err) grantee := s.grantee[0] + granteeAddr, err := s.baseCtx.AddressCodec.BytesToString(grantee) + s.Require().NoError(err) twoHours := time.Now().Add(time.Minute * 120).Unix() pastHour := time.Now().Add(-time.Minute * 60).Unix() @@ -215,7 +231,7 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { "grantee_addr", "send", fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=%s", flags.FlagFrom, fromAddr), fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), }, @@ -225,10 +241,10 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { { "Invalid spend limit", []string{ - grantee.String(), + granteeAddr, "send", fmt.Sprintf("--%s=0stake", cli.FlagSpendLimit), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=%s", flags.FlagFrom, fromAddr), fmt.Sprintf("--%s=true", flags.FlagGenerateOnly), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), }, @@ -238,10 +254,10 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { { "Invalid expiration time", []string{ - grantee.String(), + granteeAddr, "send", fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=%s", flags.FlagFrom, fromAddr), fmt.Sprintf("--%s=true", flags.FlagBroadcastMode), fmt.Sprintf("--%s=%d", cli.FlagExpiration, pastHour), }, @@ -251,10 +267,10 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { { "fail with error invalid msg-type", []string{ - grantee.String(), + granteeAddr, "generic", fmt.Sprintf("--%s=invalid-msg-type", cli.FlagMsgType), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=%s", flags.FlagFrom, fromAddr), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))).String()), @@ -266,11 +282,11 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { { "invalid bond denom for tx delegate authorization allowed validators", []string{ - grantee.String(), + granteeAddr, "delegate", fmt.Sprintf("--%s=100xyz", cli.FlagSpendLimit), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=%s", flags.FlagFrom, fromAddr), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, valAddress), @@ -282,11 +298,11 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { { "invalid bond denom for tx delegate authorization deny validators", []string{ - grantee.String(), + granteeAddr, "delegate", fmt.Sprintf("--%s=100xyz", cli.FlagSpendLimit), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=%s", flags.FlagFrom, fromAddr), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=%s", cli.FlagDenyValidators, valAddress), @@ -298,11 +314,11 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { { "invalid bond denom for tx undelegate authorization", []string{ - grantee.String(), + granteeAddr, "unbond", fmt.Sprintf("--%s=100xyz", cli.FlagSpendLimit), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=%s", flags.FlagFrom, fromAddr), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, valAddress), @@ -314,11 +330,11 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { { "invalid bond denom for tx redelegate authorization", []string{ - grantee.String(), + granteeAddr, "redelegate", fmt.Sprintf("--%s=100xyz", cli.FlagSpendLimit), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=%s", flags.FlagFrom, fromAddr), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, valAddress), @@ -330,11 +346,11 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { { "invalid decimal coin expression with more than single coin", []string{ - grantee.String(), + granteeAddr, "delegate", fmt.Sprintf("--%s=100stake,20xyz", cli.FlagSpendLimit), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=%s", flags.FlagFrom, fromAddr), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=%s", cli.FlagAllowedValidators, valAddress), @@ -346,7 +362,7 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { { "invalid authorization type", []string{ - grantee.String(), + granteeAddr, "invalid authz type", }, true, @@ -355,10 +371,10 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { { "Valid tx send authorization", []string{ - grantee.String(), + granteeAddr, "send", fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=%s", flags.FlagFrom, fromAddr), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), @@ -370,10 +386,10 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { { "Valid tx send authorization with allow list", []string{ - grantee.String(), + granteeAddr, "send", fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=%s", flags.FlagFrom, fromAddr), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), @@ -386,10 +402,10 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { { "Invalid tx send authorization with duplicate allow list", []string{ - grantee.String(), + granteeAddr, "send", fmt.Sprintf("--%s=100stake", cli.FlagSpendLimit), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=%s", flags.FlagFrom, fromAddr), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), @@ -402,10 +418,10 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { { "Valid tx generic authorization", []string{ - grantee.String(), + granteeAddr, "generic", fmt.Sprintf("--%s=%s", cli.FlagMsgType, typeMsgVote), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=%s", flags.FlagFrom, fromAddr), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), @@ -417,10 +433,10 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { { "fail when granter = grantee", []string{ - grantee.String(), + granteeAddr, "generic", fmt.Sprintf("--%s=%s", cli.FlagMsgType, typeMsgVote), - fmt.Sprintf("--%s=%s", flags.FlagFrom, grantee.String()), + fmt.Sprintf("--%s=%s", flags.FlagFrom, granteeAddr), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), @@ -432,10 +448,10 @@ func (s *CLITestSuite) TestCLITxGrantAuthorization() { { "Valid tx with amino", []string{ - grantee.String(), + granteeAddr, "generic", fmt.Sprintf("--%s=%s", cli.FlagMsgType, typeMsgVote), - fmt.Sprintf("--%s=%s", flags.FlagFrom, val[0].Address.String()), + fmt.Sprintf("--%s=%s", flags.FlagFrom, fromAddr), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%d", cli.FlagExpiration, twoHours), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), diff --git a/x/authz/keeper/grpc_query_test.go b/x/authz/keeper/grpc_query_test.go index be53c1df8e3f..6cb51dbae0f7 100644 --- a/x/authz/keeper/grpc_query_test.go +++ b/x/authz/keeper/grpc_query_test.go @@ -21,6 +21,11 @@ func (suite *TestSuite) TestGRPCQueryAuthorization() { expAuthorization authz.Authorization ) + addr0, err := suite.accountKeeper.AddressCodec().BytesToString(addrs[0]) + suite.Require().NoError(err) + addr1, err := suite.accountKeeper.AddressCodec().BytesToString(addrs[1]) + suite.Require().NoError(err) + testCases := []struct { msg string malleate func(require *require.Assertions) @@ -39,7 +44,7 @@ func (suite *TestSuite) TestGRPCQueryAuthorization() { "fail invalid grantee addr", func(require *require.Assertions) { req = &authz.QueryGrantsRequest{ - Granter: addrs[0].String(), + Granter: addr0, } }, "empty address string is not allowed", @@ -49,8 +54,8 @@ func (suite *TestSuite) TestGRPCQueryAuthorization() { "fail invalid msg-type", func(require *require.Assertions) { req = &authz.QueryGrantsRequest{ - Granter: addrs[0].String(), - Grantee: addrs[1].String(), + Granter: addr0, + Grantee: addr1, MsgTypeUrl: "unknown", } }, @@ -61,8 +66,8 @@ func (suite *TestSuite) TestGRPCQueryAuthorization() { "authorization not found", func(require *require.Assertions) { req = &authz.QueryGrantsRequest{ - Granter: addrs[1].String(), - Grantee: addrs[0].String(), + Granter: addr1, + Grantee: addr0, MsgTypeUrl: banktypes.SendAuthorization{}.MsgTypeURL(), } }, @@ -74,8 +79,8 @@ func (suite *TestSuite) TestGRPCQueryAuthorization() { func(require *require.Assertions) { expAuthorization = suite.createSendAuthorization(addrs[0], addrs[1]) req = &authz.QueryGrantsRequest{ - Granter: addrs[1].String(), - Grantee: addrs[0].String(), + Granter: addr1, + Grantee: addr0, MsgTypeUrl: expAuthorization.MsgTypeURL(), } }, @@ -95,8 +100,8 @@ func (suite *TestSuite) TestGRPCQueryAuthorization() { expAuthorization = suite.createSendAuthorizationWithAllowList(addrs[0], addrs[1]) require.Len(expAuthorization.(*banktypes.SendAuthorization).GetAllowList(), 1) req = &authz.QueryGrantsRequest{ - Granter: addrs[1].String(), - Grantee: addrs[0].String(), + Granter: addr1, + Grantee: addr0, MsgTypeUrl: expAuthorization.MsgTypeURL(), } }, @@ -132,6 +137,9 @@ func (suite *TestSuite) TestGRPCQueryGranterGrants() { require := suite.Require() queryClient, addrs := suite.queryClient, suite.addrs + addr0, err := suite.accountKeeper.AddressCodec().BytesToString(addrs[0]) + suite.Require().NoError(err) + testCases := []struct { msg string preRun func() @@ -153,7 +161,7 @@ func (suite *TestSuite) TestGRPCQueryGranterGrants() { }, false, authz.QueryGranterGrantsRequest{ - Granter: addrs[0].String(), + Granter: addr0, }, 1, }, @@ -164,7 +172,7 @@ func (suite *TestSuite) TestGRPCQueryGranterGrants() { }, false, authz.QueryGranterGrantsRequest{ - Granter: addrs[0].String(), + Granter: addr0, }, 2, }, @@ -174,7 +182,7 @@ func (suite *TestSuite) TestGRPCQueryGranterGrants() { }, false, authz.QueryGranterGrantsRequest{ - Granter: addrs[0].String(), + Granter: addr0, Pagination: &query.PageRequest{ Limit: 1, }, @@ -202,6 +210,11 @@ func (suite *TestSuite) TestGRPCQueryGranteeGrants() { require := suite.Require() queryClient, addrs := suite.queryClient, suite.addrs + addr0, err := suite.accountKeeper.AddressCodec().BytesToString(addrs[0]) + suite.Require().NoError(err) + addr2, err := suite.accountKeeper.AddressCodec().BytesToString(addrs[2]) + suite.Require().NoError(err) + testCases := []struct { msg string preRun func() @@ -223,7 +236,7 @@ func (suite *TestSuite) TestGRPCQueryGranteeGrants() { }, false, authz.QueryGranteeGrantsRequest{ - Grantee: addrs[0].String(), + Grantee: addr0, }, 1, }, @@ -232,7 +245,7 @@ func (suite *TestSuite) TestGRPCQueryGranteeGrants() { func() {}, false, authz.QueryGranteeGrantsRequest{ - Grantee: addrs[2].String(), + Grantee: addr2, }, 0, }, @@ -243,7 +256,7 @@ func (suite *TestSuite) TestGRPCQueryGranteeGrants() { }, false, authz.QueryGranteeGrantsRequest{ - Grantee: addrs[0].String(), + Grantee: addr0, }, 2, }, @@ -252,7 +265,7 @@ func (suite *TestSuite) TestGRPCQueryGranteeGrants() { func() {}, false, authz.QueryGranteeGrantsRequest{ - Grantee: addrs[0].String(), + Grantee: addr0, Pagination: &query.PageRequest{ Limit: 1, }, @@ -289,8 +302,10 @@ func (suite *TestSuite) createSendAuthorization(grantee, granter sdk.AccAddress) func (suite *TestSuite) createSendAuthorizationWithAllowList(grantee, granter sdk.AccAddress) authz.Authorization { exp := suite.ctx.HeaderInfo().Time.Add(time.Hour) newCoins := sdk.NewCoins(sdk.NewInt64Coin("steak", 100)) - authorization := &banktypes.SendAuthorization{SpendLimit: newCoins, AllowList: []string{suite.addrs[5].String()}} - err := suite.authzKeeper.SaveGrant(suite.ctx, grantee, granter, authorization, &exp) + addr, err := suite.accountKeeper.AddressCodec().BytesToString(suite.addrs[5]) + suite.Require().NoError(err) + authorization := &banktypes.SendAuthorization{SpendLimit: newCoins, AllowList: []string{addr}} + err = suite.authzKeeper.SaveGrant(suite.ctx, grantee, granter, authorization, &exp) suite.Require().NoError(err) return authorization } diff --git a/x/authz/keeper/keeper.go b/x/authz/keeper/keeper.go index 2613e4085327..1070b85b36a3 100644 --- a/x/authz/keeper/keeper.go +++ b/x/authz/keeper/keeper.go @@ -197,10 +197,19 @@ func (k Keeper) SaveGrant(ctx context.Context, grantee, granter sdk.AccAddress, return err } + granterAddr, err := k.authKeeper.AddressCodec().BytesToString(granter) + if err != nil { + return err + } + granteeAddr, err := k.authKeeper.AddressCodec().BytesToString(grantee) + if err != nil { + return err + } + return k.environment.EventService.EventManager(ctx).Emit(&authz.EventGrant{ MsgTypeUrl: authorization.MsgTypeURL(), - Granter: granter.String(), - Grantee: grantee.String(), + Granter: granterAddr, + Grantee: granteeAddr, }) } @@ -226,10 +235,18 @@ func (k Keeper) DeleteGrant(ctx context.Context, grantee, granter sdk.AccAddress return err } + granterAddr, err := k.authKeeper.AddressCodec().BytesToString(granter) + if err != nil { + return err + } + granteeAddr, err := k.authKeeper.AddressCodec().BytesToString(grantee) + if err != nil { + return err + } return k.environment.EventService.EventManager(ctx).Emit(&authz.EventRevoke{ MsgTypeUrl: msgType, - Granter: granter.String(), - Grantee: grantee.String(), + Granter: granterAddr, + Grantee: granteeAddr, }) } diff --git a/x/authz/keeper/keeper_test.go b/x/authz/keeper/keeper_test.go index b0c77f497dae..b2bd0c742862 100644 --- a/x/authz/keeper/keeper_test.go +++ b/x/authz/keeper/keeper_test.go @@ -169,7 +169,12 @@ func (s *TestSuite) TestDispatchAction() { granterAddr := addrs[0] granteeAddr := addrs[1] - recipientAddr := addrs[2] + granterStrAddr, err := s.accountKeeper.AddressCodec().BytesToString(addrs[0]) + s.Require().NoError(err) + granteeStrAddr, err := s.accountKeeper.AddressCodec().BytesToString(addrs[1]) + s.Require().NoError(err) + recipientStrAddr, err := s.accountKeeper.AddressCodec().BytesToString(addrs[2]) + s.Require().NoError(err) a := banktypes.NewSendAuthorization(coins100, nil) testCases := []struct { @@ -182,11 +187,11 @@ func (s *TestSuite) TestDispatchAction() { }{ { "expect error authorization not found", - authz.NewMsgExec(granteeAddr, []sdk.Msg{ + authz.NewMsgExec(granteeStrAddr, []sdk.Msg{ &banktypes.MsgSend{ Amount: coins10, - FromAddress: granterAddr.String(), - ToAddress: recipientAddr.String(), + FromAddress: granterStrAddr, + ToAddress: recipientStrAddr, }, }), true, @@ -201,11 +206,11 @@ func (s *TestSuite) TestDispatchAction() { }, { "expect error expired authorization", - authz.NewMsgExec(granteeAddr, []sdk.Msg{ + authz.NewMsgExec(granteeStrAddr, []sdk.Msg{ &banktypes.MsgSend{ Amount: coins10, - FromAddress: granterAddr.String(), - ToAddress: recipientAddr.String(), + FromAddress: granterStrAddr, + ToAddress: recipientStrAddr, }, }), true, @@ -220,11 +225,11 @@ func (s *TestSuite) TestDispatchAction() { }, { "expect error over spent limit", - authz.NewMsgExec(granteeAddr, []sdk.Msg{ + authz.NewMsgExec(granteeStrAddr, []sdk.Msg{ &banktypes.MsgSend{ Amount: coins1000, - FromAddress: granterAddr.String(), - ToAddress: recipientAddr.String(), + FromAddress: granterStrAddr, + ToAddress: recipientStrAddr, }, }), true, @@ -239,11 +244,11 @@ func (s *TestSuite) TestDispatchAction() { }, { "valid test verify amount left", - authz.NewMsgExec(granteeAddr, []sdk.Msg{ + authz.NewMsgExec(granteeStrAddr, []sdk.Msg{ &banktypes.MsgSend{ Amount: coins10, - FromAddress: granterAddr.String(), - ToAddress: recipientAddr.String(), + FromAddress: granterStrAddr, + ToAddress: recipientStrAddr, }, }), false, @@ -265,11 +270,11 @@ func (s *TestSuite) TestDispatchAction() { }, { "valid test verify authorization is removed when it is used up", - authz.NewMsgExec(granteeAddr, []sdk.Msg{ + authz.NewMsgExec(granteeStrAddr, []sdk.Msg{ &banktypes.MsgSend{ Amount: coins100, - FromAddress: granterAddr.String(), - ToAddress: recipientAddr.String(), + FromAddress: granterStrAddr, + ToAddress: recipientStrAddr, }, }), false, @@ -314,19 +319,24 @@ func (s *TestSuite) TestDispatchedEvents() { addrs := s.addrs granterAddr := addrs[0] granteeAddr := addrs[1] - recipientAddr := addrs[2] + granterStrAddr, err := s.accountKeeper.AddressCodec().BytesToString(addrs[0]) + s.Require().NoError(err) + granteeStrAddr, err := s.accountKeeper.AddressCodec().BytesToString(addrs[1]) + s.Require().NoError(err) + recipientStrAddr, err := s.accountKeeper.AddressCodec().BytesToString(addrs[2]) + s.Require().NoError(err) expiration := s.ctx.HeaderInfo().Time.Add(1 * time.Second) // must be in the future - msgs := authz.NewMsgExec(granteeAddr, []sdk.Msg{ + msgs := authz.NewMsgExec(granteeStrAddr, []sdk.Msg{ &banktypes.MsgSend{ Amount: coins10, - FromAddress: granterAddr.String(), - ToAddress: recipientAddr.String(), + FromAddress: granterStrAddr, + ToAddress: recipientStrAddr, }, }) // grant authorization - err := s.authzKeeper.SaveGrant(s.ctx, granteeAddr, granterAddr, &banktypes.SendAuthorization{SpendLimit: coins10}, &expiration) + err = s.authzKeeper.SaveGrant(s.ctx, granteeAddr, granterAddr, &banktypes.SendAuthorization{SpendLimit: coins10}, &expiration) require.NoError(err) authorizations, err := s.authzKeeper.GetAuthorizations(s.ctx, granteeAddr, granterAddr) require.NoError(err) diff --git a/x/authz/keeper/msg_server_test.go b/x/authz/keeper/msg_server_test.go index 879061943b14..6b1c673ece9c 100644 --- a/x/authz/keeper/msg_server_test.go +++ b/x/authz/keeper/msg_server_test.go @@ -36,6 +36,10 @@ func (suite *TestSuite) TestGrant() { coins := sdk.NewCoins(sdk.NewCoin("steak", sdkmath.NewInt(10))) grantee, granter := addrs[0], addrs[1] + granterStrAddr, err := suite.accountKeeper.AddressCodec().BytesToString(granter) + suite.Require().NoError(err) + granteeStrAddr, err := suite.accountKeeper.AddressCodec().BytesToString(grantee) + suite.Require().NoError(err) testCases := []struct { name string @@ -49,8 +53,8 @@ func (suite *TestSuite) TestGrant() { grant, err := authz.NewGrant(curBlockTime, banktypes.NewSendAuthorization(coins, nil), &oneYear) suite.Require().NoError(err) return &authz.MsgGrant{ - Granter: grantee.String(), - Grantee: grantee.String(), + Granter: granteeStrAddr, + Grantee: granteeStrAddr, Grant: grant, } }, @@ -64,7 +68,7 @@ func (suite *TestSuite) TestGrant() { suite.Require().NoError(err) return &authz.MsgGrant{ Granter: "invalid", - Grantee: grantee.String(), + Grantee: granteeStrAddr, Grant: grant, } }, @@ -77,7 +81,7 @@ func (suite *TestSuite) TestGrant() { grant, err := authz.NewGrant(curBlockTime, banktypes.NewSendAuthorization(coins, nil), &oneYear) suite.Require().NoError(err) return &authz.MsgGrant{ - Granter: granter.String(), + Granter: granterStrAddr, Grantee: "invalid", Grant: grant, } @@ -89,8 +93,8 @@ func (suite *TestSuite) TestGrant() { name: "invalid grant", malleate: func() *authz.MsgGrant { return &authz.MsgGrant{ - Granter: granter.String(), - Grantee: grantee.String(), + Granter: granterStrAddr, + Grantee: granteeStrAddr, Grant: authz.Grant{ Expiration: &oneYear, }, @@ -106,8 +110,8 @@ func (suite *TestSuite) TestGrant() { grant, err := authz.NewGrant(curBlockTime, banktypes.NewSendAuthorization(coins, nil), &oneHour) // we only need the authorization suite.Require().NoError(err) return &authz.MsgGrant{ - Granter: granter.String(), - Grantee: grantee.String(), + Granter: granterStrAddr, + Grantee: granteeStrAddr, Grant: authz.Grant{ Authorization: grant.Authorization, Expiration: &pTime, @@ -127,9 +131,13 @@ func (suite *TestSuite) TestGrant() { grant, err := authz.NewGrant(curBlockTime, banktypes.NewSendAuthorization(coins, nil), &oneYear) suite.Require().NoError(err) + + addr, err := suite.accountKeeper.AddressCodec().BytesToString(newAcc) + suite.Require().NoError(err) + return &authz.MsgGrant{ - Granter: granter.String(), - Grantee: newAcc.String(), + Granter: granterStrAddr, + Grantee: addr, Grant: grant, } }, @@ -140,8 +148,8 @@ func (suite *TestSuite) TestGrant() { grant, err := authz.NewGrant(curBlockTime, banktypes.NewSendAuthorization(coins, nil), &oneYear) suite.Require().NoError(err) return &authz.MsgGrant{ - Granter: granter.String(), - Grantee: grantee.String(), + Granter: granterStrAddr, + Grantee: granteeStrAddr, Grant: grant, } }, @@ -152,8 +160,8 @@ func (suite *TestSuite) TestGrant() { g, err := authz.NewGrant(curBlockTime, banktypes.NewSendAuthorization(coins, nil), &oneHour) suite.Require().NoError(err) _, err = suite.msgSrvr.Grant(suite.ctx, &authz.MsgGrant{ - Granter: granter.String(), - Grantee: grantee.String(), + Granter: granterStrAddr, + Grantee: granteeStrAddr, Grant: g, }) suite.Require().NoError(err) @@ -161,8 +169,8 @@ func (suite *TestSuite) TestGrant() { grant, err := authz.NewGrant(curBlockTime, authz.NewGenericAuthorization("/cosmos.bank.v1beta1.MsgUpdateParams"), &oneHour) suite.Require().NoError(err) return &authz.MsgGrant{ - Granter: granter.String(), - Grantee: grantee.String(), + Granter: granterStrAddr, + Grantee: granteeStrAddr, Grant: grant, } }, @@ -173,8 +181,8 @@ func (suite *TestSuite) TestGrant() { grant, err := authz.NewGrant(curBlockTime, banktypes.NewSendAuthorization(coins, []sdk.AccAddress{granter}), &oneYear) suite.Require().NoError(err) return &authz.MsgGrant{ - Granter: granter.String(), - Grantee: grantee.String(), + Granter: granterStrAddr, + Grantee: granteeStrAddr, Grant: grant, } }, @@ -185,8 +193,8 @@ func (suite *TestSuite) TestGrant() { grant, err := authz.NewGrant(curBlockTime, banktypes.NewSendAuthorization(coins, nil), nil) suite.Require().NoError(err) return &authz.MsgGrant{ - Granter: granter.String(), - Grantee: grantee.String(), + Granter: granterStrAddr, + Grantee: granteeStrAddr, Grant: grant, } }, @@ -210,6 +218,10 @@ func (suite *TestSuite) TestRevoke() { addrs := suite.createAccounts() grantee, granter := addrs[0], addrs[1] + granterStrAddr, err := suite.accountKeeper.AddressCodec().BytesToString(granter) + suite.Require().NoError(err) + granteeStrAddr, err := suite.accountKeeper.AddressCodec().BytesToString(grantee) + suite.Require().NoError(err) testCases := []struct { name string @@ -221,8 +233,8 @@ func (suite *TestSuite) TestRevoke() { name: "identical grantee and granter", malleate: func() *authz.MsgRevoke { return &authz.MsgRevoke{ - Granter: grantee.String(), - Grantee: grantee.String(), + Granter: granteeStrAddr, + Grantee: granteeStrAddr, MsgTypeUrl: bankSendAuthMsgType, } }, @@ -234,7 +246,7 @@ func (suite *TestSuite) TestRevoke() { malleate: func() *authz.MsgRevoke { return &authz.MsgRevoke{ Granter: "invalid", - Grantee: grantee.String(), + Grantee: granteeStrAddr, MsgTypeUrl: bankSendAuthMsgType, } }, @@ -245,7 +257,7 @@ func (suite *TestSuite) TestRevoke() { name: "invalid grantee", malleate: func() *authz.MsgRevoke { return &authz.MsgRevoke{ - Granter: granter.String(), + Granter: granterStrAddr, Grantee: "invalid", MsgTypeUrl: bankSendAuthMsgType, } @@ -257,8 +269,8 @@ func (suite *TestSuite) TestRevoke() { name: "no msg given", malleate: func() *authz.MsgRevoke { return &authz.MsgRevoke{ - Granter: granter.String(), - Grantee: grantee.String(), + Granter: granterStrAddr, + Grantee: granteeStrAddr, MsgTypeUrl: "", } }, @@ -271,8 +283,8 @@ func (suite *TestSuite) TestRevoke() { suite.createSendAuthorization(grantee, granter) return &authz.MsgRevoke{ - Granter: granter.String(), - Grantee: grantee.String(), + Granter: granterStrAddr, + Grantee: granteeStrAddr, MsgTypeUrl: bankSendAuthMsgType, } }, @@ -281,8 +293,8 @@ func (suite *TestSuite) TestRevoke() { name: "no existing grant to revoke", malleate: func() *authz.MsgRevoke { return &authz.MsgRevoke{ - Granter: granter.String(), - Grantee: grantee.String(), + Granter: granterStrAddr, + Grantee: granteeStrAddr, MsgTypeUrl: bankSendAuthMsgType, } }, @@ -308,11 +320,15 @@ func (suite *TestSuite) TestExec() { addrs := suite.createAccounts() grantee, granter := addrs[0], addrs[1] + granterStrAddr, err := suite.accountKeeper.AddressCodec().BytesToString(granter) + suite.Require().NoError(err) + granteeStrAddr, err := suite.accountKeeper.AddressCodec().BytesToString(grantee) + suite.Require().NoError(err) coins := sdk.NewCoins(sdk.NewCoin("steak", sdkmath.NewInt(10))) msg := &banktypes.MsgSend{ - FromAddress: granter.String(), - ToAddress: grantee.String(), + FromAddress: granterStrAddr, + ToAddress: granteeStrAddr, Amount: coins, } @@ -325,7 +341,7 @@ func (suite *TestSuite) TestExec() { { name: "invalid grantee (empty)", malleate: func() authz.MsgExec { - return authz.NewMsgExec(sdk.AccAddress{}, []sdk.Msg{msg}) + return authz.NewMsgExec("", []sdk.Msg{msg}) }, expErr: true, errMsg: "empty address string is not allowed", @@ -333,7 +349,7 @@ func (suite *TestSuite) TestExec() { { name: "non existing grant", malleate: func() authz.MsgExec { - return authz.NewMsgExec(grantee, []sdk.Msg{msg}) + return authz.NewMsgExec(granteeStrAddr, []sdk.Msg{msg}) }, expErr: true, errMsg: "authorization not found", @@ -341,7 +357,7 @@ func (suite *TestSuite) TestExec() { { name: "no message case", malleate: func() authz.MsgExec { - return authz.NewMsgExec(grantee, []sdk.Msg{}) + return authz.NewMsgExec(granteeStrAddr, []sdk.Msg{}) }, expErr: true, errMsg: "messages cannot be empty", @@ -350,7 +366,7 @@ func (suite *TestSuite) TestExec() { name: "valid case", malleate: func() authz.MsgExec { suite.createSendAuthorization(grantee, granter) - return authz.NewMsgExec(grantee, []sdk.Msg{msg}) + return authz.NewMsgExec(granteeStrAddr, []sdk.Msg{msg}) }, }, } @@ -372,6 +388,11 @@ func (suite *TestSuite) TestExec() { func (suite *TestSuite) TestPruneExpiredGrants() { addrs := suite.createAccounts() + addr0, err := suite.accountKeeper.AddressCodec().BytesToString(addrs[0]) + suite.Require().NoError(err) + addr1, err := suite.accountKeeper.AddressCodec().BytesToString(addrs[1]) + suite.Require().NoError(err) + timeNow := suite.ctx.BlockTime() expiration := timeNow.Add(time.Hour) coins := sdk.NewCoins(sdk.NewCoin("steak", sdkmath.NewInt(10))) @@ -379,15 +400,15 @@ func (suite *TestSuite) TestPruneExpiredGrants() { suite.Require().NoError(err) _, err = suite.msgSrvr.Grant(suite.ctx, &authz.MsgGrant{ - Granter: addrs[0].String(), - Grantee: addrs[1].String(), + Granter: addr0, + Grantee: addr1, Grant: grant, }) suite.Require().NoError(err) _, err = suite.msgSrvr.Grant(suite.ctx, &authz.MsgGrant{ - Granter: addrs[1].String(), - Grantee: addrs[0].String(), + Granter: addr1, + Grantee: addr0, Grant: grant, }) suite.Require().NoError(err) @@ -404,7 +425,7 @@ func (suite *TestSuite) TestPruneExpiredGrants() { headerInfo.Time = headerInfo.Time.Add(2 * time.Hour) suite.ctx = suite.ctx.WithHeaderInfo(headerInfo) - _, err = suite.authzKeeper.PruneExpiredGrants(suite.ctx, &authz.MsgPruneExpiredGrants{Pruner: addrs[0].String()}) + _, err = suite.authzKeeper.PruneExpiredGrants(suite.ctx, &authz.MsgPruneExpiredGrants{Pruner: addr0}) suite.Require().NoError(err) totalGrants = 0 diff --git a/x/authz/module/abci_test.go b/x/authz/module/abci_test.go index ba2ae1914a85..b8765e1fbe0d 100644 --- a/x/authz/module/abci_test.go +++ b/x/authz/module/abci_test.go @@ -71,7 +71,8 @@ func TestExpiredGrantsQueue(t *testing.T) { save := func(grantee sdk.AccAddress, exp *time.Time) { err := authzKeeper.SaveGrant(ctx, grantee, granter, sendAuthz, exp) - require.NoError(t, err, "Grant from %s", grantee.String()) + addr, _ := accountKeeper.AddressCodec().BytesToString(grantee) + require.NoError(t, err, "Grant from %s", addr) } save(grantee1, &expiration) save(grantee2, &expiration) @@ -86,8 +87,10 @@ func TestExpiredGrantsQueue(t *testing.T) { err := authzmodule.BeginBlocker(ctx, authzKeeper) require.NoError(t, err) + addr, err := accountKeeper.AddressCodec().BytesToString(granter) + require.NoError(t, err) res, err := queryClient.GranterGrants(ctx.Context(), &authz.QueryGranterGrantsRequest{ - Granter: granter.String(), + Granter: addr, }) require.NoError(t, err) require.NotNil(t, res) diff --git a/x/authz/msgs.go b/x/authz/msgs.go index ad7b34fbf1c7..2c3e57b7f490 100644 --- a/x/authz/msgs.go +++ b/x/authz/msgs.go @@ -20,10 +20,10 @@ var ( ) // NewMsgGrant creates a new MsgGrant -func NewMsgGrant(granter, grantee sdk.AccAddress, a Authorization, expiration *time.Time) (*MsgGrant, error) { +func NewMsgGrant(granter, grantee string, a Authorization, expiration *time.Time) (*MsgGrant, error) { m := &MsgGrant{ - Granter: granter.String(), - Grantee: grantee.String(), + Granter: granter, + Grantee: grantee, Grant: Grant{Expiration: expiration}, } err := m.SetAuthorization(a) @@ -71,16 +71,16 @@ func (msg MsgGrant) UnpackInterfaces(unpacker cdctypes.AnyUnpacker) error { } // NewMsgRevoke creates a new MsgRevoke -func NewMsgRevoke(granter, grantee sdk.AccAddress, msgTypeURL string) MsgRevoke { +func NewMsgRevoke(granter, grantee string, msgTypeURL string) MsgRevoke { return MsgRevoke{ - Granter: granter.String(), - Grantee: grantee.String(), + Granter: granter, + Grantee: grantee, MsgTypeUrl: msgTypeURL, } } // NewMsgExec creates a new MsgExecAuthorized -func NewMsgExec(grantee sdk.AccAddress, msgs []sdk.Msg) MsgExec { +func NewMsgExec(grantee string, msgs []sdk.Msg) MsgExec { msgsAny := make([]*cdctypes.Any, len(msgs)) for i, msg := range msgs { any, err := cdctypes.NewAnyWithValue(msg) @@ -92,7 +92,7 @@ func NewMsgExec(grantee sdk.AccAddress, msgs []sdk.Msg) MsgExec { } return MsgExec{ - Grantee: grantee.String(), + Grantee: grantee, Msgs: msgsAny, } } diff --git a/x/authz/simulation/genesis.go b/x/authz/simulation/genesis.go index 0fc5c757cf71..073bdffabc8e 100644 --- a/x/authz/simulation/genesis.go +++ b/x/authz/simulation/genesis.go @@ -5,6 +5,7 @@ import ( "time" v1 "cosmossdk.io/api/cosmos/gov/v1" + "cosmossdk.io/core/address" sdkmath "cosmossdk.io/math" "cosmossdk.io/x/authz" banktypes "cosmossdk.io/x/bank/types" @@ -16,7 +17,7 @@ import ( ) // genGrant returns a slice of authorization grants. -func genGrant(r *rand.Rand, accounts []simtypes.Account, genT time.Time) []authz.GrantAuthorization { +func genGrant(r *rand.Rand, accounts []simtypes.Account, genT time.Time, cdc address.Codec) []authz.GrantAuthorization { authorizations := make([]authz.GrantAuthorization, len(accounts)-1) for i := 0; i < len(accounts)-1; i++ { granter := accounts[i] @@ -26,9 +27,11 @@ func genGrant(r *rand.Rand, accounts []simtypes.Account, genT time.Time) []authz e := genT.AddDate(1, 0, 0) expiration = &e } + granterAddr, _ := cdc.BytesToString(granter.Address) + granteeAddr, _ := cdc.BytesToString(grantee.Address) authorizations[i] = authz.GrantAuthorization{ - Granter: granter.Address.String(), - Grantee: grantee.Address.String(), + Granter: granterAddr, + Grantee: granteeAddr, Authorization: generateRandomGrant(r), Expiration: expiration, } @@ -59,7 +62,7 @@ func newAnyAuthorization(a authz.Authorization) *codectypes.Any { func RandomizedGenState(simState *module.SimulationState) { var grants []authz.GrantAuthorization simState.AppParams.GetOrGenerate("authz", &grants, simState.Rand, func(r *rand.Rand) { - grants = genGrant(r, simState.Accounts, simState.GenTimestamp) + grants = genGrant(r, simState.Accounts, simState.GenTimestamp, simState.AddressCodec) }) authzGrantsGenesis := authz.NewGenesisState(grants) diff --git a/x/authz/simulation/operations.go b/x/authz/simulation/operations.go index c73c562b5f37..b01b09b5bbc1 100644 --- a/x/authz/simulation/operations.go +++ b/x/authz/simulation/operations.go @@ -123,7 +123,15 @@ func SimulateMsgGrant( } randomAuthz := generateRandomAuthorization(r, spendLimit) - msg, err := authz.NewMsgGrant(granter.Address, grantee.Address, randomAuthz, expiration) + granterAddr, err := ak.AddressCodec().BytesToString(granter.Address) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgGrant, "could not get granter address"), nil, nil + } + granteeAddr, err := ak.AddressCodec().BytesToString(grantee.Address) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgGrant, "could not get grantee address"), nil, nil + } + msg, err := authz.NewMsgGrant(granterAddr, granteeAddr, randomAuthz, expiration) if err != nil { return simtypes.NoOpMsg(authz.ModuleName, TypeMsgGrant, err.Error()), nil, err } @@ -202,7 +210,15 @@ func SimulateMsgRevoke( return simtypes.NoOpMsg(authz.ModuleName, TypeMsgRevoke, "authorization error"), nil, err } - msg := authz.NewMsgRevoke(granterAddr, granteeAddr, a.MsgTypeURL()) + granterStrAddr, err := ak.AddressCodec().BytesToString(granterAddr) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgRevoke, "could not get granter address"), nil, nil + } + granteeStrAddr, err := ak.AddressCodec().BytesToString(granteeAddr) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgRevoke, "could not get grantee address"), nil, nil + } + msg := authz.NewMsgRevoke(granterStrAddr, granteeStrAddr, a.MsgTypeURL()) account := ak.GetAccount(ctx, granterAddr) tx, err := simtestutil.GenSignedMockTx( r, @@ -305,7 +321,7 @@ func SimulateMsgExec( } - msgExec := authz.NewMsgExec(granteeAddr, msg) + msgExec := authz.NewMsgExec(greStr, msg) granteeSpendableCoins := bk.SpendableCoins(ctx, granteeAddr) fees, err := simtypes.RandomFees(r, granteeSpendableCoins) if err != nil { From 86a5b85ebe97164ee34abf9651d686d940162dc2 Mon Sep 17 00:00:00 2001 From: Julian Toledano Date: Tue, 19 Mar 2024 08:31:52 +0100 Subject: [PATCH 15/17] update: ExportGenesis, IterateGrants --- x/authz/CHANGELOG.md | 5 ++++- x/authz/client/cli/tx.go | 7 ++++++- x/authz/keeper/genesis.go | 24 +++++++++++++++++------- x/authz/keeper/genesis_test.go | 10 ++++++---- x/authz/keeper/keeper.go | 11 ++++++++--- x/authz/keeper/keeper_test.go | 4 ++-- x/authz/keeper/msg_server_test.go | 8 ++++---- x/authz/module/module.go | 5 ++++- x/authz/msgs.go | 2 +- x/authz/simulation/operations.go | 14 ++++++++------ 10 files changed, 60 insertions(+), 30 deletions(-) diff --git a/x/authz/CHANGELOG.md b/x/authz/CHANGELOG.md index 2e9073e4ddc2..e9531a2c5f3d 100644 --- a/x/authz/CHANGELOG.md +++ b/x/authz/CHANGELOG.md @@ -31,7 +31,10 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### API Breaking Changes -* []() `NewMsgExec`, `NewMsgGrant` and `NewMsgRevoke` now takes strings as arguments instead of `sdk.AccAddress`. +* []() Removes the use of Accouts String() method + * `NewMsgExec`, `NewMsgGrant` and `NewMsgRevoke` now takes strings as arguments instead of `sdk.AccAddress`. + * `ExportGenesis` also returns an error. + * `IterateGrants` returns an error, its handler function also returns an error. * [#19637](https://github.com/cosmos/cosmos-sdk/pull/19637) `NewKeeper` doesn't take a message router anymore. Set the message router in the `appmodule.Environment` instead. * [#19490](https://github.com/cosmos/cosmos-sdk/pull/19490) `appmodule.Environment` is received on the Keeper to get access to different application services. * [#18737](https://github.com/cosmos/cosmos-sdk/pull/18737) Update the keeper method `DequeueAndDeleteExpiredGrants` to take a limit argument for the number of grants to prune. diff --git a/x/authz/client/cli/tx.go b/x/authz/client/cli/tx.go index 75dbc2db03c8..904b210d88f6 100644 --- a/x/authz/client/cli/tx.go +++ b/x/authz/client/cli/tx.go @@ -110,11 +110,16 @@ Examples: } grantee := args[0] + if _, err := clientCtx.AddressCodec.StringToBytes(grantee); err != nil { + return err + } + granter, err := clientCtx.AddressCodec.BytesToString(clientCtx.GetFromAddress()) if err != nil { return err } - if strings.EqualFold(args[0], granter) { + + if strings.EqualFold(grantee, granter) { return errors.New("grantee and granter should be different") } diff --git a/x/authz/keeper/genesis.go b/x/authz/keeper/genesis.go index d5de1d741b09..909c54dc1421 100644 --- a/x/authz/keeper/genesis.go +++ b/x/authz/keeper/genesis.go @@ -41,17 +41,27 @@ func (k Keeper) InitGenesis(ctx context.Context, data *authz.GenesisState) error } // ExportGenesis returns a GenesisState for a given context. -func (k Keeper) ExportGenesis(ctx context.Context) *authz.GenesisState { +func (k Keeper) ExportGenesis(ctx context.Context) (*authz.GenesisState, error) { var entries []authz.GrantAuthorization - k.IterateGrants(ctx, func(granter, grantee sdk.AccAddress, grant authz.Grant) bool { + err := k.IterateGrants(ctx, func(granter, grantee sdk.AccAddress, grant authz.Grant) (bool, error) { + granterAddr, err := k.authKeeper.AddressCodec().BytesToString(granter) + if err != nil { + return false, err + } + granteeAddr, err := k.authKeeper.AddressCodec().BytesToString(grantee) + if err != nil { + return false, err + } entries = append(entries, authz.GrantAuthorization{ - Granter: granter.String(), - Grantee: grantee.String(), + Granter: granterAddr, + Grantee: granteeAddr, Expiration: grant.Expiration, Authorization: grant.Authorization, }) - return false + return false, nil }) - - return authz.NewGenesisState(entries) + if err != nil { + return nil, err + } + return authz.NewGenesisState(entries), nil } diff --git a/x/authz/keeper/genesis_test.go b/x/authz/keeper/genesis_test.go index d913c3bef304..a4a40033514d 100644 --- a/x/authz/keeper/genesis_test.go +++ b/x/authz/keeper/genesis_test.go @@ -81,18 +81,20 @@ func (suite *GenesisTestSuite) TestImportExportGenesis() { grant := &bank.SendAuthorization{SpendLimit: coins} err := suite.keeper.SaveGrant(suite.ctx, granteeAddr, granterAddr, grant, &expires) suite.Require().NoError(err) - genesis := suite.keeper.ExportGenesis(suite.ctx) - + genesis, err := suite.keeper.ExportGenesis(suite.ctx) + suite.Require().NoError(err) // Clear keeper err = suite.keeper.DeleteGrant(suite.ctx, granteeAddr, granterAddr, grant.MsgTypeURL()) suite.Require().NoError(err) - newGenesis := suite.keeper.ExportGenesis(suite.ctx) + newGenesis, err := suite.keeper.ExportGenesis(suite.ctx) + suite.Require().NoError(err) suite.Require().NotEqual(genesis, newGenesis) suite.Require().Empty(newGenesis) err = suite.keeper.InitGenesis(suite.ctx, genesis) suite.Require().NoError(err) - newGenesis = suite.keeper.ExportGenesis(suite.ctx) + newGenesis, err = suite.keeper.ExportGenesis(suite.ctx) + suite.Require().NoError(err) suite.Require().Equal(genesis, newGenesis) } diff --git a/x/authz/keeper/keeper.go b/x/authz/keeper/keeper.go index 1070b85b36a3..a4347e6132d2 100644 --- a/x/authz/keeper/keeper.go +++ b/x/authz/keeper/keeper.go @@ -299,8 +299,8 @@ func (k Keeper) GetAuthorization(ctx context.Context, grantee, granter sdk.AccAd // It should not be used in query or msg services without charging additional gas. // The iteration stops when the handler function returns true or the iterator exhaust. func (k Keeper) IterateGrants(ctx context.Context, - handler func(granterAddr, granteeAddr sdk.AccAddress, grant authz.Grant) bool, -) { + handler func(granterAddr, granteeAddr sdk.AccAddress, grant authz.Grant) (bool, error), +) error { store := runtime.KVStoreAdapter(k.environment.KVStoreService.OpenKVStore(ctx)) iter := storetypes.KVStorePrefixIterator(store, GrantKey) defer iter.Close() @@ -308,10 +308,15 @@ func (k Keeper) IterateGrants(ctx context.Context, var grant authz.Grant granterAddr, granteeAddr, _ := parseGrantStoreKey(iter.Key()) k.cdc.MustUnmarshal(iter.Value(), &grant) - if handler(granterAddr, granteeAddr, grant) { + ok, err := handler(granterAddr, granteeAddr, grant) + if err != nil { + return err + } + if ok { break } } + return nil } func (k Keeper) getGrantQueueItem(ctx context.Context, expiration time.Time, granter, grantee sdk.AccAddress) (*authz.GrantQueueItem, error) { diff --git a/x/authz/keeper/keeper_test.go b/x/authz/keeper/keeper_test.go index b2bd0c742862..c790b6fde446 100644 --- a/x/authz/keeper/keeper_test.go +++ b/x/authz/keeper/keeper_test.go @@ -155,10 +155,10 @@ func (s *TestSuite) TestKeeperIter() { err = s.authzKeeper.SaveGrant(ctx, granteeAddr, granter2Addr, sendAuthz, &e) s.Require().NoError(err) - s.authzKeeper.IterateGrants(ctx, func(granter, grantee sdk.AccAddress, grant authz.Grant) bool { + _ = s.authzKeeper.IterateGrants(ctx, func(granter, grantee sdk.AccAddress, grant authz.Grant) (bool, error) { s.Require().Equal(granteeAddr, grantee) s.Require().Contains([]sdk.AccAddress{granterAddr, granter2Addr}, granter) - return true + return true, nil }) } diff --git a/x/authz/keeper/msg_server_test.go b/x/authz/keeper/msg_server_test.go index 6b1c673ece9c..6fb013bb7fba 100644 --- a/x/authz/keeper/msg_server_test.go +++ b/x/authz/keeper/msg_server_test.go @@ -414,9 +414,9 @@ func (suite *TestSuite) TestPruneExpiredGrants() { suite.Require().NoError(err) totalGrants := 0 - suite.authzKeeper.IterateGrants(suite.ctx, func(sdk.AccAddress, sdk.AccAddress, authz.Grant) bool { + _ = suite.authzKeeper.IterateGrants(suite.ctx, func(sdk.AccAddress, sdk.AccAddress, authz.Grant) (bool, error) { totalGrants++ - return false + return false, nil }) suite.Require().Equal(len(addrs), totalGrants) @@ -429,9 +429,9 @@ func (suite *TestSuite) TestPruneExpiredGrants() { suite.Require().NoError(err) totalGrants = 0 - suite.authzKeeper.IterateGrants(suite.ctx, func(sdk.AccAddress, sdk.AccAddress, authz.Grant) bool { + _ = suite.authzKeeper.IterateGrants(suite.ctx, func(sdk.AccAddress, sdk.AccAddress, authz.Grant) (bool, error) { totalGrants++ - return false + return false, nil }) suite.Require().Equal(0, totalGrants) } diff --git a/x/authz/module/module.go b/x/authz/module/module.go index 9eb34ac5fd06..8c0aafa5df3a 100644 --- a/x/authz/module/module.go +++ b/x/authz/module/module.go @@ -134,7 +134,10 @@ func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) error // ExportGenesis returns the exported genesis state as raw bytes for the authz module. func (am AppModule) ExportGenesis(ctx context.Context) (json.RawMessage, error) { - gs := am.keeper.ExportGenesis(ctx) + gs, err := am.keeper.ExportGenesis(ctx) + if err != nil { + return nil, err + } return am.cdc.MarshalJSON(gs) } diff --git a/x/authz/msgs.go b/x/authz/msgs.go index 2c3e57b7f490..0964f45cb34b 100644 --- a/x/authz/msgs.go +++ b/x/authz/msgs.go @@ -71,7 +71,7 @@ func (msg MsgGrant) UnpackInterfaces(unpacker cdctypes.AnyUnpacker) error { } // NewMsgRevoke creates a new MsgRevoke -func NewMsgRevoke(granter, grantee string, msgTypeURL string) MsgRevoke { +func NewMsgRevoke(granter, grantee, msgTypeURL string) MsgRevoke { return MsgRevoke{ Granter: granter, Grantee: grantee, diff --git a/x/authz/simulation/operations.go b/x/authz/simulation/operations.go index b01b09b5bbc1..657383d37b5e 100644 --- a/x/authz/simulation/operations.go +++ b/x/authz/simulation/operations.go @@ -182,13 +182,16 @@ func SimulateMsgRevoke( var grant authz.Grant hasGrant := false - k.IterateGrants(ctx, func(granter, grantee sdk.AccAddress, g authz.Grant) bool { + err := k.IterateGrants(ctx, func(granter, grantee sdk.AccAddress, g authz.Grant) (bool, error) { grant = g granterAddr = granter granteeAddr = grantee hasGrant = true - return true + return true, nil }) + if err != nil { + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgRevoke, err.Error()), nil, err + } if !hasGrant { return simtypes.NoOpMsg(authz.ModuleName, TypeMsgRevoke, "no grants"), nil, nil @@ -260,19 +263,18 @@ func SimulateMsgExec( var granteeAddr sdk.AccAddress var sendAuth *banktype.SendAuthorization var err error - k.IterateGrants(ctx, func(granter, grantee sdk.AccAddress, grant authz.Grant) bool { + err = k.IterateGrants(ctx, func(granter, grantee sdk.AccAddress, grant authz.Grant) (bool, error) { granterAddr = granter granteeAddr = grantee var a authz.Authorization a, err = grant.GetAuthorization() if err != nil { - return true + return true, err } var ok bool sendAuth, ok = a.(*banktype.SendAuthorization) - return ok + return ok, nil }) - if err != nil { return simtypes.NoOpMsg(authz.ModuleName, TypeMsgExec, err.Error()), nil, err } From 434dc6f5be95c7a71f0295a2aa058fffad34b511 Mon Sep 17 00:00:00 2001 From: Julian Toledano Date: Tue, 19 Mar 2024 10:43:08 +0100 Subject: [PATCH 16/17] del: ValAddressFromBech32 --- x/authz/msgs_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/authz/msgs_test.go b/x/authz/msgs_test.go index bd0a230be281..194f93d417f3 100644 --- a/x/authz/msgs_test.go +++ b/x/authz/msgs_test.go @@ -72,7 +72,7 @@ func TestAminoJSON(t *testing.T) { sendAuthz := banktypes.NewSendAuthorization(sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(1000))), nil) sendGrant, err := authz.NewGrant(blockTime, sendAuthz, &expiresAt) require.NoError(t, err) - valAddr, err := sdk.ValAddressFromBech32("cosmosvaloper1xcy3els9ua75kdm783c3qu0rfa2eples6eavqq") + valAddr, err := valAddressCodec.StringToBytes("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)}, valAddressCodec) require.NoError(t, err) From 819adbaa16ca1ac097b507ad8bb6c490be4c67bb Mon Sep 17 00:00:00 2001 From: Julian Toledano Date: Tue, 19 Mar 2024 12:19:51 +0100 Subject: [PATCH 17/17] CHANGELOG --- x/authz/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/authz/CHANGELOG.md b/x/authz/CHANGELOG.md index e9531a2c5f3d..0963382c9e03 100644 --- a/x/authz/CHANGELOG.md +++ b/x/authz/CHANGELOG.md @@ -31,7 +31,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### API Breaking Changes -* []() Removes the use of Accouts String() method +* [#19783](https://github.com/cosmos/cosmos-sdk/pull/19783) Removes the use of Accouts String() method * `NewMsgExec`, `NewMsgGrant` and `NewMsgRevoke` now takes strings as arguments instead of `sdk.AccAddress`. * `ExportGenesis` also returns an error. * `IterateGrants` returns an error, its handler function also returns an error.