From 591b1c2cca3582518f62c93cb3bf5009469f56fb Mon Sep 17 00:00:00 2001 From: discoverdefiteam Date: Tue, 26 Sep 2023 16:36:49 -0400 Subject: [PATCH] granularize repo --- app/ante.go | 5 + app/app.go | 1158 +++--------------- app/apptesting/test_suite.go | 28 +- app/export.go | 50 +- app/keepers/keepers.go | 719 +++++++++++ app/keepers/keys.go | 114 ++ app/modules.go | 285 +++++ app/test_helpers.go | 6 +- app/upgrades/types.go | 36 + app/upgrades/v2/constants.go | 29 +- app/upgrades/v2/upgrade.go | 38 +- app/wasm_config.go | 25 + x/feeshare/keeper/keeper_test.go | 8 +- x/feeshare/keeper/msg_server_test.go | 8 +- x/tokenfactory/bindings/custom_msg_test.go | 20 +- x/tokenfactory/bindings/custom_query_test.go | 2 +- x/tokenfactory/bindings/helpers_test.go | 10 +- x/tokenfactory/bindings/validate_msg_test.go | 26 +- x/tokenfactory/keeper/admins_test.go | 18 +- x/tokenfactory/keeper/createdenom_test.go | 8 +- x/tokenfactory/keeper/genesis_test.go | 10 +- x/tokenfactory/keeper/msg_server_test.go | 2 +- 22 files changed, 1516 insertions(+), 1089 deletions(-) create mode 100644 app/keepers/keepers.go create mode 100644 app/keepers/keys.go create mode 100644 app/modules.go create mode 100644 app/wasm_config.go diff --git a/app/ante.go b/app/ante.go index 0432ffc..ff0fda1 100644 --- a/app/ante.go +++ b/app/ante.go @@ -63,6 +63,11 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) { return nil, errorsmod.Wrap(sdkerrors.ErrLogic, "tx counter key is required for ante builder") } + sigGasConsumer := options.SigGasConsumer + if sigGasConsumer == nil { + sigGasConsumer = ante.DefaultSigVerificationGasConsumer + } + anteDecorators := []sdk.AnteDecorator{ ante.NewSetUpContextDecorator(), // outermost AnteDecorator. SetUpContext must be called first wasmkeeper.NewLimitSimulationGasDecorator(options.WasmConfig.SimulationGasLimit), // after setup context to enforce limits early diff --git a/app/app.go b/app/app.go index fe834ff..416c185 100644 --- a/app/app.go +++ b/app/app.go @@ -5,9 +5,10 @@ import ( "fmt" "io" "os" - "path/filepath" "reflect" "strings" + "strconv" + "net/http" autocliv1 "cosmossdk.io/api/cosmos/autocli/v1" reflectionv1 "cosmossdk.io/api/cosmos/reflection/v1" @@ -20,8 +21,8 @@ import ( tmproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" nodeservice "github.com/cosmos/cosmos-sdk/client/grpc/node" + "github.com/prometheus/client_golang/prometheus" "github.com/cosmos/cosmos-sdk/client/grpc/tmservice" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/types" @@ -38,129 +39,43 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/version" - "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth/ante" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" "github.com/cosmos/cosmos-sdk/x/auth/posthandler" - authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation" authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - "github.com/cosmos/cosmos-sdk/x/authz" - authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper" - authzmodule "github.com/cosmos/cosmos-sdk/x/authz/module" - "github.com/cosmos/cosmos-sdk/x/bank" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/capability" - capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - "github.com/cosmos/cosmos-sdk/x/consensus" - consensusparamkeeper "github.com/cosmos/cosmos-sdk/x/consensus/keeper" - consensusparamtypes "github.com/cosmos/cosmos-sdk/x/consensus/types" "github.com/cosmos/cosmos-sdk/x/crisis" - crisiskeeper "github.com/cosmos/cosmos-sdk/x/crisis/keeper" - crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" - distr "github.com/cosmos/cosmos-sdk/x/distribution" - distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - "github.com/cosmos/cosmos-sdk/x/evidence" - evidencekeeper "github.com/cosmos/cosmos-sdk/x/evidence/keeper" - evidencetypes "github.com/cosmos/cosmos-sdk/x/evidence/types" - "github.com/cosmos/cosmos-sdk/x/feegrant" - feegrantkeeper "github.com/cosmos/cosmos-sdk/x/feegrant/keeper" - feegrantmodule "github.com/cosmos/cosmos-sdk/x/feegrant/module" - "github.com/cosmos/cosmos-sdk/x/genutil" - genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" - "github.com/cosmos/cosmos-sdk/x/gov" - govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/cosmos/cosmos-sdk/x/group" - groupkeeper "github.com/cosmos/cosmos-sdk/x/group/keeper" - groupmodule "github.com/cosmos/cosmos-sdk/x/group/module" - "github.com/cosmos/cosmos-sdk/x/mint" - mintkeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - "github.com/cosmos/cosmos-sdk/x/nft" - nftkeeper "github.com/cosmos/cosmos-sdk/x/nft/keeper" - nftmodule "github.com/cosmos/cosmos-sdk/x/nft/module" - "github.com/cosmos/cosmos-sdk/x/params" paramsclient "github.com/cosmos/cosmos-sdk/x/params/client" - paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" + paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" - paramproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - "github.com/cosmos/cosmos-sdk/x/slashing" - slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper" - slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" - "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/cosmos-sdk/x/upgrade" + upgradeclient "github.com/cosmos/cosmos-sdk/x/upgrade/client" - upgradekeeper "github.com/cosmos/cosmos-sdk/x/upgrade/keeper" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - ica "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts" - icacontroller "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller" - icacontrollerkeeper "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller/keeper" - icacontrollertypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller/types" - icahost "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/host" - icahostkeeper "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/host/keeper" - icahosttypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/host/types" - icatypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/types" - ibcfee "github.com/cosmos/ibc-go/v7/modules/apps/29-fee" - ibcfeekeeper "github.com/cosmos/ibc-go/v7/modules/apps/29-fee/keeper" - ibcfeetypes "github.com/cosmos/ibc-go/v7/modules/apps/29-fee/types" - transfer "github.com/cosmos/ibc-go/v7/modules/apps/transfer" - ibctransferkeeper "github.com/cosmos/ibc-go/v7/modules/apps/transfer/keeper" + ibcfeetypes "github.com/cosmos/ibc-go/v7/modules/apps/29-fee/types" ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" - ibc "github.com/cosmos/ibc-go/v7/modules/core" - ibcclient "github.com/cosmos/ibc-go/v7/modules/core/02-client" ibcclientclient "github.com/cosmos/ibc-go/v7/modules/core/02-client/client" ibcclienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" ibcchanneltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - porttypes "github.com/cosmos/ibc-go/v7/modules/core/05-port/types" - ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" - ibckeeper "github.com/cosmos/ibc-go/v7/modules/core/keeper" - ibctm "github.com/cosmos/ibc-go/v7/modules/light-clients/07-tendermint" ibcmock "github.com/cosmos/ibc-go/v7/testing/mock" - "github.com/terpnetwork/terp-core/v2/x/feeshare" - feesharekeeper "github.com/terpnetwork/terp-core/v2/x/feeshare/keeper" - feesharetypes "github.com/terpnetwork/terp-core/v2/x/feeshare/types" - "github.com/terpnetwork/terp-core/v2/x/globalfee" - globalfeekeeper "github.com/terpnetwork/terp-core/v2/x/globalfee/keeper" - globalfeetypes "github.com/terpnetwork/terp-core/v2/x/globalfee/types" - - ibchooks "github.com/cosmos/ibc-apps/modules/ibc-hooks/v7" - ibchookskeeper "github.com/cosmos/ibc-apps/modules/ibc-hooks/v7/keeper" - ibchookstypes "github.com/cosmos/ibc-apps/modules/ibc-hooks/v7/types" - - packetforward "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7/router" - packetforwardkeeper "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7/router/keeper" - packetforwardtypes "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7/router/types" - - icq "github.com/cosmos/ibc-apps/modules/async-icq/v7" - icqkeeper "github.com/cosmos/ibc-apps/modules/async-icq/v7/keeper" - icqtypes "github.com/cosmos/ibc-apps/modules/async-icq/v7/types" - "github.com/terpnetwork/terp-core/v2/x/tokenfactory/bindings" + "github.com/spf13/cast" govclient "github.com/cosmos/cosmos-sdk/x/gov/client" v2 "github.com/terpnetwork/terp-core/v2/app/upgrades/v2" + "github.com/terpnetwork/terp-core/v2/docs" + "github.com/terpnetwork/terp-core/v2/app/openapiconsole" "github.com/CosmWasm/wasmd/x/wasm" wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" - // token factory - "github.com/terpnetwork/terp-core/v2/x/tokenfactory" - tokenfactorykeeper "github.com/terpnetwork/terp-core/v2/x/tokenfactory/keeper" - tokenfactorytypes "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" + "github.com/terpnetwork/terp-core/v2/app/keepers" + "github.com/terpnetwork/terp-core/v2/app/upgrades" + // unnamed import of statik for swagger UI support _ "github.com/cosmos/cosmos-sdk/client/docs/statik" // statik for swagger UI support @@ -183,30 +98,11 @@ var ( // of "EnableAllProposals" (takes precedence over ProposalsEnabled) // https://github.com/terpnetwork/terp-core/blob/02a54d33ff2c064f3539ae12d75d027d9c665f05/x/wasm/internal/types/proposal.go#L28-L34 EnableSpecificProposals = "" -) - -var tokenFactoryCapabilities = []string{ - tokenfactorytypes.EnableBurnFrom, - tokenfactorytypes.EnableForceTransfer, - tokenfactorytypes.EnableSetMetadata, -} -// GetEnabledProposals parses the ProposalsEnabled / EnableSpecificProposals values to -// produce a list of enabled proposals to pass into wasmd app. -func GetEnabledProposals() []wasmtypes.ProposalType { - if EnableSpecificProposals == "" { - if ProposalsEnabled == "true" { - return wasmtypes.EnableAllProposals - } - return wasmtypes.DisableAllProposals - } - chunks := strings.Split(EnableSpecificProposals, ",") - proposals, err := wasmtypes.ConvertToProposals(chunks) - if err != nil { - panic(err) + Upgrades = []upgrades.Upgrade{ + v2.Upgrade, } - return proposals -} +) // These constants are derived from the above variables. // These are the ones we will want to use in the code, based on @@ -260,71 +156,43 @@ func SetAddressPrefixes() { }) } -var ( - // ModuleBasics defines the module BasicManager is in charge of setting up basic, - // non-dependant module elements, such as codec registration - // and genesis verification. - ModuleBasics = module.NewBasicManager( - auth.AppModuleBasic{}, - genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator), - bank.AppModuleBasic{}, - capability.AppModuleBasic{}, - staking.AppModuleBasic{}, - mint.AppModuleBasic{}, - distr.AppModuleBasic{}, - gov.NewAppModuleBasic( - []govclient.ProposalHandler{ - paramsclient.ProposalHandler, - upgradeclient.LegacyProposalHandler, - upgradeclient.LegacyCancelProposalHandler, - ibcclientclient.UpdateClientProposalHandler, - ibcclientclient.UpgradeProposalHandler, - }, - ), - params.AppModuleBasic{}, - crisis.AppModuleBasic{}, - slashing.AppModuleBasic{}, - feegrantmodule.AppModuleBasic{}, - upgrade.AppModuleBasic{}, - evidence.AppModuleBasic{}, - authzmodule.AppModuleBasic{}, - groupmodule.AppModuleBasic{}, - vesting.AppModuleBasic{}, - nftmodule.AppModuleBasic{}, - consensus.AppModuleBasic{}, - // non sdk modules - wasm.AppModuleBasic{}, - ibc.AppModuleBasic{}, - ibctm.AppModuleBasic{}, - transfer.AppModuleBasic{}, - ica.AppModuleBasic{}, - ibcfee.AppModuleBasic{}, - icq.AppModuleBasic{}, - ibchooks.AppModuleBasic{}, - packetforward.AppModuleBasic{}, - feeshare.AppModuleBasic{}, - globalfee.AppModuleBasic{}, - tokenfactory.AppModuleBasic{}, - ) +// GetEnabledProposals parses the ProposalsEnabled / EnableSpecificProposals values to +// produce a list of enabled proposals to pass into wasmd app. +func GetEnabledProposals() []wasmtypes.ProposalType { + if EnableSpecificProposals == "" { + if ProposalsEnabled == "true" { + return wasmtypes.EnableAllProposals + } + return wasmtypes.DisableAllProposals + } + chunks := strings.Split(EnableSpecificProposals, ",") + proposals, err := wasmtypes.ConvertToProposals(chunks) + if err != nil { + panic(err) + } + return proposals +} - // module account permissions - maccPerms = map[string][]string{ - authtypes.FeeCollectorName: nil, - distrtypes.ModuleName: nil, - minttypes.ModuleName: {authtypes.Minter}, - stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, - stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, - govtypes.ModuleName: {authtypes.Burner}, - nft.ModuleName: nil, - ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, - ibcfeetypes.ModuleName: nil, - icqtypes.ModuleName: nil, - icatypes.ModuleName: nil, - globalfee.ModuleName: nil, - wasmtypes.ModuleName: {authtypes.Burner}, - tokenfactorytypes.ModuleName: {authtypes.Minter, authtypes.Burner}, +func GetWasmOpts(appOpts servertypes.AppOptions) []wasmkeeper.Option { + var wasmOpts []wasmkeeper.Option + if cast.ToBool(appOpts.Get("telemetry.enabled")) { + wasmOpts = append(wasmOpts, wasmkeeper.WithVMCacheMetrics(prometheus.DefaultRegisterer)) } -) + + wasmOpts = append(wasmOpts, wasmkeeper.WithGasRegister(NewTerpWasmGasRegister())) + + return wasmOpts +} + +func getGovProposalHandlers() []govclient.ProposalHandler { + return []govclient.ProposalHandler{ + paramsclient.ProposalHandler, + upgradeclient.LegacyProposalHandler, + upgradeclient.LegacyCancelProposalHandler, + ibcclientclient.UpdateClientProposalHandler, + ibcclientclient.UpgradeProposalHandler, + } +} var ( _ runtime.AppI = (*TerpApp)(nil) @@ -344,46 +212,7 @@ type TerpApp struct { tkeys map[string]*storetypes.TransientStoreKey memKeys map[string]*storetypes.MemoryStoreKey - // keepers - AccountKeeper authkeeper.AccountKeeper - AuthzKeeper authzkeeper.Keeper - BankKeeper bankkeeper.BaseKeeper - - CapabilityKeeper *capabilitykeeper.Keeper - StakingKeeper *stakingkeeper.Keeper - SlashingKeeper slashingkeeper.Keeper - MintKeeper mintkeeper.Keeper - DistrKeeper distrkeeper.Keeper - GovKeeper govkeeper.Keeper - CrisisKeeper *crisiskeeper.Keeper - UpgradeKeeper *upgradekeeper.Keeper - ParamsKeeper paramskeeper.Keeper - EvidenceKeeper evidencekeeper.Keeper - FeeGrantKeeper feegrantkeeper.Keeper - GroupKeeper groupkeeper.Keeper - NFTKeeper nftkeeper.Keeper - ConsensusParamsKeeper consensusparamkeeper.Keeper - - IBCKeeper *ibckeeper.Keeper // IBC Keeper must be a pointer in the app, so we can SetRouter on it correctly - IBCFeeKeeper ibcfeekeeper.Keeper - IBCHooksKeeper *ibchookskeeper.Keeper - ICAControllerKeeper icacontrollerkeeper.Keeper - FeeShareKeeper feesharekeeper.Keeper - GlobalFeeKeeper globalfeekeeper.Keeper - TokenFactoryKeeper tokenfactorykeeper.Keeper - ContractKeeper *wasmkeeper.PermissionedKeeper - PacketForwardKeeper *packetforwardkeeper.Keeper - ICQKeeper icqkeeper.Keeper - ICAHostKeeper icahostkeeper.Keeper - TransferKeeper ibctransferkeeper.Keeper - WasmKeeper wasmkeeper.Keeper - - ScopedIBCKeeper capabilitykeeper.ScopedKeeper - ScopedICAHostKeeper capabilitykeeper.ScopedKeeper - ScopedICAControllerKeeper capabilitykeeper.ScopedKeeper - ScopedTransferKeeper capabilitykeeper.ScopedKeeper - ScopedIBCFeeKeeper capabilitykeeper.ScopedKeeper - ScopedWasmKeeper capabilitykeeper.ScopedKeeper + AppKeepers keepers.AppKeepers // the module manager ModuleManager *module.Manager @@ -393,10 +222,6 @@ type TerpApp struct { // module configurator configurator module.Configurator - - // Middleware wrapper - Ics20WasmHooks *ibchooks.WasmHooks - HooksICS4Wrapper ibchooks.ICS4Middleware } // NewTerpApp returns a reference to an initialized TerpApp. @@ -422,636 +247,134 @@ func NewTerpApp( bApp.SetInterfaceRegistry(interfaceRegistry) bApp.SetTxEncoder(txConfig.TxEncoder()) - keys := sdk.NewKVStoreKeys( - authtypes.StoreKey, - banktypes.StoreKey, - stakingtypes.StoreKey, - crisistypes.StoreKey, - minttypes.StoreKey, - distrtypes.StoreKey, - slashingtypes.StoreKey, - govtypes.StoreKey, - paramstypes.StoreKey, - consensusparamtypes.StoreKey, - upgradetypes.StoreKey, - feegrant.StoreKey, - evidencetypes.StoreKey, - capabilitytypes.StoreKey, - authzkeeper.StoreKey, - nftkeeper.StoreKey, - group.StoreKey, - // non sdk store keys - ibcexported.StoreKey, - ibctransfertypes.StoreKey, - ibcfeetypes.StoreKey, - wasmtypes.StoreKey, - icahosttypes.StoreKey, - icacontrollertypes.StoreKey, - icqtypes.StoreKey, - packetforwardtypes.StoreKey, - ibchookstypes.StoreKey, - feesharetypes.StoreKey, - globalfeetypes.StoreKey, - tokenfactorytypes.StoreKey, - ) - - tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey) - memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) - - // load state streaming if enabled - if _, _, err := streaming.LoadStreamingServices(bApp, appOpts, appCodec, logger, keys); err != nil { - logger.Error("failed to load state streaming", "err", err) - os.Exit(1) - } - app := &TerpApp{ BaseApp: bApp, legacyAmino: legacyAmino, appCodec: appCodec, txConfig: txConfig, interfaceRegistry: interfaceRegistry, - keys: keys, - tkeys: tkeys, - memKeys: memKeys, + tkeys: sdk.NewTransientStoreKeys(paramstypes.TStoreKey), + memKeys: sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey), } - app.ParamsKeeper = initParamsKeeper( + // Setup keepers + app.AppKeepers = keepers.NewAppKeepers( appCodec, + bApp, legacyAmino, - keys[paramstypes.StoreKey], - tkeys[paramstypes.TStoreKey], + keepers.GetMaccPerms(), + enabledProposals, + appOpts, + wasmOpts, ) + app.keys = app.AppKeepers.GetKVStoreKey() - govModAddress := authtypes.NewModuleAddress(govtypes.ModuleName).String() - - // set the BaseApp's parameter store - app.ConsensusParamsKeeper = consensusparamkeeper.NewKeeper(appCodec, keys[consensusparamtypes.StoreKey], govModAddress) - bApp.SetParamStore(&app.ConsensusParamsKeeper) - - // add capability keeper and ScopeToModule for ibc module - app.CapabilityKeeper = capabilitykeeper.NewKeeper( - appCodec, - keys[capabilitytypes.StoreKey], - memKeys[capabilitytypes.MemStoreKey], - ) - - scopedIBCKeeper := app.CapabilityKeeper.ScopeToModule(ibcexported.ModuleName) - scopedICAHostKeeper := app.CapabilityKeeper.ScopeToModule(icahosttypes.SubModuleName) - scopedICAControllerKeeper := app.CapabilityKeeper.ScopeToModule(icacontrollertypes.SubModuleName) - scopedTransferKeeper := app.CapabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName) - scopedICQKeeper := app.CapabilityKeeper.ScopeToModule(icqtypes.ModuleName) - scopedWasmKeeper := app.CapabilityKeeper.ScopeToModule(wasmtypes.ModuleName) - app.CapabilityKeeper.Seal() - - // add keepers - app.AccountKeeper = authkeeper.NewAccountKeeper( - appCodec, - keys[authtypes.StoreKey], - authtypes.ProtoBaseAccount, - maccPerms, - Bech32Prefix, - govModAddress, - ) - app.BankKeeper = bankkeeper.NewBaseKeeper( - appCodec, - keys[banktypes.StoreKey], - app.AccountKeeper, - BlockedAddresses(), - govModAddress, - ) - app.StakingKeeper = stakingkeeper.NewKeeper( - appCodec, - keys[stakingtypes.StoreKey], - app.AccountKeeper, - app.BankKeeper, - govModAddress, - ) - app.FeeGrantKeeper = feegrantkeeper.NewKeeper( - appCodec, - keys[feegrant.StoreKey], - app.AccountKeeper, - ) - - app.MintKeeper = mintkeeper.NewKeeper( - appCodec, - keys[minttypes.StoreKey], - app.StakingKeeper, - app.AccountKeeper, - app.BankKeeper, - authtypes.FeeCollectorName, - govModAddress, - ) - app.DistrKeeper = distrkeeper.NewKeeper( - appCodec, - keys[distrtypes.StoreKey], - app.AccountKeeper, - app.BankKeeper, - app.StakingKeeper, - authtypes.FeeCollectorName, - govModAddress, - ) - - app.SlashingKeeper = slashingkeeper.NewKeeper( - appCodec, - legacyAmino, - keys[slashingtypes.StoreKey], - app.StakingKeeper, - govModAddress, - ) - - app.TokenFactoryKeeper = tokenfactorykeeper.NewKeeper( - appCodec, - app.keys[tokenfactorytypes.StoreKey], - app.AccountKeeper, - app.BankKeeper, - app.DistrKeeper, - tokenFactoryCapabilities, - govModAddress, - ) - - // register the staking hooks - // NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks - app.StakingKeeper.SetHooks( - stakingtypes.NewMultiStakingHooks(app.DistrKeeper.Hooks(), app.SlashingKeeper.Hooks()), - ) - - invCheckPeriod := cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)) - app.CrisisKeeper = crisiskeeper.NewKeeper( - appCodec, - keys[crisistypes.StoreKey], - invCheckPeriod, - app.BankKeeper, - authtypes.FeeCollectorName, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - - app.FeeGrantKeeper = feegrantkeeper.NewKeeper(appCodec, keys[feegrant.StoreKey], app.AccountKeeper) - - app.AuthzKeeper = authzkeeper.NewKeeper( - keys[authzkeeper.StoreKey], - appCodec, - app.MsgServiceRouter(), - app.AccountKeeper, - ) - - groupConfig := group.DefaultConfig() - /* - Example of setting group params: - groupConfig.MaxMetadataLen = 1000 - */ - app.GroupKeeper = groupkeeper.NewKeeper(keys[group.StoreKey], appCodec, app.MsgServiceRouter(), app.AccountKeeper, groupConfig) - - // get skipUpgradeHeights from the app options - skipUpgradeHeights := map[int64]bool{} - for _, h := range cast.ToIntSlice(appOpts.Get(server.FlagUnsafeSkipUpgrades)) { - skipUpgradeHeights[int64(h)] = true - } - homePath := cast.ToString(appOpts.Get(flags.FlagHome)) - // set the governance module account as the authority for conducting upgrades - app.UpgradeKeeper = upgradekeeper.NewKeeper( - skipUpgradeHeights, - keys[upgradetypes.StoreKey], - appCodec, - homePath, - app.BaseApp, - govModAddress, - ) - - app.IBCKeeper = ibckeeper.NewKeeper( - appCodec, - keys[ibcexported.StoreKey], - app.GetSubspace(ibcexported.ModuleName), - app.StakingKeeper, - app.UpgradeKeeper, - scopedIBCKeeper, - ) - - // Register the proposal types - // Deprecated: Avoid adding new handlers, instead use the new proposal flow - // by granting the governance module the right to execute the message. - // See: https://docs.cosmos.network/main/modules/gov#proposal-messages - govRouter := govv1beta1.NewRouter() - govRouter.AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler). - AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.ParamsKeeper)). // This should be removed. It is still in place to avoid failures of modules that have not yet been upgraded. - AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(app.UpgradeKeeper)). - AddRoute(ibcclienttypes.RouterKey, ibcclient.NewClientProposalHandler(app.IBCKeeper.ClientKeeper)) - - govConfig := govtypes.DefaultConfig() - /* - Example of setting gov params: - govConfig.MaxMetadataLen = 10000 - */ - govKeeper := govkeeper.NewKeeper( - appCodec, - keys[govtypes.StoreKey], - app.AccountKeeper, - app.BankKeeper, - app.StakingKeeper, - app.MsgServiceRouter(), - govConfig, - govModAddress, - ) - - app.GovKeeper = *govKeeper.SetHooks( - govtypes.NewMultiGovHooks( - // register the governance hooks - ), - ) - - app.NFTKeeper = nftkeeper.NewKeeper( - keys[nftkeeper.StoreKey], - appCodec, - app.AccountKeeper, - app.BankKeeper, - ) - - // create evidence keeper with router - evidenceKeeper := evidencekeeper.NewKeeper( - appCodec, - keys[evidencetypes.StoreKey], - app.StakingKeeper, - app.SlashingKeeper, - ) - // If evidence needs to be handled for the app, set routes in router here and seal - app.EvidenceKeeper = *evidenceKeeper - - // Configure the hooks keeper - hooksKeeper := ibchookskeeper.NewKeeper( - keys[ibchookstypes.StoreKey], - ) - app.IBCHooksKeeper = &hooksKeeper - - terpPrefix := sdk.GetConfig().GetBech32AccountAddrPrefix() - wasmHooks := ibchooks.NewWasmHooks(app.IBCHooksKeeper, &app.WasmKeeper, terpPrefix) // The contract keeper needs to be set later // The contract keeper needs to be set later - app.Ics20WasmHooks = &wasmHooks - app.HooksICS4Wrapper = ibchooks.NewICS4Middleware( - app.IBCKeeper.ChannelKeeper, - app.Ics20WasmHooks, - ) - - // IBC Fee Module keeper - app.IBCFeeKeeper = ibcfeekeeper.NewKeeper( - appCodec, - keys[ibcfeetypes.StoreKey], - app.HooksICS4Wrapper, // replaced with IBC middleware - app.IBCKeeper.ChannelKeeper, - &app.IBCKeeper.PortKeeper, - app.AccountKeeper, - app.BankKeeper, - ) - - // Initialize packet forward middleware router - app.PacketForwardKeeper = packetforwardkeeper.NewKeeper( - appCodec, - keys[packetforwardtypes.StoreKey], - app.GetSubspace(packetforwardtypes.ModuleName), - app.TransferKeeper, // Will be zero-value here. Reference is set later on with SetTransferKeeper. - app.IBCKeeper.ChannelKeeper, - app.DistrKeeper, - app.BankKeeper, - app.IBCKeeper.ChannelKeeper, - ) - - // Create Transfer Keepers - app.TransferKeeper = ibctransferkeeper.NewKeeper( - appCodec, - keys[ibctransfertypes.StoreKey], - app.GetSubspace(ibctransfertypes.ModuleName), - // The ICS4Wrapper is replaced by the PacketForwardKeeper instead of the channel so that sending can be overridden by the middleware - app.PacketForwardKeeper, - app.IBCKeeper.ChannelKeeper, - &app.IBCKeeper.PortKeeper, - app.AccountKeeper, - app.BankKeeper, - scopedTransferKeeper, - ) - - app.PacketForwardKeeper.SetTransferKeeper(app.TransferKeeper) - - // ICQ Keeper - app.ICQKeeper = icqkeeper.NewKeeper( - appCodec, - keys[icqtypes.StoreKey], - app.GetSubspace(icqtypes.ModuleName), - app.IBCKeeper.ChannelKeeper, // may be replaced with middleware - app.IBCKeeper.ChannelKeeper, - &app.IBCKeeper.PortKeeper, - scopedICQKeeper, - app.BaseApp.GRPCQueryRouter(), - ) - - app.ICAHostKeeper = icahostkeeper.NewKeeper( - appCodec, - keys[icahosttypes.StoreKey], - app.GetSubspace(icahosttypes.SubModuleName), - app.HooksICS4Wrapper, - app.IBCKeeper.ChannelKeeper, - &app.IBCKeeper.PortKeeper, - app.AccountKeeper, - scopedICAHostKeeper, - app.MsgServiceRouter(), - ) - app.ICAControllerKeeper = icacontrollerkeeper.NewKeeper( - appCodec, - keys[icacontrollertypes.StoreKey], - app.GetSubspace(icacontrollertypes.SubModuleName), - app.IBCFeeKeeper, // use ics29 fee as ics4Wrapper in middleware stack - app.IBCKeeper.ChannelKeeper, - &app.IBCKeeper.PortKeeper, - scopedICAControllerKeeper, - app.MsgServiceRouter(), - ) - - wasmDir := filepath.Join(homePath, "wasm") - wasmConfig, err := wasm.ReadWasmConfig(appOpts) - if err != nil { - panic(fmt.Sprintf("error while reading wasm config: %s", err)) + // load state streaming if enabled + if _, _, err := streaming.LoadStreamingServices(bApp, appOpts, appCodec, logger, app.keys); err != nil { + logger.Error("failed to load state streaming", "err", err) + os.Exit(1) } - // The last arguments can contain custom message handlers, and custom query handlers, - // if we want to allow any custom callbacks - // See https://github.com/CosmWasm/cosmwasm/blob/main/docs/CAPABILITIES-BUILT-IN.md - availableCapabilities := "iterator,staking,stargate,cosmwasm_1_1,cosmwasm_1_2,token_factory" - wasmOpts = append(bindings.RegisterCustomPlugins(&app.BankKeeper, &app.TokenFactoryKeeper), wasmOpts...) - app.WasmKeeper = wasmkeeper.NewKeeper( - appCodec, - keys[wasmtypes.StoreKey], - app.AccountKeeper, - app.BankKeeper, - app.StakingKeeper, - distrkeeper.NewQuerier(app.DistrKeeper), - app.IBCFeeKeeper, // ISC4 Wrapper: fee IBC middleware - app.IBCKeeper.ChannelKeeper, - &app.IBCKeeper.PortKeeper, - scopedWasmKeeper, - app.TransferKeeper, - app.MsgServiceRouter(), - app.GRPCQueryRouter(), - wasmDir, - wasmConfig, - availableCapabilities, - govModAddress, - wasmOpts..., - ) - - app.FeeShareKeeper = feesharekeeper.NewKeeper( - keys[feesharetypes.StoreKey], - appCodec, - app.BankKeeper, - app.WasmKeeper, - app.AccountKeeper, - authtypes.FeeCollectorName, - govModAddress, - ) - - app.GlobalFeeKeeper = globalfeekeeper.NewKeeper( - appCodec, - keys[globalfeetypes.StoreKey], - govModAddress, - ) - // The gov proposal types can be individually enabled - if len(enabledProposals) != 0 { - govRouter.AddRoute(wasmtypes.RouterKey, wasmkeeper.NewWasmProposalHandler(app.WasmKeeper, enabledProposals)) //nolint:staticcheck + if maxSize := os.Getenv("MAX_WASM_SIZE"); maxSize != "" { + // https://github.com/CosmWasm/wasmd#compile-time-parameters + val, _ := strconv.ParseInt(maxSize, 10, 32) + wasmtypes.MaxWasmSize = int(val) } - // Set legacy router for backwards compatibility with gov v1beta1 - app.GovKeeper.SetLegacyRouter(govRouter) - - // Create Transfer Stack - var transferStack porttypes.IBCModule - transferStack = transfer.NewIBCModule(app.TransferKeeper) - transferStack = ibcfee.NewIBCMiddleware(transferStack, app.IBCFeeKeeper) - transferStack = ibchooks.NewIBCMiddleware(transferStack, &app.HooksICS4Wrapper) - transferStack = packetforward.NewIBCMiddleware( - transferStack, - app.PacketForwardKeeper, - 0, - packetforwardkeeper.DefaultForwardTransferPacketTimeoutTimestamp, - packetforwardkeeper.DefaultRefundTransferPacketTimeoutTimestamp, - ) - // Create Interchain Accounts Stack - // SendPacket, since it is originating from the application to core IBC: - // icaAuthModuleKeeper.SendTx -> icaController.SendPacket -> fee.SendPacket -> channel.SendPacket - var icaControllerStack porttypes.IBCModule - // integration point for custom authentication modules - // see https://medium.com/the-interchain-foundation/ibc-go-v6-changes-to-interchain-accounts-and-how-it-impacts-your-chain-806c185300d7 - var noAuthzModule porttypes.IBCModule - icaControllerStack = icacontroller.NewIBCMiddleware(noAuthzModule, app.ICAControllerKeeper) - icaControllerStack = ibcfee.NewIBCMiddleware(icaControllerStack, app.IBCFeeKeeper) - - // RecvPacket, message that originates from core IBC and goes down to app, the flow is: - // channel.RecvPacket -> fee.OnRecvPacket -> icaHost.OnRecvPacket - var icaHostStack porttypes.IBCModule - icaHostStack = icahost.NewIBCModule(app.ICAHostKeeper) - icaHostStack = ibcfee.NewIBCMiddleware(icaHostStack, app.IBCFeeKeeper) - - // Create fee enabled wasm ibc Stack - var wasmStack porttypes.IBCModule - wasmStack = wasm.NewIBCHandler(app.WasmKeeper, app.IBCKeeper.ChannelKeeper, app.IBCFeeKeeper) - wasmStack = ibcfee.NewIBCMiddleware(wasmStack, app.IBCFeeKeeper) - - // create ICQ module - icqModule := icq.NewIBCModule(app.ICQKeeper) - - // Create static IBC router, add app routes, then set and seal it - ibcRouter := porttypes.NewRouter(). - AddRoute(ibctransfertypes.ModuleName, transferStack). - AddRoute(wasmtypes.ModuleName, wasmStack). - AddRoute(icacontrollertypes.SubModuleName, icaControllerStack). - AddRoute(icahosttypes.SubModuleName, icaHostStack). - AddRoute(icqtypes.ModuleName, icqModule) - app.IBCKeeper.SetRouter(ibcRouter) - - /**** Module Options ****/ - - bondDenom := app.GetChainBondDenom() + // upgrade handlers + app.configurator = module.NewConfigurator(appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter()) + // NOTE: we may consider parsing `appOpts` inside module constructors. For the moment // we prefer to be more strict in what arguments the modules expect. skipGenesisInvariants := cast.ToBool(appOpts.Get(crisis.FlagSkipGenesisInvariants)) // NOTE: Any module instantiated in the module manager that is later modified // must be passed by reference here. - app.ModuleManager = module.NewManager( - genutil.NewAppModule( - app.AccountKeeper, - app.StakingKeeper, - app.BaseApp.DeliverTx, - encodingConfig.TxConfig, - ), - auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts, app.GetSubspace(authtypes.ModuleName)), - vesting.NewAppModule(app.AccountKeeper, app.BankKeeper), - bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper, app.GetSubspace(banktypes.ModuleName)), - capability.NewAppModule(appCodec, *app.CapabilityKeeper, false), - feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry), - gov.NewAppModule(appCodec, &app.GovKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(govtypes.ModuleName)), - mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper, nil, app.GetSubspace(minttypes.ModuleName)), - slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.GetSubspace(slashingtypes.ModuleName)), - distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.GetSubspace(distrtypes.ModuleName)), - staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(stakingtypes.ModuleName)), - upgrade.NewAppModule(app.UpgradeKeeper), - evidence.NewAppModule(app.EvidenceKeeper), - params.NewAppModule(app.ParamsKeeper), - authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), - groupmodule.NewAppModule(appCodec, app.GroupKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), - nftmodule.NewAppModule(appCodec, app.NFTKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), - consensus.NewAppModule(appCodec, app.ConsensusParamsKeeper), - feeshare.NewAppModule(app.FeeShareKeeper, app.AccountKeeper, app.GetSubspace(feesharetypes.ModuleName)), - globalfee.NewAppModule(appCodec, app.GlobalFeeKeeper, bondDenom), - tokenfactory.NewAppModule(app.TokenFactoryKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(tokenfactorytypes.ModuleName)), - wasm.NewAppModule(appCodec, &app.WasmKeeper, app.StakingKeeper, app.AccountKeeper, app.BankKeeper, app.MsgServiceRouter(), app.GetSubspace(wasmtypes.ModuleName)), - ibc.NewAppModule(app.IBCKeeper), - transfer.NewAppModule(app.TransferKeeper), - ibcfee.NewAppModule(app.IBCFeeKeeper), - ica.NewAppModule(&app.ICAControllerKeeper, &app.ICAHostKeeper), - icq.NewAppModule(app.ICQKeeper), - packetforward.NewAppModule(app.PacketForwardKeeper), - ibchooks.NewAppModule(app.AccountKeeper), - crisis.NewAppModule(app.CrisisKeeper, skipGenesisInvariants, app.GetSubspace(crisistypes.ModuleName)), // always be last to make sure that it checks for all invariants and not only part of them - ) + app.ModuleManager = module.NewManager(appModules(app, encodingConfig, skipGenesisInvariants)...) + app.ModuleManager.RegisterServices(app.configurator) // During begin block slashing happens after distr.BeginBlocker so that // there is nothing left over in the validator fee pool, so as to keep the // CanWithdrawInvariant invariant. // NOTE: staking module is required if HistoricalEntries param > 0 - // NOTE: capability module's beginblocker must come before any modules using capabilities (e.g. IBC) - app.ModuleManager.SetOrderBeginBlockers( - upgradetypes.ModuleName, capabilitytypes.ModuleName, minttypes.ModuleName, distrtypes.ModuleName, slashingtypes.ModuleName, - evidencetypes.ModuleName, stakingtypes.ModuleName, - authtypes.ModuleName, banktypes.ModuleName, govtypes.ModuleName, crisistypes.ModuleName, genutiltypes.ModuleName, - authz.ModuleName, feegrant.ModuleName, nft.ModuleName, group.ModuleName, - paramstypes.ModuleName, vestingtypes.ModuleName, consensusparamtypes.ModuleName, - // additional non simd modules - ibctransfertypes.ModuleName, - ibcexported.ModuleName, - icatypes.ModuleName, - ibcfeetypes.ModuleName, - icqtypes.ModuleName, - packetforwardtypes.ModuleName, - feesharetypes.ModuleName, - globalfee.ModuleName, - ibchookstypes.ModuleName, - tokenfactorytypes.ModuleName, - wasmtypes.ModuleName, - ) + app.ModuleManager.SetOrderBeginBlockers(orderBeginBlockers()...) + + app.ModuleManager.SetOrderEndBlockers(orderEndBlockers()...) - app.ModuleManager.SetOrderEndBlockers( - crisistypes.ModuleName, govtypes.ModuleName, stakingtypes.ModuleName, - capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, distrtypes.ModuleName, - slashingtypes.ModuleName, minttypes.ModuleName, - genutiltypes.ModuleName, evidencetypes.ModuleName, authz.ModuleName, - feegrant.ModuleName, nft.ModuleName, group.ModuleName, - paramstypes.ModuleName, upgradetypes.ModuleName, vestingtypes.ModuleName, consensusparamtypes.ModuleName, - // additional non simd modules - ibctransfertypes.ModuleName, - ibcexported.ModuleName, - icatypes.ModuleName, - ibcfeetypes.ModuleName, - icqtypes.ModuleName, - packetforwardtypes.ModuleName, - feesharetypes.ModuleName, - globalfee.ModuleName, - ibchookstypes.ModuleName, - tokenfactorytypes.ModuleName, - wasmtypes.ModuleName, - ) + app.ModuleManager.SetOrderInitGenesis(orderInitBlockers()...) - // NOTE: The genutils module must occur after staking so that pools are - // properly initialized with tokens from genesis accounts. - // NOTE: The genutils module must also occur after auth so that it can access the params from auth. - // NOTE: Capability module must occur first so that it can initialize any capabilities - // so that other modules that want to create or claim capabilities afterwards in InitChain - // can do so safely. - // NOTE: wasm module should be at the end as it can call other module functionality direct or via message dispatching during - // genesis phase. For example bank transfer, auth account check, staking, ... - genesisModuleOrder := []string{ - capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, - distrtypes.ModuleName, stakingtypes.ModuleName, slashingtypes.ModuleName, govtypes.ModuleName, - minttypes.ModuleName, crisistypes.ModuleName, genutiltypes.ModuleName, evidencetypes.ModuleName, authz.ModuleName, - feegrant.ModuleName, nft.ModuleName, group.ModuleName, paramstypes.ModuleName, upgradetypes.ModuleName, - vestingtypes.ModuleName, consensusparamtypes.ModuleName, - // additional non simd modules - ibctransfertypes.ModuleName, - ibcexported.ModuleName, - icatypes.ModuleName, - ibcfeetypes.ModuleName, - // wasm after ibc transfer - feesharetypes.ModuleName, - globalfee.ModuleName, - icqtypes.ModuleName, - packetforwardtypes.ModuleName, - ibchookstypes.ModuleName, - tokenfactorytypes.ModuleName, - wasmtypes.ModuleName, - } - app.ModuleManager.SetOrderInitGenesis(genesisModuleOrder...) - app.ModuleManager.SetOrderExportGenesis(genesisModuleOrder...) - - // Uncomment if you want to set a custom migration order here. - // app.ModuleManager.SetOrderMigrations(custom order) - - app.ModuleManager.RegisterInvariants(app.CrisisKeeper) - app.configurator = module.NewConfigurator(app.appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter()) - app.ModuleManager.RegisterServices(app.configurator) + app.ModuleManager.RegisterInvariants(app.AppKeepers.CrisisKeeper) + // initialize stores + app.MountKVStores(app.keys) + app.MountTransientStores(app.AppKeepers.GetTransientStoreKey()) + app.MountMemoryStores(app.AppKeepers.GetMemoryStoreKey()) - // RegisterUpgradeHandlers is used for registering any on-chain upgrades. - // Make sure it's called after `app.ModuleManager` and `app.configurator` are set. - app.setupUpgradeHandlers() + // register upgrade + app.setupUpgradeHandlers(app.configurator) autocliv1.RegisterQueryServer(app.GRPCQueryRouter(), runtimeservices.NewAutoCLIQueryService(app.ModuleManager.Modules)) - reflectionSvc, err := runtimeservices.NewReflectionService() if err != nil { panic(err) } reflectionv1.RegisterReflectionServiceServer(app.GRPCQueryRouter(), reflectionSvc) - // add test gRPC service for testing gRPC queries in isolation - // testdata_pulsar.RegisterQueryServer(app.GRPCQueryRouter(), testdata_pulsar.QueryImpl{}) - - // create the simulation manager and define the order of the modules for deterministic simulations - // - // NOTE: this is not required apps that don't use the simulator for fuzz testing - // transactions - overrideModules := map[string]module.AppModuleSimulation{ - authtypes.ModuleName: auth.NewAppModule(app.appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts, app.GetSubspace(authtypes.ModuleName)), + wasmConfig, err := wasm.ReadWasmConfig(appOpts) + if err != nil { + panic("error while reading wasm config: " + err.Error()) } - app.sm = module.NewSimulationManagerFromAppModules(app.ModuleManager.Modules, overrideModules) - app.sm.RegisterStoreDecoders() - // initialize stores - app.MountKVStores(keys) - app.MountTransientStores(tkeys) - app.MountMemoryStores(memKeys) + anteHandler, err := NewAnteHandler( + HandlerOptions{ + HandlerOptions: ante.HandlerOptions{ + AccountKeeper: app.AppKeepers.AccountKeeper, + BankKeeper: app.AppKeepers.BankKeeper, + FeegrantKeeper: app.AppKeepers.FeeGrantKeeper, + SignModeHandler: txConfig.SignModeHandler(), + SigGasConsumer: ante.DefaultSigVerificationGasConsumer, + }, + + GovKeeper: app.AppKeepers.GovKeeper, + IBCKeeper: app.AppKeepers.IBCKeeper, + FeeShareKeeper: app.AppKeepers.FeeShareKeeper, + BankKeeperFork: app.AppKeepers.BankKeeper, // since we need extra methods + TXCounterStoreKey: app.AppKeepers.GetKey(wasmtypes.StoreKey), + WasmConfig: &wasmConfig, + Cdc: appCodec, + + BypassMinFeeMsgTypes: GetDefaultBypassFeeMessages(), + GlobalFeeKeeper: app.AppKeepers.GlobalFeeKeeper, + StakingKeeper: *app.AppKeepers.StakingKeeper, + TxEncoder: app.txConfig.TxEncoder(), + }, + ) + if err != nil { + panic(err) + } + + // initialize BaseApp app.SetInitChainer(app.InitChainer) app.SetBeginBlocker(app.BeginBlocker) + app.SetAnteHandler(anteHandler) app.SetEndBlocker(app.EndBlocker) - app.setAnteHandler(encodingConfig.TxConfig, wasmConfig, keys[wasmtypes.StoreKey]) // must be before Loading version // requires the snapshot store to be created and registered as a BaseAppOption // see cmd/wasmd/root.go: 206 - 214 approx if manager := app.SnapshotManager(); manager != nil { err := manager.RegisterExtensions( - wasmkeeper.NewWasmSnapshotter(app.CommitMultiStore(), &app.WasmKeeper), + wasmkeeper.NewWasmSnapshotter(app.CommitMultiStore(), &app.AppKeepers.WasmKeeper), ) if err != nil { panic(fmt.Errorf("failed to register snapshot extension: %s", err)) } } - app.ScopedIBCKeeper = scopedIBCKeeper - app.ScopedTransferKeeper = scopedTransferKeeper - app.ScopedWasmKeeper = scopedWasmKeeper - app.ScopedICAHostKeeper = scopedICAHostKeeper - app.ScopedICAControllerKeeper = scopedICAControllerKeeper - - // set the contract keeper for the Ics20WasmHooks - app.ContractKeeper = wasmkeeper.NewDefaultPermissionKeeper(app.WasmKeeper) - app.Ics20WasmHooks.ContractKeeper = &app.WasmKeeper + app.setupUpgradeStoreLoaders() // In v0.46, the SDK introduces _postHandlers_. PostHandlers are like // antehandlers, but are run _after_ the `runMsgs` execution. They are also @@ -1075,49 +398,29 @@ func NewTerpApp( if loadLatest { if err := app.LoadLatestVersion(); err != nil { - logger.Error("error on loading last version", "err", err) - os.Exit(1) + tmos.Exit(err.Error()) } ctx := app.BaseApp.NewUncachedContext(true, tmproto.Header{}) - // Initialize pinned codes in wasmvm as they are not persisted there - if err := app.WasmKeeper.InitializePinnedCodes(ctx); err != nil { + if err := app.AppKeepers.WasmKeeper.InitializePinnedCodes(ctx); err != nil { tmos.Exit(fmt.Sprintf("failed initialize pinned codes %s", err)) } - } - - return app -} - -func (app *TerpApp) setAnteHandler(txConfig client.TxConfig, wasmConfig wasmtypes.WasmConfig, txCounterStoreKey storetypes.StoreKey) { - anteHandler, err := NewAnteHandler( - HandlerOptions{ - HandlerOptions: ante.HandlerOptions{ - AccountKeeper: app.AccountKeeper, - BankKeeper: app.BankKeeper, - FeegrantKeeper: app.FeeGrantKeeper, - SignModeHandler: txConfig.SignModeHandler(), - SigGasConsumer: ante.DefaultSigVerificationGasConsumer, - }, - GovKeeper: app.GovKeeper, - IBCKeeper: app.IBCKeeper, - FeeShareKeeper: app.FeeShareKeeper, - BankKeeperFork: app.BankKeeper, // since we need extra methods - WasmConfig: &wasmConfig, - TXCounterStoreKey: txCounterStoreKey, + // Initialize and seal the capability keeper so all persistent capabilities + // are loaded in-memory and prevent any further modules from creating scoped + // sub-keepers. + // This must be done during creation of baseapp rather than in InitChain so + // that in-memory capabilities get regenerated on app restart. + // Note that since this reads from the store, we can only perform it when + // `loadLatest` is set to true. + app.AppKeepers.CapabilityKeeper.Seal() + } - BypassMinFeeMsgTypes: GetDefaultBypassFeeMessages(), - GlobalFeeKeeper: app.GlobalFeeKeeper, - StakingKeeper: *app.StakingKeeper, + app.sm = module.NewSimulationManager(simulationModules(app, encodingConfig, skipGenesisInvariants)...) - TxEncoder: app.txConfig.TxEncoder(), - }, - ) - if err != nil { - panic(fmt.Errorf("failed to create AnteHandler: %s", err)) - } - app.SetAnteHandler(anteHandler) + app.sm.RegisterStoreDecoders() + + return app } func GetDefaultBypassFeeMessages() []string { @@ -1129,6 +432,9 @@ func GetDefaultBypassFeeMessages() []string { sdk.MsgTypeURL(&ibctransfertypes.MsgTransfer{}), sdk.MsgTypeURL(&ibcchanneltypes.MsgTimeout{}), sdk.MsgTypeURL(&ibcchanneltypes.MsgTimeoutOnClose{}), + // sdk.MsgTypeURL(&ibcchanneltypes.MsgChannelOpenTry{}), + // sdk.MsgTypeURL(&ibcchanneltypes.MsgChannelOpenConfirm{}), + // sdk.MsgTypeURL(&ibcchanneltypes.MsgChannelOpenAck{}), } } @@ -1156,9 +462,6 @@ func (app *TerpApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.R return app.ModuleManager.EndBlock(ctx, req) } -func (app *TerpApp) Configurator() module.Configurator { - return app.configurator -} // InitChainer application update at chain initialization func (app *TerpApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { @@ -1166,7 +469,7 @@ func (app *TerpApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci if err := json.Unmarshal(req.AppStateBytes, &genesisState); err != nil { panic(err) } - app.UpgradeKeeper.SetModuleVersionMap(ctx, app.ModuleManager.GetVersionMap()) + app.AppKeepers.UpgradeKeeper.SetModuleVersionMap(ctx, app.ModuleManager.GetVersionMap()) return app.ModuleManager.InitGenesis(ctx, app.appCodec, genesisState) } @@ -1175,6 +478,17 @@ func (app *TerpApp) LoadHeight(height int64) error { return app.LoadVersion(height) } +// ModuleAccountAddrs returns all the app's module account addresses. +func (app *TerpApp) ModuleAccountAddrs() map[string]bool { + modAccAddrs := make(map[string]bool) + for acc := range keepers.GetMaccPerms() { + modAccAddrs[authtypes.NewModuleAddress(acc).String()] = true + } + + return modAccAddrs +} + + // LegacyAmino returns legacy amino codec. // // NOTE: This is solely to be used for testing purposes as it may be desirable @@ -1196,55 +510,14 @@ func (app *TerpApp) InterfaceRegistry() types.InterfaceRegistry { return app.interfaceRegistry } -// TxConfig returns TerpApp's TxConfig -func (app *TerpApp) TxConfig() client.TxConfig { - return app.txConfig -} - -// DefaultGenesis returns a default genesis from the registered AppModuleBasic's. -func (app *TerpApp) DefaultGenesis() map[string]json.RawMessage { - return ModuleBasics.DefaultGenesis(app.appCodec) -} - -// GetKey returns the KVStoreKey for the provided store key. -// -// NOTE: This is solely to be used for testing purposes. -func (app *TerpApp) GetKey(storeKey string) *storetypes.KVStoreKey { - return app.keys[storeKey] -} - -// GetTKey returns the TransientStoreKey for the provided store key. -// -// NOTE: This is solely to be used for testing purposes. -func (app *TerpApp) GetTKey(storeKey string) *storetypes.TransientStoreKey { - return app.tkeys[storeKey] -} - -// GetMemKey returns the MemStoreKey for the provided mem key. -// -// NOTE: This is solely used for testing purposes. -func (app *TerpApp) GetMemKey(storeKey string) *storetypes.MemoryStoreKey { - return app.memKeys[storeKey] -} - // GetSubspace returns a param subspace for a given module name. // // NOTE: This is solely to be used for testing purposes. func (app *TerpApp) GetSubspace(moduleName string) paramstypes.Subspace { - subspace, _ := app.ParamsKeeper.GetSubspace(moduleName) + subspace, _ := app.AppKeepers.ParamsKeeper.GetSubspace(moduleName) return subspace } -// GetIBCKeeper implements the TestingApp interface. -func (app *TerpApp) GetIBCKeeper() *ibckeeper.Keeper { - return app.IBCKeeper -} - -// SimulationManager implements the SimulationApp interface -func (app *TerpApp) SimulationManager() *module.SimulationManager { - return app.sm -} - // RegisterAPIRoutes registers all application module routes with the provided // API server. func (app *TerpApp) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig) { @@ -1261,6 +534,10 @@ func (app *TerpApp) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APICo // Register grpc-gateway routes for all modules. ModuleBasics.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) + // register app's OpenAPI routes. + apiSvr.Router.Handle("/static/openapi.yml", http.FileServer(http.FS(docs.Docs))) + apiSvr.Router.HandleFunc("/", openapiconsole.Handler(appName, "/static/openapi.yml")) + // register swagger API from root so that other applications can override easily if err := server.RegisterSwaggerAPI(apiSvr.ClientCtx, apiSvr.Router, apiConfig.Swagger); err != nil { panic(err) @@ -1282,81 +559,56 @@ func (app *TerpApp) RegisterTendermintService(clientCtx client.Context) { ) } + func (app *TerpApp) RegisterNodeService(clientCtx client.Context) { nodeservice.RegisterNodeService(clientCtx, app.GRPCQueryRouter()) } -// GetMaccPerms returns a copy of the module account permissions -// -// NOTE: This is solely to be used for testing purposes. -func GetMaccPerms() map[string][]string { - dupMaccPerms := make(map[string][]string) - for k, v := range maccPerms { - dupMaccPerms[k] = v - } - - return dupMaccPerms -} - -// BlockedAddresses returns all the app's blocked account addresses. -func BlockedAddresses() map[string]bool { - modAccAddrs := make(map[string]bool) - for acc := range GetMaccPerms() { - modAccAddrs[authtypes.NewModuleAddress(acc).String()] = true - } - - // allow the following addresses to receive funds - delete(modAccAddrs, authtypes.NewModuleAddress(govtypes.ModuleName).String()) - - return modAccAddrs +func (app *TerpApp) Configurator() module.Configurator { + return app.configurator } -func (app *TerpApp) setupUpgradeHandlers() { - // v2 upgrade handler - app.UpgradeKeeper.SetUpgradeHandler( - v2.UpgradeName, - v2.CreateUpgradeHandler( - app.ModuleManager, app.configurator, - app.FeeShareKeeper, app.GlobalFeeKeeper, - app.TokenFactoryKeeper, app.ICQKeeper, - *app.PacketForwardKeeper, - ), - ) - - // !! ATTENTION !! - - // When a planned update height is reached, the old binary will panic - // writing on disk the height and name of the update that triggered it - // This will read that value, and execute the preparations for the upgrade. - upgradeInfo, err := app.UpgradeKeeper.ReadUpgradeInfoFromDisk() +// configure store loader that checks if version == upgradeHeight and applies store upgrades +func (app *TerpApp) setupUpgradeStoreLoaders() { + upgradeInfo, err := app.AppKeepers.UpgradeKeeper.ReadUpgradeInfoFromDisk() if err != nil { - panic(fmt.Errorf("failed to read upgrade info from disk: %w", err)) + panic("failed to read upgrade info from disk" + err.Error()) } - if app.UpgradeKeeper.IsSkipHeight(upgradeInfo.Height) { + if app.AppKeepers.UpgradeKeeper.IsSkipHeight(upgradeInfo.Height) { return } - var storeUpgrades *storetypes.StoreUpgrades - - if upgradeInfo.Name == v2.UpgradeName { - storeUpgrades = &storetypes.StoreUpgrades{ - Added: []string{ - feesharetypes.ModuleName, - globalfeetypes.ModuleName, - packetforwardtypes.StoreKey, - ibchookstypes.StoreKey, - icqtypes.ModuleName, - }, + for _, upgrade := range Upgrades { + if upgradeInfo.Name == upgrade.UpgradeName { + storeUpgrades := upgrade.StoreUpgrades + app.SetStoreLoader( + upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, &storeUpgrades), + ) } } +} - if storeUpgrades != nil { - // configure store loader that checks if version == upgradeHeight and applies store upgrades - app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, storeUpgrades)) +func (app *TerpApp) setupUpgradeHandlers(cfg module.Configurator) { + for _, upgrade := range Upgrades { + app.AppKeepers.UpgradeKeeper.SetUpgradeHandler( + upgrade.UpgradeName, + upgrade.CreateUpgradeHandler( + app.ModuleManager, + cfg, + &app.AppKeepers, + ), + ) } } + + +// SimulationManager implements the SimulationApp interface +func (app *TerpApp) SimulationManager() *module.SimulationManager { + return app.sm +} + // ChainID gets chainID from private fields of BaseApp // Should be removed once SDK 0.50.x will be adopted func (app *TerpApp) ChainID() string { @@ -1372,42 +624,6 @@ func (app *TerpApp) GetChainBondDenom() string { return d } -// ModuleAccountAddrs returns all the app's module account addresses. -func (app *TerpApp) ModuleAccountAddrs() map[string]bool { - modAccAddrs := make(map[string]bool) - for acc := range GetMaccPerms() { - modAccAddrs[authtypes.NewModuleAddress(acc).String()] = true - } - - return modAccAddrs -} - -// initParamsKeeper init params keeper and its subspaces -func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, tkey storetypes.StoreKey) paramskeeper.Keeper { - paramsKeeper := paramskeeper.NewKeeper(appCodec, legacyAmino, key, tkey) - - paramsKeeper.Subspace(authtypes.ModuleName) - paramsKeeper.Subspace(banktypes.ModuleName) - paramsKeeper.Subspace(stakingtypes.ModuleName).WithKeyTable(stakingtypes.ParamKeyTable()) // Used for GlobalFee - paramsKeeper.Subspace(minttypes.ModuleName) - paramsKeeper.Subspace(distrtypes.ModuleName) - paramsKeeper.Subspace(slashingtypes.ModuleName) - paramsKeeper.Subspace(govtypes.ModuleName) - paramsKeeper.Subspace(crisistypes.ModuleName) - paramsKeeper.Subspace(ibctransfertypes.ModuleName) - paramsKeeper.Subspace(ibcexported.ModuleName) - paramsKeeper.Subspace(tokenfactorytypes.ModuleName) - paramsKeeper.Subspace(icahosttypes.SubModuleName) - paramsKeeper.Subspace(icacontrollertypes.SubModuleName) - paramsKeeper.Subspace(icqtypes.ModuleName) - paramsKeeper.Subspace(packetforwardtypes.ModuleName) - paramsKeeper.Subspace(globalfee.ModuleName) - paramsKeeper.Subspace(feesharetypes.ModuleName) - paramsKeeper.Subspace(wasmtypes.ModuleName) - - return paramsKeeper -} - // QuerierWrapper is a local wrapper around BaseApp that exports only the Queryable interface. // This is used to pass the baseApp to Async ICQ without exposing all methods type QuerierWrapper struct { diff --git a/app/apptesting/test_suite.go b/app/apptesting/test_suite.go index e13e086..56ab8c8 100644 --- a/app/apptesting/test_suite.go +++ b/app/apptesting/test_suite.go @@ -101,18 +101,18 @@ func (s *KeeperTestHelper) Commit() { // FundAcc funds target address with specified amount. func (s *KeeperTestHelper) FundAcc(acc sdk.AccAddress, amounts sdk.Coins) { - err := banktestutil.FundAccount(s.App.BankKeeper, s.Ctx, acc, amounts) + err := banktestutil.FundAccount(s.App.AppKeepers.BankKeeper, s.Ctx, acc, amounts) s.Require().NoError(err) } // FundModuleAcc funds target modules with specified amount. func (s *KeeperTestHelper) FundModuleAcc(moduleName string, amounts sdk.Coins) { - err := banktestutil.FundModuleAccount(s.App.BankKeeper, s.Ctx, moduleName, amounts) + err := banktestutil.FundModuleAccount(s.App.AppKeepers.BankKeeper, s.Ctx, moduleName, amounts) s.Require().NoError(err) } func (s *KeeperTestHelper) MintCoins(coins sdk.Coins) { - err := s.App.BankKeeper.MintCoins(s.Ctx, minttypes.ModuleName, coins) + err := s.App.AppKeepers.BankKeeper.MintCoins(s.Ctx, minttypes.ModuleName, coins) s.Require().NoError(err) } @@ -120,12 +120,12 @@ func (s *KeeperTestHelper) MintCoins(coins sdk.Coins) { func (s *KeeperTestHelper) SetupValidator(bondStatus stakingtypes.BondStatus) sdk.ValAddress { valPub := secp256k1.GenPrivKey().PubKey() valAddr := sdk.ValAddress(valPub.Address()) - bondDenom := s.App.StakingKeeper.GetParams(s.Ctx).BondDenom + bondDenom := s.App.AppKeepers.StakingKeeper.GetParams(s.Ctx).BondDenom selfBond := sdk.NewCoins(sdk.Coin{Amount: sdk.NewInt(100), Denom: bondDenom}) s.FundAcc(sdk.AccAddress(valAddr), selfBond) - // stakingHandler := staking.NewHandler(s.App.StakingKeeper) + // stakingHandler := staking.NewHandler(s.App.AppKeepers.StakingKeeper) stakingCoin := sdk.NewCoin(appparams.BondDenom, selfBond[0].Amount) ZeroCommission := stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) _, err := stakingtypes.NewMsgCreateValidator(valAddr, valPub, stakingCoin, stakingtypes.Description{}, ZeroCommission, sdk.OneInt()) @@ -134,11 +134,11 @@ func (s *KeeperTestHelper) SetupValidator(bondStatus stakingtypes.BondStatus) sd // s.Require().NoError(err) // s.Require().NotNil(res) - val, found := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr) + val, found := s.App.AppKeepers.StakingKeeper.GetValidator(s.Ctx, valAddr) s.Require().True(found) val = val.UpdateStatus(bondStatus) - s.App.StakingKeeper.SetValidator(s.Ctx, val) + s.App.AppKeepers.StakingKeeper.SetValidator(s.Ctx, val) consAddr, err := val.GetConsAddr() s.Suite.Require().NoError(err) @@ -151,7 +151,7 @@ func (s *KeeperTestHelper) SetupValidator(bondStatus stakingtypes.BondStatus) sd false, 0, ) - s.App.SlashingKeeper.SetValidatorSigningInfo(s.Ctx, consAddr, signingInfo) + s.App.AppKeepers.SlashingKeeper.SetValidatorSigningInfo(s.Ctx, consAddr, signingInfo) return valAddr } @@ -160,14 +160,14 @@ func (s *KeeperTestHelper) SetupValidator(bondStatus stakingtypes.BondStatus) sd func (s *KeeperTestHelper) BeginNewBlock() { var valAddr []byte - validators := s.App.StakingKeeper.GetAllValidators(s.Ctx) + validators := s.App.AppKeepers.StakingKeeper.GetAllValidators(s.Ctx) if len(validators) >= 1 { valAddrFancy, err := validators[0].GetConsAddr() s.Require().NoError(err) valAddr = valAddrFancy.Bytes() } else { valAddrFancy := s.SetupValidator(stakingtypes.Bonded) - validator, _ := s.App.StakingKeeper.GetValidator(s.Ctx, valAddrFancy) + validator, _ := s.App.AppKeepers.StakingKeeper.GetValidator(s.Ctx, valAddrFancy) valAddr2, _ := validator.GetConsAddr() valAddr = valAddr2.Bytes() } @@ -177,7 +177,7 @@ func (s *KeeperTestHelper) BeginNewBlock() { // BeginNewBlockWithProposer begins a new block with a proposer. func (s *KeeperTestHelper) BeginNewBlockWithProposer(proposer sdk.ValAddress) { - validator, found := s.App.StakingKeeper.GetValidator(s.Ctx, proposer) + validator, found := s.App.AppKeepers.StakingKeeper.GetValidator(s.Ctx, proposer) s.Assert().True(found) valConsAddr, err := validator.GetConsAddr() @@ -211,18 +211,18 @@ func (s *KeeperTestHelper) EndBlock() { // AllocateRewardsToValidator allocates reward tokens to a distribution module then allocates rewards to the validator address. func (s *KeeperTestHelper) AllocateRewardsToValidator(valAddr sdk.ValAddress, rewardAmt math.Int) { - validator, found := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr) + validator, found := s.App.AppKeepers.StakingKeeper.GetValidator(s.Ctx, valAddr) s.Require().True(found) // allocate reward tokens to distribution module coins := sdk.Coins{sdk.NewCoin(appparams.BondDenom, rewardAmt)} - err := banktestutil.FundModuleAccount(s.App.BankKeeper, s.Ctx, distrtypes.ModuleName, coins) + err := banktestutil.FundModuleAccount(s.App.AppKeepers.BankKeeper, s.Ctx, distrtypes.ModuleName, coins) s.Require().NoError(err) // allocate rewards to validator s.Ctx = s.Ctx.WithBlockHeight(s.Ctx.BlockHeight() + 1) decTokens := sdk.DecCoins{{Denom: appparams.BondDenom, Amount: sdk.NewDec(20000)}} - s.App.DistrKeeper.AllocateTokensToValidator(s.Ctx, validator, decTokens) + s.App.AppKeepers.DistrKeeper.AllocateTokensToValidator(s.Ctx, validator, decTokens) } // BuildTx builds a transaction. diff --git a/app/export.go b/app/export.go index ee366ac..caa89d7 100644 --- a/app/export.go +++ b/app/export.go @@ -34,7 +34,7 @@ func (app *TerpApp) ExportAppStateAndValidators(forZeroHeight bool, jailAllowedA return servertypes.ExportedApp{}, err } - validators, err := staking.WriteValidators(ctx, app.StakingKeeper) + validators, err := staking.WriteValidators(ctx, app.AppKeepers.StakingKeeper) return servertypes.ExportedApp{ AppState: appState, Validators: validators, @@ -66,18 +66,18 @@ func (app *TerpApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ } /* Just to be safe, assert the invariants on current state. */ - app.CrisisKeeper.AssertInvariants(ctx) + app.AppKeepers.CrisisKeeper.AssertInvariants(ctx) /* Handle fee distribution state. */ // withdraw all validator commission - app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { - _, _ = app.DistrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator()) + app.AppKeepers.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { + _, _ = app.AppKeepers.DistrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator()) return false }) // withdraw all delegator rewards - dels := app.StakingKeeper.GetAllDelegations(ctx) + dels := app.AppKeepers.StakingKeeper.GetAllDelegations(ctx) for _, delegation := range dels { valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) if err != nil { @@ -86,30 +86,30 @@ func (app *TerpApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ delAddr := sdk.MustAccAddressFromBech32(delegation.DelegatorAddress) - if _, err = app.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr); err != nil { + if _, err = app.AppKeepers.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr); err != nil { panic(err) } } // clear validator slash events - app.DistrKeeper.DeleteAllValidatorSlashEvents(ctx) + app.AppKeepers.DistrKeeper.DeleteAllValidatorSlashEvents(ctx) // clear validator historical rewards - app.DistrKeeper.DeleteAllValidatorHistoricalRewards(ctx) + app.AppKeepers.DistrKeeper.DeleteAllValidatorHistoricalRewards(ctx) // set context height to zero height := ctx.BlockHeight() ctx = ctx.WithBlockHeight(0) // reinitialize all validators - app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { + app.AppKeepers.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { // donate any unwithdrawn outstanding reward fraction tokens to the community pool - scraps := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, val.GetOperator()) - feePool := app.DistrKeeper.GetFeePool(ctx) + scraps := app.AppKeepers.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, val.GetOperator()) + feePool := app.AppKeepers.DistrKeeper.GetFeePool(ctx) feePool.CommunityPool = feePool.CommunityPool.Add(scraps...) - app.DistrKeeper.SetFeePool(ctx, feePool) + app.AppKeepers.DistrKeeper.SetFeePool(ctx, feePool) - if err := app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()); err != nil { + if err := app.AppKeepers.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()); err != nil { panic(err) } return false @@ -123,12 +123,12 @@ func (app *TerpApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ } delAddr := sdk.MustAccAddressFromBech32(del.DelegatorAddress) - if err := app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr); err != nil { + if err := app.AppKeepers.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr); err != nil { // never called as BeforeDelegationCreated always returns nil panic(fmt.Errorf("error while incrementing period: %w", err)) } - if err := app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr); err != nil { + if err := app.AppKeepers.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr); err != nil { // never called as AfterDelegationModified always returns nil panic(fmt.Errorf("error while creating a new delegation period record: %w", err)) } @@ -140,32 +140,32 @@ func (app *TerpApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ /* Handle staking state. */ // iterate through redelegations, reset creation height - app.StakingKeeper.IterateRedelegations(ctx, func(_ int64, red stakingtypes.Redelegation) (stop bool) { + app.AppKeepers.StakingKeeper.IterateRedelegations(ctx, func(_ int64, red stakingtypes.Redelegation) (stop bool) { for i := range red.Entries { red.Entries[i].CreationHeight = 0 } - app.StakingKeeper.SetRedelegation(ctx, red) + app.AppKeepers.StakingKeeper.SetRedelegation(ctx, red) return false }) // iterate through unbonding delegations, reset creation height - app.StakingKeeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd stakingtypes.UnbondingDelegation) (stop bool) { + app.AppKeepers.StakingKeeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd stakingtypes.UnbondingDelegation) (stop bool) { for i := range ubd.Entries { ubd.Entries[i].CreationHeight = 0 } - app.StakingKeeper.SetUnbondingDelegation(ctx, ubd) + app.AppKeepers.StakingKeeper.SetUnbondingDelegation(ctx, ubd) return false }) // Iterate through validators by power descending, reset bond heights, and // update bond intra-tx counters. - store := ctx.KVStore(app.GetKey(stakingtypes.StoreKey)) + store := ctx.KVStore(app.AppKeepers.GetKey(stakingtypes.StoreKey)) iter := sdk.KVStoreReversePrefixIterator(store, stakingtypes.ValidatorsKey) counter := int16(0) for ; iter.Valid(); iter.Next() { addr := sdk.ValAddress(stakingtypes.AddressFromValidatorsKey(iter.Key())) - validator, found := app.StakingKeeper.GetValidator(ctx, addr) + validator, found := app.AppKeepers.StakingKeeper.GetValidator(ctx, addr) if !found { panic("expected validator, not found") } @@ -175,7 +175,7 @@ func (app *TerpApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ validator.Jailed = true } - app.StakingKeeper.SetValidator(ctx, validator) + app.AppKeepers.StakingKeeper.SetValidator(ctx, validator) counter++ } @@ -184,7 +184,7 @@ func (app *TerpApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ return } - _, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + _, err := app.AppKeepers.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) if err != nil { log.Fatal(err) } @@ -192,11 +192,11 @@ func (app *TerpApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ /* Handle slashing state. */ // reset start height on signing infos - app.SlashingKeeper.IterateValidatorSigningInfos( + app.AppKeepers.SlashingKeeper.IterateValidatorSigningInfos( ctx, func(addr sdk.ConsAddress, info slashingtypes.ValidatorSigningInfo) (stop bool) { info.StartHeight = 0 - app.SlashingKeeper.SetValidatorSigningInfo(ctx, addr, info) + app.AppKeepers.SlashingKeeper.SetValidatorSigningInfo(ctx, addr, info) return false }, ) diff --git a/app/keepers/keepers.go b/app/keepers/keepers.go new file mode 100644 index 0000000..1c9e3f7 --- /dev/null +++ b/app/keepers/keepers.go @@ -0,0 +1,719 @@ +package keepers + +import ( + "fmt" + "path/filepath" + "github.com/spf13/cast" + + "github.com/CosmWasm/wasmd/x/wasm" + wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" + wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" + + packetforward "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7/router" + packetforwardkeeper "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7/router/keeper" + packetforwardtypes "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7/router/types" + + icq "github.com/cosmos/ibc-apps/modules/async-icq/v7" + icqkeeper "github.com/cosmos/ibc-apps/modules/async-icq/v7/keeper" + icqtypes "github.com/cosmos/ibc-apps/modules/async-icq/v7/types" + + ibchooks "github.com/cosmos/ibc-apps/modules/ibc-hooks/v7" + ibchookskeeper "github.com/cosmos/ibc-apps/modules/ibc-hooks/v7/keeper" + ibchookstypes "github.com/cosmos/ibc-apps/modules/ibc-hooks/v7/types" + + icacontroller "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller" + icacontrollerkeeper "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller/keeper" + icacontrollertypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller/types" + + icahost "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/host" + icahostkeeper "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/host/keeper" + icahosttypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/host/types" + icatypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/types" + + ibcfee "github.com/cosmos/ibc-go/v7/modules/apps/29-fee" + ibcfeekeeper "github.com/cosmos/ibc-go/v7/modules/apps/29-fee/keeper" + ibcfeetypes "github.com/cosmos/ibc-go/v7/modules/apps/29-fee/types" + transfer "github.com/cosmos/ibc-go/v7/modules/apps/transfer" + + ibctransferkeeper "github.com/cosmos/ibc-go/v7/modules/apps/transfer/keeper" + ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" + ibcclient "github.com/cosmos/ibc-go/v7/modules/core/02-client" + ibcclienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" + ibcconnectiontypes "github.com/cosmos/ibc-go/v7/modules/core/03-connection/types" + + + porttypes "github.com/cosmos/ibc-go/v7/modules/core/05-port/types" + ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" + ibckeeper "github.com/cosmos/ibc-go/v7/modules/core/keeper" + + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/server" + servertypes "github.com/cosmos/cosmos-sdk/server/types" + storetypes "github.com/cosmos/cosmos-sdk/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper" + bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" + capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" + consensusparamkeeper "github.com/cosmos/cosmos-sdk/x/consensus/keeper" + consensusparamtypes "github.com/cosmos/cosmos-sdk/x/consensus/types" + crisiskeeper "github.com/cosmos/cosmos-sdk/x/crisis/keeper" + crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" + distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" + evidencekeeper "github.com/cosmos/cosmos-sdk/x/evidence/keeper" + evidencetypes "github.com/cosmos/cosmos-sdk/x/evidence/types" + "github.com/cosmos/cosmos-sdk/x/feegrant" + feegrantkeeper "github.com/cosmos/cosmos-sdk/x/feegrant/keeper" + govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" + govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" + "github.com/cosmos/cosmos-sdk/x/group" + groupkeeper "github.com/cosmos/cosmos-sdk/x/group/keeper" + mintkeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper" + minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" + "github.com/cosmos/cosmos-sdk/x/nft" + nftkeeper "github.com/cosmos/cosmos-sdk/x/nft/keeper" + "github.com/cosmos/cosmos-sdk/x/params" + paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" + paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" + paramproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" + slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper" + slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" + stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/cosmos/cosmos-sdk/x/upgrade" + upgradekeeper "github.com/cosmos/cosmos-sdk/x/upgrade/keeper" + upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + + feesharekeeper "github.com/terpnetwork/terp-core/v2/x/feeshare/keeper" + feesharetypes "github.com/terpnetwork/terp-core/v2/x/feeshare/types" + + "github.com/terpnetwork/terp-core/v2/x/globalfee" + globalfeekeeper "github.com/terpnetwork/terp-core/v2/x/globalfee/keeper" + globalfeetypes "github.com/terpnetwork/terp-core/v2/x/globalfee/types" + + // token factory + + tokenfactorykeeper "github.com/terpnetwork/terp-core/v2/x/tokenfactory/keeper" + tokenfactorytypes "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/bindings" +) + +var ( + + wasmCapabilities = "iterator,staking,stargate,token_factory,cosmwasm_1_1,cosmwasm_1_2,tokenfactory" + + tokenFactoryCapabilities = []string{ + tokenfactorytypes.EnableBurnFrom, + tokenfactorytypes.EnableForceTransfer, + tokenfactorytypes.EnableSetMetadata, + } +) + +// module account permissions +var maccPerms = map[string][]string{ + authtypes.FeeCollectorName: nil, + distrtypes.ModuleName: nil, + minttypes.ModuleName: {authtypes.Minter}, + stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, + stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, + govtypes.ModuleName: {authtypes.Burner}, + nft.ModuleName: nil, + ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, + ibcfeetypes.ModuleName: nil, + icqtypes.ModuleName: nil, + icatypes.ModuleName: nil, + globalfee.ModuleName: nil, + wasmtypes.ModuleName: {authtypes.Burner}, + tokenfactorytypes.ModuleName: {authtypes.Minter, authtypes.Burner}, +} + +type AppKeepers struct { + // keys to access the substores + keys map[string]*storetypes.KVStoreKey + tkeys map[string]*storetypes.TransientStoreKey + memKeys map[string]*storetypes.MemoryStoreKey + + // keepers + AccountKeeper authkeeper.AccountKeeper + AuthzKeeper authzkeeper.Keeper + BankKeeper bankkeeper.BaseKeeper + + CapabilityKeeper *capabilitykeeper.Keeper + StakingKeeper *stakingkeeper.Keeper + SlashingKeeper slashingkeeper.Keeper + MintKeeper mintkeeper.Keeper + DistrKeeper distrkeeper.Keeper + GovKeeper govkeeper.Keeper + CrisisKeeper *crisiskeeper.Keeper + UpgradeKeeper *upgradekeeper.Keeper + ParamsKeeper paramskeeper.Keeper + EvidenceKeeper evidencekeeper.Keeper + FeeGrantKeeper feegrantkeeper.Keeper + GroupKeeper groupkeeper.Keeper + NFTKeeper nftkeeper.Keeper + ConsensusParamsKeeper consensusparamkeeper.Keeper + + IBCKeeper *ibckeeper.Keeper // IBC Keeper must be a pointer in the app, so we can SetRouter on it correctly + IBCFeeKeeper ibcfeekeeper.Keeper + IBCHooksKeeper *ibchookskeeper.Keeper + ICAControllerKeeper icacontrollerkeeper.Keeper + FeeShareKeeper feesharekeeper.Keeper + GlobalFeeKeeper globalfeekeeper.Keeper + TokenFactoryKeeper tokenfactorykeeper.Keeper + ContractKeeper *wasmkeeper.PermissionedKeeper + PacketForwardKeeper *packetforwardkeeper.Keeper + ICQKeeper icqkeeper.Keeper + ICAHostKeeper icahostkeeper.Keeper + TransferKeeper ibctransferkeeper.Keeper + WasmKeeper wasmkeeper.Keeper + + ScopedIBCKeeper capabilitykeeper.ScopedKeeper + ScopedICAHostKeeper capabilitykeeper.ScopedKeeper + ScopedICAControllerKeeper capabilitykeeper.ScopedKeeper + ScopedTransferKeeper capabilitykeeper.ScopedKeeper + ScopedIBCFeeKeeper capabilitykeeper.ScopedKeeper + ScopedWasmKeeper capabilitykeeper.ScopedKeeper + ScopedICQKeeper capabilitykeeper.ScopedKeeper + + // Middleware wrapper + Ics20WasmHooks *ibchooks.WasmHooks + HooksICS4Wrapper ibchooks.ICS4Middleware +} + +func NewAppKeepers( + appCodec codec.Codec, + bApp *baseapp.BaseApp, + cdc *codec.LegacyAmino, + maccPerms map[string][]string, + enabledProposals []wasmtypes.ProposalType, + appOpts servertypes.AppOptions, + wasmOpts []wasmkeeper.Option, +) AppKeepers { + appKeepers := AppKeepers{} + + // Set keys KVStoreKey, TransientStoreKey, MemoryStoreKey + appKeepers.GenerateKeys() + keys := appKeepers.GetKVStoreKey() + tkeys := appKeepers.GetTransientStoreKey() + + + appKeepers.ParamsKeeper = initParamsKeeper( + appCodec, + cdc, + keys[paramstypes.StoreKey], + tkeys[paramstypes.TStoreKey], + ) + + + govModAddress := authtypes.NewModuleAddress(govtypes.ModuleName).String() + + // set the BaseApp's parameter store + appKeepers.ConsensusParamsKeeper = consensusparamkeeper.NewKeeper(appCodec, keys[consensusparamtypes.StoreKey], govModAddress) + bApp.SetParamStore(&appKeepers.ConsensusParamsKeeper) + + // add capability keeper and ScopeToModule for ibc module + appKeepers.CapabilityKeeper = capabilitykeeper.NewKeeper( + appCodec, + appKeepers.keys[capabilitytypes.StoreKey], + appKeepers.memKeys[capabilitytypes.MemStoreKey], + ) + + scopedIBCKeeper := appKeepers.CapabilityKeeper.ScopeToModule(ibcexported.ModuleName) + scopedICAHostKeeper := appKeepers.CapabilityKeeper.ScopeToModule(icahosttypes.SubModuleName) + scopedICAControllerKeeper := appKeepers.CapabilityKeeper.ScopeToModule(icacontrollertypes.SubModuleName) + scopedTransferKeeper := appKeepers.CapabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName) + scopedICQKeeper := appKeepers.CapabilityKeeper.ScopeToModule(icqtypes.ModuleName) + scopedWasmKeeper := appKeepers.CapabilityKeeper.ScopeToModule(wasmtypes.ModuleName) + + // add keepers + Bech32Prefix := "terp" + appKeepers.AccountKeeper = authkeeper.NewAccountKeeper( + appCodec, + keys[authtypes.StoreKey], + authtypes.ProtoBaseAccount, + maccPerms, + Bech32Prefix, + govModAddress, + ) + + appKeepers.BankKeeper = bankkeeper.NewBaseKeeper( + appCodec, + keys[banktypes.StoreKey], + appKeepers.AccountKeeper, + BlockedAddresses(), + govModAddress, + ) + + stakingKeeper := stakingkeeper.NewKeeper( + appCodec, + keys[stakingtypes.StoreKey], + appKeepers.AccountKeeper, + appKeepers.BankKeeper, + govModAddress, + ) + + appKeepers.MintKeeper = mintkeeper.NewKeeper( + appCodec, + appKeepers.keys[minttypes.StoreKey], + stakingKeeper, + appKeepers.AccountKeeper, + appKeepers.BankKeeper, + authtypes.FeeCollectorName, + govModAddress, + ) + + appKeepers.FeeGrantKeeper = feegrantkeeper.NewKeeper( + appCodec, + keys[feegrant.StoreKey], + appKeepers.AccountKeeper, + ) + + appKeepers.DistrKeeper = distrkeeper.NewKeeper( + appCodec, + appKeepers.keys[distrtypes.StoreKey], + appKeepers.AccountKeeper, + appKeepers.BankKeeper, + stakingKeeper, + authtypes.FeeCollectorName, + govModAddress, + ) + + appKeepers.SlashingKeeper = slashingkeeper.NewKeeper( + appCodec, + cdc, + appKeepers.keys[slashingtypes.StoreKey], + stakingKeeper, + govModAddress, + ) + + invCheckPeriod := cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)) + appKeepers.CrisisKeeper = crisiskeeper.NewKeeper( + appCodec, + keys[crisistypes.StoreKey], + invCheckPeriod, + appKeepers.BankKeeper, + authtypes.FeeCollectorName, + govModAddress, + ) + + // get skipUpgradeHeights from the app options + skipUpgradeHeights := map[int64]bool{} + for _, h := range cast.ToIntSlice(appOpts.Get(server.FlagUnsafeSkipUpgrades)) { + skipUpgradeHeights[int64(h)] = true + } + homePath := cast.ToString(appOpts.Get(flags.FlagHome)) + // set the governance module account as the authority for conducting upgrades + appKeepers.UpgradeKeeper = upgradekeeper.NewKeeper( + skipUpgradeHeights, + appKeepers.keys[upgradetypes.StoreKey], + appCodec, + homePath, + bApp, + govModAddress, + ) + + // register the staking hooks + // NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks + stakingKeeper.SetHooks( + stakingtypes.NewMultiStakingHooks(appKeepers.DistrKeeper.Hooks(), appKeepers.SlashingKeeper.Hooks()), + ) + appKeepers.StakingKeeper = stakingKeeper + + appKeepers.IBCKeeper = ibckeeper.NewKeeper( + appCodec, + appKeepers.keys[ibcexported.StoreKey], + appKeepers.GetSubspace(ibcexported.ModuleName), + appKeepers.StakingKeeper, + appKeepers.UpgradeKeeper, + scopedIBCKeeper, + ) + + + appKeepers.AuthzKeeper = authzkeeper.NewKeeper( + keys[authzkeeper.StoreKey], + appCodec, + bApp.MsgServiceRouter(), + appKeepers.AccountKeeper, + ) + + // Register the proposal types + govRouter := govv1beta1.NewRouter() + govRouter.AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler). + AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(appKeepers.ParamsKeeper)). // This should be removed. It is still in place to avoid failures of modules that have not yet been upgraded. + AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(appKeepers.UpgradeKeeper)). + AddRoute(ibcclienttypes.RouterKey, ibcclient.NewClientProposalHandler(appKeepers.IBCKeeper.ClientKeeper)) + + + govConfig := govtypes.DefaultConfig() + govKeeper := govkeeper.NewKeeper( + appCodec, + appKeepers.keys[govtypes.StoreKey], + appKeepers.AccountKeeper, + appKeepers.BankKeeper, + appKeepers.StakingKeeper, + bApp.MsgServiceRouter(), + govConfig, + govModAddress, + ) + appKeepers.GovKeeper = *govKeeper.SetHooks( + govtypes.NewMultiGovHooks( + // register the governance hooks + ), + ) + + groupConfig := group.DefaultConfig() + /* + Example of setting group params: + groupConfig.MaxMetadataLen = 1000 + */ + appKeepers.GroupKeeper = groupkeeper.NewKeeper(keys[group.StoreKey], appCodec, bApp.MsgServiceRouter(), appKeepers.AccountKeeper, groupConfig) + + appKeepers.NFTKeeper = nftkeeper.NewKeeper( + keys[nftkeeper.StoreKey], + appCodec, + appKeepers.AccountKeeper, + appKeepers.BankKeeper, + ) + + // Configure the hooks keeper + hooksKeeper := ibchookskeeper.NewKeeper( + keys[ibchookstypes.StoreKey], + ) + appKeepers.IBCHooksKeeper = &hooksKeeper + + terpPrefix := sdk.GetConfig().GetBech32AccountAddrPrefix() + wasmHooks := ibchooks.NewWasmHooks(appKeepers.IBCHooksKeeper, &appKeepers.WasmKeeper, terpPrefix) // The contract keeper needs to be set later // The contract keeper needs to be set later + appKeepers.Ics20WasmHooks = &wasmHooks + appKeepers.HooksICS4Wrapper = ibchooks.NewICS4Middleware( + appKeepers.IBCKeeper.ChannelKeeper, + appKeepers.Ics20WasmHooks, + ) + + // IBC Fee Module keeper + appKeepers.IBCFeeKeeper = ibcfeekeeper.NewKeeper( + appCodec, + appKeepers.keys[ibcfeetypes.StoreKey], + appKeepers.HooksICS4Wrapper, // replaced with IBC middleware + appKeepers.IBCKeeper.ChannelKeeper, + &appKeepers.IBCKeeper.PortKeeper, + appKeepers.AccountKeeper, + appKeepers.BankKeeper, + ) + + // Initialize packet forward middleware router + appKeepers.PacketForwardKeeper = packetforwardkeeper.NewKeeper( + appCodec, + appKeepers.keys[packetforwardtypes.StoreKey], + appKeepers.GetSubspace(packetforwardtypes.ModuleName), + appKeepers.TransferKeeper, // Will be zero-value here. Reference is set later on with SetTransferKeeper. + appKeepers.IBCKeeper.ChannelKeeper, + appKeepers.DistrKeeper, + appKeepers.BankKeeper, + appKeepers.IBCKeeper.ChannelKeeper, + ) + + // Create Transfer Keepers + appKeepers.TransferKeeper = ibctransferkeeper.NewKeeper( + appCodec, + appKeepers.keys[ibctransfertypes.StoreKey], + appKeepers.GetSubspace(ibctransfertypes.ModuleName), + // The ICS4Wrapper is replaced by the PacketForwardKeeper instead of the channel so that sending can be overridden by the middleware + appKeepers.PacketForwardKeeper, + appKeepers.IBCKeeper.ChannelKeeper, + &appKeepers.IBCKeeper.PortKeeper, + appKeepers.AccountKeeper, + appKeepers.BankKeeper, + scopedTransferKeeper, + ) + appKeepers.PacketForwardKeeper.SetTransferKeeper(appKeepers.TransferKeeper) + + // ICQ Keeper + appKeepers.ICQKeeper = icqkeeper.NewKeeper( + appCodec, + appKeepers.keys[icqtypes.StoreKey], + appKeepers.GetSubspace(icqtypes.ModuleName), + appKeepers.IBCKeeper.ChannelKeeper, // may be replaced with middleware + appKeepers.IBCKeeper.ChannelKeeper, + &appKeepers.IBCKeeper.PortKeeper, + scopedICQKeeper, + bApp.GRPCQueryRouter(), + ) + + appKeepers.ICAHostKeeper = icahostkeeper.NewKeeper( + appCodec, + appKeepers.keys[icahosttypes.StoreKey], + appKeepers.GetSubspace(icahosttypes.SubModuleName), + appKeepers.HooksICS4Wrapper, + appKeepers.IBCKeeper.ChannelKeeper, + &appKeepers.IBCKeeper.PortKeeper, + appKeepers.AccountKeeper, + scopedICAHostKeeper, + bApp.MsgServiceRouter(), + ) + + appKeepers.ICAControllerKeeper = icacontrollerkeeper.NewKeeper( + appCodec, + appKeepers.keys[icacontrollertypes.StoreKey], + appKeepers.GetSubspace(icacontrollertypes.SubModuleName), + appKeepers.IBCFeeKeeper, // use ics29 fee as ics4Wrapper in middleware stack + appKeepers.IBCKeeper.ChannelKeeper, + &appKeepers.IBCKeeper.PortKeeper, + scopedICAControllerKeeper, + bApp.MsgServiceRouter(), + ) + + // create evidence keeper with router + evidenceKeeper := evidencekeeper.NewKeeper( + appCodec, + appKeepers.keys[evidencetypes.StoreKey], + appKeepers.StakingKeeper, + appKeepers.SlashingKeeper, + ) + // If evidence needs to be handled for the app, set routes in router here and seal + appKeepers.EvidenceKeeper = *evidenceKeeper + + appKeepers.TokenFactoryKeeper = tokenfactorykeeper.NewKeeper( + appCodec, + appKeepers.keys[tokenfactorytypes.StoreKey], + appKeepers.AccountKeeper, + appKeepers.BankKeeper, + appKeepers.DistrKeeper, + tokenFactoryCapabilities, + govModAddress, + ) + + wasmDir := filepath.Join(homePath, "wasm") + wasmConfig, err := wasm.ReadWasmConfig(appOpts) + if err != nil { + panic(fmt.Sprintf("error while reading wasm config: %s", err)) + } + + tfOpts := bindings.RegisterCustomPlugins(&appKeepers.BankKeeper, &appKeepers.TokenFactoryKeeper) + wasmOpts = append(wasmOpts, tfOpts...) + + // Stargate Queries + accepted := wasmkeeper.AcceptedStargateQueries{ + // ibc + "/ibc.core.client.v1.Query/ClientState": &ibcclienttypes.QueryClientStateResponse{}, + "/ibc.core.client.v1.Query/ConsensusState": &ibcclienttypes.QueryConsensusStateResponse{}, + "/ibc.core.connection.v1.Query/Connection": &ibcconnectiontypes.QueryConnectionResponse{}, + + // governance + "/cosmos.gov.v1beta1.Query/Vote": &govv1.QueryVoteResponse{}, + + // distribution + "/cosmos.distribution.v1beta1.Query/DelegationRewards": &distrtypes.QueryDelegationRewardsResponse{}, + + // staking + "/cosmos.staking.v1beta1.Query/Delegation": &stakingtypes.QueryDelegationResponse{}, + "/cosmos.staking.v1beta1.Query/Redelegations": &stakingtypes.QueryRedelegationsResponse{}, + "/cosmos.staking.v1beta1.Query/UnbondingDelegation": &stakingtypes.QueryUnbondingDelegationResponse{}, + "/cosmos.staking.v1beta1.Query/Validator": &stakingtypes.QueryValidatorResponse{}, + "/cosmos.staking.v1beta1.Query/Params": &stakingtypes.QueryParamsResponse{}, + "/cosmos.staking.v1beta1.Query/Pool": &stakingtypes.QueryPoolResponse{}, + + // token factory + "/osmosis.tokenfactory.v1beta1.Query/Params": &tokenfactorytypes.QueryParamsResponse{}, + "/osmosis.tokenfactory.v1beta1.Query/DenomAuthorityMetadata": &tokenfactorytypes.QueryDenomAuthorityMetadataResponse{}, + "/osmosis.tokenfactory.v1beta1.Query/DenomsFromCreator": &tokenfactorytypes.QueryDenomsFromCreatorResponse{}, + } + querierOpts := wasmkeeper.WithQueryPlugins( + &wasmkeeper.QueryPlugins{ + Stargate: wasmkeeper.AcceptListStargateQuerier(accepted, bApp.GRPCQueryRouter(), appCodec), + }) + wasmOpts = append(wasmOpts, querierOpts) + + + appKeepers.WasmKeeper = wasmkeeper.NewKeeper( + appCodec, + appKeepers.keys[wasmtypes.StoreKey], + appKeepers.AccountKeeper, + appKeepers.BankKeeper, + appKeepers.StakingKeeper, + distrkeeper.NewQuerier(appKeepers.DistrKeeper), + appKeepers.IBCFeeKeeper, // ISC4 Wrapper: fee IBC middleware + appKeepers.IBCKeeper.ChannelKeeper, + &appKeepers.IBCKeeper.PortKeeper, + scopedWasmKeeper, + appKeepers.TransferKeeper, + bApp.MsgServiceRouter(), + bApp.GRPCQueryRouter(), + wasmDir, + wasmConfig, + wasmCapabilities, + govModAddress, + wasmOpts..., + ) + + // set the contract keeper for the Ics20WasmHooks + appKeepers.ContractKeeper = wasmkeeper.NewDefaultPermissionKeeper(appKeepers.WasmKeeper) + appKeepers.Ics20WasmHooks.ContractKeeper = &appKeepers.WasmKeeper + + + appKeepers.FeeShareKeeper = feesharekeeper.NewKeeper( + appKeepers.keys[feesharetypes.StoreKey], + appCodec, + appKeepers.BankKeeper, + appKeepers.WasmKeeper, + appKeepers.AccountKeeper, + authtypes.FeeCollectorName, + govModAddress, + ) + + + appKeepers.GlobalFeeKeeper = globalfeekeeper.NewKeeper( + appCodec, + appKeepers.keys[globalfeetypes.StoreKey], + govModAddress, + ) + + // The gov proposal types can be individually enabled + if len(enabledProposals) != 0 { + govRouter.AddRoute(wasmtypes.RouterKey, wasmkeeper.NewWasmProposalHandler(appKeepers.WasmKeeper, enabledProposals)) //nolint:staticcheck + } + + // Set legacy router for backwards compatibility with gov v1beta1 + appKeepers.GovKeeper.SetLegacyRouter(govRouter) + + // Create Transfer Stack + var transferStack porttypes.IBCModule + transferStack = transfer.NewIBCModule(appKeepers.TransferKeeper) + transferStack = ibcfee.NewIBCMiddleware(transferStack, appKeepers.IBCFeeKeeper) + transferStack = ibchooks.NewIBCMiddleware(transferStack, &appKeepers.HooksICS4Wrapper) + transferStack = packetforward.NewIBCMiddleware( + transferStack, + appKeepers.PacketForwardKeeper, + 0, + packetforwardkeeper.DefaultForwardTransferPacketTimeoutTimestamp, + packetforwardkeeper.DefaultRefundTransferPacketTimeoutTimestamp, + ) + + // Create Interchain Accounts Stack + // SendPacket, since it is originating from the application to core IBC: + // icaAuthModuleKeeper.SendTx -> icaController.SendPacket -> fee.SendPacket -> channel.SendPacket + var icaControllerStack porttypes.IBCModule + var noAuthzModule porttypes.IBCModule + icaControllerStack = icacontroller.NewIBCMiddleware(noAuthzModule, appKeepers.ICAControllerKeeper) + icaControllerStack = ibcfee.NewIBCMiddleware(icaControllerStack, appKeepers.IBCFeeKeeper) + + // RecvPacket, message that originates from core IBC and goes down to app, the flow is: + // channel.RecvPacket -> fee.OnRecvPacket -> icaHost.OnRecvPacket + var icaHostStack porttypes.IBCModule + icaHostStack = icahost.NewIBCModule(appKeepers.ICAHostKeeper) + icaHostStack = ibcfee.NewIBCMiddleware(icaHostStack, appKeepers.IBCFeeKeeper) + + // Create fee enabled wasm ibc Stack + var wasmStack porttypes.IBCModule + wasmStack = wasm.NewIBCHandler(appKeepers.WasmKeeper, appKeepers.IBCKeeper.ChannelKeeper, appKeepers.IBCFeeKeeper) + wasmStack = ibcfee.NewIBCMiddleware(wasmStack, appKeepers.IBCFeeKeeper) + + // create ICQ module + icqModule := icq.NewIBCModule(appKeepers.ICQKeeper) + + // Create static IBC router, add app routes, then set and seal it + ibcRouter := porttypes.NewRouter(). + AddRoute(ibctransfertypes.ModuleName, transferStack). + AddRoute(wasmtypes.ModuleName, wasmStack). + AddRoute(icacontrollertypes.SubModuleName, icaControllerStack). + AddRoute(icahosttypes.SubModuleName, icaHostStack). + AddRoute(icqtypes.ModuleName, icqModule) + appKeepers.IBCKeeper.SetRouter(ibcRouter) + + + appKeepers.ScopedIBCKeeper = scopedIBCKeeper + appKeepers.ScopedTransferKeeper = scopedTransferKeeper + appKeepers.ScopedWasmKeeper = scopedWasmKeeper + appKeepers.ScopedICQKeeper = scopedICQKeeper + appKeepers.ScopedICAHostKeeper = scopedICAHostKeeper + appKeepers.ScopedICAControllerKeeper = scopedICAControllerKeeper + + return appKeepers +} + +// initParamsKeeper init params keeper and its subspaces +func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, tkey storetypes.StoreKey) paramskeeper.Keeper { + paramsKeeper := paramskeeper.NewKeeper(appCodec, legacyAmino, key, tkey) + + paramsKeeper.Subspace(authtypes.ModuleName) + paramsKeeper.Subspace(banktypes.ModuleName) + paramsKeeper.Subspace(stakingtypes.ModuleName).WithKeyTable(stakingtypes.ParamKeyTable()) // Used for GlobalFee + paramsKeeper.Subspace(minttypes.ModuleName) + paramsKeeper.Subspace(distrtypes.ModuleName) + paramsKeeper.Subspace(slashingtypes.ModuleName) + paramsKeeper.Subspace(govtypes.ModuleName) + paramsKeeper.Subspace(crisistypes.ModuleName) + paramsKeeper.Subspace(ibctransfertypes.ModuleName) + paramsKeeper.Subspace(ibcexported.ModuleName) + paramsKeeper.Subspace(tokenfactorytypes.ModuleName) + paramsKeeper.Subspace(icahosttypes.SubModuleName) + paramsKeeper.Subspace(icacontrollertypes.SubModuleName) + paramsKeeper.Subspace(icqtypes.ModuleName) + paramsKeeper.Subspace(packetforwardtypes.ModuleName) + paramsKeeper.Subspace(globalfee.ModuleName) + paramsKeeper.Subspace(feesharetypes.ModuleName) + paramsKeeper.Subspace(wasmtypes.ModuleName) + + return paramsKeeper +} + +// GetSubspace returns a param subspace for a given module name. +// +// NOTE: This is solely to be used for testing purposes. +func (app *AppKeepers) GetSubspace(moduleName string) paramstypes.Subspace { + subspace, _ := app.ParamsKeeper.GetSubspace(moduleName) + return subspace +} + +// GetStakingKeeper implements the TestingApp interface. +func (appKeepers *AppKeepers) GetStakingKeeper() *stakingkeeper.Keeper { + return appKeepers.StakingKeeper +} + +// GetIBCKeeper implements the TestingApp interface. +func (appKeepers *AppKeepers) GetIBCKeeper() *ibckeeper.Keeper { + return appKeepers.IBCKeeper +} + +// GetScopedIBCKeeper implements the TestingApp interface. +func (appKeepers *AppKeepers) GetScopedIBCKeeper() capabilitykeeper.ScopedKeeper { + return appKeepers.ScopedIBCKeeper +} + +// GetWasmKeeper implements the TestingApp interface. +func (appKeepers *AppKeepers) GetWasmKeeper() wasmkeeper.Keeper { + return appKeepers.WasmKeeper +} + +// BlockedAddresses returns all the app's blocked account addresses. +func BlockedAddresses() map[string]bool { + modAccAddrs := make(map[string]bool) + for acc := range GetMaccPerms() { + modAccAddrs[authtypes.NewModuleAddress(acc).String()] = true + } + + // allow the following addresses to receive funds + delete(modAccAddrs, authtypes.NewModuleAddress(govtypes.ModuleName).String()) + + return modAccAddrs +} + + +// GetMaccPerms returns a copy of the module account permissions +// +// NOTE: This is solely to be used for testing purposes. +func GetMaccPerms() map[string][]string { + dupMaccPerms := make(map[string][]string) + for k, v := range maccPerms { + dupMaccPerms[k] = v + } + + return dupMaccPerms +} \ No newline at end of file diff --git a/app/keepers/keys.go b/app/keepers/keys.go new file mode 100644 index 0000000..ca7012d --- /dev/null +++ b/app/keepers/keys.go @@ -0,0 +1,114 @@ +package keepers + +import ( + storetypes "github.com/cosmos/cosmos-sdk/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" + consensusparamtypes "github.com/cosmos/cosmos-sdk/x/consensus/types" + crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" + evidencetypes "github.com/cosmos/cosmos-sdk/x/evidence/types" + "github.com/cosmos/cosmos-sdk/x/feegrant" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + nftkeeper "github.com/cosmos/cosmos-sdk/x/nft/keeper" + paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" + slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + ibcfeetypes "github.com/cosmos/ibc-go/v7/modules/apps/29-fee/types" + ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" + minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" + "github.com/cosmos/cosmos-sdk/x/group" + icahosttypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/host/types" + icacontrollertypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller/types" + packetforwardtypes "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7/router/types" + feesharetypes "github.com/terpnetwork/terp-core/v2/x/feeshare/types" + globalfeetypes "github.com/terpnetwork/terp-core/v2/x/globalfee/types" + tokenfactorytypes "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" + + ibchookstypes "github.com/cosmos/ibc-apps/modules/ibc-hooks/v7/types" + ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" + wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" + icqtypes "github.com/cosmos/ibc-apps/modules/async-icq/v7/types" + + + + + +) + +func (appKeepers *AppKeepers) GenerateKeys() { + appKeepers.keys = sdk.NewKVStoreKeys( + authtypes.StoreKey, + banktypes.StoreKey, + stakingtypes.StoreKey, + crisistypes.StoreKey, + minttypes.StoreKey, + distrtypes.StoreKey, + slashingtypes.StoreKey, + govtypes.StoreKey, + paramstypes.StoreKey, + consensusparamtypes.StoreKey, + upgradetypes.StoreKey, + feegrant.StoreKey, + evidencetypes.StoreKey, + capabilitytypes.StoreKey, + authzkeeper.StoreKey, + nftkeeper.StoreKey, + group.StoreKey, + // non sdk store keys + ibcexported.StoreKey, + ibctransfertypes.StoreKey, + ibcfeetypes.StoreKey, + wasmtypes.StoreKey, + icahosttypes.StoreKey, + icacontrollertypes.StoreKey, + icqtypes.StoreKey, + packetforwardtypes.StoreKey, + ibchookstypes.StoreKey, + feesharetypes.StoreKey, + globalfeetypes.StoreKey, + tokenfactorytypes.StoreKey, + ) + + + appKeepers.tkeys = sdk.NewTransientStoreKeys(paramstypes.TStoreKey) + appKeepers.memKeys = sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) +} + +func (appKeepers *AppKeepers) GetKVStoreKey() map[string]*storetypes.KVStoreKey { + return appKeepers.keys +} + +func (appKeepers *AppKeepers) GetTransientStoreKey() map[string]*storetypes.TransientStoreKey { + return appKeepers.tkeys +} + + +func (appKeepers *AppKeepers) GetMemoryStoreKey() map[string]*storetypes.MemoryStoreKey { + return appKeepers.memKeys +} + +// GetKey returns the KVStoreKey for the provided store key. +// +// NOTE: This is solely to be used for testing purposes. +func (appKeepers *AppKeepers) GetKey(storeKey string) *storetypes.KVStoreKey { + return appKeepers.keys[storeKey] +} + +// GetTKey returns the TransientStoreKey for the provided store key. +// +// NOTE: This is solely to be used for testing purposes. +func (appKeepers *AppKeepers) GetTKey(storeKey string) *storetypes.TransientStoreKey { + return appKeepers.tkeys[storeKey] +} + +// GetMemKey returns the MemStoreKey for the provided mem key. +// +// NOTE: This is solely used for testing purposes. +func (appKeepers *AppKeepers) GetMemKey(storeKey string) *storetypes.MemoryStoreKey { + return appKeepers.memKeys[storeKey] +} \ No newline at end of file diff --git a/app/modules.go b/app/modules.go new file mode 100644 index 0000000..ae8925f --- /dev/null +++ b/app/modules.go @@ -0,0 +1,285 @@ +package app +import ( + wasm "github.com/CosmWasm/wasmd/x/wasm" + wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" + + packetforward "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7/router" + packetforwardtypes "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7/router/types" + icq "github.com/cosmos/ibc-apps/modules/async-icq/v7" + icqtypes "github.com/cosmos/ibc-apps/modules/async-icq/v7/types" + ica "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts" + icatypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/types" + ibcfee "github.com/cosmos/ibc-go/v7/modules/apps/29-fee" + ibcfeetypes "github.com/cosmos/ibc-go/v7/modules/apps/29-fee/types" + transfer "github.com/cosmos/ibc-go/v7/modules/apps/transfer" + ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" + ibc "github.com/cosmos/ibc-go/v7/modules/core" + ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" + ibctm "github.com/cosmos/ibc-go/v7/modules/light-clients/07-tendermint" + + mint "github.com/cosmos/cosmos-sdk/x/mint" + minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" + + + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/auth" + authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" + "github.com/cosmos/cosmos-sdk/x/authz" + authzmodule "github.com/cosmos/cosmos-sdk/x/authz/module" + "github.com/cosmos/cosmos-sdk/x/bank" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/cosmos/cosmos-sdk/x/capability" + capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" + "github.com/cosmos/cosmos-sdk/x/consensus" + consensusparamtypes "github.com/cosmos/cosmos-sdk/x/consensus/types" + "github.com/cosmos/cosmos-sdk/x/crisis" + crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" + distr "github.com/cosmos/cosmos-sdk/x/distribution" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" + "github.com/cosmos/cosmos-sdk/x/evidence" + evidencetypes "github.com/cosmos/cosmos-sdk/x/evidence/types" + "github.com/cosmos/cosmos-sdk/x/feegrant" + feegrantmodule "github.com/cosmos/cosmos-sdk/x/feegrant/module" + "github.com/cosmos/cosmos-sdk/x/genutil" + genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" + "github.com/cosmos/cosmos-sdk/x/gov" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/nft" + nftmodule "github.com/cosmos/cosmos-sdk/x/nft/module" + "github.com/cosmos/cosmos-sdk/x/params" + paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" + "github.com/cosmos/cosmos-sdk/x/slashing" + slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" + "github.com/cosmos/cosmos-sdk/x/staking" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/cosmos/cosmos-sdk/x/upgrade" + upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + + encparams "github.com/terpnetwork/terp-core/v2/app/params" + "github.com/terpnetwork/terp-core/v2/x/feeshare" + feesharetypes "github.com/terpnetwork/terp-core/v2/x/feeshare/types" + "github.com/terpnetwork/terp-core/v2/x/globalfee" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory" + + tokenfactorytypes "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" + ibchooks "github.com/cosmos/ibc-apps/modules/ibc-hooks/v7" + ibchookstypes "github.com/cosmos/ibc-apps/modules/ibc-hooks/v7/types" + "github.com/cosmos/cosmos-sdk/x/group" + + groupmodule "github.com/cosmos/cosmos-sdk/x/group/module" +) + +// ModuleBasics defines the module BasicManager is in charge of setting up basic, +// non-dependant module elements, such as codec registration +// and genesis verification. +var ModuleBasics = module.NewBasicManager( + auth.AppModuleBasic{}, + genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator), + bank.AppModuleBasic{}, + capability.AppModuleBasic{}, + staking.AppModuleBasic{}, + mint.AppModuleBasic{}, + distr.AppModuleBasic{}, + gov.NewAppModuleBasic(getGovProposalHandlers()), + params.AppModuleBasic{}, + crisis.AppModuleBasic{}, + slashing.AppModuleBasic{}, + feegrantmodule.AppModuleBasic{}, + upgrade.AppModuleBasic{}, + evidence.AppModuleBasic{}, + authzmodule.AppModuleBasic{}, + groupmodule.AppModuleBasic{}, + vesting.AppModuleBasic{}, + nftmodule.AppModuleBasic{}, + consensus.AppModuleBasic{}, + // non sdk modules + wasm.AppModuleBasic{}, + ibc.AppModuleBasic{}, + ibctm.AppModuleBasic{}, + transfer.AppModuleBasic{}, + ica.AppModuleBasic{}, + ibcfee.AppModuleBasic{}, + icq.AppModuleBasic{}, + ibchooks.AppModuleBasic{}, + packetforward.AppModuleBasic{}, + feeshare.AppModuleBasic{}, + globalfee.AppModuleBasic{}, + tokenfactory.AppModuleBasic{}, +) + +func appModules( + app *TerpApp, + encodingConfig encparams.EncodingConfig, + skipGenesisInvariants bool, +) []module.AppModule { + appCodec := encodingConfig.Marshaler + + bondDenom := app.GetChainBondDenom() + + return []module.AppModule{ + genutil.NewAppModule( + app.AppKeepers.AccountKeeper, + app.AppKeepers.StakingKeeper, + app.BaseApp.DeliverTx, + encodingConfig.TxConfig, + ), + auth.NewAppModule(appCodec, app.AppKeepers.AccountKeeper, authsims.RandomGenesisAccounts, app.GetSubspace(authtypes.ModuleName)), + vesting.NewAppModule(app.AppKeepers.AccountKeeper, app.AppKeepers.BankKeeper), + bank.NewAppModule(appCodec, app.AppKeepers.BankKeeper, app.AppKeepers.AccountKeeper, app.GetSubspace(banktypes.ModuleName)), + capability.NewAppModule(appCodec, *app.AppKeepers.CapabilityKeeper, false), + feegrantmodule.NewAppModule(appCodec, app.AppKeepers.AccountKeeper, app.AppKeepers.BankKeeper, app.AppKeepers.FeeGrantKeeper, app.interfaceRegistry), + gov.NewAppModule(appCodec, &app.AppKeepers.GovKeeper, app.AppKeepers.AccountKeeper, app.AppKeepers.BankKeeper, app.GetSubspace(govtypes.ModuleName)), + mint.NewAppModule(appCodec, app.AppKeepers.MintKeeper, app.AppKeepers.AccountKeeper, nil, app.GetSubspace(minttypes.ModuleName)), + slashing.NewAppModule(appCodec, app.AppKeepers.SlashingKeeper, app.AppKeepers.AccountKeeper, app.AppKeepers.BankKeeper, app.AppKeepers.StakingKeeper, app.GetSubspace(slashingtypes.ModuleName)), + distr.NewAppModule(appCodec, app.AppKeepers.DistrKeeper, app.AppKeepers.AccountKeeper, app.AppKeepers.BankKeeper, app.AppKeepers.StakingKeeper, app.GetSubspace(distrtypes.ModuleName)), + staking.NewAppModule(appCodec, app.AppKeepers.StakingKeeper, app.AppKeepers.AccountKeeper, app.AppKeepers.BankKeeper, app.GetSubspace(stakingtypes.ModuleName)), + upgrade.NewAppModule(app.AppKeepers.UpgradeKeeper), + evidence.NewAppModule(app.AppKeepers.EvidenceKeeper), + params.NewAppModule(app.AppKeepers.ParamsKeeper), + authzmodule.NewAppModule(appCodec, app.AppKeepers.AuthzKeeper, app.AppKeepers.AccountKeeper, app.AppKeepers.BankKeeper, app.interfaceRegistry), + groupmodule.NewAppModule(appCodec, app.AppKeepers.GroupKeeper, app.AppKeepers.AccountKeeper, app.AppKeepers.BankKeeper, app.interfaceRegistry), + nftmodule.NewAppModule(appCodec, app.AppKeepers.NFTKeeper, app.AppKeepers.AccountKeeper, app.AppKeepers.BankKeeper, app.interfaceRegistry), + consensus.NewAppModule(appCodec, app.AppKeepers.ConsensusParamsKeeper), + feeshare.NewAppModule(app.AppKeepers.FeeShareKeeper, app.AppKeepers.AccountKeeper, app.GetSubspace(feesharetypes.ModuleName)), + globalfee.NewAppModule(appCodec, app.AppKeepers.GlobalFeeKeeper, bondDenom), + tokenfactory.NewAppModule(app.AppKeepers.TokenFactoryKeeper, app.AppKeepers.AccountKeeper, app.AppKeepers.BankKeeper, app.GetSubspace(tokenfactorytypes.ModuleName)), + wasm.NewAppModule(appCodec, &app.AppKeepers.WasmKeeper, app.AppKeepers.StakingKeeper, app.AppKeepers.AccountKeeper, app.AppKeepers.BankKeeper, app.MsgServiceRouter(), app.GetSubspace(wasmtypes.ModuleName)), + ibc.NewAppModule(app.AppKeepers.IBCKeeper), + transfer.NewAppModule(app.AppKeepers.TransferKeeper), + ibcfee.NewAppModule(app.AppKeepers.IBCFeeKeeper), + ica.NewAppModule(&app.AppKeepers.ICAControllerKeeper, &app.AppKeepers.ICAHostKeeper), + icq.NewAppModule(app.AppKeepers.ICQKeeper), + packetforward.NewAppModule(app.AppKeepers.PacketForwardKeeper), + ibchooks.NewAppModule(app.AppKeepers.AccountKeeper), + crisis.NewAppModule(app.AppKeepers.CrisisKeeper, skipGenesisInvariants, app.GetSubspace(crisistypes.ModuleName)), // always be last to make sure that it checks for all invariants and not only part of them + } +} + +func simulationModules( + app *TerpApp, + encodingConfig encparams.EncodingConfig, + _ bool, +) []module.AppModuleSimulation { + appCodec := encodingConfig.Marshaler + + // bondDenom := app.GetChainBondDenom() + + return []module.AppModuleSimulation{ + auth.NewAppModule(appCodec, app.AppKeepers.AccountKeeper, authsims.RandomGenesisAccounts, app.GetSubspace(authtypes.ModuleName)), + bank.NewAppModule(appCodec, app.AppKeepers.BankKeeper, app.AppKeepers.AccountKeeper, app.GetSubspace(banktypes.ModuleName)), + capability.NewAppModule(appCodec, *app.AppKeepers.CapabilityKeeper, false), + feegrantmodule.NewAppModule(appCodec, app.AppKeepers.AccountKeeper, app.AppKeepers.BankKeeper, app.AppKeepers.FeeGrantKeeper, app.interfaceRegistry), + authzmodule.NewAppModule(appCodec, app.AppKeepers.AuthzKeeper, app.AppKeepers.AccountKeeper, app.AppKeepers.BankKeeper, app.interfaceRegistry), + gov.NewAppModule(appCodec, &app.AppKeepers.GovKeeper, app.AppKeepers.AccountKeeper, app.AppKeepers.BankKeeper, app.GetSubspace(govtypes.ModuleName)), + mint.NewAppModule(appCodec, app.AppKeepers.MintKeeper, app.AppKeepers.AccountKeeper, nil, app.GetSubspace(minttypes.ModuleName)), + staking.NewAppModule(appCodec, app.AppKeepers.StakingKeeper, app.AppKeepers.AccountKeeper, app.AppKeepers.BankKeeper, app.GetSubspace(stakingtypes.ModuleName)), + distr.NewAppModule(appCodec, app.AppKeepers.DistrKeeper, app.AppKeepers.AccountKeeper, app.AppKeepers.BankKeeper, app.AppKeepers.StakingKeeper, app.GetSubspace(distrtypes.ModuleName)), + slashing.NewAppModule(appCodec, app.AppKeepers.SlashingKeeper, app.AppKeepers.AccountKeeper, app.AppKeepers.BankKeeper, app.AppKeepers.StakingKeeper, app.GetSubspace(stakingtypes.ModuleName)), + params.NewAppModule(app.AppKeepers.ParamsKeeper), + evidence.NewAppModule(app.AppKeepers.EvidenceKeeper), + wasm.NewAppModule(appCodec, &app.AppKeepers.WasmKeeper, app.AppKeepers.StakingKeeper, app.AppKeepers.AccountKeeper, app.AppKeepers.BankKeeper, app.MsgServiceRouter(), app.GetSubspace(wasmtypes.ModuleName)), + ibc.NewAppModule(app.AppKeepers.IBCKeeper), + transfer.NewAppModule(app.AppKeepers.TransferKeeper), + feeshare.NewAppModule(app.AppKeepers.FeeShareKeeper, app.AppKeepers.AccountKeeper, app.GetSubspace(feesharetypes.ModuleName)), + ibcfee.NewAppModule(app.AppKeepers.IBCFeeKeeper), + } +} + +func orderBeginBlockers() []string { + return []string{ + upgradetypes.ModuleName, + capabilitytypes.ModuleName, + minttypes.ModuleName, + distrtypes.ModuleName, + slashingtypes.ModuleName, + evidencetypes.ModuleName, + stakingtypes.ModuleName, + authtypes.ModuleName, + banktypes.ModuleName, + govtypes.ModuleName, + crisistypes.ModuleName, + genutiltypes.ModuleName, + authz.ModuleName, + feegrant.ModuleName, + nft.ModuleName, + group.ModuleName, + paramstypes.ModuleName, + vestingtypes.ModuleName, + consensusparamtypes.ModuleName, + // additional non simd modules + ibctransfertypes.ModuleName, + ibcexported.ModuleName, + icatypes.ModuleName, + ibcfeetypes.ModuleName, + icqtypes.ModuleName, + packetforwardtypes.ModuleName, + feesharetypes.ModuleName, + globalfee.ModuleName, + ibchookstypes.ModuleName, + tokenfactorytypes.ModuleName, + wasmtypes.ModuleName, + } +} + + +func orderEndBlockers() []string { + return []string{ + crisistypes.ModuleName, + govtypes.ModuleName, + stakingtypes.ModuleName, + capabilitytypes.ModuleName, + authtypes.ModuleName, + banktypes.ModuleName, + distrtypes.ModuleName, + slashingtypes.ModuleName, + minttypes.ModuleName, + genutiltypes.ModuleName, + evidencetypes.ModuleName, + authz.ModuleName, + feegrant.ModuleName, + nft.ModuleName, + group.ModuleName, + paramstypes.ModuleName, + upgradetypes.ModuleName, + vestingtypes.ModuleName, + consensusparamtypes.ModuleName, + // additional non simd modules + ibctransfertypes.ModuleName, + ibcexported.ModuleName, + icatypes.ModuleName, + ibcfeetypes.ModuleName, + icqtypes.ModuleName, + packetforwardtypes.ModuleName, + feesharetypes.ModuleName, + globalfee.ModuleName, + ibchookstypes.ModuleName, + tokenfactorytypes.ModuleName, + wasmtypes.ModuleName, + } +} + +func orderInitBlockers() []string { + return []string{ + capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, + distrtypes.ModuleName, stakingtypes.ModuleName, slashingtypes.ModuleName, govtypes.ModuleName, + minttypes.ModuleName, crisistypes.ModuleName, genutiltypes.ModuleName, evidencetypes.ModuleName, authz.ModuleName, + feegrant.ModuleName, nft.ModuleName, group.ModuleName, paramstypes.ModuleName, upgradetypes.ModuleName, + vestingtypes.ModuleName, consensusparamtypes.ModuleName, + // additional non simd modules + ibctransfertypes.ModuleName, + ibcexported.ModuleName, + icatypes.ModuleName, + ibcfeetypes.ModuleName, + // wasm after ibc transfer + feesharetypes.ModuleName, + globalfee.ModuleName, + icqtypes.ModuleName, + packetforwardtypes.ModuleName, + ibchookstypes.ModuleName, + tokenfactorytypes.ModuleName, + wasmtypes.ModuleName, + } +} \ No newline at end of file diff --git a/app/test_helpers.go b/app/test_helpers.go index 829d1c5..0148173 100644 --- a/app/test_helpers.go +++ b/app/test_helpers.go @@ -94,8 +94,8 @@ func Setup(t *testing.T) *TerpApp { // SetupWithGenesisValSet initializes a new junoApp with a validator set and genesis accounts // that also act as delegators. For simplicity, each validator is bonded with a delegation -// of one consensus engine unit in the default token of the JunoApp from first genesis -// account. A Nop logger is set in JunoApp. +// of one consensus engine unit in the default token of the TerpApp from first genesis +// account. A Nop logger is set in TerpApp. func SetupWithGenesisValSet(t *testing.T, valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) *TerpApp { t.Helper() @@ -259,7 +259,7 @@ func ExecuteRawCustom(t *testing.T, ctx sdk.Context, app *TerpApp, contract sdk. coins = sdk.Coins{funds} } - contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(app.WasmKeeper) + contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(app.AppKeepers.WasmKeeper) _, err = contractKeeper.Execute(ctx, contract, sender, oracleBz, coins) return err } diff --git a/app/upgrades/types.go b/app/upgrades/types.go index 61e1d65..0d820b0 100644 --- a/app/upgrades/types.go +++ b/app/upgrades/types.go @@ -2,8 +2,44 @@ package upgrades import ( "strings" + + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + + store "github.com/cosmos/cosmos-sdk/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + + "github.com/terpnetwork/terp-core/v2/app/keepers" + ) +// BaseAppParamManager defines an interrace that BaseApp is expected to fullfil +// that allows upgrade handlers to modify BaseApp parameters. +type BaseAppParamManager interface { + GetConsensusParams(ctx sdk.Context) *tmproto.ConsensusParams + StoreConsensusParams(ctx sdk.Context, cp *tmproto.ConsensusParams) +} + +// Upgrade defines a struct containing necessary fields that a SoftwareUpgradeProposal +// must have written, in order for the state migration to go smoothly. +// An upgrade must implement this struct, and then set it in the app.go. +// The app.go will then define the handler. +type Upgrade struct { + // Upgrade version name, for the upgrade handler, e.g. `v7` + UpgradeName string + + // CreateUpgradeHandler defines the function that creates an upgrade handler + CreateUpgradeHandler func( + *module.Manager, + module.Configurator, + *keepers.AppKeepers, + ) upgradetypes.UpgradeHandler + + // Store upgrades, should be used for any new modules introduced, new modules deleted, or store names renamed. + StoreUpgrades store.StoreUpgrades +} + func GetChainsDenomToken(chainID string) string { if strings.HasPrefix(chainID, "90u-") { return "uterpx" diff --git a/app/upgrades/v2/constants.go b/app/upgrades/v2/constants.go index 589c712..d46916d 100644 --- a/app/upgrades/v2/constants.go +++ b/app/upgrades/v2/constants.go @@ -1,5 +1,30 @@ package v2 -const ( - UpgradeName = "v2" +import ( + feesharetypes "github.com/terpnetwork/terp-core/v2/x/feeshare/types" + globalfeetypes "github.com/terpnetwork/terp-core/v2/x/globalfee/types" + packetforwardtypes "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7/router/types" + ibchookstypes "github.com/cosmos/ibc-apps/modules/ibc-hooks/v7/types" + icqtypes "github.com/cosmos/ibc-apps/modules/async-icq/v7/types" + + + store "github.com/cosmos/cosmos-sdk/store/types" + + "github.com/terpnetwork/terp-core/v2/app/upgrades" + ) +const UpgradeName = "v2" + +var Upgrade = upgrades.Upgrade{ + UpgradeName: UpgradeName, + CreateUpgradeHandler: CreateV2UpgradeHandler, + StoreUpgrades: store.StoreUpgrades{ + Added: []string{ + feesharetypes.ModuleName, + globalfeetypes.ModuleName, + packetforwardtypes.StoreKey, + ibchookstypes.StoreKey, + icqtypes.ModuleName, + }, + }, +} \ No newline at end of file diff --git a/app/upgrades/v2/upgrade.go b/app/upgrades/v2/upgrade.go index 18234aa..29f6a5f 100644 --- a/app/upgrades/v2/upgrade.go +++ b/app/upgrades/v2/upgrade.go @@ -7,21 +7,18 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - feesharekeeper "github.com/terpnetwork/terp-core/v2/x/feeshare/keeper" + feesharetypes "github.com/terpnetwork/terp-core/v2/x/feeshare/types" - globalfeekeeper "github.com/terpnetwork/terp-core/v2/x/globalfee/keeper" globalfeetypes "github.com/terpnetwork/terp-core/v2/x/globalfee/types" - tokenfactorykeeper "github.com/terpnetwork/terp-core/v2/x/tokenfactory/keeper" tokenfactorytypes "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" - icqkeeper "github.com/cosmos/ibc-apps/modules/async-icq/v7/keeper" icqtypes "github.com/cosmos/ibc-apps/modules/async-icq/v7/types" - packetforwardkeeper "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7/router/keeper" packetforwardtypes "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7/router/types" + "github.com/terpnetwork/terp-core/v2/app/keepers" "github.com/terpnetwork/terp-core/v2/app/upgrades" ) @@ -29,17 +26,22 @@ import ( const NewDenomCreationGasConsume uint64 = 2_000_000 // CreateUpgradeHandler creates an SDK upgrade handler for v2 -func CreateUpgradeHandler( +func CreateV2UpgradeHandler( mm *module.Manager, - configurator module.Configurator, - fsk feesharekeeper.Keeper, - gfk globalfeekeeper.Keeper, - tfk tokenfactorykeeper.Keeper, - icqk icqkeeper.Keeper, - pfk packetforwardkeeper.Keeper, + cfg module.Configurator, + keepers *keepers.AppKeepers, ) upgradetypes.UpgradeHandler { return func(ctx sdk.Context, _ upgradetypes.Plan, vm module.VersionMap) (module.VersionMap, error) { logger := ctx.Logger().With("upgrade", UpgradeName) + + // Run migrations + logger.Info(fmt.Sprintf("pre migrate version map: %v", vm)) + versionMap, err := mm.RunMigrations(ctx, cfg, vm) + if err != nil { + return nil, err + } + logger.Info(fmt.Sprintf("post migrate version map: %v", versionMap)) + nativeDenom := upgrades.GetChainsDenomToken(ctx.ChainID()) logger.Info(fmt.Sprintf("With native denom %s", nativeDenom)) @@ -50,7 +52,7 @@ func CreateUpgradeHandler( DeveloperShares: sdk.NewDecWithPrec(50, 2), // = 50% AllowedDenoms: []string{nativeDenom}, } - if err := fsk.SetParams(ctx, newFeeShareParams); err != nil { + if err := keepers.FeeShareKeeper.SetParams(ctx, newFeeShareParams); err != nil { return nil, err } logger.Info("set feeshare params") @@ -63,7 +65,7 @@ func CreateUpgradeHandler( newGlobalFeeParams := globalfeetypes.Params{ MinimumGasPrices: minGasPrices, } - if err := gfk.SetParams(ctx, newGlobalFeeParams); err != nil { + if err := keepers.GlobalFeeKeeper.SetParams(ctx, newGlobalFeeParams); err != nil { return nil, err } logger.Info(fmt.Sprintf("upgraded global fee params to %s", minGasPrices)) @@ -75,20 +77,20 @@ func CreateUpgradeHandler( DenomCreationGasConsume: NewDenomCreationGasConsume, } - if err := tfk.SetParams(ctx, updatedTf); err != nil { + if err := keepers.TokenFactoryKeeper.SetParams(ctx, updatedTf); err != nil { return nil, err } logger.Info(fmt.Sprintf("updated tokenfactory params to %v", updatedTf)) // // Interchain Queries icqParams := icqtypes.NewParams(true, nil) - icqk.SetParams(ctx, icqParams) + keepers.ICQKeeper.SetParams(ctx, icqParams) // Packet Forward middleware initial params - pfk.SetParams(ctx, packetforwardtypes.DefaultParams()) + keepers.PacketForwardKeeper.SetParams(ctx, packetforwardtypes.DefaultParams()) // Leave modules are as-is to avoid running InitGenesis. logger.Debug("running module migrations ...") - return mm.RunMigrations(ctx, configurator, vm) + return versionMap, err } } diff --git a/app/wasm_config.go b/app/wasm_config.go new file mode 100644 index 0000000..eb9cac7 --- /dev/null +++ b/app/wasm_config.go @@ -0,0 +1,25 @@ +package app + +import ( + wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" +) + +const ( + // DefaultTerpInstanceCost is initially set the same as in wasmd + DefaultTerpInstanceCost uint64 = 60_000 + // DefaultTerpCompileCost set to a large number for testing + DefaultTerpCompileCost uint64 = 3 +) + +// TerpGasRegisterConfig is defaults plus a custom compile amount +func TerpGasRegisterConfig() wasmkeeper.WasmGasRegisterConfig { + gasConfig := wasmkeeper.DefaultGasRegisterConfig() + gasConfig.InstanceCost = DefaultTerpInstanceCost + gasConfig.CompileCost = DefaultTerpCompileCost + + return gasConfig +} + +func NewTerpWasmGasRegister() wasmkeeper.WasmGasRegister { + return wasmkeeper.NewWasmGasRegister(TerpGasRegisterConfig()) +} diff --git a/x/feeshare/keeper/keeper_test.go b/x/feeshare/keeper/keeper_test.go index 9144caa..5c2b10e 100644 --- a/x/feeshare/keeper/keeper_test.go +++ b/x/feeshare/keeper/keeper_test.go @@ -51,12 +51,12 @@ func (s *IntegrationTestSuite) SetupTest() { }) queryHelper := baseapp.NewQueryServerTestHelper(s.ctx, s.app.InterfaceRegistry()) - types.RegisterQueryServer(queryHelper, keeper.NewQuerier(s.app.FeeShareKeeper)) + types.RegisterQueryServer(queryHelper, keeper.NewQuerier(s.app.AppKeepers.FeeShareKeeper)) s.queryClient = types.NewQueryClient(queryHelper) - s.bankKeeper = s.app.BankKeeper - s.accountKeeper = s.app.AccountKeeper - s.feeShareMsgServer = s.app.FeeShareKeeper + s.bankKeeper = s.app.AppKeepers.BankKeeper + s.accountKeeper = s.app.AppKeepers.AccountKeeper + s.feeShareMsgServer = s.app.AppKeepers.FeeShareKeeper s.wasmMsgServer = wasmkeeper.NewMsgServerImpl(&s.app.WasmKeeper) } diff --git a/x/feeshare/keeper/msg_server_test.go b/x/feeshare/keeper/msg_server_test.go index 7fa8116..9b145d9 100644 --- a/x/feeshare/keeper/msg_server_test.go +++ b/x/feeshare/keeper/msg_server_test.go @@ -30,7 +30,7 @@ func (s *IntegrationTestSuite) StoreCode() { expHash := sha256.Sum256(wasmContract) s.Require().Equal(expHash[:], result.Checksum) // and - info := s.app.WasmKeeper.GetCodeInfo(s.ctx, 1) + info := s.app.AppKeepers.WasmKeeper.GetCodeInfo(s.ctx, 1) s.Require().NotNil(info) s.Require().Equal(expHash[:], info.CodeHash) s.Require().Equal(sender.String(), info.Creator) @@ -54,7 +54,7 @@ func (s *IntegrationTestSuite) InstantiateContract(sender string, admin string) s.Require().NoError(err) var result wasmtypes.MsgInstantiateContractResponse s.Require().NoError(s.app.AppCodec().Unmarshal(resp.Data, &result)) - contractInfo := s.app.WasmKeeper.GetContractInfo(s.ctx, sdk.MustAccAddressFromBech32(result.Address)) + contractInfo := s.app.AppKeepers.WasmKeeper.GetContractInfo(s.ctx, sdk.MustAccAddressFromBech32(result.Address)) s.Require().Equal(contractInfo.CodeID, uint64(1)) s.Require().Equal(contractInfo.Admin, admin) s.Require().Equal(contractInfo.Creator, sender) @@ -99,10 +99,10 @@ func (s *IntegrationTestSuite) TestGetContractAdminOrCreatorAddress() { tc := tc s.Run(tc.desc, func() { if !tc.shouldErr { - _, err := s.app.FeeShareKeeper.GetContractAdminOrCreatorAddress(s.ctx, sdk.MustAccAddressFromBech32(tc.contractAddress), tc.deployerAddress) + _, err := s.app.AppKeepers.FeeShareKeeper.GetContractAdminOrCreatorAddress(s.ctx, sdk.MustAccAddressFromBech32(tc.contractAddress), tc.deployerAddress) s.Require().NoError(err) } else { - _, err := s.app.FeeShareKeeper.GetContractAdminOrCreatorAddress(s.ctx, sdk.MustAccAddressFromBech32(tc.contractAddress), tc.deployerAddress) + _, err := s.app.AppKeepers.FeeShareKeeper.GetContractAdminOrCreatorAddress(s.ctx, sdk.MustAccAddressFromBech32(tc.contractAddress), tc.deployerAddress) s.Require().Error(err) } }) diff --git a/x/tokenfactory/bindings/custom_msg_test.go b/x/tokenfactory/bindings/custom_msg_test.go index 22d56d7..6d8e469 100644 --- a/x/tokenfactory/bindings/custom_msg_test.go +++ b/x/tokenfactory/bindings/custom_msg_test.go @@ -60,7 +60,7 @@ func TestMintMsg(t *testing.T) { fundAccount(t, ctx, terpapp, reflect, reflectAmount) // lucky was broke - balances := terpapp.BankKeeper.GetAllBalances(ctx, lucky) + balances := terpapp.AppKeepers.BankKeeper.GetAllBalances(ctx, lucky) require.Empty(t, balances) // Create denom for minting @@ -81,7 +81,7 @@ func TestMintMsg(t *testing.T) { err = executeCustom(t, ctx, terpapp, reflect, lucky, msg, sdk.Coin{}) require.NoError(t, err) - balances = terpapp.BankKeeper.GetAllBalances(ctx, lucky) + balances = terpapp.AppKeepers.BankKeeper.GetAllBalances(ctx, lucky) require.Len(t, balances, 1) coin := balances[0] require.Equal(t, amount, coin.Amount) @@ -103,7 +103,7 @@ func TestMintMsg(t *testing.T) { err = executeCustom(t, ctx, terpapp, reflect, lucky, msg, sdk.Coin{}) require.NoError(t, err) - balances = terpapp.BankKeeper.GetAllBalances(ctx, lucky) + balances = terpapp.AppKeepers.BankKeeper.GetAllBalances(ctx, lucky) require.Len(t, balances, 1) coin = balances[0] require.Equal(t, amount.MulRaw(2), coin.Amount) @@ -139,7 +139,7 @@ func TestMintMsg(t *testing.T) { err = executeCustom(t, ctx, terpapp, reflect, lucky, msg, sdk.Coin{}) require.NoError(t, err) - balances = terpapp.BankKeeper.GetAllBalances(ctx, lucky) + balances = terpapp.AppKeepers.BankKeeper.GetAllBalances(ctx, lucky) require.Len(t, balances, 2) coin = balances[0] require.Equal(t, amount, coin.Amount) @@ -189,7 +189,7 @@ func TestForceTransfer(t *testing.T) { fundAccount(t, ctx, terpapp, reflect, reflectAmount) // lucky was broke - balances := terpapp.BankKeeper.GetAllBalances(ctx, lucky) + balances := terpapp.AppKeepers.BankKeeper.GetAllBalances(ctx, lucky) require.Empty(t, balances) // Create denom for minting @@ -223,7 +223,7 @@ func TestForceTransfer(t *testing.T) { require.NoError(t, err) // check the balance of rcpt - balances = terpapp.BankKeeper.GetAllBalances(ctx, rcpt) + balances = terpapp.AppKeepers.BankKeeper.GetAllBalances(ctx, rcpt) require.Len(t, balances, 1) coin := balances[0] require.Equal(t, sdk.NewInt(100), coin.Amount) @@ -242,7 +242,7 @@ func TestBurnMsg(t *testing.T) { fundAccount(t, ctx, terpapp, reflect, reflectAmount) // lucky was broke - balances := terpapp.BankKeeper.GetAllBalances(ctx, lucky) + balances := terpapp.AppKeepers.BankKeeper.GetAllBalances(ctx, lucky) require.Empty(t, balances) // Create denom for minting @@ -276,8 +276,8 @@ func TestBurnMsg(t *testing.T) { require.NoError(t, err) // lucky needs to send balance to reflect contract to burn it - luckyBalance := terpapp.BankKeeper.GetAllBalances(ctx, lucky) - err = terpapp.BankKeeper.SendCoins(ctx, lucky, reflect, luckyBalance) + luckyBalance := terpapp.AppKeepers.BankKeeper.GetAllBalances(ctx, lucky) + err = terpapp.AppKeepers.BankKeeper.SendCoins(ctx, lucky, reflect, luckyBalance) require.NoError(t, err) msg = bindings.TokenMsg{BurnTokens: &bindings.BurnTokens{ @@ -325,7 +325,7 @@ func executeCustom(t *testing.T, ctx sdk.Context, terpapp *app.TerpApp, contract coins = sdk.Coins{funds} } - contractKeeper := keeper.NewDefaultPermissionKeeper(terpapp.WasmKeeper) + contractKeeper := keeper.NewDefaultPermissionKeeper(terpapp.AppKeepers.WasmKeeper) _, err = contractKeeper.Execute(ctx, contract, sender, reflectBz, coins) return err } diff --git a/x/tokenfactory/bindings/custom_query_test.go b/x/tokenfactory/bindings/custom_query_test.go index e603a7c..e025ddb 100644 --- a/x/tokenfactory/bindings/custom_query_test.go +++ b/x/tokenfactory/bindings/custom_query_test.go @@ -64,7 +64,7 @@ func queryCustom(t *testing.T, ctx sdk.Context, terpapp *app.TerpApp, contract s require.NoError(t, err) fmt.Println("queryCustom2", string(queryBz)) - resBz, err := terpapp.WasmKeeper.QuerySmart(ctx, contract, queryBz) + resBz, err := terpapp.AppKeepers.WasmKeeper.QuerySmart(ctx, contract, queryBz) require.NoError(t, err) var resp ChainResponse err = json.Unmarshal(resBz, &resp) diff --git a/x/tokenfactory/bindings/helpers_test.go b/x/tokenfactory/bindings/helpers_test.go index 6b4f840..6b6c401 100644 --- a/x/tokenfactory/bindings/helpers_test.go +++ b/x/tokenfactory/bindings/helpers_test.go @@ -25,7 +25,7 @@ func CreateTestInput(t *testing.T) (*app.TerpApp, sdk.Context) { } func FundAccount(t *testing.T, ctx sdk.Context, terpapp *app.TerpApp, acct sdk.AccAddress) { - err := banktestutil.FundAccount(terpapp.BankKeeper, ctx, acct, sdk.NewCoins( + err := banktestutil.FundAccount(terpapp.AppKeepers.BankKeeper, ctx, acct, sdk.NewCoins( sdk.NewCoin("uosmo", sdk.NewInt(10000000000)), )) require.NoError(t, err) @@ -52,7 +52,7 @@ func storeReflectCode(t *testing.T, ctx sdk.Context, terpapp *app.TerpApp, addr wasmCode, err := os.ReadFile("./testdata/token_reflect.wasm") require.NoError(t, err) - contractKeeper := keeper.NewDefaultPermissionKeeper(terpapp.WasmKeeper) + contractKeeper := keeper.NewDefaultPermissionKeeper(terpapp.AppKeepers.WasmKeeper) codeID, _, err := contractKeeper.Create(ctx, addr, wasmCode, nil) require.NoError(t, err) @@ -61,7 +61,7 @@ func storeReflectCode(t *testing.T, ctx sdk.Context, terpapp *app.TerpApp, addr func instantiateReflectContract(t *testing.T, ctx sdk.Context, terpapp *app.TerpApp, funder sdk.AccAddress) sdk.AccAddress { initMsgBz := []byte("{}") - contractKeeper := keeper.NewDefaultPermissionKeeper(terpapp.WasmKeeper) + contractKeeper := keeper.NewDefaultPermissionKeeper(terpapp.AppKeepers.WasmKeeper) codeID := uint64(1) addr, _, err := contractKeeper.Instantiate(ctx, codeID, funder, funder, initMsgBz, "demo contract", nil) require.NoError(t, err) @@ -71,7 +71,7 @@ func instantiateReflectContract(t *testing.T, ctx sdk.Context, terpapp *app.Terp func fundAccount(t *testing.T, ctx sdk.Context, terpapp *app.TerpApp, addr sdk.AccAddress, coins sdk.Coins) { err := banktestutil.FundAccount( - terpapp.BankKeeper, + terpapp.AppKeepers.BankKeeper, ctx, addr, coins, @@ -81,7 +81,7 @@ func fundAccount(t *testing.T, ctx sdk.Context, terpapp *app.TerpApp, addr sdk.A func SetupCustomApp(t *testing.T, addr sdk.AccAddress) (*app.TerpApp, sdk.Context) { terpapp, ctx := CreateTestInput(t) - wasmKeeper := terpapp.WasmKeeper + wasmKeeper := terpapp.AppKeepers.WasmKeeper storeReflectCode(t, ctx, terpapp, addr) diff --git a/x/tokenfactory/bindings/validate_msg_test.go b/x/tokenfactory/bindings/validate_msg_test.go index 0d94920..b89adf6 100644 --- a/x/tokenfactory/bindings/validate_msg_test.go +++ b/x/tokenfactory/bindings/validate_msg_test.go @@ -50,7 +50,7 @@ func TestCreateDenom(t *testing.T) { for name, spec := range specs { t.Run(name, func(t *testing.T) { // when - _, gotErr := wasmbinding.PerformCreateDenom(&terpapp.TokenFactoryKeeper, &terpapp.BankKeeper, ctx, actor, spec.createDenom) + _, gotErr := wasmbinding.PerformCreateDenom(&terpapp.AppKeepers.TokenFactoryKeeper, &terpapp.AppKeepers.BankKeeper, ctx, actor, spec.createDenom) // then if spec.expErr { t.Logf("validate_msg_test got error: %v", gotErr) @@ -149,12 +149,12 @@ func TestChangeAdmin(t *testing.T) { actorAmount := sdk.NewCoins(sdk.NewCoin(types.DefaultParams().DenomCreationFee[0].Denom, types.DefaultParams().DenomCreationFee[0].Amount.MulRaw(100))) fundAccount(t, ctx, terpapp, tokenCreator, actorAmount) - _, err := wasmbinding.PerformCreateDenom(&terpapp.TokenFactoryKeeper, &terpapp.BankKeeper, ctx, tokenCreator, &bindings.CreateDenom{ + _, err := wasmbinding.PerformCreateDenom(&terpapp.AppKeepers.TokenFactoryKeeper, &terpapp.AppKeepers.BankKeeper, ctx, tokenCreator, &bindings.CreateDenom{ Subdenom: validDenom, }) require.NoError(t, err) - err = wasmbinding.ChangeAdmin(&terpapp.TokenFactoryKeeper, ctx, spec.actor, spec.changeAdmin) + err = wasmbinding.ChangeAdmin(&terpapp.AppKeepers.TokenFactoryKeeper, ctx, spec.actor, spec.changeAdmin) if len(spec.expErrMsg) > 0 { require.Error(t, err) actualErrMsg := err.Error() @@ -178,13 +178,13 @@ func TestMint(t *testing.T) { validDenom := bindings.CreateDenom{ Subdenom: "MOON", } - _, err := wasmbinding.PerformCreateDenom(&terpapp.TokenFactoryKeeper, &terpapp.BankKeeper, ctx, creator, &validDenom) + _, err := wasmbinding.PerformCreateDenom(&terpapp.AppKeepers.TokenFactoryKeeper, &terpapp.AppKeepers.BankKeeper, ctx, creator, &validDenom) require.NoError(t, err) emptyDenom := bindings.CreateDenom{ Subdenom: "", } - _, err = wasmbinding.PerformCreateDenom(&terpapp.TokenFactoryKeeper, &terpapp.BankKeeper, ctx, creator, &emptyDenom) + _, err = wasmbinding.PerformCreateDenom(&terpapp.AppKeepers.TokenFactoryKeeper, &terpapp.AppKeepers.BankKeeper, ctx, creator, &emptyDenom) require.NoError(t, err) validDenomStr := fmt.Sprintf("factory/%s/%s", creator.String(), validDenom.Subdenom) @@ -193,7 +193,7 @@ func TestMint(t *testing.T) { lucky := RandomAccountAddress() // lucky was broke - balances := terpapp.BankKeeper.GetAllBalances(ctx, lucky) + balances := terpapp.AppKeepers.BankKeeper.GetAllBalances(ctx, lucky) require.Empty(t, balances) amount, ok := sdk.NewIntFromString("8080") @@ -274,7 +274,7 @@ func TestMint(t *testing.T) { for name, spec := range specs { t.Run(name, func(t *testing.T) { // when - gotErr := wasmbinding.PerformMint(&terpapp.TokenFactoryKeeper, &terpapp.BankKeeper, ctx, creator, spec.mint) + gotErr := wasmbinding.PerformMint(&terpapp.AppKeepers.TokenFactoryKeeper, &terpapp.AppKeepers.BankKeeper, ctx, creator, spec.mint) // then if spec.expErr { require.Error(t, gotErr) @@ -297,19 +297,19 @@ func TestBurn(t *testing.T) { validDenom := bindings.CreateDenom{ Subdenom: "MOON", } - _, err := wasmbinding.PerformCreateDenom(&terpapp.TokenFactoryKeeper, &terpapp.BankKeeper, ctx, creator, &validDenom) + _, err := wasmbinding.PerformCreateDenom(&terpapp.AppKeepers.TokenFactoryKeeper, &terpapp.AppKeepers.BankKeeper, ctx, creator, &validDenom) require.NoError(t, err) emptyDenom := bindings.CreateDenom{ Subdenom: "", } - _, err = wasmbinding.PerformCreateDenom(&terpapp.TokenFactoryKeeper, &terpapp.BankKeeper, ctx, creator, &emptyDenom) + _, err = wasmbinding.PerformCreateDenom(&terpapp.AppKeepers.TokenFactoryKeeper, &terpapp.AppKeepers.BankKeeper, ctx, creator, &emptyDenom) require.NoError(t, err) lucky := RandomAccountAddress() // lucky was broke - balances := terpapp.BankKeeper.GetAllBalances(ctx, lucky) + balances := terpapp.AppKeepers.BankKeeper.GetAllBalances(ctx, lucky) require.Empty(t, balances) validDenomStr := fmt.Sprintf("factory/%s/%s", creator.String(), validDenom.Subdenom) @@ -391,7 +391,7 @@ func TestBurn(t *testing.T) { Amount: mintAmount, MintToAddress: creator.String(), } - err := wasmbinding.PerformMint(&terpapp.TokenFactoryKeeper, &terpapp.BankKeeper, ctx, creator, mintBinding) + err := wasmbinding.PerformMint(&terpapp.AppKeepers.TokenFactoryKeeper, &terpapp.AppKeepers.BankKeeper, ctx, creator, mintBinding) require.NoError(t, err) emptyDenomMintBinding := &bindings.MintTokens{ @@ -399,11 +399,11 @@ func TestBurn(t *testing.T) { Amount: mintAmount, MintToAddress: creator.String(), } - err = wasmbinding.PerformMint(&terpapp.TokenFactoryKeeper, &terpapp.BankKeeper, ctx, creator, emptyDenomMintBinding) + err = wasmbinding.PerformMint(&terpapp.AppKeepers.TokenFactoryKeeper, &terpapp.AppKeepers.BankKeeper, ctx, creator, emptyDenomMintBinding) require.NoError(t, err) // when - gotErr := wasmbinding.PerformBurn(&terpapp.TokenFactoryKeeper, ctx, creator, spec.burn) + gotErr := wasmbinding.PerformBurn(&terpapp.AppKeepers.TokenFactoryKeeper, ctx, creator, spec.burn) // then if spec.expErr { require.Error(t, gotErr) diff --git a/x/tokenfactory/keeper/admins_test.go b/x/tokenfactory/keeper/admins_test.go index ac602a5..8f19b61 100644 --- a/x/tokenfactory/keeper/admins_test.go +++ b/x/tokenfactory/keeper/admins_test.go @@ -13,7 +13,7 @@ func (suite *KeeperTestSuite) TestAdminMsgs() { addr0bal := int64(0) addr1bal := int64(0) - bankKeeper := suite.App.BankKeeper + bankKeeper := suite.App.AppKeepers.BankKeeper suite.CreateDefaultDenom() // Make sure that the admin is set correctly @@ -33,15 +33,15 @@ func (suite *KeeperTestSuite) TestAdminMsgs() { _, err = suite.msgServer.Mint(sdk.WrapSDKContext(suite.Ctx), types.NewMsgMintTo(suite.TestAccs[0].String(), sdk.NewInt64Coin(suite.defaultDenom, 10), suite.TestAccs[1].String())) addr1bal += 10 suite.Require().NoError(err) - suite.Require().True(suite.App.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[1], suite.defaultDenom).Amount.Int64() == addr1bal, suite.App.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[1], suite.defaultDenom)) + suite.Require().True(suite.App.AppKeepers.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[1], suite.defaultDenom).Amount.Int64() == addr1bal, suite.App.AppKeepers.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[1], suite.defaultDenom)) // Test force transferring _, err = suite.msgServer.ForceTransfer(sdk.WrapSDKContext(suite.Ctx), types.NewMsgForceTransfer(suite.TestAccs[0].String(), sdk.NewInt64Coin(suite.defaultDenom, 5), suite.TestAccs[1].String(), suite.TestAccs[0].String())) addr1bal -= 5 addr0bal += 5 suite.Require().NoError(err) - suite.Require().True(suite.App.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], suite.defaultDenom).Amount.Int64() == addr0bal, suite.App.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], suite.defaultDenom)) - suite.Require().True(suite.App.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[1], suite.defaultDenom).Amount.Int64() == addr1bal, suite.App.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[1], suite.defaultDenom)) + suite.Require().True(suite.App.AppKeepers.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], suite.defaultDenom).Amount.Int64() == addr0bal, suite.App.AppKeepers.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], suite.defaultDenom)) + suite.Require().True(suite.App.AppKeepers.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[1], suite.defaultDenom).Amount.Int64() == addr1bal, suite.App.AppKeepers.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[1], suite.defaultDenom)) // Test burning from own account _, err = suite.msgServer.Burn(sdk.WrapSDKContext(suite.Ctx), types.NewMsgBurn(suite.TestAccs[0].String(), sdk.NewInt64Coin(suite.defaultDenom, 5))) @@ -141,7 +141,7 @@ func (suite *KeeperTestSuite) TestMintDenom() { } mintToAddr, _ := sdk.AccAddressFromBech32(tc.mintMsg.MintToAddress) - bal := suite.App.BankKeeper.GetBalance(suite.Ctx, mintToAddr, suite.defaultDenom).Amount + bal := suite.App.AppKeepers.BankKeeper.GetBalance(suite.Ctx, mintToAddr, suite.defaultDenom).Amount suite.Require().Equal(bal.Int64(), balances[tc.mintMsg.MintToAddress]) }) } @@ -218,7 +218,7 @@ func (suite *KeeperTestSuite) TestBurnDenom() { } burnFromAddr, _ := sdk.AccAddressFromBech32(tc.burnMsg.BurnFromAddress) - bal := suite.App.BankKeeper.GetBalance(suite.Ctx, burnFromAddr, suite.defaultDenom).Amount + bal := suite.App.AppKeepers.BankKeeper.GetBalance(suite.Ctx, burnFromAddr, suite.defaultDenom).Amount suite.Require().Equal(bal.Int64(), balances[tc.burnMsg.BurnFromAddress]) }) } @@ -296,12 +296,12 @@ func (suite *KeeperTestSuite) TestForceTransferDenom() { fromAddr, err := sdk.AccAddressFromBech32(tc.forceTransferMsg.TransferFromAddress) suite.Require().NoError(err) - fromBal := suite.App.BankKeeper.GetBalance(suite.Ctx, fromAddr, suite.defaultDenom).Amount + fromBal := suite.App.AppKeepers.BankKeeper.GetBalance(suite.Ctx, fromAddr, suite.defaultDenom).Amount suite.Require().True(fromBal.Int64() == balances[tc.forceTransferMsg.TransferFromAddress]) toAddr, err := sdk.AccAddressFromBech32(tc.forceTransferMsg.TransferToAddress) suite.Require().NoError(err) - toBal := suite.App.BankKeeper.GetBalance(suite.Ctx, toAddr, suite.defaultDenom).Amount + toBal := suite.App.AppKeepers.BankKeeper.GetBalance(suite.Ctx, toAddr, suite.defaultDenom).Amount suite.Require().True(toBal.Int64() == balances[tc.forceTransferMsg.TransferToAddress]) }) } @@ -509,7 +509,7 @@ func (suite *KeeperTestSuite) TestSetDenomMetaData() { } { suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { tc := tc - bankKeeper := suite.App.BankKeeper + bankKeeper := suite.App.AppKeepers.BankKeeper res, err := suite.msgServer.SetDenomMetadata(sdk.WrapSDKContext(suite.Ctx), &tc.msgSetDenomMetadata) if tc.expectedPass { suite.Require().NoError(err) diff --git a/x/tokenfactory/keeper/createdenom_test.go b/x/tokenfactory/keeper/createdenom_test.go index b64c50a..52784e3 100644 --- a/x/tokenfactory/keeper/createdenom_test.go +++ b/x/tokenfactory/keeper/createdenom_test.go @@ -12,8 +12,8 @@ import ( func (suite *KeeperTestSuite) TestMsgCreateDenom() { var ( - tokenFactoryKeeper = suite.App.TokenFactoryKeeper - bankKeeper = suite.App.BankKeeper + tokenFactoryKeeper = suite.App.AppKeepers.TokenFactoryKeeper + bankKeeper = suite.App.AppKeepers.BankKeeper denomCreationFee = tokenFactoryKeeper.GetParams(suite.Ctx).DenomCreationFee ) @@ -138,8 +138,8 @@ func (suite *KeeperTestSuite) TestCreateDenom() { if tc.setup != nil { tc.setup() } - tokenFactoryKeeper := suite.App.TokenFactoryKeeper - bankKeeper := suite.App.BankKeeper + tokenFactoryKeeper := suite.App.AppKeepers.TokenFactoryKeeper + bankKeeper := suite.App.AppKeepers.BankKeeper // Set denom creation fee in params if err := tokenFactoryKeeper.SetParams(suite.Ctx, tc.denomCreationFee); err != nil { suite.Require().NoError(err) diff --git a/x/tokenfactory/keeper/genesis_test.go b/x/tokenfactory/keeper/genesis_test.go index 71e8711..a3bae50 100644 --- a/x/tokenfactory/keeper/genesis_test.go +++ b/x/tokenfactory/keeper/genesis_test.go @@ -38,20 +38,20 @@ func (suite *KeeperTestSuite) TestGenesis() { for i, denom := range genesisState.FactoryDenoms { // hacky, sets bank metadata to exist if i != 0, to cover both cases. if i != 0 { - app.BankKeeper.SetDenomMetaData(suite.Ctx, banktypes.Metadata{Base: denom.GetDenom()}) + app.AppKeepers.BankKeeper.SetDenomMetaData(suite.Ctx, banktypes.Metadata{Base: denom.GetDenom()}) } } - if err := app.TokenFactoryKeeper.SetParams(suite.Ctx, types.Params{DenomCreationFee: sdk.Coins{sdk.NewInt64Coin("stake", 100)}}); err != nil { + if err := app.AppKeepers.TokenFactoryKeeper.SetParams(suite.Ctx, types.Params{DenomCreationFee: sdk.Coins{sdk.NewInt64Coin("stake", 100)}}); err != nil { panic(err) } - app.TokenFactoryKeeper.InitGenesis(suite.Ctx, genesisState) + app.AppKeepers.TokenFactoryKeeper.InitGenesis(suite.Ctx, genesisState) // check that the module account is now initialized - tokenfactoryModuleAccount := app.AccountKeeper.GetAccount(suite.Ctx, app.AccountKeeper.GetModuleAddress(types.ModuleName)) + tokenfactoryModuleAccount := appAppKeepers.AppKeepers.AccountKeeper.GetAccount(suite.Ctx, app.AppKeepers.AccountKeeper.GetModuleAddress(types.ModuleName)) suite.Require().NotNil(tokenfactoryModuleAccount) - exportedGenesis := app.TokenFactoryKeeper.ExportGenesis(suite.Ctx) + exportedGenesis := app.AppKeepers.TokenFactoryKeeper.ExportGenesis(suite.Ctx) suite.Require().NotNil(exportedGenesis) suite.Require().Equal(genesisState, *exportedGenesis) } diff --git a/x/tokenfactory/keeper/msg_server_test.go b/x/tokenfactory/keeper/msg_server_test.go index e341568..2f5b7d5 100644 --- a/x/tokenfactory/keeper/msg_server_test.go +++ b/x/tokenfactory/keeper/msg_server_test.go @@ -115,7 +115,7 @@ func (suite *KeeperTestSuite) TestCreateDenomMsg() { } { suite.SetupTest() suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { - tokenFactoryKeeper := suite.App.TokenFactoryKeeper + tokenFactoryKeeper := suite.App.AppKeepers.TokenFactoryKeeper ctx := suite.Ctx.WithEventManager(sdk.NewEventManager()) suite.Require().Equal(0, len(ctx.EventManager().Events())) // Set denom creation fee in params