From 06e9b052a55619129808e870b944a4190147d9e6 Mon Sep 17 00:00:00 2001 From: Daniel Wedul Date: Tue, 16 Apr 2024 15:04:47 -0600 Subject: [PATCH 1/3] Reinstate usage of some SDK functionality unique to our fork. (#1930) * [1760]: Use ReadPageRequestWithPageKeyDecoded everywhere we used to. * [1760]: Clean up uses of cosmossdk.io/simapp * [1760]: Handle some of the count-authz TODOs, but I forgot to update the grant command, so there's a couple things that are still needed in the SDK. * [1760]: Switch to a local version of the SDK that has the count authz cmd fix. * [1760]: Fix the rest of the count-authz TODOs. * [1760]: Use GenerateOrBroadcastTxCLIAsGovProp now that it's back. * [1760]: Put the locked coins stuff back in. * [1760]: Put back uses of InputOutputCoins and InputOutputCoinsProv. * [1760]: Get rid of the test_amino build tag and the make targets for it. Remove the check-test stuff since we've also got build-tests which is easier for me to remember. * [1760]: Untab the make build comment about removing the delay so that it's actually a comment rather than a command that's printed. * [1760]: Refactor the make build-tests target to behave just use the same flow as make test, and also give it the same tags. * [1760]: Update a TODO comment that is now half done. * [1760]: Use a BaseKeeper for the bank keeper instead of the Keeper interface since that interface doesn't have InputOutputCoinsProv. * [1760]: Fix the exchange mock bank keeper to have InputOutputCoinsProv instead of the old one. * [1760]: Use a concrete bank BaseKeeper in the app instead of a reference to one because there's some deep down-stream wiring stuff that assumes it's concrete. * [1760]: Update the hold tests that check spendable balances. The actual test is commented out right now until the quarantine PR merges that has the needed query helper. * [1760]: Bump the sdk to v0.50.5-pio-3 (from v0.50.5-pio-2). * [1760]: Allow defining the TEST_PACKAGES used in the make test target. * [1760]: Add the migration of bank params to the umber upgrade. * [1760]: Add changelog entry. * [1760]: Uncomment the hold cli unit test that gets spendable balances so that once the quarantine PR is merged, this will be ready too. * [1760]: Do a string comparison of the coins in TestHoldsNotInFromSpendable. --- CHANGELOG.md | 3 + Makefile | 26 +--- app/app.go | 20 +-- app/app_test.go | 3 +- app/params/amino.go | 27 ----- app/params/proto.go | 7 +- app/sim_test.go | 13 +- app/upgrades.go | 41 ++++++- app/upgrades_test.go | 4 + go.mod | 5 +- go.sum | 6 +- internal/provcli/cli_helpers.go | 17 +-- x/attribute/client/cli/query.go | 8 +- x/exchange/client/cli/helpers.go | 9 +- x/exchange/client/cli/query_setup.go | 10 +- x/exchange/client/cli/tx.go | 10 +- x/exchange/expected_keepers.go | 4 +- x/exchange/keeper/keeper.go | 12 +- x/exchange/keeper/mocks_test.go | 2 +- x/hold/client/cli/cli_test.go | 63 +++++----- x/hold/client/cli/query.go | 2 +- x/hold/expected_keepers.go | 4 +- x/hold/keeper/invariants.go | 3 +- x/hold/keeper/keeper.go | 2 +- x/hold/keeper/keeper_test.go | 14 +-- x/hold/keeper/locked_coins.go | 10 +- x/hold/keeper/mock_keepers_test.go | 9 +- x/hold/locked_coins.go | 23 ++-- x/ibcratelimit/client/cli/tx.go | 35 ++---- x/marker/client/cli/query.go | 4 +- x/marker/client/cli/tx.go | 16 +-- x/marker/keeper/send_restrictions_test.go | 2 +- x/metadata/client/cli/cli_test.go | 4 +- x/metadata/client/cli/query.go | 20 +-- x/metadata/keeper/signers_test.go | 141 ++++++++++------------ x/metadata/keeper/signers_utils_test.go | 89 ++++++-------- x/msgfees/client/cli/query.go | 2 +- x/name/client/cli/query.go | 2 +- x/name/client/cli/tx.go | 48 ++------ x/oracle/client/cli/tx.go | 34 ++---- x/trigger/client/cli/query.go | 2 +- 41 files changed, 322 insertions(+), 434 deletions(-) delete mode 100644 app/params/amino.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d0c3dbd95..93cadb4ae6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -61,6 +61,9 @@ Ref: https://keepachangelog.com/en/1.0.0/ * Attribute module param migration [#1927](https://github.com/provenance-io/provenance/pull/1927) * Marker module param migration [#1934](https://github.com/provenance-io/provenance/pull/1934) * Metadata module param migration [#1932](https://github.com/provenance-io/provenance/pull/1932) +* Restore the hold module [#1930](https://github.com/provenance-io/provenance/pull/1930). +* Restore gov-prop cli commands and fix next key decoding [#1930](https://github.com/provenance-io/provenance/pull/1930). +* Switch to InputOutputCoinsProv for exchange transfers [#1930](https://github.com/provenance-io/provenance/pull/1930). ### Dependencies diff --git a/Makefile b/Makefile index 001783950a..b7a34cd5c7 100644 --- a/Makefile +++ b/Makefile @@ -132,7 +132,7 @@ install: go.sum CGO_LDFLAGS="$(CGO_LDFLAGS)" CGO_CFLAGS="$(CGO_CFLAGS)" $(GO) install $(BUILD_FLAGS) ./cmd/provenanced build: validate-go-version go.sum - # TODO[1760]: Remove this delay once we're stable again. +# TODO[1760]: Remove this delay once we're stable again. @if [ -z "${ACK_50}" ]; then printf '\033[93mWARNING:\033[0m This branch is currently unstable and should not be built for use.\n To bypass this 10 second delay: ACK_50=1 make build\n'; sleep 10; fi mkdir -p $(BUILDDIR) CGO_LDFLAGS="$(CGO_LDFLAGS)" CGO_CFLAGS="$(CGO_CFLAGS)" $(GO) build -o $(BUILDDIR)/ $(BUILD_FLAGS) ./cmd/provenanced @@ -330,14 +330,15 @@ PACKAGES := $(shell $(GO) list ./... 2>/dev/null || true) PACKAGES_NOSIMULATION := $(filter-out %/simulation%,$(PACKAGES)) PACKAGES_SIMULATION := $(filter %/simulation%,$(PACKAGES)) -TEST_PACKAGES=./... -TEST_TARGETS := test-unit test-unit-amino test-unit-proto test-ledger-mock test-race test-ledger test-race +TEST_PACKAGES ?= ./... +TEST_TARGETS := test-unit test-unit-proto test-ledger-mock test-race test-ledger build-tests # Test runs-specific rules. To add a new test target, just add # a new rule, customise TAGS, ARGS and/or TEST_PACKAGES ad libitum, and # append the new rule to the TEST_TARGETS list. test-unit: TAGS+=cgo ledger test_ledger_mock norace -test-unit-amino: TAGS+=ledger test_ledger_mock test_amino norace +build-tests: TAGS+=cgo ledger test_ledger_mock norace +build-tests: ARGS+=-run='ZYX_NOPE_NOPE_XYZ' test-ledger: TAGS+=cgo ledger norace test-ledger-mock: TAGS+=ledger test_ledger_mock norace test-race: ARGS+=-race @@ -345,14 +346,6 @@ test-race: TAGS+=cgo ledger test_ledger_mock test-race: TEST_PACKAGES=$(PACKAGES_NOSIMULATION) $(TEST_TARGETS): run-tests -# check-* compiles and collects tests without running them -# note: go test -c doesn't support multiple packages yet (https://github.com/golang/go/issues/15513) -CHECK_TEST_TARGETS := check-test-unit check-test-unit-amino -check-test-unit: TAGS+=cgo ledger test_ledger_mock norace -check-test-unit-amino: TAGS+=ledger test_ledger_mock test_amino norace -$(CHECK_TEST_TARGETS): ARGS+=-run=none -$(CHECK_TEST_TARGETS): run-tests - run-tests: go.sum ifneq (,$(shell which tparse 2>/dev/null)) $(GO) test -mod=readonly -json $(ARGS) -tags='$(TAGS)' $(TEST_PACKAGES) | tparse @@ -360,20 +353,13 @@ else $(GO) test -mod=readonly $(ARGS) -tags='$(TAGS)' $(TEST_PACKAGES) endif -build-tests: go.sum -ifneq (,$(shell which tparse 2>/dev/null)) - $(GO) test -mod=readonly -json $(ARGS) -tags='$(TAGS)' -run='ZYX_NOPE_NOPE_XYZ' $(TEST_PACKAGES) | tparse -else - $(GO) test -mod=readonly $(ARGS) -tags='$(TAGS)' -run='ZYX_NOPE_NOPE_XYZ' $(TEST_PACKAGES) -endif - test-cover: export VERSION=$(VERSION); bash -x contrib/test_cover.sh benchmark: $(GO) test -mod=readonly -bench=. $(PACKAGES_NOSIMULATION) -.PHONY: test test-all test-unit test-race test-cover benchmark run-tests build-tests $(TEST_TARGETS) +.PHONY: test test-all test-cover benchmark run-tests build-tests $(TEST_TARGETS) ############################## # Test Network Targets diff --git a/app/app.go b/app/app.go index 45a3550163..d7013845c7 100644 --- a/app/app.go +++ b/app/app.go @@ -8,21 +8,20 @@ import ( "path/filepath" "strings" - "github.com/CosmWasm/wasmd/x/wasm" - wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" - wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" "github.com/gorilla/mux" "github.com/rakyll/statik/fs" "github.com/spf13/cast" "github.com/spf13/viper" + "github.com/CosmWasm/wasmd/x/wasm" + wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" + wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" + abci "github.com/cometbft/cometbft/abci/types" cmtos "github.com/cometbft/cometbft/libs/os" "cosmossdk.io/log" sdkmath "cosmossdk.io/math" - "cosmossdk.io/x/tx/signing" - storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/evidence" evidencekeeper "cosmossdk.io/x/evidence/keeper" @@ -30,12 +29,10 @@ import ( "cosmossdk.io/x/feegrant" feegrantkeeper "cosmossdk.io/x/feegrant/keeper" feegrantmodule "cosmossdk.io/x/feegrant/module" + "cosmossdk.io/x/tx/signing" "cosmossdk.io/x/upgrade" upgradekeeper "cosmossdk.io/x/upgrade/keeper" upgradetypes "cosmossdk.io/x/upgrade/types" - "github.com/cosmos/cosmos-sdk/codec/address" - "github.com/cosmos/cosmos-sdk/std" - "github.com/cosmos/gogoproto/proto" icq "github.com/cosmos/ibc-apps/modules/async-icq/v8" icqkeeper "github.com/cosmos/ibc-apps/modules/async-icq/v8/keeper" @@ -47,11 +44,13 @@ import ( "github.com/cosmos/cosmos-sdk/client/grpc/cmtservice" nodeservice "github.com/cosmos/cosmos-sdk/client/grpc/node" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/server/api" serverconfig "github.com/cosmos/cosmos-sdk/server/config" servertypes "github.com/cosmos/cosmos-sdk/server/types" + "github.com/cosmos/cosmos-sdk/std" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" sigtypes "github.com/cosmos/cosmos-sdk/types/tx/signing" @@ -107,11 +106,12 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/cosmos/gogoproto/proto" + "github.com/cosmos/ibc-go/modules/capability" capabilitykeeper "github.com/cosmos/ibc-go/modules/capability/keeper" capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types" ica "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts" - icahost "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts/host" icahostkeeper "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts/host/keeper" icahosttypes "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts/host/types" @@ -248,7 +248,7 @@ type App struct { // keepers AccountKeeper authkeeper.AccountKeeper - BankKeeper bankkeeper.Keeper + BankKeeper bankkeeper.BaseKeeper CapabilityKeeper *capabilitykeeper.Keeper StakingKeeper *stakingkeeper.Keeper SlashingKeeper slashingkeeper.Keeper diff --git a/app/app_test.go b/app/app_test.go index bd3769afdf..62abf5c52f 100644 --- a/app/app_test.go +++ b/app/app_test.go @@ -11,7 +11,6 @@ import ( "cosmossdk.io/log" sdkmath "cosmossdk.io/math" - sdksim "cosmossdk.io/simapp" dbm "github.com/cosmos/cosmos-db" sdktypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -159,7 +158,7 @@ func TestExportAppStateAndValidators(t *testing.T) { exported, err := app.ExportAppStateAndValidators(false, nil, nil) require.NoError(t, err, "ExportAppStateAndValidators") - var genState sdksim.GenesisState + var genState map[string]json.RawMessage err = json.Unmarshal(exported.AppState, &genState) require.NoError(t, err, "unmarshalling exported app state") diff --git a/app/params/amino.go b/app/params/amino.go deleted file mode 100644 index c7d8ba0045..0000000000 --- a/app/params/amino.go +++ /dev/null @@ -1,27 +0,0 @@ -//go:build test_amino -// +build test_amino - -package params - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" -) - -// MakeTestEncodingConfig creates an EncodingConfig for an amino based test configuration. -// This function should be used only internally (in the SDK). -// App user shouldn't create new codecs - use the app.AppCodec instead. -// [DEPRECATED] -func MakeTestEncodingConfig() EncodingConfig { - cdc := codec.NewLegacyAmino() - interfaceRegistry := types.NewInterfaceRegistry() - marshaler := codec.NewAminoCodec(cdc) - - return EncodingConfig{ - InterfaceRegistry: interfaceRegistry, - Marshaler: marshaler, - TxConfig: legacytx.StdTxConfig{Cdc: cdc}, - Amino: cdc, - } -} diff --git a/app/params/proto.go b/app/params/proto.go index e046afbd7b..983cf7159f 100644 --- a/app/params/proto.go +++ b/app/params/proto.go @@ -1,10 +1,8 @@ -//go:build !test_amino -// +build !test_amino - package params import ( "cosmossdk.io/x/tx/signing" + "github.com/cosmos/cosmos-sdk/codec" amino "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/address" @@ -19,8 +17,7 @@ import ( // App user shouldn't create new codecs - use the app.AppCodec instead. // // TODO[1760]: Update all the simulation stuff that uses this to instead get what's needed from the SimState. -// That will involve passing the SimSate into many places where we used to provide a codec. -// Then delete this file and amino.go, and clean up stuff in the Makefile that uses the test_amino tag. +// That will involve passing the SimSate into many places where we used to provide a codec. Then, delete this file. // // Deprecated: Either get this from the app (app.GetEncodingConfig()) or use MakeTestEncodingConfig (from the app package), // or get what's needed from the SimSate. diff --git a/app/sim_test.go b/app/sim_test.go index f320d10023..aa6e075bc2 100644 --- a/app/sim_test.go +++ b/app/sim_test.go @@ -19,7 +19,6 @@ import ( cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" "cosmossdk.io/log" - sdksim "cosmossdk.io/simapp" "cosmossdk.io/store" storetypes "cosmossdk.io/store/types" evidencetypes "cosmossdk.io/x/evidence/types" @@ -71,7 +70,7 @@ type StoreKeysPrefixes struct { Prefixes [][]byte } -// ProvAppStateFn wraps the sdksim.AppStateFn and sets the ICA GenesisState if isn't yet defined in the appState. +// ProvAppStateFn wraps the simtypes.AppStateFn and sets the ICA GenesisState if isn't yet defined in the appState. func ProvAppStateFn(cdc codec.JSONCodec, simManager *module.SimulationManager, genesisState map[string]json.RawMessage) simtypes.AppStateFn { return func(r *rand.Rand, accs []simtypes.Account, config simtypes.Config) (json.RawMessage, []simtypes.Account, string, time.Time) { appState, simAccs, chainID, genesisTimestamp := simtestutil.AppStateFn(cdc, simManager, genesisState)(r, accs, config) @@ -201,7 +200,7 @@ func TestSimple(t *testing.T) { // /usr/local/go/bin/go test -benchmem -run=^$ github.com/provenance-io/provenance -bench ^BenchmarkFullAppSimulation$ -Commit=true -cpuprofile cpu.out func TestAppImportExport(t *testing.T) { // uncomment to run in ide without flags. - //sdksim.FlagEnabledValue = true + //simcli.FlagEnabledValue = true config, db, dir, logger, skip, err := setupSimulation("leveldb-app-sim", "Simulation") if skip { @@ -257,7 +256,7 @@ func TestAppImportExport(t *testing.T) { newApp := New(log.NewNopLogger(), newDB, nil, true, map[int64]bool{}, home, simcli.FlagPeriodValue, simtestutil.EmptyAppOptions{}, fauxMerkleModeOpt) - var genesisState sdksim.GenesisState + var genesisState map[string]json.RawMessage err = json.Unmarshal(exported.AppState, &genesisState) require.NoError(t, err) @@ -402,9 +401,9 @@ func TestAppSimulationAfterImport(t *testing.T) { // and doesn't depend on the application. func TestAppStateDeterminism(t *testing.T) { // uncomment these to run in ide without flags. - //sdksim.FlagEnabledValue = true - //sdksim.FlagBlockSizeValue = 100 - //sdksim.FlagNumBlocksValue = 50 + //simcli.FlagEnabledValue = true + //simcli.FlagBlockSizeValue = 100 + //simcli.FlagNumBlocksValue = 50 if !simcli.FlagEnabledValue { t.Skip("skipping application simulation") diff --git a/app/upgrades.go b/app/upgrades.go index 1b4f6e92bc..d1dbf5fa8f 100644 --- a/app/upgrades.go +++ b/app/upgrades.go @@ -6,9 +6,11 @@ import ( storetypes "cosmossdk.io/store/types" upgradetypes "cosmossdk.io/x/upgrade/types" + "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" "github.com/cosmos/ibc-go/v8/modules/core/exported" @@ -49,7 +51,7 @@ var upgrades = map[string]appUpgrade{ Handler: func(ctx sdk.Context, app *App, vm module.VersionMap) (module.VersionMap, error) { var err error - if err := pruneIBCExpiredConsensusStates(ctx, app); err != nil { + if err = pruneIBCExpiredConsensusStates(ctx, app); err != nil { return nil, err } @@ -58,6 +60,11 @@ var upgrades = map[string]appUpgrade{ return nil, err } + err = migrateBankParams(ctx, app) + if err != nil { + return nil, err + } + migrateAttributeParams(ctx, app) migrateMarkerParams(ctx, app) migrateMetadataOSLocatorParams(ctx, app) @@ -83,7 +90,7 @@ var upgrades = map[string]appUpgrade{ Handler: func(ctx sdk.Context, app *App, vm module.VersionMap) (module.VersionMap, error) { var err error - if err := pruneIBCExpiredConsensusStates(ctx, app); err != nil { + if err = pruneIBCExpiredConsensusStates(ctx, app); err != nil { return nil, err } @@ -92,6 +99,11 @@ var upgrades = map[string]appUpgrade{ return nil, err } + err = migrateBankParams(ctx, app) + if err != nil { + return nil, err + } + migrateAttributeParams(ctx, app) migrateMarkerParams(ctx, app) migrateMetadataOSLocatorParams(ctx, app) @@ -262,7 +274,7 @@ func pruneIBCExpiredConsensusStates(ctx sdk.Context, app *App) error { ctx.Logger().Info("Pruning expired consensus states for IBC.") _, err := ibctmmigrations.PruneExpiredConsensusStates(ctx, app.appCodec, app.IBCKeeper.ClientKeeper) if err != nil { - ctx.Logger().Error(fmt.Sprintf("unable to prune expired consensus states, error: %s.", err)) + ctx.Logger().Error(fmt.Sprintf("Unable to prune expired consensus states, error: %s.", err)) return err } ctx.Logger().Info("Done pruning expired consensus states for IBC.") @@ -287,13 +299,34 @@ func migrateBaseappParams(ctx sdk.Context, app *App) error { legacyBaseAppSubspace := app.ParamsKeeper.Subspace(baseapp.Paramspace).WithKeyTable(paramstypes.ConsensusParamsKeyTable()) err := baseapp.MigrateParams(ctx, legacyBaseAppSubspace, app.ConsensusParamsKeeper.ParamsStore) if err != nil { - ctx.Logger().Error(fmt.Sprintf("unable to migrate legacy params to ConsensusParamsKeeper, error: %s.", err)) + ctx.Logger().Error(fmt.Sprintf("Unable to migrate legacy params to ConsensusParamsKeeper, error: %s.", err)) return err } ctx.Logger().Info("Done migrating legacy params.") return nil } +// migrateBankParams migrates the bank params from the params module to the bank module's state. +// The SDK has this as part of their bank v4 migration, but we're already on v4, so that one +// won't run on its own. This is the only part of that migration that we still need to have +// done, and this brings us in-line with format the bank state on v4. +// TODO: delete with the umber handlers. +func migrateBankParams(ctx sdk.Context, app *App) (err error) { + ctx.Logger().Info("Migrating bank params.") + defer func() { + if err != nil { + ctx.Logger().Error(fmt.Sprintf("Unable to migrate bank params, error: %s.", err)) + } + ctx.Logger().Info("Done migrating bank params.") + }() + + bankParamsSpace, ok := app.ParamsKeeper.GetSubspace(banktypes.ModuleName) + if !ok { + return fmt.Errorf("params subspace not found: %q", banktypes.ModuleName) + } + return app.BankKeeper.MigrateParamsProv(ctx, bankParamsSpace) +} + // migrateAttributeParams migrates to new Attribute Params store // TODO: Remove with the umber handlers. func migrateAttributeParams(ctx sdk.Context, app *App) { diff --git a/app/upgrades_test.go b/app/upgrades_test.go index 1a33f404cc..4a7b0a6de9 100644 --- a/app/upgrades_test.go +++ b/app/upgrades_test.go @@ -379,6 +379,8 @@ func (s *UpgradeTestSuite) TestUmberRC1() { "INF Done pruning expired consensus states for IBC.", "INF Migrating legacy params.", "INF Done migrating legacy params.", + "INF Migrating bank params.", + "INF Done migrating bank params.", "INF Migrating attribute params.", "INF Done migrating attribute params.", "INF Migrating marker params.", @@ -402,6 +404,8 @@ func (s *UpgradeTestSuite) TestUmber() { "INF Done pruning expired consensus states for IBC.", "INF Migrating legacy params.", "INF Done migrating legacy params.", + "INF Migrating bank params.", + "INF Done migrating bank params.", "INF Migrating attribute params.", "INF Done migrating attribute params.", "INF Migrating marker params.", diff --git a/go.mod b/go.mod index f4acc75093..c5599e5824 100644 --- a/go.mod +++ b/go.mod @@ -8,7 +8,6 @@ require ( cosmossdk.io/errors v1.0.1 cosmossdk.io/log v1.3.1 cosmossdk.io/math v1.3.0 - cosmossdk.io/simapp v0.0.0-20231107193120-9814f684b9dd // TODO[1760]: Copy needed stuff out of simapp and remove this require. cosmossdk.io/store v1.0.2 cosmossdk.io/x/evidence v0.1.0 cosmossdk.io/x/feegrant v0.1.0 @@ -58,7 +57,6 @@ require ( cosmossdk.io/client/v2 v2.0.0-beta.1 // indirect cosmossdk.io/depinject v1.0.0-alpha.4 // indirect cosmossdk.io/x/circuit v0.1.0 // indirect - cosmossdk.io/x/nft v0.1.0 // indirect filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect github.com/99designs/keyring v1.2.2 // indirect @@ -216,8 +214,7 @@ replace ( // This is required for https://github.com/provenance-io/provenance/issues/1414 // TODO[1760]: wasm: Put this CosmWasm/wasmd replace back with an updated version (or delete it). // github.com/CosmWasm/wasmd => github.com/provenance-io/wasmd v0.30.0-pio-5 - // TODO[1760]: sdk: Put this replace back with an updated version of the sdk from our fork. - github.com/cosmos/cosmos-sdk => github.com/provenance-io/cosmos-sdk v0.50.5-pio-2 + github.com/cosmos/cosmos-sdk => github.com/provenance-io/cosmos-sdk v0.50.5-pio-3 // TODO[1760]: Update once async-icq creates tag with our changes https://github.com/cosmos/ibc-apps/pull/168 github.com/cosmos/ibc-apps/modules/async-icq/v8 => github.com/provenance-io/ibc-apps/modules/async-icq/v8 v8.0.0-prov-1 diff --git a/go.sum b/go.sum index 8d8557c281..c7a3c42cc4 100644 --- a/go.sum +++ b/go.sum @@ -200,8 +200,6 @@ cosmossdk.io/log v1.3.1 h1:UZx8nWIkfbbNEWusZqzAx3ZGvu54TZacWib3EzUYmGI= cosmossdk.io/log v1.3.1/go.mod h1:2/dIomt8mKdk6vl3OWJcPk2be3pGOS8OQaLUM/3/tCM= cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= cosmossdk.io/math v1.3.0/go.mod h1:vnRTxewy+M7BtXBNFybkuhSH4WfedVAAnERHgVFhp3k= -cosmossdk.io/simapp v0.0.0-20231107193120-9814f684b9dd h1:KwV+LjYFc4N+KwUrPtCfKW6m+zIdCI0kz1Zr+RrDW/Y= -cosmossdk.io/simapp v0.0.0-20231107193120-9814f684b9dd/go.mod h1:qnOJ7OPtF1kNzces9lnB3vpeMhQu4uQE9i+h0+vb+RA= cosmossdk.io/store v1.0.2 h1:lSg5BTvJBHUDwswNNyeh4K/CbqiHER73VU4nDNb8uk0= cosmossdk.io/store v1.0.2/go.mod h1:EFtENTqVTuWwitGW1VwaBct+yDagk7oG/axBMPH+FXs= cosmossdk.io/x/circuit v0.1.0 h1:IAej8aRYeuOMritczqTlljbUVHq1E85CpBqaCTwYgXs= @@ -916,8 +914,8 @@ github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4O github.com/prometheus/procfs v0.3.0/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= github.com/prometheus/procfs v0.12.0 h1:jluTpSng7V9hY0O2R9DzzJHYb2xULk9VTR1V1R/k6Bo= github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3cnaOZAZEfOo= -github.com/provenance-io/cosmos-sdk v0.50.5-pio-2 h1:qK+ZN2jBBFEOZZOpefAMBrU5mWj+znU87Gvxbsl8feA= -github.com/provenance-io/cosmos-sdk v0.50.5-pio-2/go.mod h1:oV/k6GJgXV9QPoM2fsYDPPsyPBgQbdotv532O6Mz1OQ= +github.com/provenance-io/cosmos-sdk v0.50.5-pio-3 h1:QwJ4feMM43a9fu2YZ1oSHd1wqEIsANDdqXKsoOin85Q= +github.com/provenance-io/cosmos-sdk v0.50.5-pio-3/go.mod h1:oV/k6GJgXV9QPoM2fsYDPPsyPBgQbdotv532O6Mz1OQ= github.com/provenance-io/ibc-apps/modules/async-icq/v8 v8.0.0-prov-1 h1:p+7pxHB0ukO2aow+M6uW9gHgeQl7YJyYGyMSKHZ5My8= github.com/provenance-io/ibc-apps/modules/async-icq/v8 v8.0.0-prov-1/go.mod h1:tObW9uxibh5Z22CtOaHVeTDotCSMyc/2B4MrYdaViBo= github.com/rakyll/statik v0.1.7 h1:OF3QCZUuyPxuGEP7B4ypUa7sB/iHtqOTDYZXGM8KOdQ= diff --git a/internal/provcli/cli_helpers.go b/internal/provcli/cli_helpers.go index 4872465f9b..b4a38ceac3 100644 --- a/internal/provcli/cli_helpers.go +++ b/internal/provcli/cli_helpers.go @@ -8,7 +8,6 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" govcli "github.com/cosmos/cosmos-sdk/x/gov/client/cli" @@ -43,8 +42,8 @@ func GetAuthority(flagSet *pflag.FlagSet) string { } // GenerateOrBroadcastTxCLIAsGovProp wraps the provided msgs in a governance proposal -// and calls GenerateOrBroadcastTxCLI for that proposal. -// At least one msg is required. +// and calls GenerateOrBroadcastTxCLI for that proposal. At least one msg is required. +// // This uses flags added by govcli.AddGovPropFlagsToCmd to fill in the rest of the proposal. func GenerateOrBroadcastTxCLIAsGovProp(clientCtx client.Context, flagSet *pflag.FlagSet, msgs ...sdk.Msg) error { if len(msgs) == 0 { @@ -56,15 +55,9 @@ func GenerateOrBroadcastTxCLIAsGovProp(clientCtx client.Context, flagSet *pflag. return err } - prop.Messages = make([]*codectypes.Any, len(msgs)) - for i, msg := range msgs { - prop.Messages[i], err = codectypes.NewAnyWithValue(msg) - if err != nil { - if len(msgs) == 1 { - return fmt.Errorf("could not wrap %T message as Any: %w", msg, err) - } - return fmt.Errorf("could not wrap message %d (%T) as Any: %w", i, msg, err) - } + err = prop.SetMsgs(msgs) + if err != nil { + return fmt.Errorf("error wrapping msg(s) as Any: %w", err) } return tx.GenerateOrBroadcastTxCLI(clientCtx, flagSet, prop) diff --git a/x/attribute/client/cli/query.go b/x/attribute/client/cli/query.go index 8b9c5b5577..236a156fcb 100644 --- a/x/attribute/client/cli/query.go +++ b/x/attribute/client/cli/query.go @@ -84,7 +84,7 @@ func GetAccountAttributeCmd() *cobra.Command { } queryClient := types.NewQueryClient(clientCtx) - pageReq, err := client.ReadPageRequest(cmd.Flags()) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + pageReq, err := client.ReadPageRequestWithPageKeyDecoded(cmd.Flags()) if err != nil { return err } @@ -130,7 +130,7 @@ func ListAccountAttributesCmd() *cobra.Command { } queryClient := types.NewQueryClient(clientCtx) - pageReq, err := client.ReadPageRequest(cmd.Flags()) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + pageReq, err := client.ReadPageRequestWithPageKeyDecoded(cmd.Flags()) if err != nil { return err } @@ -174,7 +174,7 @@ func ScanAccountAttributesCmd() *cobra.Command { } queryClient := types.NewQueryClient(clientCtx) - pageReq, err := client.ReadPageRequest(cmd.Flags()) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + pageReq, err := client.ReadPageRequestWithPageKeyDecoded(cmd.Flags()) if err != nil { return err } @@ -219,7 +219,7 @@ func GetAttributeAccountsCmd() *cobra.Command { } queryClient := types.NewQueryClient(clientCtx) - pageReq, err := client.ReadPageRequest(cmd.Flags()) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + pageReq, err := client.ReadPageRequestWithPageKeyDecoded(cmd.Flags()) if err != nil { return err } diff --git a/x/exchange/client/cli/helpers.go b/x/exchange/client/cli/helpers.go index a04252beab..e7c0aa3c39 100644 --- a/x/exchange/client/cli/helpers.go +++ b/x/exchange/client/cli/helpers.go @@ -5,7 +5,6 @@ import ( "fmt" "strings" - "github.com/cosmos/gogoproto/proto" "github.com/spf13/cobra" "github.com/spf13/pflag" "google.golang.org/grpc" @@ -16,11 +15,11 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - // govcli "github.com/cosmos/cosmos-sdk/x/gov/client/cli" // TODO[1760]: gov-cli govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" + "github.com/cosmos/gogoproto/proto" + "github.com/provenance-io/provenance/internal/provcli" "github.com/provenance-io/provenance/x/exchange" ) @@ -79,9 +78,7 @@ func govTxRunE[R sdk.Msg](maker msgMaker[R]) func(cmd *cobra.Command, args []str } cmd.SilenceUsage = true - // return govcli.GenerateOrBroadcastTxCLIAsGovProp(clientCtx, flagSet, msg) // TODO[1760]: gov-cli - _ = msg - return fmt.Errorf("not yet updated") + return provcli.GenerateOrBroadcastTxCLIAsGovProp(clientCtx, flagSet, msg) } } diff --git a/x/exchange/client/cli/query_setup.go b/x/exchange/client/cli/query_setup.go index 886b5bf02f..a16e5ec4d1 100644 --- a/x/exchange/client/cli/query_setup.go +++ b/x/exchange/client/cli/query_setup.go @@ -185,7 +185,7 @@ func MakeQueryGetMarketOrders(_ client.Context, flagSet *pflag.FlagSet, args []s req.MarketId, errs[0] = ReadFlagMarketOrArg(flagSet, args) req.OrderType, errs[1] = ReadFlagsAsksBidsOpt(flagSet) req.AfterOrderId, errs[2] = flagSet.GetUint64(FlagAfter) - req.Pagination, errs[3] = client.ReadPageRequest(flagSet) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + req.Pagination, errs[3] = client.ReadPageRequestWithPageKeyDecoded(flagSet) return req, errors.Join(errs...) } @@ -223,7 +223,7 @@ func MakeQueryGetOwnerOrders(_ client.Context, flagSet *pflag.FlagSet, args []st req.Owner, errs[0] = ReadStringFlagOrArg(flagSet, args, FlagOwner, "owner") req.OrderType, errs[1] = ReadFlagsAsksBidsOpt(flagSet) req.AfterOrderId, errs[2] = flagSet.GetUint64(FlagAfter) - req.Pagination, errs[3] = client.ReadPageRequest(flagSet) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + req.Pagination, errs[3] = client.ReadPageRequestWithPageKeyDecoded(flagSet) return req, errors.Join(errs...) } @@ -261,7 +261,7 @@ func MakeQueryGetAssetOrders(_ client.Context, flagSet *pflag.FlagSet, args []st req.Asset, errs[0] = ReadStringFlagOrArg(flagSet, args, FlagDenom, "asset") req.OrderType, errs[1] = ReadFlagsAsksBidsOpt(flagSet) req.AfterOrderId, errs[2] = flagSet.GetUint64(FlagAfter) - req.Pagination, errs[3] = client.ReadPageRequest(flagSet) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + req.Pagination, errs[3] = client.ReadPageRequestWithPageKeyDecoded(flagSet) return req, errors.Join(errs...) } @@ -284,7 +284,7 @@ func MakeQueryGetAllOrders(_ client.Context, flagSet *pflag.FlagSet, _ []string) req := &exchange.QueryGetAllOrdersRequest{} var err error - req.Pagination, err = client.ReadPageRequest(flagSet) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + req.Pagination, err = client.ReadPageRequestWithPageKeyDecoded(flagSet) return req, err } @@ -439,7 +439,7 @@ func MakeQueryGetAllMarkets(_ client.Context, flagSet *pflag.FlagSet, _ []string req := &exchange.QueryGetAllMarketsRequest{} var err error - req.Pagination, err = client.ReadPageRequest(flagSet) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + req.Pagination, err = client.ReadPageRequestWithPageKeyDecoded(flagSet) return req, err } diff --git a/x/exchange/client/cli/tx.go b/x/exchange/client/cli/tx.go index ef9c3e4b27..e3fb6fc1c3 100644 --- a/x/exchange/client/cli/tx.go +++ b/x/exchange/client/cli/tx.go @@ -7,7 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - // govcli "github.com/cosmos/cosmos-sdk/x/gov/client/cli" // TODO[1760]: gov-cli + govcli "github.com/cosmos/cosmos-sdk/x/gov/client/cli" "github.com/provenance-io/provenance/x/exchange" ) @@ -402,7 +402,7 @@ func CmdTxGovCreateMarket() *cobra.Command { } flags.AddTxFlagsToCmd(cmd) - // govcli.AddGovPropFlagsToCmd(cmd) // TODO[1760]: gov-cli + govcli.AddGovPropFlagsToCmd(cmd) SetupCmdTxGovCreateMarket(cmd) return cmd } @@ -417,7 +417,7 @@ func CmdTxGovManageFees() *cobra.Command { } flags.AddTxFlagsToCmd(cmd) - // govcli.AddGovPropFlagsToCmd(cmd) // TODO[1760]: gov-cli + govcli.AddGovPropFlagsToCmd(cmd) SetupCmdTxGovManageFees(cmd) return cmd } @@ -432,7 +432,7 @@ func CmdTxGovCloseMarket() *cobra.Command { } flags.AddTxFlagsToCmd(cmd) - // govcli.AddGovPropFlagsToCmd(cmd) // TODO[1760]: gov-cli + govcli.AddGovPropFlagsToCmd(cmd) SetupCmdTxGovCloseMarket(cmd) return cmd } @@ -447,7 +447,7 @@ func CmdTxGovUpdateParams() *cobra.Command { } flags.AddTxFlagsToCmd(cmd) - // govcli.AddGovPropFlagsToCmd(cmd) // TODO[1760]: gov-cli + govcli.AddGovPropFlagsToCmd(cmd) SetupCmdTxGovUpdateParams(cmd) return cmd } diff --git a/x/exchange/expected_keepers.go b/x/exchange/expected_keepers.go index e615eed334..28ba2115da 100644 --- a/x/exchange/expected_keepers.go +++ b/x/exchange/expected_keepers.go @@ -4,6 +4,7 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" attrtypes "github.com/provenance-io/provenance/x/attribute/types" markertypes "github.com/provenance-io/provenance/x/marker/types" ) @@ -22,8 +23,7 @@ type AttributeKeeper interface { type BankKeeper interface { SendCoins(ctx context.Context, fromAddr, toAddr sdk.AccAddress, amt sdk.Coins) error SendCoinsFromAccountToModule(ctx context.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - // TODO[1760]: exchange: Put InputOutputCoins back in this expected keeper once our fork is back in place. - // InputOutputCoins(ctx context.Context, inputs []banktypes.Input, outputs []banktypes.Output) error + InputOutputCoinsProv(ctx context.Context, inputs []banktypes.Input, outputs []banktypes.Output) error BlockedAddr(addr sdk.AccAddress) bool } diff --git a/x/exchange/keeper/keeper.go b/x/exchange/keeper/keeper.go index 6aa0a0d0f4..e7bdd856a8 100644 --- a/x/exchange/keeper/keeper.go +++ b/x/exchange/keeper/keeper.go @@ -221,9 +221,7 @@ func (k Keeper) DoTransfer(ctxIn sdk.Context, inputs []banktypes.Input, outputs } } - // TODO[1760]: exchange: Put this back once we have InputOutputCoins again. - // return k.bankKeeper.InputOutputCoins(ctx, inputs, outputs) - return nil + return k.bankKeeper.InputOutputCoinsProv(ctx, inputs, outputs) } // CalculateExchangeSplit calculates the amount that the exchange will keep of the provided fee. @@ -301,11 +299,9 @@ func (k Keeper) CollectFees(ctx sdk.Context, marketID uint32, inputs []banktypes marketAddr := exchange.GetMarketAddress(marketID) outputs := []banktypes.Output{{Address: marketAddr.String(), Coins: feeAmt}} - // TODO[1760]: exchange: Put this back once we have InputOutputCoins again. - _ = outputs - // if err := k.bankKeeper.InputOutputCoins(ctx, inputs, outputs); err != nil { - // return fmt.Errorf("error collecting fees for market %d: %w", marketID, err) - // } + if err := k.bankKeeper.InputOutputCoinsProv(ctx, inputs, outputs); err != nil { + return fmt.Errorf("error collecting fees for market %d: %w", marketID, err) + } if !exchangeAmt.IsZero() { if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, marketAddr, k.feeCollectorName, exchangeAmt); err != nil { return fmt.Errorf("error collecting exchange fee %s (based off %s) from market %d: %w", exchangeAmt, feeAmt, marketID, err) diff --git a/x/exchange/keeper/mocks_test.go b/x/exchange/keeper/mocks_test.go index 61b943d9e8..a65112737e 100644 --- a/x/exchange/keeper/mocks_test.go +++ b/x/exchange/keeper/mocks_test.go @@ -353,7 +353,7 @@ func (k *MockBankKeeper) SendCoinsFromAccountToModule(ctx context.Context, sende return err } -func (k *MockBankKeeper) InputOutputCoins(ctx context.Context, inputs []banktypes.Input, outputs []banktypes.Output) error { +func (k *MockBankKeeper) InputOutputCoinsProv(ctx context.Context, inputs []banktypes.Input, outputs []banktypes.Output) error { k.Calls.InputOutputCoins = append(k.Calls.InputOutputCoins, NewInputOutputCoinsArgs(ctx, inputs, outputs)) var err error if len(k.InputOutputCoinsResultsQueue) > 0 { diff --git a/x/hold/client/cli/cli_test.go b/x/hold/client/cli/cli_test.go index 1ced76734f..f6fdd85566 100644 --- a/x/hold/client/cli/cli_test.go +++ b/x/hold/client/cli/cli_test.go @@ -6,11 +6,12 @@ import ( "testing" "time" - "github.com/cosmos/gogoproto/proto" "github.com/ghodss/yaml" "github.com/spf13/cobra" "github.com/stretchr/testify/suite" + "github.com/cosmos/gogoproto/proto" + cmtcli "github.com/cometbft/cometbft/libs/cli" "github.com/cosmos/cosmos-sdk/client/flags" @@ -24,6 +25,7 @@ import ( "github.com/provenance-io/provenance/internal/antewrapper" "github.com/provenance-io/provenance/internal/pioconfig" "github.com/provenance-io/provenance/testutil" + "github.com/provenance-io/provenance/testutil/queries" "github.com/provenance-io/provenance/x/hold" "github.com/provenance-io/provenance/x/hold/client/cli" holdkeeper "github.com/provenance-io/provenance/x/hold/keeper" @@ -130,8 +132,8 @@ func (s *IntegrationCLITestSuite) SetupSuite() { // - One denom fully on hold. s.addr1Desc = "addr with large amounts" addr1Plus := "15banana,5000000000000000000000hugecoin,1xenon" - addr1Esrow := "5banana,2000000000000000000000hugecoin,1xenon" - s.addr1Bal, s.addr1Hold, s.addr1Spendable = newAmounts("addr1", addr1Plus, addr1Esrow) + addr1Escrow := "5banana,2000000000000000000000hugecoin,1xenon" + s.addr1Bal, s.addr1Hold, s.addr1Spendable = newAmounts("addr1", addr1Plus, addr1Escrow) // addr2 characteristics: // - One extra denom. @@ -505,53 +507,42 @@ func (s *IntegrationCLITestSuite) TestQueryCmdGetAllHolds() { func (s *IntegrationCLITestSuite) TestHoldsNotInFromSpendable() { // The purpose of these tests is to make sure that the bank module is // being properly informed of the locked hold funds. - cmdGen := func() *cobra.Command { - // TODO[1760]: bank: Put this back once we know how to query spendable balances again. - return nil - // return bankcli.GetSpendableBalancesCmd() - } - resp := func(balances sdk.Coins) *banktypes.QuerySpendableBalancesResponse { - return &banktypes.QuerySpendableBalancesResponse{ - Balances: balances, - Pagination: &query.PageResponse{ - NextKey: nil, - Total: 0, - }, - } - } - - tests := []queryCmdTestCase{ + tests := []struct { + name string + addr sdk.AccAddress + exp sdk.Coins + }{ { - name: s.addr1Desc + ": get spendable", - args: []string{s.addr1.String(), s.flagAsJSON}, - expOut: s.asJSON(resp(s.addr1Spendable)), + name: s.addr1Desc + ": get spendable", + addr: s.addr1, + exp: s.addr1Spendable, }, { - name: s.addr2Desc + ": get spendable", - args: []string{s.addr2.String(), s.flagAsJSON}, - expOut: s.asJSON(resp(s.addr2Spendable)), + name: s.addr2Desc + ": get spendable", + addr: s.addr2, + exp: s.addr2Spendable, }, { - name: s.addr3Desc + ": get spendable", - args: []string{s.addr3.String(), s.flagAsJSON}, - expOut: s.asJSON(resp(s.addr3Spendable)), + name: s.addr3Desc + ": get spendable", + addr: s.addr3, + exp: s.addr3Spendable, }, { - name: s.addr4Desc + ": get spendable", - args: []string{s.addr4.String(), s.flagAsJSON}, - expOut: s.asJSON(resp(s.addr4Spendable)), + name: s.addr4Desc + ": get spendable", + addr: s.addr4, + exp: s.addr4Spendable, }, { - name: s.addr5Desc + ": get spendable", - args: []string{s.addr5.String(), s.flagAsJSON}, - expOut: s.asJSON(resp(s.addr5Spendable)), + name: s.addr5Desc + ": get spendable", + addr: s.addr5, + exp: s.addr5Spendable, }, } for _, tc := range tests { s.Run(tc.name, func() { - tc.cmd = cmdGen() - s.assertQueryCmdTestCase(tc) + actual := queries.GetSpendableBalances(s.T(), s.testnet, tc.addr.String()) + s.Assert().Equal(tc.exp.String(), actual.String(), "spendable balances") }) } } diff --git a/x/hold/client/cli/query.go b/x/hold/client/cli/query.go index 49deb2e113..ee83b97c28 100644 --- a/x/hold/client/cli/query.go +++ b/x/hold/client/cli/query.go @@ -87,7 +87,7 @@ func QueryCmdGetAllHolds() *cobra.Command { } req := hold.GetAllHoldsRequest{} - req.Pagination, err = client.ReadPageRequest(cmd.Flags()) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + req.Pagination, err = client.ReadPageRequestWithPageKeyDecoded(cmd.Flags()) if err != nil { return err } diff --git a/x/hold/expected_keepers.go b/x/hold/expected_keepers.go index c2dac5ea89..bea77f2886 100644 --- a/x/hold/expected_keepers.go +++ b/x/hold/expected_keepers.go @@ -4,10 +4,10 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" - // banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" // TODO[1760]: locked-coins + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" ) type BankKeeper interface { - // AppendLockedCoinsGetter(getter banktypes.GetLockedCoinsFn) // TODO[1760]: locked-coins + AppendLockedCoinsGetter(getter banktypes.GetLockedCoinsFn) SpendableCoins(ctx context.Context, addr sdk.AccAddress) sdk.Coins } diff --git a/x/hold/keeper/invariants.go b/x/hold/keeper/invariants.go index c167a58a6f..1919f541b7 100644 --- a/x/hold/keeper/invariants.go +++ b/x/hold/keeper/invariants.go @@ -5,6 +5,7 @@ import ( "strings" sdk "github.com/cosmos/cosmos-sdk/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/provenance-io/provenance/x/hold" ) @@ -44,7 +45,7 @@ func holdAccountBalancesInvariantHelper(ctx sdk.Context, keeper Keeper) (string, // So, long story short (too late), if the block time is zero, also bypass the vesting locked funds getter. blockTime := ctx.BlockTime() if blockTime.IsZero() { - ctx = ctx // banktypes.WithVestingLockedBypass(ctx) // TODO[1760]: locked-coins + ctx = banktypes.WithVestingLockedBypass(ctx) } var addr sdk.AccAddress var total sdk.Coins diff --git a/x/hold/keeper/keeper.go b/x/hold/keeper/keeper.go index e7dd89d263..a6a2c93aae 100644 --- a/x/hold/keeper/keeper.go +++ b/x/hold/keeper/keeper.go @@ -27,7 +27,7 @@ func NewKeeper(cdc codec.BinaryCodec, storeKey storetypes.StoreKey, bankKeeper h storeKey: storeKey, bankKeeper: bankKeeper, } - // bankKeeper.AppendLockedCoinsGetter(rv.GetLockedCoins) // TODO[1760]: locked-coins + bankKeeper.AppendLockedCoinsGetter(rv.GetLockedCoins) return rv } diff --git a/x/hold/keeper/keeper_test.go b/x/hold/keeper/keeper_test.go index 08e21baf0f..cb18fd1e9f 100644 --- a/x/hold/keeper/keeper_test.go +++ b/x/hold/keeper/keeper_test.go @@ -1599,13 +1599,13 @@ func (s *TestSuite) TestVestingAndHoldOverTime() { }, "casting addr account to %T", acc) stepResults[i] = &stepResult{ - step: step, - balance: s.app.BankKeeper.GetAllBalances(ctx, addr), - delegated: s.app.BankKeeper.GetAllBalances(ctx, modAddr), - spendable: s.app.BankKeeper.SpendableCoins(ctx, addr), - locked: s.app.BankKeeper.LockedCoins(ctx, addr), - lockedHold: s.keeper.GetLockedCoins(ctx, addr), - // lockedVest: s.app.BankKeeper.UnvestedCoins(ctx, addr), TODO[1760]: locked-coins + step: step, + balance: s.app.BankKeeper.GetAllBalances(ctx, addr), + delegated: s.app.BankKeeper.GetAllBalances(ctx, modAddr), + spendable: s.app.BankKeeper.SpendableCoins(ctx, addr), + locked: s.app.BankKeeper.LockedCoins(ctx, addr), + lockedHold: s.keeper.GetLockedCoins(ctx, addr), + lockedVest: s.app.BankKeeper.UnvestedCoins(ctx, addr), accVesting: acc.GetVestingCoins(blockTime), accVested: acc.GetVestedCoins(blockTime), accDelegatedVesting: acc.GetDelegatedVesting(), diff --git a/x/hold/keeper/locked_coins.go b/x/hold/keeper/locked_coins.go index ea84dd56a7..30a833e9a5 100644 --- a/x/hold/keeper/locked_coins.go +++ b/x/hold/keeper/locked_coins.go @@ -1,20 +1,22 @@ package keeper import ( + "context" + sdk "github.com/cosmos/cosmos-sdk/types" - // banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" // TODO[1760]: locked-coins + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/provenance-io/provenance/x/hold" ) -// var _ banktypes.GetLockedCoinsFn = Keeper{}.GetLockedCoins // TODO[1760]: locked-coins +var _ banktypes.GetLockedCoinsFn = Keeper{}.GetLockedCoins // GetLockedCoins gets all the coins that are on hold for the given address. -func (k Keeper) GetLockedCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins { +func (k Keeper) GetLockedCoins(ctx context.Context, addr sdk.AccAddress) sdk.Coins { if hold.HasBypass(ctx) { return nil } - rv, err := k.GetHoldCoins(ctx, addr) + rv, err := k.GetHoldCoins(sdk.UnwrapSDKContext(ctx), addr) if err != nil { panic(err) } diff --git a/x/hold/keeper/mock_keepers_test.go b/x/hold/keeper/mock_keepers_test.go index 497fad6cc5..a0efa5310f 100644 --- a/x/hold/keeper/mock_keepers_test.go +++ b/x/hold/keeper/mock_keepers_test.go @@ -4,7 +4,7 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" - // banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" // TODO[1760]: locked-coins + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/provenance-io/provenance/x/hold" ) @@ -28,10 +28,9 @@ func (k *MockBankKeeper) WithSpendable(addr sdk.AccAddress, amount sdk.Coins) *M return k } -// TODO[1760]: locked-coins -// func (k *MockBankKeeper) AppendLockedCoinsGetter(_ banktypes.GetLockedCoinsFn) { -// // Do nothing. -// } +func (k *MockBankKeeper) AppendLockedCoinsGetter(_ banktypes.GetLockedCoinsFn) { + // Do nothing. +} func (k *MockBankKeeper) SpendableCoins(_ context.Context, addr sdk.AccAddress) sdk.Coins { return k.Spendable[string(addr)] diff --git a/x/hold/locked_coins.go b/x/hold/locked_coins.go index ef852c2b79..34b66b29ff 100644 --- a/x/hold/locked_coins.go +++ b/x/hold/locked_coins.go @@ -1,22 +1,31 @@ package hold -import sdk "github.com/cosmos/cosmos-sdk/types" +import ( + "context" + + sdk "github.com/cosmos/cosmos-sdk/types" +) const bypassKey = "bypass-" + ModuleName + "-locked-coins" // WithBypass returns a new context that will cause the hold locked coins lookup to be skipped. -func WithBypass(ctx sdk.Context) sdk.Context { - return ctx.WithValue(bypassKey, true) +func WithBypass[C context.Context](ctx C) C { + sdkCtx := sdk.UnwrapSDKContext(ctx) + sdkCtx = sdkCtx.WithValue(bypassKey, true) + return context.Context(sdkCtx).(C) } // WithoutBypass returns a new context that will cause the hold locked coins lookup to not be skipped. -func WithoutBypass(ctx sdk.Context) sdk.Context { - return ctx.WithValue(bypassKey, false) +func WithoutBypass[C context.Context](ctx C) C { + sdkCtx := sdk.UnwrapSDKContext(ctx) + sdkCtx = sdkCtx.WithValue(bypassKey, false) + return context.Context(sdkCtx).(C) } // HasBypass checks the context to see if the hold locked coins lookup should be skipped. -func HasBypass(ctx sdk.Context) bool { - bypassValue := ctx.Value(bypassKey) +func HasBypass[C context.Context](ctx C) bool { + sdkCtx := sdk.UnwrapSDKContext(ctx) + bypassValue := sdkCtx.Value(bypassKey) if bypassValue == nil { return false } diff --git a/x/ibcratelimit/client/cli/tx.go b/x/ibcratelimit/client/cli/tx.go index 0d34550b25..a8e08011b0 100644 --- a/x/ibcratelimit/client/cli/tx.go +++ b/x/ibcratelimit/client/cli/tx.go @@ -8,11 +8,9 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/version" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - // govcli "github.com/cosmos/cosmos-sdk/x/gov/client/cli" // TODO[1760]: gov-cli - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + govcli "github.com/cosmos/cosmos-sdk/x/gov/client/cli" + "github.com/provenance-io/provenance/internal/provcli" "github.com/provenance-io/provenance/x/ibcratelimit" ) @@ -49,32 +47,15 @@ func GetCmdParamsUpdate() *cobra.Command { return err } - authority := authtypes.NewModuleAddress(govtypes.ModuleName) - - msg := ibcratelimit.NewMsgGovUpdateParamsRequest( - authority.String(), - args[0], - ) - - // TODO[1760]: gov-cli: Replace this with GenerateOrBroadcastTxCLIAsGovProp once its back. - _, _ = msg, clientCtx - /* - proposal, govErr := govcli.ReadGovPropFlags(clientCtx, cmd.Flags()) - if govErr != nil { - return govErr - } - proposal.Messages, govErr = sdktx.SetMsgs([]sdk.Msg{msg}) - if govErr != nil { - return govErr - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), proposal) - */ - return fmt.Errorf("not yet updated") + flagSet := cmd.Flags() + authority := provcli.GetAuthority(flagSet) + msg := ibcratelimit.NewMsgGovUpdateParamsRequest(authority, args[0]) + return provcli.GenerateOrBroadcastTxCLIAsGovProp(clientCtx, flagSet, msg) }, } - // govcli.AddGovPropFlagsToCmd(cmd) // TODO[1760]: gov-cli + govcli.AddGovPropFlagsToCmd(cmd) + provcli.AddAuthorityFlagToCmd(cmd) flags.AddTxFlagsToCmd(cmd) return cmd diff --git a/x/marker/client/cli/query.go b/x/marker/client/cli/query.go index 84d0527656..6baa36df59 100644 --- a/x/marker/client/cli/query.go +++ b/x/marker/client/cli/query.go @@ -81,7 +81,7 @@ func AllMarkersCmd() *cobra.Command { } queryClient := types.NewQueryClient(clientCtx) - pageReq, err := client.ReadPageRequest(cmd.Flags()) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + pageReq, err := client.ReadPageRequestWithPageKeyDecoded(cmd.Flags()) if err != nil { return err } @@ -128,7 +128,7 @@ func AllHoldersCmd() *cobra.Command { } id := strings.ToLower(strings.TrimSpace(args[0])) queryClient := types.NewQueryClient(clientCtx) - pageReq, err := client.ReadPageRequest(cmd.Flags()) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + pageReq, err := client.ReadPageRequestWithPageKeyDecoded(cmd.Flags()) if err != nil { return err } diff --git a/x/marker/client/cli/tx.go b/x/marker/client/cli/tx.go index 866b25e363..3b0ce7e4e7 100644 --- a/x/marker/client/cli/tx.go +++ b/x/marker/client/cli/tx.go @@ -21,12 +21,12 @@ import ( "github.com/cosmos/cosmos-sdk/version" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/authz" - - // govcli "github.com/cosmos/cosmos-sdk/x/gov/client/cli" // TODO[1760]: gov-cli + govcli "github.com/cosmos/cosmos-sdk/x/gov/client/cli" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" channelutils "github.com/cosmos/ibc-go/v8/modules/core/04-channel/client/utils" + "github.com/provenance-io/provenance/internal/provcli" attrcli "github.com/provenance-io/provenance/x/attribute/client/cli" "github.com/provenance-io/provenance/x/marker/types" ) @@ -461,7 +461,6 @@ func GetNewTransferCmd() *cobra.Command { // GetIbcTransferTxCmd returns the command to create a GetIbcTransferTxCmd transaction func GetIbcTransferTxCmd() *cobra.Command { - // TODO: refactor ibc-transfer usage comments to be provenance specific cmd := &cobra.Command{ Use: "ibc-transfer [src-port] [src-channel] [sender] [receiver] [amount]", Short: "Transfer a restricted marker token through IBC", @@ -949,13 +948,11 @@ func GetCmdUpdateForcedTransfer() *cobra.Command { return err } - // return govcli.GenerateOrBroadcastTxCLIAsGovProp(clientCtx, cmd.Flags(), msg) // TODO[1760]: gov-cli - _, _ = msg, clientCtx - return fmt.Errorf("not yet updated") + return provcli.GenerateOrBroadcastTxCLIAsGovProp(clientCtx, cmd.Flags(), msg) }, } - // govcli.AddGovPropFlagsToCmd(cmd) // TODO[1760]: gov-cli + govcli.AddGovPropFlagsToCmd(cmd) flags.AddTxFlagsToCmd(cmd) return cmd } @@ -1224,7 +1221,7 @@ func ParseBoolStrict(input string) (bool, error) { // See also: generateOrBroadcastOptGovProp func addOptGovPropFlags(cmd *cobra.Command) { cmd.Flags().Bool(FlagGovProposal, false, "submit message as a gov proposal") - // govcli.AddGovPropFlagsToCmd(cmd) // TODO[1760]: gov-cli + govcli.AddGovPropFlagsToCmd(cmd) } // generateOrBroadcastOptGovProp either calls GenerateOrBroadcastTxCLIAsGovProp or GenerateOrBroadcastTxCLI @@ -1245,8 +1242,7 @@ func generateOrBroadcastOptGovProp(clientCtx client.Context, flagSet *pflag.Flag } if isGov { - // return govcli.GenerateOrBroadcastTxCLIAsGovProp(clientCtx, flagSet, msg) // TODO[1760]: gov-cli - return fmt.Errorf("not yet updated") + return provcli.GenerateOrBroadcastTxCLIAsGovProp(clientCtx, flagSet, msg) } return tx.GenerateOrBroadcastTxCLI(clientCtx, flagSet, msg) } diff --git a/x/marker/keeper/send_restrictions_test.go b/x/marker/keeper/send_restrictions_test.go index e302e08197..581021be67 100644 --- a/x/marker/keeper/send_restrictions_test.go +++ b/x/marker/keeper/send_restrictions_test.go @@ -878,7 +878,7 @@ func TestBankInputOutputCoinsUsesSendRestrictionFn(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - // err = app.BankKeeper.InputOutputCoins(ctx, []banktypes.Input{tc.input}, tc.outputs) // TODO[1760]: bank + err = app.BankKeeper.InputOutputCoins(ctx, tc.input, tc.outputs) if len(tc.expErr) != 0 { assert.EqualError(t, err, tc.expErr, "InputOutputCoins") } else { diff --git a/x/metadata/client/cli/cli_test.go b/x/metadata/client/cli/cli_test.go index 4e0e16d1c7..d232ab6b1b 100644 --- a/x/metadata/client/cli/cli_test.go +++ b/x/metadata/client/cli/cli_test.go @@ -3809,7 +3809,7 @@ func (s *IntegrationCLITestSuite) TestCountAuthorizationIntactTxCommands() { args: []string{ s.user3AddrStr, "count", - // fmt.Sprintf("--%s=%d", authzcli.FlagAllowedAuthorizations, 1), // TODO[1760]: count-authz + fmt.Sprintf("--%s=%d", authzcli.FlagAllowedAuthorizations, 1), fmt.Sprintf("--%s=%s", authzcli.FlagMsgType, metadatatypes.TypeURLMsgDeleteScopeRequest), fmt.Sprintf("--%s=%s", flags.FlagFrom, s.user1AddrStr), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), @@ -3836,7 +3836,7 @@ func (s *IntegrationCLITestSuite) TestCountAuthorizationIntactTxCommands() { args: []string{ s.user3AddrStr, "count", - // fmt.Sprintf("--%s=%d", authzcli.FlagAllowedAuthorizations, 2), // TODO[1760]: count-authz + fmt.Sprintf("--%s=%d", authzcli.FlagAllowedAuthorizations, 2), fmt.Sprintf("--%s=%s", authzcli.FlagMsgType, metadatatypes.TypeURLMsgDeleteScopeRequest), fmt.Sprintf("--%s=%s", flags.FlagFrom, s.user2AddrStr), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), diff --git a/x/metadata/client/cli/query.go b/x/metadata/client/cli/query.go index 774c5f7ba3..5816eac6ba 100644 --- a/x/metadata/client/cli/query.go +++ b/x/metadata/client/cli/query.go @@ -670,7 +670,7 @@ func outputScopesAll(cmd *cobra.Command) error { if err != nil { return err } - pageReq, e := client.ReadPageRequest(cmd.Flags()) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + pageReq, e := client.ReadPageRequestWithPageKeyDecoded(cmd.Flags()) if e != nil { return e } @@ -726,7 +726,7 @@ func outputSessionsAll(cmd *cobra.Command) error { if err != nil { return err } - pageReq, e := client.ReadPageRequest(cmd.Flags()) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + pageReq, e := client.ReadPageRequestWithPageKeyDecoded(cmd.Flags()) if e != nil { return e } @@ -779,7 +779,7 @@ func outputRecordsAll(cmd *cobra.Command) error { if err != nil { return err } - pageReq, e := client.ReadPageRequest(cmd.Flags()) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + pageReq, e := client.ReadPageRequestWithPageKeyDecoded(cmd.Flags()) if e != nil { return e } @@ -805,7 +805,7 @@ func outputOwnership(cmd *cobra.Command, address string) error { if err != nil { return err } - pageReq, e := client.ReadPageRequest(cmd.Flags()) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + pageReq, e := client.ReadPageRequestWithPageKeyDecoded(cmd.Flags()) if e != nil { return e } @@ -827,7 +827,7 @@ func outputValueOwnership(cmd *cobra.Command, address string) error { if err != nil { return err } - pageReq, e := client.ReadPageRequest(cmd.Flags()) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + pageReq, e := client.ReadPageRequestWithPageKeyDecoded(cmd.Flags()) if e != nil { return e } @@ -873,7 +873,7 @@ func outputScopeSpecsAll(cmd *cobra.Command) error { if err != nil { return err } - pageReq, e := client.ReadPageRequest(cmd.Flags()) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + pageReq, e := client.ReadPageRequestWithPageKeyDecoded(cmd.Flags()) if e != nil { return e } @@ -922,7 +922,7 @@ func outputContractSpecsAll(cmd *cobra.Command) error { if err != nil { return err } - pageReq, e := client.ReadPageRequest(cmd.Flags()) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + pageReq, e := client.ReadPageRequestWithPageKeyDecoded(cmd.Flags()) if e != nil { return e } @@ -993,7 +993,7 @@ func outputRecordSpecsAll(cmd *cobra.Command) error { if err != nil { return err } - pageReq, e := client.ReadPageRequest(cmd.Flags()) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + pageReq, e := client.ReadPageRequestWithPageKeyDecoded(cmd.Flags()) if e != nil { return e } @@ -1055,7 +1055,7 @@ func outputOSLocatorsByURI(cmd *cobra.Command, uri string) error { if err != nil { return err } - pageReq, e := client.ReadPageRequest(cmd.Flags()) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + pageReq, e := client.ReadPageRequestWithPageKeyDecoded(cmd.Flags()) if e != nil { return e } @@ -1095,7 +1095,7 @@ func outputOSLocatorsAll(cmd *cobra.Command) error { if err != nil { return err } - pageReq, e := client.ReadPageRequest(cmd.Flags()) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + pageReq, e := client.ReadPageRequestWithPageKeyDecoded(cmd.Flags()) if e != nil { return e } diff --git a/x/metadata/keeper/signers_test.go b/x/metadata/keeper/signers_test.go index abebcdce2c..859027f97e 100644 --- a/x/metadata/keeper/signers_test.go +++ b/x/metadata/keeper/signers_test.go @@ -756,36 +756,32 @@ func (s *AuthzTestSuite) TestValidateAllRequiredPartiesSigned_CountAuthorization }.Real(), } - // TODO[1760]: count-authz: Uncomment the rest of this test once we have that back in the SDK. - _, _, _, _ = reqParties, availableParties, reqRoles, expDetails - /* - msg := &types.MsgDeleteScopeRequest{Signers: []string{accStr(signer)}} - msgTypeURL := types.TypeURLMsgDeleteScopeRequest + msg := &types.MsgDeleteScopeRequest{Signers: []string{accStr(signer)}} + msgTypeURL := types.TypeURLMsgDeleteScopeRequest - ctx := s.FreshCtx() + ctx := s.FreshCtx() - // first grant: signer can sign for party1 one time. - auth1 := authz.NewCountAuthorization(msgTypeURL, 1) - err := s.app.AuthzKeeper.SaveGrant(ctx, acc(signer), acc(party1), auth1, nil) - s.Require().NoError(err, "SaveGrant signer can sign for party1: 1 use") + // first grant: signer can sign for party1 one time. + auth1 := authz.NewCountAuthorization(msgTypeURL, 1) + err := s.app.AuthzKeeper.SaveGrant(ctx, acc(signer), acc(party1), auth1, nil) + s.Require().NoError(err, "SaveGrant signer can sign for party1: 1 use") - // second grant: signer can sign for party2 two times. - auth2 := authz.NewCountAuthorization(msgTypeURL, 2) - err = s.app.AuthzKeeper.SaveGrant(ctx, acc(signer), acc(party2), auth2, nil) - s.Require().NoError(err, "SaveGrant signer can sign for party2: 2 uses") + // second grant: signer can sign for party2 two times. + auth2 := authz.NewCountAuthorization(msgTypeURL, 2) + err = s.app.AuthzKeeper.SaveGrant(ctx, acc(signer), acc(party2), auth2, nil) + s.Require().NoError(err, "SaveGrant signer can sign for party2: 2 uses") - details, err := s.app.MetadataKeeper.ValidateAllRequiredPartiesSigned(ctx, reqParties, availableParties, reqRoles, msg) - s.Require().NoError(err, "ValidateSignersWithParties error") - s.Assert().Equal(expDetails, details, "ValidateSignersWithParties party details") + details, err := s.app.MetadataKeeper.ValidateAllRequiredPartiesSigned(ctx, reqParties, availableParties, reqRoles, msg) + s.Require().NoError(err, "ValidateSignersWithParties error") + s.Assert().Equal(expDetails, details, "ValidateSignersWithParties party details") - auth1Final, _ := s.app.AuthzKeeper.GetAuthorization(ctx, acc(signer), acc(party1), msgTypeURL) - s.Assert().Nil(auth1Final, "GetAuthorization after only allowed use") + auth1Final, _ := s.app.AuthzKeeper.GetAuthorization(ctx, acc(signer), acc(party1), msgTypeURL) + s.Assert().Nil(auth1Final, "GetAuthorization after only allowed use") - auth2Final, _ := s.app.AuthzKeeper.GetAuthorization(ctx, acc(signer), acc(party2), msgTypeURL) - s.Assert().NotNil(auth2Final, "GetAuthorization after first of two uses") - actual := auth2Final.(*authz.CountAuthorization).AllowedAuthorizations - s.Assert().Equal(1, int(actual), "number of uses left after first of two uses") - */ + auth2Final, _ := s.app.AuthzKeeper.GetAuthorization(ctx, acc(signer), acc(party2), msgTypeURL) + s.Assert().NotNil(auth2Final, "GetAuthorization after first of two uses") + actual := auth2Final.(*authz.CountAuthorization).AllowedAuthorizations + s.Assert().Equal(1, int(actual), "number of uses left after first of two uses") } func TestAssociateSigners(t *testing.T) { @@ -6357,12 +6353,9 @@ func (s *AuthzTestSuite) TestValidateAllRequiredSigned_CountAuthorizations() { ctx := s.FreshCtx() msgTypeURL := sdk.MsgTypeURL(tc.msg) if tc.grantee != nil && tc.granter != nil { - // TODO[1760]: count-authz: Uncomment the rest of this test once we have that back in the SDK. - /* - a := authz.NewCountAuthorization(msgTypeURL, tc.count) - err := s.app.AuthzKeeper.SaveGrant(ctx, tc.grantee, tc.granter, a, nil) - s.Require().NoError(err, "SaveGrant") - */ + a := authz.NewCountAuthorization(msgTypeURL, tc.count) + err := s.app.AuthzKeeper.SaveGrant(ctx, tc.grantee, tc.granter, a, nil) + s.Require().NoError(err, "SaveGrant") } _, err := s.app.MetadataKeeper.ValidateAllRequiredSigned(ctx, tc.owners, tc.msg) @@ -6375,59 +6368,53 @@ func (s *AuthzTestSuite) TestValidateAllRequiredSigned_CountAuthorizations() { // authorization is deleted after one use s.Assert().Nil(auth, "GetAuthorization after only allowed use") } else { - // TODO[1760]: count-authz: Uncomment the rest of this test once we have that back in the SDK. - /* - actual := auth.(*authz.CountAuthorization).AllowedAuthorizations - s.Assert().Equal(tc.count-1, actual, "uses left on authorization") - */ + actual := auth.(*authz.CountAuthorization).AllowedAuthorizations + s.Assert().Equal(tc.count-1, actual, "uses left on authorization") } } }) } s.Run("ensure authorizations are updated", func() { - // TODO[1760]: count-authz: Uncomment the rest of this test once we have that back in the SDK. - /* - ctx := s.FreshCtx() - // Two owners (1 & 2), and one signer (3), - // Two authz count authorization - // - count grants: - // granter: 1, grantee: 3, count: 1 - // granter: 2, grantee: 3, count: 2 - // Require signatures from 1 and 2, but sign with 3. - // Ensure both authorizations are applied and updated. - - msg := &types.MsgDeleteScopeRequest{} - msgTypeUrl := sdk.MsgTypeURL(msg) - - // first grant: 3 can sign for 1 one time. - a := authz.NewCountAuthorization(msgTypeUrl, 1) - err := s.app.AuthzKeeper.SaveGrant(ctx, s.user3Addr, s.user1Addr, a, nil) - s.Assert().NoError(err, "SaveGrant 1 -> 3, 1 use") - - // second grant: 3 can sign for 2 two times. - a = authz.NewCountAuthorization(msgTypeUrl, 2) - err = s.app.AuthzKeeper.SaveGrant(ctx, s.user3Addr, s.user2Addr, a, nil) - s.Assert().NoError(err, "SaveGrant 2 -> 3, 2 uses") - - // two owners (1 & 2), and one signer (3) - owners := []string{s.user1, s.user2} - msg.Signers = []string{s.user3} - - // Validate signatures. This should also use both count authorizations. - _, err = s.app.MetadataKeeper.ValidateAllRequiredSigned(ctx, owners, msg) - s.Assert().NoError(err, "ValidateSignersWithoutParties") - - // first grant should be deleted because it used its last use. - auth, _ := s.app.AuthzKeeper.GetAuthorization(ctx, s.user3Addr, s.user1Addr, msgTypeUrl) - s.Assert().Nil(auth, "GetAuthorization 1 -> 3 after only allowed use") - - // second grant should still exist, but only have one use left. - auth, _ = s.app.AuthzKeeper.GetAuthorization(ctx, s.user3Addr, s.user2Addr, msgTypeUrl) - s.Assert().NotNil(auth, "GetAuthorization 2 -> 3 after one use") - actual := auth.(*authz.CountAuthorization).AllowedAuthorizations - s.Assert().Equal(1, int(actual), "number of uses left on 2 -> 3 authorization") - */ + ctx := s.FreshCtx() + // Two owners (1 & 2), and one signer (3), + // Two authz count authorization + // - count grants: + // granter: 1, grantee: 3, count: 1 + // granter: 2, grantee: 3, count: 2 + // Require signatures from 1 and 2, but sign with 3. + // Ensure both authorizations are applied and updated. + + msg := &types.MsgDeleteScopeRequest{} + msgTypeUrl := sdk.MsgTypeURL(msg) + + // first grant: 3 can sign for 1 one time. + a := authz.NewCountAuthorization(msgTypeUrl, 1) + err := s.app.AuthzKeeper.SaveGrant(ctx, s.user3Addr, s.user1Addr, a, nil) + s.Assert().NoError(err, "SaveGrant 1 -> 3, 1 use") + + // second grant: 3 can sign for 2 two times. + a = authz.NewCountAuthorization(msgTypeUrl, 2) + err = s.app.AuthzKeeper.SaveGrant(ctx, s.user3Addr, s.user2Addr, a, nil) + s.Assert().NoError(err, "SaveGrant 2 -> 3, 2 uses") + + // two owners (1 & 2), and one signer (3) + owners := []string{s.user1, s.user2} + msg.Signers = []string{s.user3} + + // Validate signatures. This should also use both count authorizations. + _, err = s.app.MetadataKeeper.ValidateAllRequiredSigned(ctx, owners, msg) + s.Assert().NoError(err, "ValidateSignersWithoutParties") + + // first grant should be deleted because it used its last use. + auth, _ := s.app.AuthzKeeper.GetAuthorization(ctx, s.user3Addr, s.user1Addr, msgTypeUrl) + s.Assert().Nil(auth, "GetAuthorization 1 -> 3 after only allowed use") + + // second grant should still exist, but only have one use left. + auth, _ = s.app.AuthzKeeper.GetAuthorization(ctx, s.user3Addr, s.user2Addr, msgTypeUrl) + s.Assert().NotNil(auth, "GetAuthorization 2 -> 3 after one use") + actual := auth.(*authz.CountAuthorization).AllowedAuthorizations + s.Assert().Equal(1, int(actual), "number of uses left on 2 -> 3 authorization") }) } diff --git a/x/metadata/keeper/signers_utils_test.go b/x/metadata/keeper/signers_utils_test.go index 84d9411d35..6fd6f461b8 100644 --- a/x/metadata/keeper/signers_utils_test.go +++ b/x/metadata/keeper/signers_utils_test.go @@ -1960,7 +1960,7 @@ func TestNewAuthzCache(t *testing.T) { func TestAuthzCache_Clear(t *testing.T) { c := keeper.NewAuthzCache() - // c.AcceptableMap()["key1"] = &authz.CountAuthorization{} // TODO[1760]: count-authz + c.AcceptableMap()["key1"] = &authz.CountAuthorization{} c.AcceptableMap()["key2"] = &authz.GenericAuthorization{} c.IsWasmMap()["key3"] = true c.IsWasmMap()["key4"] = false @@ -1972,21 +1972,18 @@ func TestAuthzCache_Clear(t *testing.T) { } func TestAuthzCache_SetAcceptable(t *testing.T) { - // TODO[1760]: count-authz: Uncomment the rest of this test once we have that back in the SDK. - /* - c := keeper.NewAuthzCache() - grantee := sdk.AccAddress("grantee") - granter := sdk.AccAddress("granter") - msgTypeURL := "msgTypeURL" - authorization := &authz.CountAuthorization{ - Msg: msgTypeURL, - AllowedAuthorizations: 77, - } + c := keeper.NewAuthzCache() + grantee := sdk.AccAddress("grantee") + granter := sdk.AccAddress("granter") + msgTypeURL := "msgTypeURL" + authorization := &authz.CountAuthorization{ + Msg: msgTypeURL, + AllowedAuthorizations: 77, + } - c.SetAcceptable(grantee, granter, msgTypeURL, authorization) - actual := c.AcceptableMap()[keeper.AuthzCacheAcceptableKey(grantee, granter, msgTypeURL)] - assert.Equal(t, authorization, actual, "the authorization stored by SetAcceptable") - */ + c.SetAcceptable(grantee, granter, msgTypeURL, authorization) + actual := c.AcceptableMap()[keeper.AuthzCacheAcceptableKey(grantee, granter, msgTypeURL)] + assert.Equal(t, authorization, actual, "the authorization stored by SetAcceptable") } func TestAuthzCache_GetAcceptable(t *testing.T) { @@ -1996,21 +1993,17 @@ func TestAuthzCache_GetAcceptable(t *testing.T) { msgTypeURL := "msgTypeURL" key := keeper.AuthzCacheAcceptableKey(grantee, granter, msgTypeURL) - // TODO[1760]: count-authz: Uncomment the rest of this test once we have that back in the SDK. - _, _ = c, key - /* - authorization := &authz.CountAuthorization{ - Msg: msgTypeURL, - AllowedAuthorizations: 8, - } - c.AcceptableMap()[key] = authorization + authorization := &authz.CountAuthorization{ + Msg: msgTypeURL, + AllowedAuthorizations: 8, + } + c.AcceptableMap()[key] = authorization - actual := c.GetAcceptable(grantee, granter, msgTypeURL) - assert.Equal(t, authorization, actual, "GetAcceptable result") + actual := c.GetAcceptable(grantee, granter, msgTypeURL) + assert.Equal(t, authorization, actual, "GetAcceptable result") - notThere := c.GetAcceptable(granter, grantee, msgTypeURL) - assert.Nil(t, notThere, "GetAcceptable on an entry that should not exist") - */ + notThere := c.GetAcceptable(granter, grantee, msgTypeURL) + assert.Nil(t, notThere, "GetAcceptable on an entry that should not exist") } func TestAuthzCache_SetIsWasm(t *testing.T) { @@ -2135,30 +2128,26 @@ func TestAddAuthzCacheToContext(t *testing.T) { }) t.Run("context already has an AuthzCache", func(t *testing.T) { - // TODO[1760]: count-authz: Uncomment the rest of this test once we have that back in the SDK. - /* - grantee := sdk.AccAddress("grantee") - granter := sdk.AccAddress("granter") - msgTypeURL := "msgTypeURL" - authorization := &authz.CountAuthorization{ - Msg: msgTypeURL, - AllowedAuthorizations: 8, - } - origCache := keeper.NewAuthzCache() - origCache.SetAcceptable(grantee, granter, msgTypeURL, authorization) - - origCtx := emptySdkContext().WithValue(keeper.AuthzCacheContextKey, origCache) - newCtx := keeper.AddAuthzCacheToContext(origCtx) + grantee := sdk.AccAddress("grantee") + granter := sdk.AccAddress("granter") + msgTypeURL := "msgTypeURL" + authorization := &authz.CountAuthorization{ + Msg: msgTypeURL, + AllowedAuthorizations: 8, + } + origCache := keeper.NewAuthzCache() + origCache.SetAcceptable(grantee, granter, msgTypeURL, authorization) - var newCache *keeper.AuthzCache - testFunc := func() { - newCache = keeper.GetAuthzCache(newCtx) - } - require.NotPanics(t, testFunc, "GetAuthzCache") - assert.Same(t, origCache, newCache, "cache from new context") - assert.Empty(t, newCache.AcceptableMap(), "cache acceptable map") + origCtx := emptySdkContext().WithValue(keeper.AuthzCacheContextKey, origCache) + newCtx := keeper.AddAuthzCacheToContext(origCtx) - */ + var newCache *keeper.AuthzCache + testFunc := func() { + newCache = keeper.GetAuthzCache(newCtx) + } + require.NotPanics(t, testFunc, "GetAuthzCache") + assert.Same(t, origCache, newCache, "cache from new context") + assert.Empty(t, newCache.AcceptableMap(), "cache acceptable map") }) t.Run("context has something else", func(t *testing.T) { diff --git a/x/msgfees/client/cli/query.go b/x/msgfees/client/cli/query.go index 109570c330..7a4f2c7486 100644 --- a/x/msgfees/client/cli/query.go +++ b/x/msgfees/client/cli/query.go @@ -42,7 +42,7 @@ func AllMsgFeesCmd() *cobra.Command { } queryClient := types.NewQueryClient(clientCtx) - pageReq, err := client.ReadPageRequest(cmd.Flags()) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + pageReq, err := client.ReadPageRequestWithPageKeyDecoded(cmd.Flags()) if err != nil { return err } diff --git a/x/name/client/cli/query.go b/x/name/client/cli/query.go index 41374a1823..c4a6a537ba 100644 --- a/x/name/client/cli/query.go +++ b/x/name/client/cli/query.go @@ -111,7 +111,7 @@ $ %[1]s query name lookup pb1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk --page=2 --l } queryClient := types.NewQueryClient(clientCtx) - pageReq, err := client.ReadPageRequest(cmd.Flags()) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + pageReq, err := client.ReadPageRequestWithPageKeyDecoded(cmd.Flags()) if err != nil { return err } diff --git a/x/name/client/cli/tx.go b/x/name/client/cli/tx.go index 322543391d..25eb92f9ce 100644 --- a/x/name/client/cli/tx.go +++ b/x/name/client/cli/tx.go @@ -12,18 +12,16 @@ import ( "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - // govcli "github.com/cosmos/cosmos-sdk/x/gov/client/cli" // TODO[1760]: gov-cli - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + govcli "github.com/cosmos/cosmos-sdk/x/gov/client/cli" + "github.com/provenance-io/provenance/internal/provcli" "github.com/provenance-io/provenance/x/name/types" ) -// The flag for creating unrestricted names +// FlagUnrestricted is the flag for creating unrestricted names const FlagUnrestricted = "unrestrict" -// The flag to specify that the command should be ran as a gov proposal +// FlagGovProposal is the flag to specify that the command should be run as a gov proposal const FlagGovProposal = "gov-proposal" // NewTxCmd is the top-level command for name CLI transactions. @@ -140,46 +138,24 @@ $ %s tx name modify-name \ return err } - var authority sdk.AccAddress - if !isGov { - authority = clientCtx.GetFromAddress() - } else { - authority = authtypes.NewModuleAddress(govtypes.ModuleName) - } - - modifyMsg := types.MsgModifyNameRequest{ - Authority: authority.String(), - Record: types.NewNameRecord(strings.ToLower(args[0]), owner, !viper.GetBool(FlagUnrestricted)), + modifyMsg := &types.MsgModifyNameRequest{ + Record: types.NewNameRecord(strings.ToLower(args[0]), owner, !viper.GetBool(FlagUnrestricted)), } - var req sdk.Msg if isGov { - // TODO[1760]: gov-cli: Replace this with GenerateOrBroadcastTxCLIAsGovProp once its back. - /* - var govErr error - proposal, govErr := govcli.ReadGovPropFlags(clientCtx, cmd.Flags()) - if govErr != nil { - return govErr - } - anys, govErr := sdktx.SetMsgs([]sdk.Msg{&modifyMsg}) - if govErr != nil { - return govErr - } - proposal.Messages = anys - req = proposal - */ - return fmt.Errorf("not yet updated") - } else { - req = &modifyMsg + modifyMsg.Authority = provcli.GetAuthority(cmd.Flags()) + return provcli.GenerateOrBroadcastTxCLIAsGovProp(clientCtx, cmd.Flags(), modifyMsg) } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), req) + modifyMsg.Authority = clientCtx.GetFromAddress().String() + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), modifyMsg) }, } cmd.Flags().BoolP(FlagUnrestricted, "u", false, "Allow child name creation by everyone") cmd.Flags().Bool(FlagGovProposal, false, "Run transaction as gov proposal") - // govcli.AddGovPropFlagsToCmd(cmd) // TODO[1760]: gov-cli + govcli.AddGovPropFlagsToCmd(cmd) + provcli.AddAuthorityFlagToCmd(cmd) flags.AddTxFlagsToCmd(cmd) return cmd } diff --git a/x/oracle/client/cli/tx.go b/x/oracle/client/cli/tx.go index bb20ae7cfd..ae60b0ad12 100644 --- a/x/oracle/client/cli/tx.go +++ b/x/oracle/client/cli/tx.go @@ -11,11 +11,9 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/version" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - // govcli "github.com/cosmos/cosmos-sdk/x/gov/client/cli" // TODO[1760]: gov-cli - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + govcli "github.com/cosmos/cosmos-sdk/x/gov/client/cli" + "github.com/provenance-io/provenance/internal/provcli" "github.com/provenance-io/provenance/x/oracle/types" ) @@ -53,32 +51,16 @@ func GetCmdOracleUpdate() *cobra.Command { return err } - authority := authtypes.NewModuleAddress(govtypes.ModuleName) - - msg := types.NewMsgUpdateOracle( - authority.String(), - args[0], - ) + flagSet := cmd.Flags() + authority := provcli.GetAuthority(flagSet) - // TODO[1760]: gov-cli: Replace this with GenerateOrBroadcastTxCLIAsGovProp once its back. - _, _ = msg, clientCtx - /* - proposal, govErr := govcli.ReadGovPropFlags(clientCtx, cmd.Flags()) - if govErr != nil { - return govErr - } - proposal.Messages, govErr = sdktx.SetMsgs([]sdk.Msg{msg}) - if govErr != nil { - return govErr - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), proposal) - */ - return fmt.Errorf("not yet updated") + msg := types.NewMsgUpdateOracle(authority, args[0]) + return provcli.GenerateOrBroadcastTxCLIAsGovProp(clientCtx, flagSet, msg) }, } - // govcli.AddGovPropFlagsToCmd(cmd) // TODO[1760]: gov-cli + govcli.AddGovPropFlagsToCmd(cmd) + provcli.AddAuthorityFlagToCmd(cmd) flags.AddTxFlagsToCmd(cmd) return cmd diff --git a/x/trigger/client/cli/query.go b/x/trigger/client/cli/query.go index b0dd7e2bf4..aba2fcb487 100644 --- a/x/trigger/client/cli/query.go +++ b/x/trigger/client/cli/query.go @@ -57,7 +57,7 @@ func GetTriggersCmd() *cobra.Command { } var request types.QueryTriggersRequest - request.Pagination, err = client.ReadPageRequest(cmd.Flags()) // TODO[1760]: cli: ReadPageRequestWithPageKeyDecoded + request.Pagination, err = client.ReadPageRequestWithPageKeyDecoded(cmd.Flags()) if err != nil { return err } From f6fb2ca4679d8c4a5afc3318cb9a2e9ca4a5329d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 16 Apr 2024 21:18:59 +0000 Subject: [PATCH 2/3] Bump peter-evans/create-pull-request from 6.0.2 to 6.0.3 (#1929) * Bump peter-evans/create-pull-request from 6.0.2 to 6.0.3 Bumps [peter-evans/create-pull-request](https://github.com/peter-evans/create-pull-request) from 6.0.2 to 6.0.3. - [Release notes](https://github.com/peter-evans/create-pull-request/releases) - [Commits](https://github.com/peter-evans/create-pull-request/compare/v6.0.2...v6.0.3) --- updated-dependencies: - dependency-name: peter-evans/create-pull-request dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] * Updated Changelog --------- Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: dependabot[bot] Co-authored-by: Daniel Wedul --- .github/workflows/proto-registry.yml | 2 +- CHANGELOG.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/proto-registry.yml b/.github/workflows/proto-registry.yml index a9fff6d499..02cb8abd3b 100644 --- a/.github/workflows/proto-registry.yml +++ b/.github/workflows/proto-registry.yml @@ -54,7 +54,7 @@ jobs: git commit -S -m "Update buf.lock to latest commit hash" - name: Create Pull Request id: cpr - uses: peter-evans/create-pull-request@v6.0.2 + uses: peter-evans/create-pull-request@v6.0.3 with: base: main branch: provenanceio-bot/patch-buf-lock diff --git a/CHANGELOG.md b/CHANGELOG.md index 93cadb4ae6..1dbbce1df5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -75,6 +75,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ - Bump `github.com/cometbft/cometbft` from 0.38.5 to 0.38.6 ([#1912](https://github.com/provenance-io/provenance/pull/1912)) - Bump `cosmossdk.io/x/upgrade` from 0.1.0 to 0.1.1 ([#1913](https://github.com/provenance-io/provenance/pull/1913)) - Bump `github.com/hashicorp/go-metrics` from 0.5.2 to 0.5.3 ([#1914](https://github.com/provenance-io/provenance/pull/1914)) +- Bump `peter-evans/create-pull-request` from 6.0.2 to 6.0.3 ([#1929](https://github.com/provenance-io/provenance/pull/1929)) --- From bca91646bc168bbbbd63605883581f491b3a6386 Mon Sep 17 00:00:00 2001 From: Daniel Wedul Date: Tue, 16 Apr 2024 15:38:33 -0600 Subject: [PATCH 3/3] Use SimulationState fields for the encoders needed in the simulations. (#1931) * [1760]: Remove use of MakeTestEncodingConfig from the attribute module. * [1760]: Remove use of MakeTestEncodingConfig from the ibcratelimit module. * [1760]: Remove use of MakeTestEncodingConfig from the marker module. * [1760]: Remove use of MakeTestEncodingConfig from the name module. * [1760]: Remove use of MakeTestEncodingConfig from the provwasm simulation stuff. * [1760]: Remove use of MakeTestEncodingConfig from the oracle module. Make the oracle operations tests run. * [1760]: Remove use of MakeTestEncodingConfig from the trigger module. * [1760]: Remove use of MakeTestEncodingConfig from the sanction module. * [1760]: Remove use of MakeTestEncodingConfig from the quarantine module. * [1760]: Delete the now-unwanted MakeTestEncodingConfig func (and the file it was in since that's all that was in there). * [1760]: Add changelog entry. * [1760]: Shrink all the WeightedOperations funcs by removing some newlines inside function calls and stuff. * [1760]: Fix all uses of simtypes.NoOpMsg that were providing the msg-type URL instead of the router key. Move all the test kick-off funcs to the tops of the operations tests so that next time one is copy/pasted, it's harder to accidentally delete it. --- CHANGELOG.md | 1 + app/params/proto.go | 46 ------ internal/provwasm/simulation.go | 64 ++++--- x/attribute/module.go | 5 +- x/attribute/simulation/operations.go | 127 ++++++-------- x/attribute/simulation/operations_test.go | 33 ++-- x/ibcratelimit/module/module.go | 7 +- x/ibcratelimit/simulation/operations.go | 43 +++-- x/ibcratelimit/simulation/operations_test.go | 27 ++- x/marker/module.go | 2 +- x/marker/simulation/operations.go | 165 +++++++------------ x/marker/simulation/operations_test.go | 43 ++--- x/name/module.go | 7 +- x/name/simulation/operations.go | 91 ++++------ x/name/simulation/operations_test.go | 29 ++-- x/oracle/module/module.go | 4 +- x/oracle/simulation/operations.go | 64 +++---- x/oracle/simulation/operations_test.go | 24 ++- x/quarantine/module/module.go | 6 +- x/quarantine/simulation/operations.go | 82 +++++---- x/quarantine/simulation/operations_test.go | 28 ++-- x/sanction/module/module.go | 2 +- x/sanction/simulation/operations.go | 54 +++--- x/sanction/simulation/operations_test.go | 15 +- x/trigger/module/module.go | 4 +- x/trigger/simulation/operations.go | 63 +++---- x/trigger/simulation/operations_test.go | 31 ++-- 27 files changed, 464 insertions(+), 603 deletions(-) delete mode 100644 app/params/proto.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 1dbbce1df5..5e0e143005 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -64,6 +64,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ * Restore the hold module [#1930](https://github.com/provenance-io/provenance/pull/1930). * Restore gov-prop cli commands and fix next key decoding [#1930](https://github.com/provenance-io/provenance/pull/1930). * Switch to InputOutputCoinsProv for exchange transfers [#1930](https://github.com/provenance-io/provenance/pull/1930). +* Use fields of the SimulationState for the encoders needed for simulations [#1931](https://github.com/provenance-io/provenance/pull/1931). ### Dependencies diff --git a/app/params/proto.go b/app/params/proto.go deleted file mode 100644 index 983cf7159f..0000000000 --- a/app/params/proto.go +++ /dev/null @@ -1,46 +0,0 @@ -package params - -import ( - "cosmossdk.io/x/tx/signing" - - "github.com/cosmos/cosmos-sdk/codec" - amino "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/address" - "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/tx" - "github.com/cosmos/gogoproto/proto" -) - -// MakeTestEncodingConfig creates an EncodingConfig for a non-amino based test configuration. -// This function should be used only internally (in the SDK). -// App user shouldn't create new codecs - use the app.AppCodec instead. -// -// TODO[1760]: Update all the simulation stuff that uses this to instead get what's needed from the SimState. -// That will involve passing the SimSate into many places where we used to provide a codec. Then, delete this file. -// -// Deprecated: Either get this from the app (app.GetEncodingConfig()) or use MakeTestEncodingConfig (from the app package), -// or get what's needed from the SimSate. -func MakeTestEncodingConfig() EncodingConfig { - cdc := amino.NewLegacyAmino() - signingOptions := signing.Options{ - AddressCodec: address.Bech32Codec{ - Bech32Prefix: sdk.GetConfig().GetBech32AccountAddrPrefix(), - }, - ValidatorAddressCodec: address.Bech32Codec{ - Bech32Prefix: sdk.GetConfig().GetBech32ValidatorAddrPrefix(), - }, - } - interfaceRegistry, _ := types.NewInterfaceRegistryWithOptions(types.InterfaceRegistryOptions{ - ProtoFiles: proto.HybridResolver, - SigningOptions: signingOptions, - }) - marshaler := codec.NewProtoCodec(interfaceRegistry) - - return EncodingConfig{ - InterfaceRegistry: interfaceRegistry, - Marshaler: marshaler, - TxConfig: tx.NewTxConfig(marshaler, tx.DefaultSignModes), - Amino: cdc, - } -} diff --git a/internal/provwasm/simulation.go b/internal/provwasm/simulation.go index f7b5037516..447b060b42 100644 --- a/internal/provwasm/simulation.go +++ b/internal/provwasm/simulation.go @@ -11,13 +11,11 @@ import ( "github.com/CosmWasm/wasmd/x/wasm/types" sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" "github.com/cosmos/cosmos-sdk/x/bank/exported" @@ -99,18 +97,18 @@ func (pw Wrapper) RegisterStoreDecoder(sdr simtypes.StoreDecoderRegistry) { } // WeightedOperations returns the all the provwasm operations with their respective weights. -func (pw Wrapper) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation { +func (pw Wrapper) WeightedOperations(simSate module.SimulationState) []simtypes.WeightedOperation { count := 0 return []simtypes.WeightedOperation{ simulation.NewWeightedOperation( 100, - SimulateMsgBindName(pw.ak, pw.bk, pw.nk, &count), + SimulateMsgBindName(simSate, pw.ak, pw.bk, pw.nk, &count), ), } } // SimulateMsgBindName will bind a NAME under an existing name -func SimulateMsgBindName(ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, nk namekeeper.Keeper, count *int) simtypes.Operation { +func SimulateMsgBindName(simState module.SimulationState, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, nk namekeeper.Keeper, count *int) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -149,17 +147,17 @@ func SimulateMsgBindName(ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, nk false), parent) - op, future, err2 := namesim.Dispatch(r, app, ctx, ak, bk, node, chainID, msg) + op, future, err2 := namesim.Dispatch(r, app, ctx, simState, ak, bk, node, chainID, msg) name := namePrefix + "." + parent.Name - future = append(future, simtypes.FutureOperation{Op: SimulateMsgAddMarker(ak, bk, nk, node, feebucket, merchant, consumer, name), BlockHeight: int(ctx.BlockHeight()) + 1}) + future = append(future, simtypes.FutureOperation{Op: SimulateMsgAddMarker(simState, ak, bk, nk, node, feebucket, merchant, consumer, name), BlockHeight: int(ctx.BlockHeight()) + 1}) return op, future, err2 } } -func SimulateMsgAddMarker(ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, nk namekeeper.Keeper, node, feebucket, merchant, consumer simtypes.Account, name string) simtypes.Operation { +func SimulateMsgAddMarker(simState module.SimulationState, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, nk namekeeper.Keeper, node, feebucket, merchant, consumer simtypes.Account, name string) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -189,58 +187,58 @@ func SimulateMsgAddMarker(ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, nk return simtypes.NoOpMsg("provwasm", "", "unable to fund account"), nil, nil } - msg2, ops, err := markersim.Dispatch(r, app, ctx, ak, bk, node, chainID, msg, nil) + msg2, ops, err := markersim.Dispatch(r, app, ctx, simState, ak, bk, node, chainID, msg, nil) - ops = append(ops, simtypes.FutureOperation{Op: SimulateMsgAddAccess(ak, bk, nk, node, feebucket, merchant, consumer, name), BlockHeight: int(ctx.BlockHeight()) + 1}) + ops = append(ops, simtypes.FutureOperation{Op: SimulateMsgAddAccess(simState, ak, bk, nk, node, feebucket, merchant, consumer, name), BlockHeight: int(ctx.BlockHeight()) + 1}) return msg2, ops, err } } -func SimulateMsgAddAccess(ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, nk namekeeper.Keeper, node, feebucket, merchant, consumer simtypes.Account, name string) simtypes.Operation { +func SimulateMsgAddAccess(simState module.SimulationState, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, nk namekeeper.Keeper, node, feebucket, merchant, consumer simtypes.Account, name string) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { accessTypes := []markertypes.Access{markertypes.AccessByName("withdraw")} grant := *markertypes.NewAccessGrant(node.Address, accessTypes) msg := markertypes.NewMsgAddAccessRequest(denom, node.Address, grant) - msg2, ops, err := markersim.Dispatch(r, app, ctx, ak, bk, node, chainID, msg, nil) + msg2, ops, err := markersim.Dispatch(r, app, ctx, simState, ak, bk, node, chainID, msg, nil) - ops = append(ops, simtypes.FutureOperation{Op: SimulateFinalizeMarker(ak, bk, nk, node, feebucket, merchant, consumer, name), BlockHeight: int(ctx.BlockHeight()) + 1}) + ops = append(ops, simtypes.FutureOperation{Op: SimulateFinalizeMarker(simState, ak, bk, nk, node, feebucket, merchant, consumer, name), BlockHeight: int(ctx.BlockHeight()) + 1}) return msg2, ops, err } } -func SimulateFinalizeMarker(ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, nk namekeeper.Keeper, node, feebucket, merchant, consumer simtypes.Account, name string) simtypes.Operation { +func SimulateFinalizeMarker(simState module.SimulationState, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, nk namekeeper.Keeper, node, feebucket, merchant, consumer simtypes.Account, name string) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { msg := markertypes.NewMsgFinalizeRequest(denom, node.Address) - msg2, ops, err := markersim.Dispatch(r, app, ctx, ak, bk, node, chainID, msg, nil) + msg2, ops, err := markersim.Dispatch(r, app, ctx, simState, ak, bk, node, chainID, msg, nil) - ops = append(ops, simtypes.FutureOperation{Op: SimulateActivateMarker(ak, bk, nk, node, feebucket, merchant, consumer, name), BlockHeight: int(ctx.BlockHeight()) + 1}) + ops = append(ops, simtypes.FutureOperation{Op: SimulateActivateMarker(simState, ak, bk, nk, node, feebucket, merchant, consumer, name), BlockHeight: int(ctx.BlockHeight()) + 1}) return msg2, ops, err } } -func SimulateActivateMarker(ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, nk namekeeper.Keeper, node, feebucket, merchant, consumer simtypes.Account, name string) simtypes.Operation { +func SimulateActivateMarker(simState module.SimulationState, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, nk namekeeper.Keeper, node, feebucket, merchant, consumer simtypes.Account, name string) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { msg := markertypes.NewMsgActivateRequest(denom, node.Address) - msg2, ops, err := markersim.Dispatch(r, app, ctx, ak, bk, node, chainID, msg, nil) + msg2, ops, err := markersim.Dispatch(r, app, ctx, simState, ak, bk, node, chainID, msg, nil) - ops = append(ops, simtypes.FutureOperation{Op: SimulateMsgWithdrawRequest(ak, bk, nk, node, feebucket, merchant, consumer, name), BlockHeight: int(ctx.BlockHeight()) + 1}) + ops = append(ops, simtypes.FutureOperation{Op: SimulateMsgWithdrawRequest(simState, ak, bk, nk, node, feebucket, merchant, consumer, name), BlockHeight: int(ctx.BlockHeight()) + 1}) return msg2, ops, err } } -func SimulateMsgWithdrawRequest(ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, nk namekeeper.Keeper, node, feebucket, merchant, consumer simtypes.Account, name string) simtypes.Operation { +func SimulateMsgWithdrawRequest(simState module.SimulationState, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, nk namekeeper.Keeper, node, feebucket, merchant, consumer simtypes.Account, name string) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -249,15 +247,15 @@ func SimulateMsgWithdrawRequest(ak authkeeper.AccountKeeperI, bk bankkeeper.Keep Amount: sdkmath.NewIntFromUint64(1_000_000), }} msg := markertypes.NewMsgWithdrawRequest(node.Address, consumer.Address, denom, coins) - msg2, ops, err := markersim.Dispatch(r, app, ctx, ak, bk, node, chainID, msg, nil) + msg2, ops, err := markersim.Dispatch(r, app, ctx, simState, ak, bk, node, chainID, msg, nil) - ops = append(ops, simtypes.FutureOperation{Op: SimulateMsgStoreContract(ak, bk, nk, node, feebucket, merchant, consumer, name), BlockHeight: int(ctx.BlockHeight()) + 1}) + ops = append(ops, simtypes.FutureOperation{Op: SimulateMsgStoreContract(simState, ak, bk, nk, node, feebucket, merchant, consumer, name), BlockHeight: int(ctx.BlockHeight()) + 1}) return msg2, ops, err } } -func SimulateMsgStoreContract(ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper, nk namekeeper.Keeper, node, feebucket, merchant, consumer simtypes.Account, name string) simtypes.Operation { +func SimulateMsgStoreContract(simState module.SimulationState, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper, nk namekeeper.Keeper, node, feebucket, merchant, consumer simtypes.Account, name string) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -272,15 +270,15 @@ func SimulateMsgStoreContract(ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKe WASMByteCode: code, } - msg2, ops, _, storeErr := Dispatch(r, app, ctx, ak, bk, feebucket, chainID, msg, nil, nil) + msg2, ops, _, storeErr := Dispatch(r, app, ctx, simState, ak, bk, feebucket, chainID, msg, nil, nil) - ops = append(ops, simtypes.FutureOperation{Op: SimulateMsgInstantiateContract(ak, bk, nk, node, feebucket, merchant, consumer, name), BlockHeight: int(ctx.BlockHeight()) + 1}) + ops = append(ops, simtypes.FutureOperation{Op: SimulateMsgInstantiateContract(simState, ak, bk, nk, node, feebucket, merchant, consumer, name), BlockHeight: int(ctx.BlockHeight()) + 1}) return msg2, ops, storeErr } } -func SimulateMsgInstantiateContract(ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper, nk namekeeper.Keeper, node, feebucket, merchant, consumer simtypes.Account, name string) simtypes.Operation { +func SimulateMsgInstantiateContract(simState module.SimulationState, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper, nk namekeeper.Keeper, node, feebucket, merchant, consumer simtypes.Account, name string) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -310,7 +308,7 @@ func SimulateMsgInstantiateContract(ak authkeeper.AccountKeeperI, bk bankkeeper. Funds: amount, } - msg2, ops, sdkResponse, instantiateErr := Dispatch(r, app, ctx, ak, bk, feebucket, chainID, msg, amount, nil) + msg2, ops, sdkResponse, instantiateErr := Dispatch(r, app, ctx, simState, ak, bk, feebucket, chainID, msg, amount, nil) // get the contract address for use when executing the contract if len(sdkResponse.MsgResponses) == 0 { @@ -340,13 +338,13 @@ func SimulateMsgInstantiateContract(ak authkeeper.AccountKeeperI, bk bankkeeper. contractAddr := pInstResp.Address - ops = append(ops, simtypes.FutureOperation{Op: SimulateMsgExecuteContract(ak, bk, node, consumer, contractAddr), BlockHeight: int(ctx.BlockHeight()) + 1}) + ops = append(ops, simtypes.FutureOperation{Op: SimulateMsgExecuteContract(simState, ak, bk, node, consumer, contractAddr), BlockHeight: int(ctx.BlockHeight()) + 1}) return msg2, ops, instantiateErr } } -func SimulateMsgExecuteContract(ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper, _, consumer simtypes.Account, contractAddr string) simtypes.Operation { +func SimulateMsgExecuteContract(simState module.SimulationState, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper, _, consumer simtypes.Account, contractAddr string) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -364,7 +362,7 @@ func SimulateMsgExecuteContract(ak authkeeper.AccountKeeperI, bk bankkeeper.View Msg: []byte("{\"purchase\":{\"id\":\"12345\"}}"), } - msg2, ops, _, err2 := Dispatch(r, app, ctx, ak, bk, consumer, chainID, msg, amount, nil) + msg2, ops, _, err2 := Dispatch(r, app, ctx, simState, ak, bk, consumer, chainID, msg, amount, nil) return msg2, ops, err2 } } @@ -376,6 +374,7 @@ func Dispatch( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, + simState module.SimulationState, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper, from simtypes.Account, @@ -401,10 +400,9 @@ func Dispatch( panic("no fees") } - txGen := moduletestutil.MakeTestEncodingConfig().TxConfig tx, err := simtestutil.GenSignedMockTx( r, - txGen, + simState.TxConfig, []sdk.Msg{msg}, fees, simtestutil.DefaultGenTxGas*10, // storing a contract requires more gas than most txs @@ -417,7 +415,7 @@ func Dispatch( panic(err) } - _, sdkResponse, err2 := app.SimDeliver(txGen.TxEncoder(), tx) + _, sdkResponse, err2 := app.SimDeliver(simState.TxConfig.TxEncoder(), tx) if err2 != nil { panic(err2) } diff --git a/x/attribute/module.go b/x/attribute/module.go index d2a5534476..61b43bb8ef 100644 --- a/x/attribute/module.go +++ b/x/attribute/module.go @@ -12,6 +12,7 @@ import ( abci "github.com/cometbft/cometbft/abci/types" "cosmossdk.io/core/appmodule" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -179,9 +180,7 @@ func (am AppModule) RegisterStoreDecoder(sdr simtypes.StoreDecoderRegistry) { // WeightedOperations returns the all the attribute module operations with their respective weights. func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { - return simulation.WeightedOperations( - simState.AppParams, simState.Cdc, am.keeper, am.ak, am.bk, am.nk, - ) + return simulation.WeightedOperations(simState, am.keeper, am.ak, am.bk, am.nk) } // ConsensusVersion implements AppModule/ConsensusVersion. diff --git a/x/attribute/simulation/operations.go b/x/attribute/simulation/operations.go index ce5706c54d..5e37a913be 100644 --- a/x/attribute/simulation/operations.go +++ b/x/attribute/simulation/operations.go @@ -6,11 +6,10 @@ import ( "github.com/google/uuid" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" @@ -39,81 +38,47 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simtypes.AppParams, cdc codec.JSONCodec, k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper, nk namekeeper.Keeper, + simState module.SimulationState, k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper, nk namekeeper.Keeper, ) simulation.WeightedOperations { var ( - weightMsgAddAttribute int - weightMsgUpdateAttribute int - weightMsgDeleteAttribute int - weightMsgDeleteDistinctAttribute int - weightMsgSetAccountDataRequest int - ) - - appParams.GetOrGenerate(OpWeightMsgAddAttribute, &weightMsgAddAttribute, nil, - func(_ *rand.Rand) { - weightMsgAddAttribute = simappparams.DefaultWeightMsgAddAttribute - }, - ) - - appParams.GetOrGenerate(OpWeightMsgUpdateAttribute, &weightMsgUpdateAttribute, nil, - func(_ *rand.Rand) { - weightMsgUpdateAttribute = simappparams.DefaultWeightMsgUpdateAttribute - }, - ) - - appParams.GetOrGenerate(OpWeightMsgDeleteAttribute, &weightMsgDeleteAttribute, nil, - func(_ *rand.Rand) { - weightMsgDeleteAttribute = simappparams.DefaultWeightMsgDeleteAttribute - }, + wMsgAddAttribute int + wMsgUpdateAttribute int + wMsgDeleteAttribute int + wMsgDeleteDistinctAttribute int + wMsgSetAccountDataRequest int ) - appParams.GetOrGenerate(OpWeightMsgDeleteDistinctAttribute, &weightMsgDeleteDistinctAttribute, nil, - func(_ *rand.Rand) { - weightMsgDeleteDistinctAttribute = simappparams.DefaultWeightMsgDeleteDistinctAttribute - }, - ) - - appParams.GetOrGenerate(OpWeightMsgSetAccountData, &weightMsgSetAccountDataRequest, nil, - func(_ *rand.Rand) { - weightMsgSetAccountDataRequest = simappparams.DefaultWeightMsgSetAccountData - }, - ) + simState.AppParams.GetOrGenerate(OpWeightMsgAddAttribute, &wMsgAddAttribute, nil, + func(_ *rand.Rand) { wMsgAddAttribute = simappparams.DefaultWeightMsgAddAttribute }) + simState.AppParams.GetOrGenerate(OpWeightMsgUpdateAttribute, &wMsgUpdateAttribute, nil, + func(_ *rand.Rand) { wMsgUpdateAttribute = simappparams.DefaultWeightMsgUpdateAttribute }) + simState.AppParams.GetOrGenerate(OpWeightMsgDeleteAttribute, &wMsgDeleteAttribute, nil, + func(_ *rand.Rand) { wMsgDeleteAttribute = simappparams.DefaultWeightMsgDeleteAttribute }) + simState.AppParams.GetOrGenerate(OpWeightMsgDeleteDistinctAttribute, &wMsgDeleteDistinctAttribute, nil, + func(_ *rand.Rand) { wMsgDeleteDistinctAttribute = simappparams.DefaultWeightMsgDeleteDistinctAttribute }) + simState.AppParams.GetOrGenerate(OpWeightMsgSetAccountData, &wMsgSetAccountDataRequest, nil, + func(_ *rand.Rand) { wMsgSetAccountDataRequest = simappparams.DefaultWeightMsgSetAccountData }) return simulation.WeightedOperations{ - simulation.NewWeightedOperation( - weightMsgAddAttribute, - SimulateMsgAddAttribute(k, ak, bk, nk), - ), - simulation.NewWeightedOperation( - weightMsgUpdateAttribute, - SimulateMsgUpdateAttribute(k, ak, bk, nk), - ), - simulation.NewWeightedOperation( - weightMsgDeleteAttribute, - SimulateMsgDeleteAttribute(k, ak, bk, nk), - ), - simulation.NewWeightedOperation( - weightMsgDeleteDistinctAttribute, - SimulateMsgDeleteDistinctAttribute(k, ak, bk, nk), - ), - simulation.NewWeightedOperation( - weightMsgSetAccountDataRequest, - SimulateMsgSetAccountData(k, ak, bk), - ), + simulation.NewWeightedOperation(wMsgAddAttribute, SimulateMsgAddAttribute(simState, k, ak, bk, nk)), + simulation.NewWeightedOperation(wMsgUpdateAttribute, SimulateMsgUpdateAttribute(simState, k, ak, bk, nk)), + simulation.NewWeightedOperation(wMsgDeleteAttribute, SimulateMsgDeleteAttribute(simState, k, ak, bk, nk)), + simulation.NewWeightedOperation(wMsgDeleteDistinctAttribute, SimulateMsgDeleteDistinctAttribute(simState, k, ak, bk, nk)), + simulation.NewWeightedOperation(wMsgSetAccountDataRequest, SimulateMsgSetAccountData(simState, k, ak, bk)), } } // SimulateMsgAddAttribute will add an attribute under an account with a random type. -func SimulateMsgAddAttribute(_ keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper, nk namekeeper.Keeper) simtypes.Operation { +func SimulateMsgAddAttribute(simState module.SimulationState, _ keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper, nk namekeeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { randomRecord, simAccount, found, err := getRandomNameRecord(r, ctx, &nk, accs) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgAddAttributeRequest{}), sdk.MsgTypeURL(&types.MsgAddAttributeRequest{}), "iterator of existing name records failed"), nil, err + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgAddAttributeRequest{}), "iterator of existing name records failed"), nil, err } if !found { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgAddAttributeRequest{}), sdk.MsgTypeURL(&types.MsgAddAttributeRequest{}), "no name records available to create under"), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgAddAttributeRequest{}), "no name records available to create under"), nil, nil } t := types.AttributeType(r.Intn(9)) @@ -125,21 +90,21 @@ func SimulateMsgAddAttribute(_ keeper.Keeper, ak authkeeper.AccountKeeperI, bk b getRandomValueOfType(r, t), ) - return Dispatch(r, app, ctx, ak, bk, simAccount, chainID, msg) + return Dispatch(r, app, ctx, simState, ak, bk, simAccount, chainID, msg) } } // SimulateMsgUpdateAttribute will add an attribute under an account with a random type. -func SimulateMsgUpdateAttribute(k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper, nk namekeeper.Keeper) simtypes.Operation { +func SimulateMsgUpdateAttribute(simState module.SimulationState, k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper, nk namekeeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { randomAttribute, simAccount, found, err := getRandomAttribute(r, ctx, k, &nk, accs) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgUpdateAttributeRequest{}), sdk.MsgTypeURL(&types.MsgUpdateAttributeRequest{}), "iterator of existing attributes failed"), nil, err + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgUpdateAttributeRequest{}), "iterator of existing attributes failed"), nil, err } if !found { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgUpdateAttributeRequest{}), sdk.MsgTypeURL(&types.MsgUpdateAttributeRequest{}), "no attributes available to delete"), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgUpdateAttributeRequest{}), "no attributes available to delete"), nil, nil } t := types.AttributeType(r.Intn(9)) @@ -153,50 +118,50 @@ func SimulateMsgUpdateAttribute(k keeper.Keeper, ak authkeeper.AccountKeeperI, b t, ) - return Dispatch(r, app, ctx, ak, bk, simAccount, chainID, msg) + return Dispatch(r, app, ctx, simState, ak, bk, simAccount, chainID, msg) } } // SimulateMsgDeleteAttribute will dispatch a delete attribute operation against a random record -func SimulateMsgDeleteAttribute(k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper, nk namekeeper.Keeper) simtypes.Operation { +func SimulateMsgDeleteAttribute(simState module.SimulationState, k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper, nk namekeeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { randomAttribute, simAccount, found, err := getRandomAttribute(r, ctx, k, &nk, accs) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgDeleteAttributeRequest{}), sdk.MsgTypeURL(&types.MsgDeleteAttributeRequest{}), "iterator of existing attributes failed"), nil, err + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgDeleteAttributeRequest{}), "iterator of existing attributes failed"), nil, err } if !found { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgDeleteAttributeRequest{}), sdk.MsgTypeURL(&types.MsgDeleteAttributeRequest{}), "no attributes available to delete"), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgDeleteAttributeRequest{}), "no attributes available to delete"), nil, nil } msg := types.NewMsgDeleteAttributeRequest(randomAttribute.Address, simAccount.Address, randomAttribute.Name) - return Dispatch(r, app, ctx, ak, bk, simAccount, chainID, msg) + return Dispatch(r, app, ctx, simState, ak, bk, simAccount, chainID, msg) } } // SimulateMsgDeleteDistinctAttribute will dispatch a delete attribute operation against a random record -func SimulateMsgDeleteDistinctAttribute(k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper, nk namekeeper.Keeper) simtypes.Operation { +func SimulateMsgDeleteDistinctAttribute(simState module.SimulationState, k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper, nk namekeeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { randomAttribute, simAccount, found, err := getRandomAttribute(r, ctx, k, &nk, accs) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgDeleteDistinctAttributeRequest{}), sdk.MsgTypeURL(&types.MsgDeleteDistinctAttributeRequest{}), "iterator of existing attributes failed"), nil, err + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgDeleteDistinctAttributeRequest{}), "iterator of existing attributes failed"), nil, err } if !found { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgDeleteDistinctAttributeRequest{}), sdk.MsgTypeURL(&types.MsgDeleteDistinctAttributeRequest{}), "no attributes available to delete distinct"), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgDeleteDistinctAttributeRequest{}), "no attributes available to delete distinct"), nil, nil } msg := types.NewMsgDeleteDistinctAttributeRequest(randomAttribute.Address, simAccount.Address, randomAttribute.Name, randomAttribute.Value) - return Dispatch(r, app, ctx, ak, bk, simAccount, chainID, msg) + return Dispatch(r, app, ctx, simState, ak, bk, simAccount, chainID, msg) } } // SimulateMsgSetAccountData will dispatch a set account data operation for a random account. -func SimulateMsgSetAccountData(k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper) simtypes.Operation { +func SimulateMsgSetAccountData(simState module.SimulationState, k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -219,7 +184,7 @@ func SimulateMsgSetAccountData(k keeper.Keeper, ak authkeeper.AccountKeeperI, bk Account: acc.Address.String(), } - return Dispatch(r, app, ctx, ak, bk, acc, chainID, msg) + return Dispatch(r, app, ctx, simState, ak, bk, acc, chainID, msg) } } @@ -252,6 +217,7 @@ func Dispatch( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, + simState module.SimulationState, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper, from simtypes.Account, @@ -270,10 +236,9 @@ func Dispatch( return simtypes.NoOpMsg(types.ModuleName, fmt.Sprintf("%T", msg), "unable to generate fees"), nil, err } - txGen := simappparams.MakeTestEncodingConfig().TxConfig tx, err := simtestutil.GenSignedMockTx( r, - txGen, + simState.TxConfig, []sdk.Msg{msg}, fees, simtestutil.DefaultGenTxGas, @@ -283,12 +248,12 @@ func Dispatch( from.PrivKey, ) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), "unable to generate mock tx"), nil, err + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "unable to generate mock tx"), nil, err } - _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) + _, _, err = app.SimDeliver(simState.TxConfig.TxEncoder(), tx) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), err.Error()), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), err.Error()), nil, nil } return simtypes.NewOperationMsg(msg, true, ""), nil, nil diff --git a/x/attribute/simulation/operations_test.go b/x/attribute/simulation/operations_test.go index cde1180dea..f807c6948f 100644 --- a/x/attribute/simulation/operations_test.go +++ b/x/attribute/simulation/operations_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/suite" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/bank/testutil" @@ -26,6 +27,10 @@ type SimTestSuite struct { app *app.App } +func TestSimTestSuite(t *testing.T) { + suite.Run(t, new(SimTestSuite)) +} + func (s *SimTestSuite) SetupTest() { s.app = app.Setup(s.T()) s.ctx = s.app.BaseApp.NewContext(false) @@ -58,11 +63,17 @@ func (s *SimTestSuite) LogIfError(err error, format string, args ...interface{}) } } -func (s *SimTestSuite) TestWeightedOperations() { - cdc := s.app.AppCodec() - appParams := make(simtypes.AppParams) +// MakeTestSimState creates a new module.SimulationState struct with the fields needed by the functions being tested. +func (s *SimTestSuite) MakeTestSimState() module.SimulationState { + return module.SimulationState{ + AppParams: make(simtypes.AppParams), + Cdc: s.app.AppCodec(), + TxConfig: s.app.GetTxConfig(), + } +} - weightedOps := simulation.WeightedOperations(appParams, cdc, s.app.AttributeKeeper, +func (s *SimTestSuite) TestWeightedOperations() { + weightedOps := simulation.WeightedOperations(s.MakeTestSimState(), s.app.AttributeKeeper, s.app.AccountKeeper, s.app.BankKeeper, s.app.NameKeeper, ) @@ -120,7 +131,7 @@ func (s *SimTestSuite) TestSimulateMsgAddAttribute() { s.LogIfError(s.app.NameKeeper.SetNameRecord(s.ctx, name, accounts[0].Address, false), "SetNameRecord(%q) error", name) // execute operation - op := simulation.SimulateMsgAddAttribute(s.app.AttributeKeeper, s.app.AccountKeeper, s.app.BankKeeper, s.app.NameKeeper) + op := simulation.SimulateMsgAddAttribute(s.MakeTestSimState(), s.app.AttributeKeeper, s.app.AccountKeeper, s.app.BankKeeper, s.app.NameKeeper) operationMsg, futureOperations, err := op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err, "SimulateMsgAddAttribute op(...) error") s.LogOperationMsg(operationMsg) @@ -152,7 +163,7 @@ func (s *SimTestSuite) TestSimulateMsgUpdateAttribute() { s.LogIfError(s.app.AttributeKeeper.SetAttribute(s.ctx, attr, accounts[0].Address), "SetAttribute(%q) error", name) // execute operation - op := simulation.SimulateMsgUpdateAttribute(s.app.AttributeKeeper, s.app.AccountKeeper, s.app.BankKeeper, s.app.NameKeeper) + op := simulation.SimulateMsgUpdateAttribute(s.MakeTestSimState(), s.app.AttributeKeeper, s.app.AccountKeeper, s.app.BankKeeper, s.app.NameKeeper) operationMsg, futureOperations, err := op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err, "SimulateMsgUpdateAttribute op(...) error") s.LogOperationMsg(operationMsg) @@ -182,7 +193,7 @@ func (s *SimTestSuite) TestSimulateMsgDeleteAttribute() { s.LogIfError(s.app.AttributeKeeper.SetAttribute(s.ctx, attr, accounts[0].Address), "SetAttribute(%q) error", name) // execute operation - op := simulation.SimulateMsgDeleteAttribute(s.app.AttributeKeeper, s.app.AccountKeeper, s.app.BankKeeper, s.app.NameKeeper) + op := simulation.SimulateMsgDeleteAttribute(s.MakeTestSimState(), s.app.AttributeKeeper, s.app.AccountKeeper, s.app.BankKeeper, s.app.NameKeeper) operationMsg, futureOperations, err := op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err, "SimulateMsgDeleteAttribute op(...) error") s.LogOperationMsg(operationMsg) @@ -212,7 +223,7 @@ func (s *SimTestSuite) TestSimulateMsgDeleteDistinctAttribute() { s.LogIfError(s.app.AttributeKeeper.SetAttribute(s.ctx, attr, accounts[0].Address), "SetAttribute(%q) error", name) // execute operation - op := simulation.SimulateMsgDeleteDistinctAttribute(s.app.AttributeKeeper, s.app.AccountKeeper, s.app.BankKeeper, s.app.NameKeeper) + op := simulation.SimulateMsgDeleteDistinctAttribute(s.MakeTestSimState(), s.app.AttributeKeeper, s.app.AccountKeeper, s.app.BankKeeper, s.app.NameKeeper) operationMsg, futureOperations, err := op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err, "SimulateMsgDeleteDistinctAttribute op(...) error") s.LogOperationMsg(operationMsg) @@ -236,7 +247,7 @@ func (s *SimTestSuite) TestSimulateMsgSetAccountData() { accounts := s.getTestingAccounts(r, 3) // execute operation - op := simulation.SimulateMsgSetAccountData(s.app.AttributeKeeper, s.app.AccountKeeper, s.app.BankKeeper) + op := simulation.SimulateMsgSetAccountData(s.MakeTestSimState(), s.app.AttributeKeeper, s.app.AccountKeeper, s.app.BankKeeper) operationMsg, futureOperations, err := op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err, "SimulateMsgDeleteDistinctAttribute op(...) error") s.LogOperationMsg(operationMsg) @@ -280,7 +291,3 @@ func GenerateRandomTime(minHours int) time.Time { return randomTime } - -func TestSimTestSuite(t *testing.T) { - suite.Run(t, new(SimTestSuite)) -} diff --git a/x/ibcratelimit/module/module.go b/x/ibcratelimit/module/module.go index 01e51d9f42..6e05a17163 100644 --- a/x/ibcratelimit/module/module.go +++ b/x/ibcratelimit/module/module.go @@ -6,13 +6,14 @@ import ( "fmt" "math/rand" - "cosmossdk.io/core/appmodule" "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" abci "github.com/cometbft/cometbft/abci/types" + "cosmossdk.io/core/appmodule" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -135,9 +136,7 @@ func (am AppModule) RegisterStoreDecoder(sdr simtypes.StoreDecoderRegistry) { // WeightedOperations returns simulation operations (i.e msgs) with their respective weight func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { - return simulation.WeightedOperations( - simState.AppParams, simState.Cdc, am.keeper, am.accountKeeper, am.bankKeeper, - ) + return simulation.WeightedOperations(simState, am.keeper, am.accountKeeper, am.bankKeeper) } // Name returns the ibcratelimit module's name. diff --git a/x/ibcratelimit/simulation/operations.go b/x/ibcratelimit/simulation/operations.go index 7f2f3b7afc..20f1400584 100644 --- a/x/ibcratelimit/simulation/operations.go +++ b/x/ibcratelimit/simulation/operations.go @@ -4,13 +4,12 @@ import ( "fmt" "math/rand" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdkmath "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" @@ -31,34 +30,28 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simtypes.AppParams, cdc codec.JSONCodec, k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, + simState module.SimulationState, k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, ) simulation.WeightedOperations { var ( - weightMsgUpdateParams int + wMsgUpdateParams int ) - appParams.GetOrGenerate(OpWeightMsgUpdateParams, &weightMsgUpdateParams, nil, - func(_ *rand.Rand) { - weightMsgUpdateParams = simappparams.DefaultWeightGovUpdateParams - }, - ) + simState.AppParams.GetOrGenerate(OpWeightMsgUpdateParams, &wMsgUpdateParams, nil, + func(_ *rand.Rand) { wMsgUpdateParams = simappparams.DefaultWeightGovUpdateParams }) return simulation.WeightedOperations{ - simulation.NewWeightedOperation( - weightMsgUpdateParams, - SimulateMsgGovUpdateParams(k, ak, bk), - ), + simulation.NewWeightedOperation(wMsgUpdateParams, SimulateMsgGovUpdateParams(simState, k, ak, bk)), } } // SimulateMsgGovUpdateParams sends a MsgUpdateParams. -func SimulateMsgGovUpdateParams(_ keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper) simtypes.Operation { +func SimulateMsgGovUpdateParams(simState module.SimulationState, _ keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { raccs, err := RandomAccs(r, accs, uint64(len(accs))) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&ibcratelimit.MsgGovUpdateParamsRequest{}), sdk.MsgTypeURL(&ibcratelimit.MsgGovUpdateParamsRequest{}), err.Error()), nil, nil + return simtypes.NoOpMsg(ibcratelimit.ModuleName, sdk.MsgTypeURL(&ibcratelimit.MsgGovUpdateParamsRequest{}), err.Error()), nil, nil } // 50% chance to be from the module's authority @@ -67,7 +60,8 @@ func SimulateMsgGovUpdateParams(_ keeper.Keeper, ak authkeeper.AccountKeeperI, b msg := ibcratelimit.NewMsgGovUpdateParamsRequest(from.Address.String(), to.Address.String()) - return Dispatch(r, app, ctx, from, chainID, msg, ak, bk, nil) + // TODO[1760]: Refactor this to submit it as a gov prop and return futures for votes. + return Dispatch(r, app, ctx, simState, from, chainID, msg, ak, bk, nil) } } @@ -77,6 +71,7 @@ func Dispatch( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, + simState module.SimulationState, from simtypes.Account, chainID string, msg sdk.Msg, @@ -93,19 +88,19 @@ func Dispatch( fees, err := simtypes.RandomFees(r, ctx, spendable) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), "unable to generate fees"), nil, err + return simtypes.NoOpMsg(ibcratelimit.ModuleName, sdk.MsgTypeURL(msg), "unable to generate fees"), nil, err } err = testutil.FundAccount(ctx, bk, account.GetAddress(), sdk.NewCoins(sdk.Coin{ Denom: pioconfig.GetProvenanceConfig().BondDenom, Amount: sdkmath.NewInt(1_000_000_000_000_000), })) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), "unable to fund account"), nil, err + return simtypes.NoOpMsg(ibcratelimit.ModuleName, sdk.MsgTypeURL(msg), "unable to fund account"), nil, err } - txGen := simappparams.MakeTestEncodingConfig().TxConfig + tx, err := simtestutil.GenSignedMockTx( r, - txGen, + simState.TxConfig, []sdk.Msg{msg}, fees, simtestutil.DefaultGenTxGas, @@ -115,12 +110,12 @@ func Dispatch( from.PrivKey, ) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), "unable to generate mock tx"), nil, err + return simtypes.NoOpMsg(ibcratelimit.ModuleName, sdk.MsgTypeURL(msg), "unable to generate mock tx"), nil, err } - _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) + _, _, err = app.SimDeliver(simState.TxConfig.TxEncoder(), tx) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), err.Error()), nil, nil + return simtypes.NoOpMsg(ibcratelimit.ModuleName, sdk.MsgTypeURL(msg), err.Error()), nil, nil } return simtypes.NewOperationMsg(msg, true, ""), futures, nil diff --git a/x/ibcratelimit/simulation/operations_test.go b/x/ibcratelimit/simulation/operations_test.go index 314754ba95..ccd77955b1 100644 --- a/x/ibcratelimit/simulation/operations_test.go +++ b/x/ibcratelimit/simulation/operations_test.go @@ -5,10 +5,12 @@ import ( "fmt" "math/rand" "strings" + "testing" "github.com/stretchr/testify/suite" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/bank/testutil" @@ -16,7 +18,6 @@ import ( simappparams "github.com/provenance-io/provenance/app/params" "github.com/provenance-io/provenance/x/ibcratelimit" "github.com/provenance-io/provenance/x/ibcratelimit/simulation" - "github.com/provenance-io/provenance/x/trigger/types" ) type SimTestSuite struct { @@ -26,6 +27,10 @@ type SimTestSuite struct { app *app.App } +func TestSimTestSuite(t *testing.T) { + suite.Run(t, new(SimTestSuite)) +} + func (s *SimTestSuite) SetupTest() { s.app = app.Setup(s.T()) s.ctx = s.app.BaseApp.NewContext(false) @@ -50,11 +55,17 @@ func (s *SimTestSuite) LogOperationMsg(operationMsg simtypes.OperationMsg, msg s ) } -func (s *SimTestSuite) TestWeightedOperations() { - cdc := s.app.AppCodec() - appParams := make(simtypes.AppParams) +// MakeTestSimState creates a new module.SimulationState struct with the fields needed by the functions being tested. +func (s *SimTestSuite) MakeTestSimState() module.SimulationState { + return module.SimulationState{ + AppParams: make(simtypes.AppParams), + Cdc: s.app.AppCodec(), + TxConfig: s.app.GetTxConfig(), + } +} - weightedOps := simulation.WeightedOperations(appParams, cdc, *s.app.RateLimitingKeeper, +func (s *SimTestSuite) TestWeightedOperations() { + weightedOps := simulation.WeightedOperations(s.MakeTestSimState(), *s.app.RateLimitingKeeper, s.app.AccountKeeper, s.app.BankKeeper, ) @@ -68,7 +79,7 @@ func (s *SimTestSuite) TestWeightedOperations() { opMsgRoute string opMsgName string }{ - {simappparams.DefaultWeightGovUpdateParams, sdk.MsgTypeURL(&ibcratelimit.MsgGovUpdateParamsRequest{}), sdk.MsgTypeURL(&ibcratelimit.MsgGovUpdateParamsRequest{})}, + {simappparams.DefaultWeightGovUpdateParams, ibcratelimit.ModuleName, sdk.MsgTypeURL(&ibcratelimit.MsgGovUpdateParamsRequest{})}, } expNames := make([]string, len(expected)) @@ -103,7 +114,7 @@ func (s *SimTestSuite) TestSimulateMsgGovUpdateParams() { accounts := s.getTestingAccounts(r, 3) // execute operation - op := simulation.SimulateMsgGovUpdateParams(*s.app.RateLimitingKeeper, s.app.AccountKeeper, s.app.BankKeeper) + op := simulation.SimulateMsgGovUpdateParams(s.MakeTestSimState(), *s.app.RateLimitingKeeper, s.app.AccountKeeper, s.app.BankKeeper) operationMsg, futureOperations, err := op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err, "SimulateMsgGovUpdateParams op(...) error") s.LogOperationMsg(operationMsg, "good") @@ -113,7 +124,7 @@ func (s *SimTestSuite) TestSimulateMsgGovUpdateParams() { s.Assert().True(operationMsg.OK, "operationMsg.OK") s.Assert().Equal(sdk.MsgTypeURL(&msg), operationMsg.Name, "operationMsg.Name") - s.Assert().Equal(types.RouterKey, operationMsg.Route, "operationMsg.Route") + s.Assert().Equal(ibcratelimit.ModuleName, operationMsg.Route, "operationMsg.Route") s.Assert().Len(futureOperations, 0, "futureOperations") } diff --git a/x/marker/module.go b/x/marker/module.go index e36cd4be88..33978d7c43 100644 --- a/x/marker/module.go +++ b/x/marker/module.go @@ -194,7 +194,7 @@ func (am AppModule) RegisterStoreDecoder(_ simtypes.StoreDecoderRegistry) { // WeightedOperations returns the all the marker module operations with their respective weights. func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { return simulation.WeightedOperations( - simState.AppParams, simState.Cdc, codec.NewProtoCodec(am.registry), + simState, codec.NewProtoCodec(am.registry), am.keeper, am.accountKeeper, am.bankKeeper, am.govKeeper, am.attrKeeper, ) } diff --git a/x/marker/simulation/operations.go b/x/marker/simulation/operations.go index 4a2f66af39..c507087e35 100644 --- a/x/marker/simulation/operations.go +++ b/x/marker/simulation/operations.go @@ -14,6 +14,7 @@ import ( codectypes "github.com/cosmos/cosmos-sdk/codec/types" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" @@ -47,12 +48,11 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simtypes.AppParams, cdc codec.JSONCodec, protoCodec *codec.ProtoCodec, + simState module.SimulationState, protoCodec *codec.ProtoCodec, k keeper.Keeper, ak authkeeper.AccountKeeper, bk bankkeeper.Keeper, gk govkeeper.Keeper, attrk types.AttrKeeper, ) simulation.WeightedOperations { args := &WeightedOpsArgs{ - AppParams: appParams, - JSONCodec: cdc, + SimState: simState, ProtoCodec: protoCodec, AK: ak, BK: bk, @@ -61,91 +61,43 @@ func WeightedOperations( } var ( - weightMsgAddMarker int - weightMsgChangeStatus int - weightMsgAddAccess int - weightMsgAddFinalizeActivateMarker int - weightMsgAddMarkerProposal int - weightMsgSetAccountData int - weightMsgUpdateSendDenyList int + wMsgAddMarker int + wMsgChangeStatus int + wMsgAddAccess int + wMsgAFAM int + wMsgAddMarkerProposal int + wMsgSetAccountData int + wMsgUpdateSendDenyList int ) - appParams.GetOrGenerate(OpWeightMsgAddMarker, &weightMsgAddMarker, nil, - func(_ *rand.Rand) { - weightMsgAddMarker = simappparams.DefaultWeightMsgAddMarker - }, - ) - - appParams.GetOrGenerate(OpWeightMsgChangeStatus, &weightMsgChangeStatus, nil, - func(_ *rand.Rand) { - weightMsgChangeStatus = simappparams.DefaultWeightMsgChangeStatus - }, - ) - - appParams.GetOrGenerate(OpWeightMsgAddAccess, &weightMsgAddAccess, nil, - func(_ *rand.Rand) { - weightMsgAddAccess = simappparams.DefaultWeightMsgAddAccess - }, - ) - - appParams.GetOrGenerate(OpWeightMsgAddActivateFinalizeMarker, &weightMsgAddFinalizeActivateMarker, nil, - func(_ *rand.Rand) { - weightMsgAddFinalizeActivateMarker = simappparams.DefaultWeightMsgAddFinalizeActivateMarker - }, - ) - - appParams.GetOrGenerate(OpWeightMsgAddMarkerProposal, &weightMsgAddMarkerProposal, nil, - func(_ *rand.Rand) { - weightMsgAddMarkerProposal = simappparams.DefaultWeightMsgAddMarkerProposal - }, - ) - - appParams.GetOrGenerate(OpWeightMsgSetAccountData, &weightMsgSetAccountData, nil, - func(_ *rand.Rand) { - weightMsgSetAccountData = simappparams.DefaultWeightMsgSetAccountData - }, - ) - - appParams.GetOrGenerate(OpWeightMsgUpdateSendDenyList, &weightMsgUpdateSendDenyList, nil, - func(_ *rand.Rand) { - weightMsgUpdateSendDenyList = simappparams.DefaultWeightMsgUpdateDenySendList - }, - ) + simState.AppParams.GetOrGenerate(OpWeightMsgAddMarker, &wMsgAddMarker, nil, + func(_ *rand.Rand) { wMsgAddMarker = simappparams.DefaultWeightMsgAddMarker }) + simState.AppParams.GetOrGenerate(OpWeightMsgChangeStatus, &wMsgChangeStatus, nil, + func(_ *rand.Rand) { wMsgChangeStatus = simappparams.DefaultWeightMsgChangeStatus }) + simState.AppParams.GetOrGenerate(OpWeightMsgAddAccess, &wMsgAddAccess, nil, + func(_ *rand.Rand) { wMsgAddAccess = simappparams.DefaultWeightMsgAddAccess }) + simState.AppParams.GetOrGenerate(OpWeightMsgAddActivateFinalizeMarker, &wMsgAFAM, nil, + func(_ *rand.Rand) { wMsgAFAM = simappparams.DefaultWeightMsgAddFinalizeActivateMarker }) + simState.AppParams.GetOrGenerate(OpWeightMsgAddMarkerProposal, &wMsgAddMarkerProposal, nil, + func(_ *rand.Rand) { wMsgAddMarkerProposal = simappparams.DefaultWeightMsgAddMarkerProposal }) + simState.AppParams.GetOrGenerate(OpWeightMsgSetAccountData, &wMsgSetAccountData, nil, + func(_ *rand.Rand) { wMsgSetAccountData = simappparams.DefaultWeightMsgSetAccountData }) + simState.AppParams.GetOrGenerate(OpWeightMsgUpdateSendDenyList, &wMsgUpdateSendDenyList, nil, + func(_ *rand.Rand) { wMsgUpdateSendDenyList = simappparams.DefaultWeightMsgUpdateDenySendList }) return simulation.WeightedOperations{ - simulation.NewWeightedOperation( - weightMsgAddMarker, - SimulateMsgAddMarker(k, ak, bk), - ), - simulation.NewWeightedOperation( - weightMsgChangeStatus, - SimulateMsgChangeStatus(k, ak, bk), - ), - simulation.NewWeightedOperation( - weightMsgAddAccess, - SimulateMsgAddAccess(k, ak, bk), - ), - simulation.NewWeightedOperation( - weightMsgAddFinalizeActivateMarker, - SimulateMsgAddFinalizeActivateMarker(k, ak, bk), - ), - simulation.NewWeightedOperation( - weightMsgAddMarkerProposal, - SimulateMsgAddMarkerProposal(k, args), - ), - simulation.NewWeightedOperation( - weightMsgSetAccountData, - SimulateMsgSetAccountData(k, args), - ), - simulation.NewWeightedOperation( - weightMsgUpdateSendDenyList, - SimulateMsgUpdateSendDenyList(k, args), - ), + simulation.NewWeightedOperation(wMsgAddMarker, SimulateMsgAddMarker(k, args)), + simulation.NewWeightedOperation(wMsgChangeStatus, SimulateMsgChangeStatus(k, args)), + simulation.NewWeightedOperation(wMsgAddAccess, SimulateMsgAddAccess(k, args)), + simulation.NewWeightedOperation(wMsgAFAM, SimulateMsgAddFinalizeActivateMarker(k, args)), + simulation.NewWeightedOperation(wMsgAddMarkerProposal, SimulateMsgAddMarkerProposal(k, args)), + simulation.NewWeightedOperation(wMsgSetAccountData, SimulateMsgSetAccountData(k, args)), + simulation.NewWeightedOperation(wMsgUpdateSendDenyList, SimulateMsgUpdateSendDenyList(k, args)), } } // SimulateMsgAddMarker will Add a random marker with random configuration. -func SimulateMsgAddMarker(k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper) simtypes.Operation { +func SimulateMsgAddMarker(k keeper.Keeper, args *WeightedOpsArgs) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -166,12 +118,12 @@ func SimulateMsgAddMarker(k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bank 0, ) - return Dispatch(r, app, ctx, ak, bk, simAccount, chainID, msg, nil) + return Dispatch(r, app, ctx, args.SimState, args.AK, args.BK, simAccount, chainID, msg, nil) } } // SimulateMsgChangeStatus will randomly change the status of the marker depending on it's current state. -func SimulateMsgChangeStatus(k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper) simtypes.Operation { +func SimulateMsgChangeStatus(k keeper.Keeper, args *WeightedOpsArgs) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -201,46 +153,46 @@ func SimulateMsgChangeStatus(k keeper.Keeper, ak authkeeper.AccountKeeperI, bk b case types.StatusActive: simAccount, found = randomAccWithAccess(r, m, accs, types.Access_Delete) if !found { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgCancelRequest{}), sdk.MsgTypeURL(&types.MsgCancelRequest{}), "no account has cancel access"), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgCancelRequest{}), "no account has cancel access"), nil, nil } msg = types.NewMsgCancelRequest(m.GetDenom(), simAccount.Address) case types.StatusCancelled: simAccount, found = randomAccWithAccess(r, m, accs, types.Access_Delete) if !found { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgDeleteRequest{}), sdk.MsgTypeURL(&types.MsgDeleteRequest{}), "no account has delete access"), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgDeleteRequest{}), "no account has delete access"), nil, nil } msg = types.NewMsgDeleteRequest(m.GetDenom(), simAccount.Address) case types.StatusDestroyed: return simtypes.NoOpMsg(types.ModuleName, "ChangeStatus", "marker status is destroyed"), nil, nil default: - return simtypes.NoOpMsg("marker", "", "unknown marker status"), nil, fmt.Errorf("unknown marker status: %#v", m) + return simtypes.NoOpMsg(types.ModuleName, "", "unknown marker status"), nil, fmt.Errorf("unknown marker status: %#v", m) } - return Dispatch(r, app, ctx, ak, bk, simAccount, chainID, msg, nil) + return Dispatch(r, app, ctx, args.SimState, args.AK, args.BK, simAccount, chainID, msg, nil) } } // SimulateMsgAddAccess will Add a random access to an account. -func SimulateMsgAddAccess(k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper) simtypes.Operation { +func SimulateMsgAddAccess(k keeper.Keeper, args *WeightedOpsArgs) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { simAccount, _ := simtypes.RandomAcc(r, accs) m := randomMarker(r, ctx, k) if m == nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgAddAccessRequest{}), sdk.MsgTypeURL(&types.MsgAddAccessRequest{}), "unable to get marker for access change"), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgAddAccessRequest{}), "unable to get marker for access change"), nil, nil } if !m.GetManager().Equals(sdk.AccAddress{}) { simAccount, _ = simtypes.FindAccount(accs, m.GetManager()) } grants := randomAccessGrants(r, accs, 100, m.GetMarkerType()) msg := types.NewMsgAddAccessRequest(m.GetDenom(), simAccount.Address, grants[0]) - return Dispatch(r, app, ctx, ak, bk, simAccount, chainID, msg, nil) + return Dispatch(r, app, ctx, args.SimState, args.AK, args.BK, simAccount, chainID, msg, nil) } } // SimulateMsgAddFinalizeActivateMarker will bind a NAME under an existing name using a 40% probability of restricting it. -func SimulateMsgAddFinalizeActivateMarker(k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper) simtypes.Operation { +func SimulateMsgAddFinalizeActivateMarker(k keeper.Keeper, args *WeightedOpsArgs) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -269,7 +221,7 @@ func SimulateMsgAddFinalizeActivateMarker(k keeper.Keeper, ak authkeeper.Account msg.AllowForcedTransfer = false } - return Dispatch(r, app, ctx, ak, bk, simAccount, chainID, msg, nil) + return Dispatch(r, app, ctx, args.SimState, args.AK, args.BK, simAccount, chainID, msg, nil) } } @@ -362,7 +314,7 @@ func SimulateMsgSetAccountData(k keeper.Keeper, args *WeightedOpsArgs) simtypes. marker, signer := randomMarkerWithAccessSigner(r, ctx, k, accs, types.Access_Deposit) if marker == nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), "unable to find marker with a deposit signer"), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "unable to find marker with a deposit signer"), nil, nil } msg.Denom = marker.GetDenom() @@ -379,7 +331,7 @@ func SimulateMsgSetAccountData(k keeper.Keeper, args *WeightedOpsArgs) simtypes. msg.Value = simtypes.RandStringOfLength(r, strLen) } - return Dispatch(r, app, ctx, args.AK, args.BK, signer, chainID, msg, nil) + return Dispatch(r, app, ctx, args.SimState, args.AK, args.BK, signer, chainID, msg, nil) } } @@ -392,7 +344,7 @@ func SimulateMsgUpdateSendDenyList(k keeper.Keeper, args *WeightedOpsArgs) simty marker, signer := randomMarkerWithAccessSigner(r, ctx, k, accs, types.Access_Transfer) if marker == nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), "unable to find marker with a transfer signer"), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "unable to find marker with a transfer signer"), nil, nil } rDenyAccounts := simtypes.RandomAccounts(r, 10) @@ -405,7 +357,7 @@ func SimulateMsgUpdateSendDenyList(k keeper.Keeper, args *WeightedOpsArgs) simty msg.AddDeniedAddresses = addDenyAddresses msg.Authority = signer.Address.String() - return Dispatch(r, app, ctx, args.AK, args.BK, signer, chainID, msg, nil) + return Dispatch(r, app, ctx, args.SimState, args.AK, args.BK, signer, chainID, msg, nil) } } @@ -415,6 +367,7 @@ func Dispatch( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, + simState module.SimulationState, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, from simtypes.Account, @@ -431,7 +384,7 @@ func Dispatch( fees, err := simtypes.RandomFees(r, ctx, spendable) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), "unable to generate fees"), nil, err + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "unable to generate fees"), nil, err } // fund account with nhash for additional fees, if the account exists (100m stake) if sdk.MsgTypeURL(msg) == "/provenance.marker.v1.MsgAddMarkerRequest" && ak.GetAccount(ctx, account.GetAddress()) != nil { @@ -440,7 +393,7 @@ func Dispatch( Amount: sdkmath.NewInt(100_000_000_000_000), })) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), "unable to fund account with additional fee"), nil, err + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "unable to fund account with additional fee"), nil, err } fees = fees.Add(sdk.Coin{ Denom: "stake", @@ -448,10 +401,9 @@ func Dispatch( }) } - txGen := simappparams.MakeTestEncodingConfig().TxConfig tx, err := simtestutil.GenSignedMockTx( r, - txGen, + simState.TxConfig, []sdk.Msg{msg}, fees, simtestutil.DefaultGenTxGas, @@ -461,12 +413,12 @@ func Dispatch( from.PrivKey, ) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), "unable to generate mock tx"), nil, err + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "unable to generate mock tx"), nil, err } - _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) + _, _, err = app.SimDeliver(simState.TxConfig.TxEncoder(), tx) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), err.Error()), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), err.Error()), nil, nil } return simtypes.NewOperationMsg(msg, true, ""), futures, nil @@ -585,10 +537,9 @@ func randomInt63(r *rand.Rand, max int64) (result int64) { // WeightedOpsArgs holds all the args provided to WeightedOperations so that they can be passed on later more easily. type WeightedOpsArgs struct { - AppParams simtypes.AppParams - JSONCodec codec.JSONCodec + SimState module.SimulationState ProtoCodec *codec.ProtoCodec - AK authkeeper.AccountKeeper + AK authkeeper.AccountKeeperI BK bankkeeper.Keeper GK govkeeper.Keeper AttrK types.AttrKeeper @@ -640,7 +591,7 @@ func SendGovMsg(args *SendGovMsgArgs) (bool, simtypes.OperationMsg, error) { txCtx := simulation.OperationInput{ R: args.R, App: args.App, - TxGen: simappparams.MakeTestEncodingConfig().TxConfig, + TxGen: args.SimState.TxConfig, Cdc: args.ProtoCodec, Msg: govMsg, CoinsSpentInMsg: govMsg.InitialDeposit, @@ -670,7 +621,7 @@ func OperationMsgVote(args *WeightedOpsArgs, voter simtypes.Account, govPropID u txCtx := simulation.OperationInput{ R: r, App: app, - TxGen: simappparams.MakeTestEncodingConfig().TxConfig, + TxGen: args.SimState.TxConfig, Cdc: args.ProtoCodec, Msg: msg, CoinsSpentInMsg: sdk.Coins{}, diff --git a/x/marker/simulation/operations_test.go b/x/marker/simulation/operations_test.go index 89ef1a4e58..e57fb12088 100644 --- a/x/marker/simulation/operations_test.go +++ b/x/marker/simulation/operations_test.go @@ -10,9 +10,9 @@ import ( "github.com/stretchr/testify/suite" sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/bank/testutil" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types/v1" @@ -31,6 +31,10 @@ type SimTestSuite struct { app *app.App } +func TestSimTestSuite(t *testing.T) { + suite.Run(t, new(SimTestSuite)) +} + func (s *SimTestSuite) SetupTest() { s.app = app.Setup(s.T()) s.ctx = s.app.BaseApp.NewContext(false) @@ -54,11 +58,17 @@ func (s *SimTestSuite) LogOperationMsg(operationMsg simtypes.OperationMsg) { ) } -func (s *SimTestSuite) TestWeightedOperations() { - cdc := s.app.AppCodec() - appParams := make(simtypes.AppParams) +// MakeTestSimState creates a new module.SimulationState struct with the fields needed by the functions being tested. +func (s *SimTestSuite) MakeTestSimState() module.SimulationState { + return module.SimulationState{ + AppParams: make(simtypes.AppParams), + Cdc: s.app.AppCodec(), + TxConfig: s.app.GetTxConfig(), + } +} - weightedOps := simulation.WeightedOperations(appParams, cdc, codec.NewProtoCodec(s.app.InterfaceRegistry()), s.app.MarkerKeeper, +func (s *SimTestSuite) TestWeightedOperations() { + weightedOps := simulation.WeightedOperations(s.MakeTestSimState(), codec.NewProtoCodec(s.app.InterfaceRegistry()), s.app.MarkerKeeper, s.app.AccountKeeper, s.app.BankKeeper, s.app.GovKeeper, s.app.AttributeKeeper, ) @@ -132,7 +142,7 @@ func (s *SimTestSuite) TestSimulateMsgAddMarker() { accounts := s.getTestingAccounts(r, 3) // execute operation - op := simulation.SimulateMsgAddMarker(s.app.MarkerKeeper, s.app.AccountKeeper, s.app.BankKeeper) + op := simulation.SimulateMsgAddMarker(s.app.MarkerKeeper, s.getWeightedOpsArgs()) operationMsg, futureOperations, err := op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err) @@ -154,7 +164,7 @@ func (s *SimTestSuite) TestSimulateMsgAddActivateFinalizeMarker() { accounts := s.getTestingAccounts(r, 3) // execute operation - op := simulation.SimulateMsgAddFinalizeActivateMarker(s.app.MarkerKeeper, s.app.AccountKeeper, s.app.BankKeeper) + op := simulation.SimulateMsgAddFinalizeActivateMarker(s.app.MarkerKeeper, s.getWeightedOpsArgs()) operationMsg, futureOperations, err := op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err) @@ -308,7 +318,7 @@ func (s *SimTestSuite) TestSimulateMsgAddMarkerProposal() { s.Run(tc.name, func() { args := &simulation.SendGovMsgArgs{ - WeightedOpsArgs: s.getWeightedOpsArgs(), + WeightedOpsArgs: *s.getWeightedOpsArgs(), R: rand.New(rand.NewSource(1)), App: s.app.BaseApp, Ctx: s.ctx, @@ -378,9 +388,8 @@ func (s *SimTestSuite) TestSimulateMsgSetAccountData() { _, err := markerMsgServer.AddFinalizeActivateMarker(s.ctx, newMarker) s.Require().NoError(err, "AddFinalizeActivateMarker") - args := s.getWeightedOpsArgs() // execute operation - op := simulation.SimulateMsgSetAccountData(s.app.MarkerKeeper, &args) + op := simulation.SimulateMsgSetAccountData(s.app.MarkerKeeper, s.getWeightedOpsArgs()) operationMsg, futureOperations, err := op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err, "SimulateMsgSetAccountData op(...) error") s.LogOperationMsg(operationMsg) @@ -427,9 +436,8 @@ func (s *SimTestSuite) TestSimulateMsgUpdateSendDenyList() { _, err := markerMsgServer.AddFinalizeActivateMarker(s.ctx, newMarker) s.Require().NoError(err, "AddFinalizeActivateMarker") - args := s.getWeightedOpsArgs() // execute operation - op := simulation.SimulateMsgUpdateSendDenyList(s.app.MarkerKeeper, &args) + op := simulation.SimulateMsgUpdateSendDenyList(s.app.MarkerKeeper, s.getWeightedOpsArgs()) operationMsg, futureOperations, err := op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err, "SimulateMsgUpdateSendDenyList op(...) error") s.LogOperationMsg(operationMsg) @@ -463,15 +471,10 @@ func (s *SimTestSuite) getTestingAccounts(r *rand.Rand, n int) []simtypes.Accoun return accounts } -func TestSimTestSuite(t *testing.T) { - suite.Run(t, new(SimTestSuite)) -} - // getWeightedOpsArgs creates a standard WeightedOpsArgs. -func (s *SimTestSuite) getWeightedOpsArgs() simulation.WeightedOpsArgs { - return simulation.WeightedOpsArgs{ - AppParams: make(simtypes.AppParams), - JSONCodec: s.app.AppCodec(), +func (s *SimTestSuite) getWeightedOpsArgs() *simulation.WeightedOpsArgs { + return &simulation.WeightedOpsArgs{ + SimState: s.MakeTestSimState(), ProtoCodec: codec.NewProtoCodec(s.app.InterfaceRegistry()), AK: s.app.AccountKeeper, BK: s.app.BankKeeper, diff --git a/x/name/module.go b/x/name/module.go index ea37c1656b..05e556519d 100644 --- a/x/name/module.go +++ b/x/name/module.go @@ -6,10 +6,11 @@ import ( "fmt" "math/rand" - "cosmossdk.io/core/appmodule" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" + "cosmossdk.io/core/appmodule" + abci "github.com/cometbft/cometbft/abci/types" sdkclient "github.com/cosmos/cosmos-sdk/client" @@ -169,9 +170,7 @@ func (am AppModule) RegisterStoreDecoder(sdr simtypes.StoreDecoderRegistry) { // WeightedOperations returns the all the gov module operations with their respective weights. func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { - return simulation.WeightedOperations( - simState.AppParams, simState.Cdc, am.keeper, am.ak, am.bk, - ) + return simulation.WeightedOperations(simState, am.keeper, am.ak, am.bk) } // ConsensusVersion implements AppModule/ConsensusVersion. diff --git a/x/name/simulation/operations.go b/x/name/simulation/operations.go index 1f1fb5c2fe..fd39039d60 100644 --- a/x/name/simulation/operations.go +++ b/x/name/simulation/operations.go @@ -4,19 +4,18 @@ import ( "math/rand" "strings" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" "github.com/cosmos/cosmos-sdk/x/simulation" simappparams "github.com/provenance-io/provenance/app/params" - keeper "github.com/provenance-io/provenance/x/name/keeper" - types "github.com/provenance-io/provenance/x/name/types" + "github.com/provenance-io/provenance/x/name/keeper" + "github.com/provenance-io/provenance/x/name/types" ) // Simulation operation weights constants @@ -31,60 +30,40 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simtypes.AppParams, cdc codec.JSONCodec, k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper, + simState module.SimulationState, k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper, ) simulation.WeightedOperations { var ( - weightMsgBindName int - weightMsgDeleteName int - weightMsgModifyName int - ) - - appParams.GetOrGenerate(OpWeightMsgBindName, &weightMsgBindName, nil, - func(_ *rand.Rand) { - weightMsgBindName = simappparams.DefaultWeightMsgBindName - }, - ) - - appParams.GetOrGenerate(OpWeightMsgDeleteName, &weightMsgDeleteName, nil, - func(_ *rand.Rand) { - weightMsgDeleteName = simappparams.DefaultWeightMsgDeleteName - }, + wMsgBindName int + wMsgDeleteName int + wMsgModifyName int ) - appParams.GetOrGenerate(OpWeightMsgModifyName, &weightMsgModifyName, nil, - func(_ *rand.Rand) { - weightMsgModifyName = simappparams.DefaultWeightMsgModifyName - }, - ) + simState.AppParams.GetOrGenerate(OpWeightMsgBindName, &wMsgBindName, nil, + func(_ *rand.Rand) { wMsgBindName = simappparams.DefaultWeightMsgBindName }) + simState.AppParams.GetOrGenerate(OpWeightMsgDeleteName, &wMsgDeleteName, nil, + func(_ *rand.Rand) { wMsgDeleteName = simappparams.DefaultWeightMsgDeleteName }) + simState.AppParams.GetOrGenerate(OpWeightMsgModifyName, &wMsgModifyName, nil, + func(_ *rand.Rand) { wMsgModifyName = simappparams.DefaultWeightMsgModifyName }) return simulation.WeightedOperations{ - simulation.NewWeightedOperation( - weightMsgBindName, - SimulateMsgBindName(k, ak, bk), - ), - simulation.NewWeightedOperation( - weightMsgDeleteName, - SimulateMsgDeleteName(k, ak, bk), - ), - simulation.NewWeightedOperation( - weightMsgModifyName, - SimulateMsgModifyName(k, ak, bk), - ), + simulation.NewWeightedOperation(wMsgBindName, SimulateMsgBindName(simState, k, ak, bk)), + simulation.NewWeightedOperation(wMsgDeleteName, SimulateMsgDeleteName(simState, k, ak, bk)), + simulation.NewWeightedOperation(wMsgModifyName, SimulateMsgModifyName(simState, k, ak, bk)), } } // SimulateMsgBindName will bind a NAME under an existing name using a 40% probability of restricting it. -func SimulateMsgBindName(k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper) simtypes.Operation { +func SimulateMsgBindName(simState module.SimulationState, k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { params := k.GetParams(ctx) parentRecord, parentOwner, found, err := getRandomRecord(r, ctx, k, accs, 1, int(params.MaxNameLevels)-1) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgBindNameRequest{}), sdk.MsgTypeURL(&types.MsgBindNameRequest{}), "iterator of existing records failed"), nil, err + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgBindNameRequest{}), "iterator of existing records failed"), nil, err } if !found { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgBindNameRequest{}), sdk.MsgTypeURL(&types.MsgBindNameRequest{}), "no name records available to create under"), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgBindNameRequest{}), "no name records available to create under"), nil, nil } nameLen := randIntBetween(r, int(params.GetMinSegmentLength()), int(params.GetMaxSegmentLength())) @@ -97,12 +76,12 @@ func SimulateMsgBindName(k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankk newRecord := types.NewNameRecord(newRecordName, newRecordOwner.Address, newRecordRestricted) msg := types.NewMsgBindNameRequest(newRecord, parentRecord) - return Dispatch(r, app, ctx, ak, bk, parentOwner, chainID, msg) + return Dispatch(r, app, ctx, simState, ak, bk, parentOwner, chainID, msg) } } // SimulateMsgDeleteName will dispatch a delete name operation against a random name record -func SimulateMsgDeleteName(k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper) simtypes.Operation { +func SimulateMsgDeleteName(simState module.SimulationState, k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { @@ -111,37 +90,37 @@ func SimulateMsgDeleteName(k keeper.Keeper, ak authkeeper.AccountKeeperI, bk ban // Not doing a min/max params lookup because they can change during the sim and don't apply to this operation. randomRecord, simAccount, found, err := getRandomRecord(r, ctx, k, accs, 2, 1_000_000) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgDeleteNameRequest{}), sdk.MsgTypeURL(&types.MsgDeleteNameRequest{}), "iterator of existing records failed"), nil, err + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgDeleteNameRequest{}), "iterator of existing records failed"), nil, err } if !found { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgDeleteNameRequest{}), sdk.MsgTypeURL(&types.MsgDeleteNameRequest{}), "no name records available to delete"), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgDeleteNameRequest{}), "no name records available to delete"), nil, nil } msg := types.NewMsgDeleteNameRequest(randomRecord) - return Dispatch(r, app, ctx, ak, bk, simAccount, chainID, msg) + return Dispatch(r, app, ctx, simState, ak, bk, simAccount, chainID, msg) } } // SimulateMsgModifyName will dispatch a modify name operation against a random name record -func SimulateMsgModifyName(k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper) simtypes.Operation { +func SimulateMsgModifyName(simState module.SimulationState, k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { params := k.GetParams(ctx) randomRecord, simAccount, found, err := getRandomRecord(r, ctx, k, accs, 1, int(params.MaxNameLevels)) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgModifyNameRequest{}), sdk.MsgTypeURL(&types.MsgModifyNameRequest{}), "iterator of existing records failed"), nil, err + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgModifyNameRequest{}), "iterator of existing records failed"), nil, err } if !found { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgModifyNameRequest{}), sdk.MsgTypeURL(&types.MsgModifyNameRequest{}), "no name records available to modify"), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgModifyNameRequest{}), "no name records available to modify"), nil, nil } newOwner, _ := simtypes.RandomAcc(r, accs) restrict := r.Intn(9) < 4 msg := types.NewMsgModifyNameRequest(simAccount.Address.String(), randomRecord.Name, newOwner.Address, restrict) - return Dispatch(r, app, ctx, ak, bk, simAccount, chainID, msg) + return Dispatch(r, app, ctx, simState, ak, bk, simAccount, chainID, msg) } } @@ -151,6 +130,7 @@ func Dispatch( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, + simState module.SimulationState, ak authkeeper.AccountKeeperI, bk bankkeeper.ViewKeeper, from simtypes.Account, @@ -166,13 +146,12 @@ func Dispatch( fees, err := simtypes.RandomFees(r, ctx, spendable) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), "unable to generate fees"), nil, err + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "unable to generate fees"), nil, err } - txGen := simappparams.MakeTestEncodingConfig().TxConfig tx, err := simtestutil.GenSignedMockTx( r, - txGen, + simState.TxConfig, []sdk.Msg{msg}, fees, simtestutil.DefaultGenTxGas, @@ -182,12 +161,12 @@ func Dispatch( from.PrivKey, ) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), "unable to generate mock tx"), nil, err + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "unable to generate mock tx"), nil, err } - _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) + _, _, err = app.SimDeliver(simState.TxConfig.TxEncoder(), tx) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), err.Error()), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), err.Error()), nil, nil } return simtypes.NewOperationMsg(msg, true, ""), nil, nil diff --git a/x/name/simulation/operations_test.go b/x/name/simulation/operations_test.go index 2e97795fce..a189f1d3c4 100644 --- a/x/name/simulation/operations_test.go +++ b/x/name/simulation/operations_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/suite" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/bank/testutil" @@ -25,6 +26,10 @@ type SimTestSuite struct { app *app.App } +func TestSimTestSuite(t *testing.T) { + suite.Run(t, new(SimTestSuite)) +} + func (s *SimTestSuite) SetupTest() { s.app = app.Setup(s.T()) s.ctx = s.app.BaseApp.NewContext(false) @@ -56,11 +61,17 @@ func (s *SimTestSuite) LogIfError(err error, format string, args ...interface{}) } } -func (s *SimTestSuite) TestWeightedOperations() { - cdc := s.app.AppCodec() - appParams := make(simtypes.AppParams) +// MakeTestSimState creates a new module.SimulationState struct with the fields needed by the functions being tested. +func (s *SimTestSuite) MakeTestSimState() module.SimulationState { + return module.SimulationState{ + AppParams: make(simtypes.AppParams), + Cdc: s.app.AppCodec(), + TxConfig: s.app.GetTxConfig(), + } +} - weightedOps := simulation.WeightedOperations(appParams, cdc, s.app.NameKeeper, +func (s *SimTestSuite) TestWeightedOperations() { + weightedOps := simulation.WeightedOperations(s.MakeTestSimState(), s.app.NameKeeper, s.app.AccountKeeper, s.app.BankKeeper, ) @@ -117,7 +128,7 @@ func (s *SimTestSuite) TestSimulateMsgBindName() { s.LogIfError(s.app.NameKeeper.SetNameRecord(s.ctx, name, accounts[0].Address, false), "SetNameRecord(%q)", name) // execute operation - op := simulation.SimulateMsgBindName(s.app.NameKeeper, s.app.AccountKeeper, s.app.BankKeeper) + op := simulation.SimulateMsgBindName(s.MakeTestSimState(), s.app.NameKeeper, s.app.AccountKeeper, s.app.BankKeeper) operationMsg, futureOperations, err := op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err, "SimulateMsgBindName op(...) error") s.LogOperationMsg(operationMsg) @@ -148,7 +159,7 @@ func (s *SimTestSuite) TestSimulateMsgDeleteName() { s.LogIfError(s.app.NameKeeper.SetNameRecord(s.ctx, name, accounts[0].Address, false), "SetNameRecord(%q)", name) // execute operation - op := simulation.SimulateMsgDeleteName(s.app.NameKeeper, s.app.AccountKeeper, s.app.BankKeeper) + op := simulation.SimulateMsgDeleteName(s.MakeTestSimState(), s.app.NameKeeper, s.app.AccountKeeper, s.app.BankKeeper) operationMsg, futureOperations, err := op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err, "SimulateMsgDeleteName op(...) error") s.LogOperationMsg(operationMsg) @@ -177,7 +188,7 @@ func (s *SimTestSuite) TestSimulateMsgModifyName() { s.LogIfError(s.app.NameKeeper.SetNameRecord(s.ctx, name, accounts[0].Address, false), "SetNameRecord(%q)", name) // execute operation - op := simulation.SimulateMsgModifyName(s.app.NameKeeper, s.app.AccountKeeper, s.app.BankKeeper) + op := simulation.SimulateMsgModifyName(s.MakeTestSimState(), s.app.NameKeeper, s.app.AccountKeeper, s.app.BankKeeper) operationMsg, futureOperations, err := op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err, "SimulateMsgModifyName op(...) error") s.LogOperationMsg(operationMsg) @@ -209,7 +220,3 @@ func (s *SimTestSuite) getTestingAccounts(r *rand.Rand, n int) []simtypes.Accoun return accounts } - -func TestSimTestSuite(t *testing.T) { - suite.Run(t, new(SimTestSuite)) -} diff --git a/x/oracle/module/module.go b/x/oracle/module/module.go index 5b7b3e9543..007fe3b387 100644 --- a/x/oracle/module/module.go +++ b/x/oracle/module/module.go @@ -143,9 +143,7 @@ func (am AppModule) RegisterStoreDecoder(sdr simtypes.StoreDecoderRegistry) { // WeightedOperations returns simulation operations (i.e msgs) with their respective weight func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { - return simulation.WeightedOperations( - simState.AppParams, simState.Cdc, am.keeper, am.accountKeeper, am.bankKeeper, am.channelKeeper, - ) + return simulation.WeightedOperations(simState, am.keeper, am.accountKeeper, am.bankKeeper, am.channelKeeper) } // Name returns the oracle module's name. diff --git a/x/oracle/simulation/operations.go b/x/oracle/simulation/operations.go index c3d4f49405..abc357fa2b 100644 --- a/x/oracle/simulation/operations.go +++ b/x/oracle/simulation/operations.go @@ -4,13 +4,12 @@ import ( "fmt" "math/rand" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdkmath "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" @@ -34,44 +33,32 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simtypes.AppParams, cdc codec.JSONCodec, k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, ck channelkeeper.Keeper, + simState module.SimulationState, k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, ck channelkeeper.Keeper, ) simulation.WeightedOperations { var ( - weightMsgUpdateOracle int - weightMsgSendOracleQuery int + wMsgUpdateOracle int + wMsgSendOracleQuery int ) - appParams.GetOrGenerate(OpWeightMsgUpdateOracle, &weightMsgUpdateOracle, nil, - func(_ *rand.Rand) { - weightMsgUpdateOracle = simappparams.DefaultWeightUpdateOracle - }, - ) - appParams.GetOrGenerate(OpWeightMsgSendOracleQuery, &weightMsgSendOracleQuery, nil, - func(_ *rand.Rand) { - weightMsgSendOracleQuery = simappparams.DefaultWeightSendOracleQuery - }, - ) + simState.AppParams.GetOrGenerate(OpWeightMsgUpdateOracle, &wMsgUpdateOracle, nil, + func(_ *rand.Rand) { wMsgUpdateOracle = simappparams.DefaultWeightUpdateOracle }) + simState.AppParams.GetOrGenerate(OpWeightMsgSendOracleQuery, &wMsgSendOracleQuery, nil, + func(_ *rand.Rand) { wMsgSendOracleQuery = simappparams.DefaultWeightSendOracleQuery }) return simulation.WeightedOperations{ - simulation.NewWeightedOperation( - weightMsgUpdateOracle, - SimulateMsgUpdateOracle(k, ak, bk), - ), - simulation.NewWeightedOperation( - weightMsgSendOracleQuery, - SimulateMsgSendQueryOracle(k, ak, bk, ck), - ), + simulation.NewWeightedOperation(wMsgUpdateOracle, SimulateMsgUpdateOracle(simState, k, ak, bk)), + simulation.NewWeightedOperation(wMsgSendOracleQuery, SimulateMsgSendQueryOracle(simState, k, ak, bk, ck)), } } // SimulateMsgUpdateOracle sends a MsgUpdateOracle. -func SimulateMsgUpdateOracle(_ keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper) simtypes.Operation { +func SimulateMsgUpdateOracle(simState module.SimulationState, _ keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { raccs, err := RandomAccs(r, accs, uint64(len(accs))) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgUpdateOracleRequest{}), sdk.MsgTypeURL(&types.MsgUpdateOracleRequest{}), err.Error()), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgUpdateOracleRequest{}), err.Error()), nil, nil } // 50% chance to be from the module's authority @@ -80,30 +67,30 @@ func SimulateMsgUpdateOracle(_ keeper.Keeper, ak authkeeper.AccountKeeperI, bk b msg := types.NewMsgUpdateOracle(from.Address.String(), to.Address.String()) - return Dispatch(r, app, ctx, from, chainID, msg, ak, bk, nil) + return Dispatch(r, app, ctx, simState, from, chainID, msg, ak, bk, nil) } } // SimulateMsgSendQueryOracle sends a MsgSendQueryOracle. -func SimulateMsgSendQueryOracle(_ keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, ck channelkeeper.Keeper) simtypes.Operation { +func SimulateMsgSendQueryOracle(simState module.SimulationState, _ keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, ck channelkeeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { raccs, err := RandomAccs(r, accs, 1) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgSendQueryOracleRequest{}), sdk.MsgTypeURL(&types.MsgSendQueryOracleRequest{}), err.Error()), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgSendQueryOracleRequest{}), err.Error()), nil, nil } addr := raccs[0] channel, err := randomChannel(r, ctx, ck) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgSendQueryOracleRequest{}), sdk.MsgTypeURL(&types.MsgSendQueryOracleRequest{}), err.Error()), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgSendQueryOracleRequest{}), err.Error()), nil, nil } query := randomQuery(r) msg := types.NewMsgSendQueryOracle(addr.Address.String(), channel, query) - return Dispatch(r, app, ctx, addr, chainID, msg, ak, bk, nil) + return Dispatch(r, app, ctx, simState, addr, chainID, msg, ak, bk, nil) } } @@ -113,6 +100,7 @@ func Dispatch( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, + simState module.SimulationState, from simtypes.Account, chainID string, msg sdk.Msg, @@ -129,19 +117,19 @@ func Dispatch( fees, err := simtypes.RandomFees(r, ctx, spendable) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), "unable to generate fees"), nil, err + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "unable to generate fees"), nil, err } err = testutil.FundAccount(ctx, bk, account.GetAddress(), sdk.NewCoins(sdk.Coin{ Denom: pioconfig.GetProvenanceConfig().BondDenom, Amount: sdkmath.NewInt(1_000_000_000_000_000), })) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), "unable to fund account"), nil, err + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "unable to fund account"), nil, err } - txGen := simappparams.MakeTestEncodingConfig().TxConfig + tx, err := simtestutil.GenSignedMockTx( r, - txGen, + simState.TxConfig, []sdk.Msg{msg}, fees, simtestutil.DefaultGenTxGas, @@ -151,12 +139,12 @@ func Dispatch( from.PrivKey, ) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), "unable to generate mock tx"), nil, err + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "unable to generate mock tx"), nil, err } - _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) + _, _, err = app.SimDeliver(simState.TxConfig.TxEncoder(), tx) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), err.Error()), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), err.Error()), nil, nil } return simtypes.NewOperationMsg(msg, true, ""), futures, nil diff --git a/x/oracle/simulation/operations_test.go b/x/oracle/simulation/operations_test.go index f8ee1f7173..1d8874b2a2 100644 --- a/x/oracle/simulation/operations_test.go +++ b/x/oracle/simulation/operations_test.go @@ -5,10 +5,12 @@ import ( "fmt" "math/rand" "strings" + "testing" "github.com/stretchr/testify/suite" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/bank/testutil" @@ -25,6 +27,10 @@ type SimTestSuite struct { app *app.App } +func TestSimTestSuite(t *testing.T) { + suite.Run(t, new(SimTestSuite)) +} + func (s *SimTestSuite) SetupTest() { s.app = app.Setup(s.T()) s.ctx = s.app.BaseApp.NewContext(false) @@ -49,11 +55,17 @@ func (s *SimTestSuite) LogOperationMsg(operationMsg simtypes.OperationMsg, msg s ) } -func (s *SimTestSuite) TestWeightedOperations() { - cdc := s.app.AppCodec() - appParams := make(simtypes.AppParams) +// MakeTestSimState creates a new module.SimulationState struct with the fields needed by the functions being tested. +func (s *SimTestSuite) MakeTestSimState() module.SimulationState { + return module.SimulationState{ + AppParams: make(simtypes.AppParams), + Cdc: s.app.AppCodec(), + TxConfig: s.app.GetTxConfig(), + } +} - weightedOps := simulation.WeightedOperations(appParams, cdc, s.app.OracleKeeper, +func (s *SimTestSuite) TestWeightedOperations() { + weightedOps := simulation.WeightedOperations(s.MakeTestSimState(), s.app.OracleKeeper, s.app.AccountKeeper, s.app.BankKeeper, s.app.IBCKeeper.ChannelKeeper, ) @@ -103,7 +115,7 @@ func (s *SimTestSuite) TestSimulateMsgUpdateOracle() { accounts := s.getTestingAccounts(r, 3) // execute operation - op := simulation.SimulateMsgUpdateOracle(s.app.OracleKeeper, s.app.AccountKeeper, s.app.BankKeeper) + op := simulation.SimulateMsgUpdateOracle(s.MakeTestSimState(), s.app.OracleKeeper, s.app.AccountKeeper, s.app.BankKeeper) operationMsg, futureOperations, err := op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err, "SimulateMsgUpdateOracle op(...) error") s.LogOperationMsg(operationMsg, "good") @@ -124,7 +136,7 @@ func (s *SimTestSuite) TestSimulateMsgSendQueryOracle() { accounts := s.getTestingAccounts(r, 3) // execute operation - op := simulation.SimulateMsgSendQueryOracle(s.app.OracleKeeper, s.app.AccountKeeper, s.app.BankKeeper, s.app.IBCKeeper.ChannelKeeper) + op := simulation.SimulateMsgSendQueryOracle(s.MakeTestSimState(), s.app.OracleKeeper, s.app.AccountKeeper, s.app.BankKeeper, s.app.IBCKeeper.ChannelKeeper) operationMsg, futureOperations, err := op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err, "SimulateMsgSendQueryOracle op(...) error") s.LogOperationMsg(operationMsg, "good") diff --git a/x/quarantine/module/module.go b/x/quarantine/module/module.go index d1a1f73304..cc0bac33b8 100644 --- a/x/quarantine/module/module.go +++ b/x/quarantine/module/module.go @@ -12,6 +12,7 @@ import ( abci "github.com/cometbft/cometbft/abci/types" "cosmossdk.io/core/appmodule" + sdkclient "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -164,8 +165,5 @@ func (am AppModule) RegisterStoreDecoder(sdr simtypes.StoreDecoderRegistry) { // WeightedOperations returns the all the quarantine module operations with their respective weights. func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { - return simulation.WeightedOperations( - simState.AppParams, simState.Cdc, - am.accKeeper, am.bankKeeper, am.keeper, am.cdc, - ) + return simulation.WeightedOperations(simState, am.accKeeper, am.bankKeeper, am.keeper) } diff --git a/x/quarantine/simulation/operations.go b/x/quarantine/simulation/operations.go index 4ee023aee6..30b953ec39 100644 --- a/x/quarantine/simulation/operations.go +++ b/x/quarantine/simulation/operations.go @@ -5,15 +5,13 @@ import ( "math/rand" "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" - cdctypes "github.com/cosmos/cosmos-sdk/codec/types" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" - simappparams "github.com/provenance-io/provenance/app/params" "github.com/provenance-io/provenance/x/quarantine" "github.com/provenance-io/provenance/x/quarantine/keeper" ) @@ -47,39 +45,38 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simtypes.AppParams, _ codec.JSONCodec, - ak quarantine.AccountKeeper, bk quarantine.BankKeeper, k keeper.Keeper, _ cdctypes.AnyUnpacker, + simState module.SimulationState, ak quarantine.AccountKeeper, bk quarantine.BankKeeper, k keeper.Keeper, ) simulation.WeightedOperations { var ( - weightMsgOptIn int - weightMsgOptOut int - weightMsgAccept int - weightMsgDecline int - weightMsgUpdateAutoResponses int + wMsgOptIn int + wMsgOptOut int + wMsgAccept int + wMsgDecline int + wMsgUpdateAutoResponses int ) - appParams.GetOrGenerate(OpMsgOptIn, &weightMsgOptIn, nil, - func(_ *rand.Rand) { weightMsgOptIn = WeightMsgOptIn }) - appParams.GetOrGenerate(OpMsgOptOut, &weightMsgOptOut, nil, - func(_ *rand.Rand) { weightMsgOptOut = WeightMsgOptOut }) - appParams.GetOrGenerate(OpMsgAccept, &weightMsgAccept, nil, - func(_ *rand.Rand) { weightMsgAccept = WeightMsgAccept }) - appParams.GetOrGenerate(OpMsgDecline, &weightMsgDecline, nil, - func(_ *rand.Rand) { weightMsgDecline = WeightMsgDecline }) - appParams.GetOrGenerate(OpMsgUpdateAutoResponses, &weightMsgUpdateAutoResponses, nil, - func(_ *rand.Rand) { weightMsgUpdateAutoResponses = WeightMsgUpdateAutoResponses }) + simState.AppParams.GetOrGenerate(OpMsgOptIn, &wMsgOptIn, nil, + func(_ *rand.Rand) { wMsgOptIn = WeightMsgOptIn }) + simState.AppParams.GetOrGenerate(OpMsgOptOut, &wMsgOptOut, nil, + func(_ *rand.Rand) { wMsgOptOut = WeightMsgOptOut }) + simState.AppParams.GetOrGenerate(OpMsgAccept, &wMsgAccept, nil, + func(_ *rand.Rand) { wMsgAccept = WeightMsgAccept }) + simState.AppParams.GetOrGenerate(OpMsgDecline, &wMsgDecline, nil, + func(_ *rand.Rand) { wMsgDecline = WeightMsgDecline }) + simState.AppParams.GetOrGenerate(OpMsgUpdateAutoResponses, &wMsgUpdateAutoResponses, nil, + func(_ *rand.Rand) { wMsgUpdateAutoResponses = WeightMsgUpdateAutoResponses }) return simulation.WeightedOperations{ - simulation.NewWeightedOperation(weightMsgOptIn, SimulateMsgOptIn(ak, bk)), - simulation.NewWeightedOperation(weightMsgOptOut, SimulateMsgOptOut(ak, bk, k)), - simulation.NewWeightedOperation(weightMsgAccept, SimulateMsgAccept(ak, bk, k)), - simulation.NewWeightedOperation(weightMsgDecline, SimulateMsgDecline(ak, bk, k)), - simulation.NewWeightedOperation(weightMsgUpdateAutoResponses, SimulateMsgUpdateAutoResponses(ak, bk, k)), + simulation.NewWeightedOperation(wMsgOptIn, SimulateMsgOptIn(simState, ak, bk)), + simulation.NewWeightedOperation(wMsgOptOut, SimulateMsgOptOut(simState, ak, bk, k)), + simulation.NewWeightedOperation(wMsgAccept, SimulateMsgAccept(simState, ak, bk, k)), + simulation.NewWeightedOperation(wMsgDecline, SimulateMsgDecline(simState, ak, bk, k)), + simulation.NewWeightedOperation(wMsgUpdateAutoResponses, SimulateMsgUpdateAutoResponses(simState, ak, bk, k)), } } // SimulateMsgOptIn opts an account into quarantine. -func SimulateMsgOptIn(ak quarantine.AccountKeeper, bk quarantine.BankKeeper) simtypes.Operation { +func SimulateMsgOptIn(simState module.SimulationState, ak quarantine.AccountKeeper, bk quarantine.BankKeeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, @@ -98,10 +95,9 @@ func SimulateMsgOptIn(ak quarantine.AccountKeeper, bk quarantine.BankKeeper) sim account := ak.GetAccount(ctx, acct.Address) - encCfg := simappparams.MakeTestEncodingConfig() tx, err := simtestutil.GenSignedMockTx( r, - encCfg.TxConfig, + simState.TxConfig, []sdk.Msg{msg}, fees, simtestutil.DefaultGenTxGas, @@ -114,7 +110,7 @@ func SimulateMsgOptIn(ak quarantine.AccountKeeper, bk quarantine.BankKeeper) sim return simtypes.NoOpMsg(quarantine.ModuleName, msgType, "unable to generate mock tx"), nil, err } - _, _, err = app.SimDeliver(encCfg.TxConfig.TxEncoder(), tx) + _, _, err = app.SimDeliver(simState.TxConfig.TxEncoder(), tx) if err != nil { return simtypes.NoOpMsg(quarantine.ModuleName, msgType, "unable to deliver tx"), nil, err } @@ -124,7 +120,7 @@ func SimulateMsgOptIn(ak quarantine.AccountKeeper, bk quarantine.BankKeeper) sim } // SimulateMsgOptOut opts an account out of quarantine. -func SimulateMsgOptOut(ak quarantine.AccountKeeper, bk quarantine.BankKeeper, k keeper.Keeper) simtypes.Operation { +func SimulateMsgOptOut(simState module.SimulationState, ak quarantine.AccountKeeper, bk quarantine.BankKeeper, k keeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, @@ -161,10 +157,9 @@ func SimulateMsgOptOut(ak quarantine.AccountKeeper, bk quarantine.BankKeeper, k account := ak.GetAccount(ctx, acct.Address) - encCfg := simappparams.MakeTestEncodingConfig() tx, err := simtestutil.GenSignedMockTx( r, - encCfg.TxConfig, + simState.TxConfig, []sdk.Msg{msg}, fees, simtestutil.DefaultGenTxGas, @@ -177,7 +172,7 @@ func SimulateMsgOptOut(ak quarantine.AccountKeeper, bk quarantine.BankKeeper, k return simtypes.NoOpMsg(quarantine.ModuleName, msgType, "unable to generate mock tx"), nil, err } - _, _, err = app.SimDeliver(encCfg.TxConfig.TxEncoder(), tx) + _, _, err = app.SimDeliver(simState.TxConfig.TxEncoder(), tx) if err != nil { return simtypes.NoOpMsg(quarantine.ModuleName, msgType, "unable to deliver tx"), nil, err } @@ -187,7 +182,7 @@ func SimulateMsgOptOut(ak quarantine.AccountKeeper, bk quarantine.BankKeeper, k } // SimulateMsgAccept accepts quarantined funds. -func SimulateMsgAccept(ak quarantine.AccountKeeper, bk quarantine.BankKeeper, k keeper.Keeper) simtypes.Operation { +func SimulateMsgAccept(simState module.SimulationState, ak quarantine.AccountKeeper, bk quarantine.BankKeeper, k keeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, @@ -234,10 +229,9 @@ func SimulateMsgAccept(ak quarantine.AccountKeeper, bk quarantine.BankKeeper, k account := ak.GetAccount(ctx, acct.Address) - encCfg := simappparams.MakeTestEncodingConfig() tx, err := simtestutil.GenSignedMockTx( r, - encCfg.TxConfig, + simState.TxConfig, []sdk.Msg{msg}, fees, simtestutil.DefaultGenTxGas, @@ -250,7 +244,7 @@ func SimulateMsgAccept(ak quarantine.AccountKeeper, bk quarantine.BankKeeper, k return simtypes.NoOpMsg(quarantine.ModuleName, msgType, "unable to generate mock tx"), nil, err } - _, _, err = app.SimDeliver(encCfg.TxConfig.TxEncoder(), tx) + _, _, err = app.SimDeliver(simState.TxConfig.TxEncoder(), tx) if err != nil { return simtypes.NoOpMsg(quarantine.ModuleName, msgType, "unable to deliver tx"), nil, err } @@ -260,7 +254,7 @@ func SimulateMsgAccept(ak quarantine.AccountKeeper, bk quarantine.BankKeeper, k } // SimulateMsgDecline declines quarantined funds. -func SimulateMsgDecline(ak quarantine.AccountKeeper, bk quarantine.BankKeeper, k keeper.Keeper) simtypes.Operation { +func SimulateMsgDecline(simState module.SimulationState, ak quarantine.AccountKeeper, bk quarantine.BankKeeper, k keeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, @@ -307,10 +301,9 @@ func SimulateMsgDecline(ak quarantine.AccountKeeper, bk quarantine.BankKeeper, k account := ak.GetAccount(ctx, acct.Address) - encCfg := simappparams.MakeTestEncodingConfig() tx, err := simtestutil.GenSignedMockTx( r, - encCfg.TxConfig, + simState.TxConfig, []sdk.Msg{msg}, fees, simtestutil.DefaultGenTxGas, @@ -323,7 +316,7 @@ func SimulateMsgDecline(ak quarantine.AccountKeeper, bk quarantine.BankKeeper, k return simtypes.NoOpMsg(quarantine.ModuleName, msgType, "unable to generate mock tx"), nil, err } - _, _, err = app.SimDeliver(encCfg.TxConfig.TxEncoder(), tx) + _, _, err = app.SimDeliver(simState.TxConfig.TxEncoder(), tx) if err != nil { return simtypes.NoOpMsg(quarantine.ModuleName, msgType, "unable to deliver tx"), nil, err } @@ -333,7 +326,7 @@ func SimulateMsgDecline(ak quarantine.AccountKeeper, bk quarantine.BankKeeper, k } // SimulateMsgUpdateAutoResponses updates an accounts auto-responses -func SimulateMsgUpdateAutoResponses(ak quarantine.AccountKeeper, bk quarantine.BankKeeper, k keeper.Keeper) simtypes.Operation { +func SimulateMsgUpdateAutoResponses(simState module.SimulationState, ak quarantine.AccountKeeper, bk quarantine.BankKeeper, k keeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, @@ -391,10 +384,9 @@ func SimulateMsgUpdateAutoResponses(ak quarantine.AccountKeeper, bk quarantine.B account := ak.GetAccount(ctx, acct.Address) - encCfg := simappparams.MakeTestEncodingConfig() tx, err := simtestutil.GenSignedMockTx( r, - encCfg.TxConfig, + simState.TxConfig, []sdk.Msg{msg}, fees, simtestutil.DefaultGenTxGas, @@ -407,7 +399,7 @@ func SimulateMsgUpdateAutoResponses(ak quarantine.AccountKeeper, bk quarantine.B return simtypes.NoOpMsg(quarantine.ModuleName, msgType, "unable to generate mock tx"), nil, err } - _, _, err = app.SimDeliver(encCfg.TxConfig.TxEncoder(), tx) + _, _, err = app.SimDeliver(simState.TxConfig.TxEncoder(), tx) if err != nil { return simtypes.NoOpMsg(quarantine.ModuleName, msgType, "unable to deliver tx"), nil, err } diff --git a/x/quarantine/simulation/operations_test.go b/x/quarantine/simulation/operations_test.go index 10a0ab46e6..963a1c1a26 100644 --- a/x/quarantine/simulation/operations_test.go +++ b/x/quarantine/simulation/operations_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/suite" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/bank/testutil" @@ -48,10 +49,16 @@ func (s *SimTestSuite) SetupTest() { s.ctx = s.app.BaseApp.NewContext(false) } -func (s *SimTestSuite) TestWeightedOperations() { - cdc := s.app.AppCodec() - appParams := make(simtypes.AppParams) +// MakeTestSimState creates a new module.SimulationState struct with the fields needed by the functions being tested. +func (s *SimTestSuite) MakeTestSimState() module.SimulationState { + return module.SimulationState{ + AppParams: make(simtypes.AppParams), + Cdc: s.app.AppCodec(), + TxConfig: s.app.GetTxConfig(), + } +} +func (s *SimTestSuite) TestWeightedOperations() { expected := []struct { weight int opsMsgRoute string @@ -64,10 +71,7 @@ func (s *SimTestSuite) TestWeightedOperations() { {simulation.WeightMsgUpdateAutoResponses, quarantine.ModuleName, simulation.TypeMsgUpdateAutoResponses}, } - weightedOps := simulation.WeightedOperations( - appParams, cdc, - s.app.AccountKeeper, s.app.BankKeeper, s.app.QuarantineKeeper, cdc, - ) + weightedOps := simulation.WeightedOperations(s.MakeTestSimState(), s.app.AccountKeeper, s.app.BankKeeper, s.app.QuarantineKeeper) s.Require().Len(weightedOps, len(expected), "weighted ops") @@ -92,7 +96,7 @@ func (s *SimTestSuite) TestSimulateMsgOptIn() { r := rand.New(rand.NewSource(1)) accounts := s.getTestingAccounts(r, 10) - op := simulation.SimulateMsgOptIn(s.app.AccountKeeper, s.app.BankKeeper) + op := simulation.SimulateMsgOptIn(s.MakeTestSimState(), s.app.AccountKeeper, s.app.BankKeeper) opMsg, futureOps, err := op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err, "running SimulateMsgOptIn op") @@ -113,7 +117,7 @@ func (s *SimTestSuite) TestSimulateMsgOptOut() { err := s.app.QuarantineKeeper.SetOptIn(s.ctx, accounts[0].Address) s.Require().NoError(err, "SetOptIn on accounts[0]") - op := simulation.SimulateMsgOptOut(s.app.AccountKeeper, s.app.BankKeeper, s.app.QuarantineKeeper) + op := simulation.SimulateMsgOptOut(s.MakeTestSimState(), s.app.AccountKeeper, s.app.BankKeeper, s.app.QuarantineKeeper) opMsg, futureOps, err := op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err, "running SimulateMsgOptIn op") @@ -139,7 +143,7 @@ func (s *SimTestSuite) TestSimulateMsgAccept() { err = s.app.BankKeeper.SendCoins(s.ctx, accounts[1].Address, accounts[0].Address, toSend) s.Require().NoError(err, "SendCoins") - op := simulation.SimulateMsgAccept(s.app.AccountKeeper, s.app.BankKeeper, s.app.QuarantineKeeper) + op := simulation.SimulateMsgAccept(s.MakeTestSimState(), s.app.AccountKeeper, s.app.BankKeeper, s.app.QuarantineKeeper) opMsg, futureOps, err := op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err, "running SimulateMsgOptIn op") @@ -165,7 +169,7 @@ func (s *SimTestSuite) TestSimulateMsgDecline() { err = s.app.BankKeeper.SendCoins(s.ctx, accounts[1].Address, accounts[0].Address, toSend) s.Require().NoError(err, "SendCoins") - op := simulation.SimulateMsgDecline(s.app.AccountKeeper, s.app.BankKeeper, s.app.QuarantineKeeper) + op := simulation.SimulateMsgDecline(s.MakeTestSimState(), s.app.AccountKeeper, s.app.BankKeeper, s.app.QuarantineKeeper) opMsg, futureOps, err := op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err, "running SimulateMsgOptIn op") @@ -186,7 +190,7 @@ func (s *SimTestSuite) TestSimulateMsgUpdateAutoResponses() { err := s.app.QuarantineKeeper.SetOptIn(s.ctx, accounts[0].Address) s.Require().NoError(err, "SetOptIn on accounts[0]") - op := simulation.SimulateMsgUpdateAutoResponses(s.app.AccountKeeper, s.app.BankKeeper, s.app.QuarantineKeeper) + op := simulation.SimulateMsgUpdateAutoResponses(s.MakeTestSimState(), s.app.AccountKeeper, s.app.BankKeeper, s.app.QuarantineKeeper) opMsg, futureOps, err := op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err, "running SimulateMsgOptIn op") diff --git a/x/sanction/module/module.go b/x/sanction/module/module.go index d071ca0df0..060c1b2df7 100644 --- a/x/sanction/module/module.go +++ b/x/sanction/module/module.go @@ -167,7 +167,7 @@ func (am AppModule) RegisterStoreDecoder(sdr simtypes.StoreDecoderRegistry) { // WeightedOperations returns the all the sanction module operations with their respective weights. func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { return simulation.WeightedOperations( - simState.AppParams, simState.Cdc, codec.NewProtoCodec(am.registry), + simState, codec.NewProtoCodec(am.registry), am.accKeeper, am.bankKeeper, am.govKeeper, am.keeper, ) } diff --git a/x/sanction/simulation/operations.go b/x/sanction/simulation/operations.go index 5cee3b49b2..fac142c5da 100644 --- a/x/sanction/simulation/operations.go +++ b/x/sanction/simulation/operations.go @@ -8,12 +8,12 @@ import ( "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" "github.com/cosmos/cosmos-sdk/x/simulation" - simappparams "github.com/provenance-io/provenance/app/params" "github.com/provenance-io/provenance/x/sanction" "github.com/provenance-io/provenance/x/sanction/keeper" ) @@ -34,8 +34,7 @@ const ( // WeightedOpsArgs holds all the args provided to WeightedOperations so that they can be passed on later more easily. type WeightedOpsArgs struct { - AppParams simtypes.AppParams - JSONCodec codec.JSONCodec + SimState module.SimulationState ProtoCodec *codec.ProtoCodec AK sanction.AccountKeeper BK sanction.BankKeeper @@ -60,12 +59,11 @@ type SendGovMsgArgs struct { } func WeightedOperations( - appParams simtypes.AppParams, jsonCodec codec.JSONCodec, protoCodec *codec.ProtoCodec, + simState module.SimulationState, protoCodec *codec.ProtoCodec, ak sanction.AccountKeeper, bk sanction.BankKeeper, gk govkeeper.Keeper, sk keeper.Keeper, ) simulation.WeightedOperations { args := &WeightedOpsArgs{ - AppParams: appParams, - JSONCodec: jsonCodec, + SimState: simState, ProtoCodec: protoCodec, AK: ak, BK: bk, @@ -74,30 +72,30 @@ func WeightedOperations( } var ( - weightSanction int - weightSanctionImmediate int - weightUnsanction int - weightUnsanctionImmediate int - weightUpdateParams int + wSanction int + wSanctionImmediate int + wUnsanction int + wUnsanctionImmediate int + wUpdateParams int ) - appParams.GetOrGenerate(OpWeightSanction, &weightSanction, nil, - func(_ *rand.Rand) { weightSanction = DefaultWeightSanction }) - appParams.GetOrGenerate(OpWeightSanctionImmediate, &weightSanctionImmediate, nil, - func(_ *rand.Rand) { weightSanctionImmediate = DefaultWeightSanctionImmediate }) - appParams.GetOrGenerate(OpWeightUnsanction, &weightUnsanction, nil, - func(_ *rand.Rand) { weightUnsanction = DefaultWeightUnsanction }) - appParams.GetOrGenerate(OpWeightUnsanctionImmediate, &weightUnsanctionImmediate, nil, - func(_ *rand.Rand) { weightUnsanctionImmediate = DefaultWeightUnsanctionImmediate }) - appParams.GetOrGenerate(OpWeightUpdateParams, &weightUpdateParams, nil, - func(_ *rand.Rand) { weightUpdateParams = DefaultWeightUpdateParams }) + simState.AppParams.GetOrGenerate(OpWeightSanction, &wSanction, nil, + func(_ *rand.Rand) { wSanction = DefaultWeightSanction }) + simState.AppParams.GetOrGenerate(OpWeightSanctionImmediate, &wSanctionImmediate, nil, + func(_ *rand.Rand) { wSanctionImmediate = DefaultWeightSanctionImmediate }) + simState.AppParams.GetOrGenerate(OpWeightUnsanction, &wUnsanction, nil, + func(_ *rand.Rand) { wUnsanction = DefaultWeightUnsanction }) + simState.AppParams.GetOrGenerate(OpWeightUnsanctionImmediate, &wUnsanctionImmediate, nil, + func(_ *rand.Rand) { wUnsanctionImmediate = DefaultWeightUnsanctionImmediate }) + simState.AppParams.GetOrGenerate(OpWeightUpdateParams, &wUpdateParams, nil, + func(_ *rand.Rand) { wUpdateParams = DefaultWeightUpdateParams }) return simulation.WeightedOperations{ - simulation.NewWeightedOperation(weightSanction, SimulateGovMsgSanction(args)), - simulation.NewWeightedOperation(weightSanctionImmediate, SimulateGovMsgSanctionImmediate(args)), - simulation.NewWeightedOperation(weightUnsanction, SimulateGovMsgUnsanction(args)), - simulation.NewWeightedOperation(weightUnsanctionImmediate, SimulateGovMsgUnsanctionImmediate(args)), - simulation.NewWeightedOperation(weightUpdateParams, SimulateGovMsgUpdateParams(args)), + simulation.NewWeightedOperation(wSanction, SimulateGovMsgSanction(args)), + simulation.NewWeightedOperation(wSanctionImmediate, SimulateGovMsgSanctionImmediate(args)), + simulation.NewWeightedOperation(wUnsanction, SimulateGovMsgUnsanction(args)), + simulation.NewWeightedOperation(wUnsanctionImmediate, SimulateGovMsgUnsanctionImmediate(args)), + simulation.NewWeightedOperation(wUpdateParams, SimulateGovMsgUpdateParams(args)), } } @@ -132,7 +130,7 @@ func SendGovMsg(args *SendGovMsgArgs) (bool, simtypes.OperationMsg, error) { txCtx := simulation.OperationInput{ R: args.R, App: args.App, - TxGen: simappparams.MakeTestEncodingConfig().TxConfig, + TxGen: args.SimState.TxConfig, Cdc: args.ProtoCodec, Msg: govMsg, CoinsSpentInMsg: govMsg.InitialDeposit, @@ -162,7 +160,7 @@ func OperationMsgVote(args *WeightedOpsArgs, voter simtypes.Account, govPropID u txCtx := simulation.OperationInput{ R: r, App: app, - TxGen: simappparams.MakeTestEncodingConfig().TxConfig, + TxGen: args.SimState.TxConfig, Cdc: args.ProtoCodec, Msg: msg, CoinsSpentInMsg: sdk.Coins{}, diff --git a/x/sanction/simulation/operations_test.go b/x/sanction/simulation/operations_test.go index 2f5c78e3c2..7f2194e2d9 100644 --- a/x/sanction/simulation/operations_test.go +++ b/x/sanction/simulation/operations_test.go @@ -15,6 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" bankutil "github.com/cosmos/cosmos-sdk/x/bank/testutil" govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" @@ -227,11 +228,19 @@ func (s *SimTestSuite) requireSanctionAddresses(addrs []sdk.AccAddress) { }) } +// MakeTestSimState creates a new module.SimulationState struct with the fields needed by the functions being tested. +func (s *SimTestSuite) MakeTestSimState() module.SimulationState { + return module.SimulationState{ + AppParams: make(simtypes.AppParams), + Cdc: s.app.AppCodec(), + TxConfig: s.app.GetTxConfig(), + } +} + // getWeightedOpsArgs creates a standard WeightedOpsArgs. func (s *SimTestSuite) getWeightedOpsArgs() simulation.WeightedOpsArgs { return simulation.WeightedOpsArgs{ - AppParams: make(simtypes.AppParams), - JSONCodec: s.app.AppCodec(), + SimState: s.MakeTestSimState(), ProtoCodec: codec.NewProtoCodec(s.app.InterfaceRegistry()), AK: s.app.AccountKeeper, BK: s.app.BankKeeper, @@ -259,7 +268,7 @@ func (s *SimTestSuite) TestWeightedOperations() { } weightedOps := simulation.WeightedOperations( - make(simtypes.AppParams), s.app.AppCodec(), codec.NewProtoCodec(s.app.InterfaceRegistry()), + s.MakeTestSimState(), codec.NewProtoCodec(s.app.InterfaceRegistry()), s.app.AccountKeeper, s.app.BankKeeper, s.app.GovKeeper, s.app.SanctionKeeper, ) diff --git a/x/trigger/module/module.go b/x/trigger/module/module.go index fdd8401471..e56c59ed6e 100644 --- a/x/trigger/module/module.go +++ b/x/trigger/module/module.go @@ -143,9 +143,7 @@ func (am AppModule) RegisterStoreDecoder(sdr simtypes.StoreDecoderRegistry) { // WeightedOperations returns simulation operations (i.e msgs) with their respective weight func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { - return simulation.WeightedOperations( - simState.AppParams, simState.Cdc, am.keeper, am.accountKeeper, am.bankKeeper, - ) + return simulation.WeightedOperations(simState, am.keeper, am.accountKeeper, am.bankKeeper) } // Name returns the trigger module's name. diff --git a/x/trigger/simulation/operations.go b/x/trigger/simulation/operations.go index 33c745a702..eeff1f7591 100644 --- a/x/trigger/simulation/operations.go +++ b/x/trigger/simulation/operations.go @@ -7,9 +7,9 @@ import ( sdkmath "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" @@ -32,66 +32,54 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simtypes.AppParams, cdc codec.JSONCodec, k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, + simState module.SimulationState, k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper, ) simulation.WeightedOperations { var ( - weightMsgCreateTrigger int - weightMsgDestroyTrigger int + wMsgCreateTrigger int + wMsgDestroyTrigger int ) - appParams.GetOrGenerate(OpWeightMsgCreateTrigger, &weightMsgCreateTrigger, nil, - func(_ *rand.Rand) { - weightMsgCreateTrigger = simappparams.DefaultWeightSubmitCreateTrigger - }, - ) - appParams.GetOrGenerate(OpWeightMsgDestroyTrigger, &weightMsgDestroyTrigger, nil, - func(_ *rand.Rand) { - weightMsgDestroyTrigger = simappparams.DefaultWeightSubmitDestroyTrigger - }, - ) + simState.AppParams.GetOrGenerate(OpWeightMsgCreateTrigger, &wMsgCreateTrigger, nil, + func(_ *rand.Rand) { wMsgCreateTrigger = simappparams.DefaultWeightSubmitCreateTrigger }) + simState.AppParams.GetOrGenerate(OpWeightMsgDestroyTrigger, &wMsgDestroyTrigger, nil, + func(_ *rand.Rand) { wMsgDestroyTrigger = simappparams.DefaultWeightSubmitDestroyTrigger }) return simulation.WeightedOperations{ - simulation.NewWeightedOperation( - weightMsgCreateTrigger, - SimulateMsgCreateTrigger(k, ak, bk), - ), - simulation.NewWeightedOperation( - weightMsgDestroyTrigger, - SimulateMsgDestroyTrigger(k, ak, bk), - ), + simulation.NewWeightedOperation(wMsgCreateTrigger, SimulateMsgCreateTrigger(simState, k, ak, bk)), + simulation.NewWeightedOperation(wMsgDestroyTrigger, SimulateMsgDestroyTrigger(simState, k, ak, bk)), } } // SimulateMsgCreateTrigger sends a MsgCreateTriggerRequest. -func SimulateMsgCreateTrigger(_ keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper) simtypes.Operation { +func SimulateMsgCreateTrigger(simState module.SimulationState, _ keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { now := ctx.BlockTime() raccs, err := RandomAccs(r, accs, 2) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgCreateTriggerRequest{}), sdk.MsgTypeURL(&types.MsgCreateTriggerRequest{}), err.Error()), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgCreateTriggerRequest{}), err.Error()), nil, nil } from := raccs[0] to := raccs[1] msg, err := types.NewCreateTriggerRequest([]string{from.Address.String()}, NewRandomEvent(r, now), []sdk.Msg{NewRandomAction(r, from.Address.String(), to.Address.String())}) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), "error creating message"), nil, err + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "error creating message"), nil, err } - return Dispatch(r, app, ctx, from, chainID, msg, ak, bk, nil) + return Dispatch(r, app, ctx, simState, from, chainID, msg, ak, bk, nil) } } // SimulateMsgDestroyTrigger sends a MsgDestroyTriggerRequest. -func SimulateMsgDestroyTrigger(k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper) simtypes.Operation { +func SimulateMsgDestroyTrigger(simState module.SimulationState, k keeper.Keeper, ak authkeeper.AccountKeeperI, bk bankkeeper.Keeper) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { trigger := randomTrigger(r, ctx, k) if trigger == nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgDestroyTriggerRequest{}), sdk.MsgTypeURL(&types.MsgDestroyTriggerRequest{}), "unable to find a valid trigger"), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgDestroyTriggerRequest{}), "unable to find a valid trigger"), nil, nil } addr, err := sdk.AccAddressFromBech32(trigger.Owner) if err != nil { @@ -100,10 +88,10 @@ func SimulateMsgDestroyTrigger(k keeper.Keeper, ak authkeeper.AccountKeeperI, bk } simAccount, found := simtypes.FindAccount(accs, addr) if !found { - return simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgDestroyTriggerRequest{}), sdk.MsgTypeURL(&types.MsgDestroyTriggerRequest{}), "creator of trigger does not exist"), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgDestroyTriggerRequest{}), "creator of trigger does not exist"), nil, nil } msg := types.NewDestroyTriggerRequest(trigger.GetOwner(), trigger.GetId()) - return Dispatch(r, app, ctx, simAccount, chainID, msg, ak, bk, nil) + return Dispatch(r, app, ctx, simState, simAccount, chainID, msg, ak, bk, nil) } } @@ -113,6 +101,7 @@ func Dispatch( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, + simState module.SimulationState, from simtypes.Account, chainID string, msg sdk.Msg, @@ -129,19 +118,19 @@ func Dispatch( fees, err := simtypes.RandomFees(r, ctx, spendable) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), "unable to generate fees"), nil, err + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "unable to generate fees"), nil, err } err = testutil.FundAccount(ctx, bk, account.GetAddress(), sdk.NewCoins(sdk.Coin{ Denom: pioconfig.GetProvenanceConfig().BondDenom, Amount: sdkmath.NewInt(1_000_000_000_000_000), })) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), "unable to fund account"), nil, err + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "unable to fund account"), nil, err } - txGen := simappparams.MakeTestEncodingConfig().TxConfig + tx, err := simtestutil.GenSignedMockTx( r, - txGen, + simState.TxConfig, []sdk.Msg{msg}, fees, simtestutil.DefaultGenTxGas, @@ -151,12 +140,12 @@ func Dispatch( from.PrivKey, ) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), "unable to generate mock tx"), nil, err + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), "unable to generate mock tx"), nil, err } - _, _, err = app.SimDeliver(txGen.TxEncoder(), tx) + _, _, err = app.SimDeliver(simState.TxConfig.TxEncoder(), tx) if err != nil { - return simtypes.NoOpMsg(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), err.Error()), nil, nil + return simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(msg), err.Error()), nil, nil } return simtypes.NewOperationMsg(msg, true, ""), futures, nil diff --git a/x/trigger/simulation/operations_test.go b/x/trigger/simulation/operations_test.go index b01f90bc81..0c678dc376 100644 --- a/x/trigger/simulation/operations_test.go +++ b/x/trigger/simulation/operations_test.go @@ -11,6 +11,7 @@ import ( codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" sdktx "github.com/cosmos/cosmos-sdk/types/tx" "github.com/cosmos/cosmos-sdk/x/bank/testutil" @@ -28,6 +29,10 @@ type SimTestSuite struct { app *app.App } +func TestSimTestSuite(t *testing.T) { + suite.Run(t, new(SimTestSuite)) +} + func (s *SimTestSuite) SetupTest() { s.app = app.Setup(s.T()) s.ctx = s.app.BaseApp.NewContext(false) @@ -52,11 +57,17 @@ func (s *SimTestSuite) LogOperationMsg(operationMsg simtypes.OperationMsg, msg s ) } -func (s *SimTestSuite) TestWeightedOperations() { - cdc := s.app.AppCodec() - appParams := make(simtypes.AppParams) +// MakeTestSimState creates a new module.SimulationState struct with the fields needed by the functions being tested. +func (s *SimTestSuite) MakeTestSimState() module.SimulationState { + return module.SimulationState{ + AppParams: make(simtypes.AppParams), + Cdc: s.app.AppCodec(), + TxConfig: s.app.GetTxConfig(), + } +} - weightedOps := simulation.WeightedOperations(appParams, cdc, s.app.TriggerKeeper, +func (s *SimTestSuite) TestWeightedOperations() { + weightedOps := simulation.WeightedOperations(s.MakeTestSimState(), s.app.TriggerKeeper, s.app.AccountKeeper, s.app.BankKeeper, ) @@ -106,8 +117,8 @@ func (s *SimTestSuite) TestSimulateMsgCreateTrigger() { accounts := s.getTestingAccounts(r, 3) // bad operation - op := simulation.SimulateMsgCreateTrigger(s.app.TriggerKeeper, s.app.AccountKeeper, s.app.BankKeeper) - expBadOp := simtypes.NoOpMsg(sdk.MsgTypeURL(&types.MsgCreateTriggerRequest{}), sdk.MsgTypeURL(&types.MsgCreateTriggerRequest{}), "cannot choose 2 accounts because there are only 1") + op := simulation.SimulateMsgCreateTrigger(s.MakeTestSimState(), s.app.TriggerKeeper, s.app.AccountKeeper, s.app.BankKeeper) + expBadOp := simtypes.NoOpMsg(types.ModuleName, sdk.MsgTypeURL(&types.MsgCreateTriggerRequest{}), "cannot choose 2 accounts because there are only 1") operationMsg, futureOperations, err := op(r, s.app.BaseApp, s.ctx, accounts[0:1], "") s.LogOperationMsg(operationMsg, "bad SimulateMsgCreateTrigger") s.Assert().Equal(expBadOp, operationMsg, "bad operationMsg") @@ -115,7 +126,7 @@ func (s *SimTestSuite) TestSimulateMsgCreateTrigger() { s.Assert().NoError(err, "bad SimulateMsgCreateTrigger op(...) error") // execute operation - op = simulation.SimulateMsgCreateTrigger(s.app.TriggerKeeper, s.app.AccountKeeper, s.app.BankKeeper) + op = simulation.SimulateMsgCreateTrigger(s.MakeTestSimState(), s.app.TriggerKeeper, s.app.AccountKeeper, s.app.BankKeeper) operationMsg, futureOperations, err = op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err, "SimulateMsgCreateTrigger op(...) error") s.LogOperationMsg(operationMsg, "good") @@ -143,7 +154,7 @@ func (s *SimTestSuite) TestSimulateMsgDestroyTrigger() { s.app.TriggerKeeper.SetGasLimit(s.ctx, trigger.GetId(), 1000) // execute operation - op := simulation.SimulateMsgDestroyTrigger(s.app.TriggerKeeper, s.app.AccountKeeper, s.app.BankKeeper) + op := simulation.SimulateMsgDestroyTrigger(s.MakeTestSimState(), s.app.TriggerKeeper, s.app.AccountKeeper, s.app.BankKeeper) operationMsg, futureOperations, err := op(r, s.app.BaseApp, s.ctx, accounts, "") s.Require().NoError(err, "SimulateMsgDestroyTrigger op(...) error") s.LogOperationMsg(operationMsg, "good") @@ -217,10 +228,6 @@ func (s *SimTestSuite) TestRandomAccs() { } } -func TestSimTestSuite(t *testing.T) { - suite.Run(t, new(SimTestSuite)) -} - func (s *SimTestSuite) getTestingAccounts(r *rand.Rand, n int) []simtypes.Account { accounts := simtypes.RandomAccounts(r, n)