From 7da4339041448d28b7fe4a37eb4c2b5e1b5e2295 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9CDongLieu=E2=80=9D?= Date: Sun, 8 Sep 2024 22:11:17 +0700 Subject: [PATCH] base app --- app/app.go | 635 ++++++++----- app/app_config.go | 301 ------ app/export.go | 149 +-- app/ibc.go | 206 ----- app/keepers/keepers.go | 346 +++++++ app/keepers/keys.go | 93 ++ app/module.go | 230 +++++ app/sim_bench_test.go | 39 +- app/sim_test.go | 120 ++- cmd/reserved/cmd/commands.go | 49 +- cmd/reserved/cmd/root.go | 125 ++- docs/static/openapi.yml | 2 +- go.mod | 5 +- go.sum | 4 - multinode.sh | 164 ++++ proto/reserve/psm/module/v1/module.proto | 18 + proto/reserve/psm/v1/genesis.proto | 17 + proto/reserve/psm/v1/params.proto | 23 + proto/reserve/psm/v1/proposals.proto | 62 ++ proto/reserve/psm/v1/psm.proto | 35 + proto/reserve/psm/v1/query.proto | 30 + proto/reserve/psm/v1/tx.proto | 40 + testutil/keeper/psm.go | 56 ++ testutil/network/network.go | 144 +-- x/psm/client/cli/tx.go | 103 +++ x/psm/keeper/keeper.go | 125 +++ x/psm/keeper/msg_server.go | 17 + x/psm/keeper/msg_update_params.go | 29 + x/psm/keeper/msg_update_params_test.go | 66 ++ x/psm/keeper/params.go | 33 + x/psm/keeper/proposals.go | 50 + x/psm/keeper/query.go | 17 + x/psm/keeper/query_params.go | 30 + x/psm/keeper/query_params_test.go | 23 + x/psm/module/autocli.go | 35 + x/psm/module/genesis.go | 29 + x/psm/module/genesis_test.go | 31 + x/psm/module/module.go | 227 +++++ x/psm/module/proposal_handler.go | 32 + x/psm/module/simulation.go | 59 ++ x/psm/simulation/helpers.go | 15 + x/psm/types/codec.go | 17 + x/psm/types/errors.go | 14 + x/psm/types/event.go | 10 + x/psm/types/expected_keepers.go | 25 + x/psm/types/genesis.go | 20 + x/psm/types/genesis.pb.go | 324 +++++++ x/psm/types/genesis_test.go | 41 + x/psm/types/keys.go | 32 + x/psm/types/module.pb.go | 322 +++++++ x/psm/types/params.go | 53 ++ x/psm/types/params.pb.go | 369 ++++++++ x/psm/types/proposals.go | 95 ++ x/psm/types/proposals.pb.go | 1076 ++++++++++++++++++++++ x/psm/types/psm.go | 21 + x/psm/types/psm.pb.go | 516 +++++++++++ x/psm/types/query.pb.go | 541 +++++++++++ x/psm/types/query.pb.gw.go | 153 +++ x/psm/types/tx.pb.go | 599 ++++++++++++ x/psm/types/types.go | 1 + x/reserve/types/genesis.pb.go | 7 +- x/reserve/types/module.pb.go | 5 +- x/reserve/types/params.pb.go | 7 +- x/reserve/types/query.pb.go | 7 +- x/reserve/types/tx.pb.go | 7 +- 65 files changed, 7066 insertions(+), 1010 deletions(-) delete mode 100644 app/app_config.go delete mode 100644 app/ibc.go create mode 100644 app/keepers/keepers.go create mode 100644 app/keepers/keys.go create mode 100644 app/module.go create mode 100755 multinode.sh create mode 100644 proto/reserve/psm/module/v1/module.proto create mode 100644 proto/reserve/psm/v1/genesis.proto create mode 100644 proto/reserve/psm/v1/params.proto create mode 100644 proto/reserve/psm/v1/proposals.proto create mode 100644 proto/reserve/psm/v1/psm.proto create mode 100644 proto/reserve/psm/v1/query.proto create mode 100644 proto/reserve/psm/v1/tx.proto create mode 100644 testutil/keeper/psm.go create mode 100644 x/psm/client/cli/tx.go create mode 100644 x/psm/keeper/keeper.go create mode 100644 x/psm/keeper/msg_server.go create mode 100644 x/psm/keeper/msg_update_params.go create mode 100644 x/psm/keeper/msg_update_params_test.go create mode 100644 x/psm/keeper/params.go create mode 100644 x/psm/keeper/proposals.go create mode 100644 x/psm/keeper/query.go create mode 100644 x/psm/keeper/query_params.go create mode 100644 x/psm/keeper/query_params_test.go create mode 100644 x/psm/module/autocli.go create mode 100644 x/psm/module/genesis.go create mode 100644 x/psm/module/genesis_test.go create mode 100644 x/psm/module/module.go create mode 100644 x/psm/module/proposal_handler.go create mode 100644 x/psm/module/simulation.go create mode 100644 x/psm/simulation/helpers.go create mode 100644 x/psm/types/codec.go create mode 100644 x/psm/types/errors.go create mode 100644 x/psm/types/event.go create mode 100644 x/psm/types/expected_keepers.go create mode 100644 x/psm/types/genesis.go create mode 100644 x/psm/types/genesis.pb.go create mode 100644 x/psm/types/genesis_test.go create mode 100644 x/psm/types/keys.go create mode 100644 x/psm/types/module.pb.go create mode 100644 x/psm/types/params.go create mode 100644 x/psm/types/params.pb.go create mode 100644 x/psm/types/proposals.go create mode 100644 x/psm/types/proposals.pb.go create mode 100644 x/psm/types/psm.go create mode 100644 x/psm/types/psm.pb.go create mode 100644 x/psm/types/query.pb.go create mode 100644 x/psm/types/query.pb.gw.go create mode 100644 x/psm/types/tx.pb.go create mode 100644 x/psm/types/types.go diff --git a/app/app.go b/app/app.go index ea66081..3e994bb 100644 --- a/app/app.go +++ b/app/app.go @@ -1,29 +1,25 @@ package app import ( + "fmt" "io" + "os" + "path/filepath" _ "cosmossdk.io/api/cosmos/tx/config/v1" // import for side-effects - clienthelpers "cosmossdk.io/client/v2/helpers" - "cosmossdk.io/depinject" "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" _ "cosmossdk.io/x/circuit" // import for side-effects - circuitkeeper "cosmossdk.io/x/circuit/keeper" + _ "cosmossdk.io/x/evidence" // import for side-effects - evidencekeeper "cosmossdk.io/x/evidence/keeper" - feegrantkeeper "cosmossdk.io/x/feegrant/keeper" + _ "cosmossdk.io/x/feegrant/module" // import for side-effects - nftkeeper "cosmossdk.io/x/nft/keeper" - _ "cosmossdk.io/x/nft/module" // import for side-effects - _ "cosmossdk.io/x/upgrade" // import for side-effects - upgradekeeper "cosmossdk.io/x/upgrade/keeper" - abci "github.com/cometbft/cometbft/abci/types" + dbm "github.com/cosmos/cosmos-db" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server/api" @@ -31,57 +27,58 @@ import ( servertypes "github.com/cosmos/cosmos-sdk/server/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/auth" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation" _ "github.com/cosmos/cosmos-sdk/x/auth/tx/config" // import for side-effects - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + _ "github.com/cosmos/cosmos-sdk/x/auth/vesting" // import for side-effects - authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper" + _ "github.com/cosmos/cosmos-sdk/x/authz/module" // import for side-effects _ "github.com/cosmos/cosmos-sdk/x/bank" // import for side-effects - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" + _ "github.com/cosmos/cosmos-sdk/x/consensus" // import for side-effects - consensuskeeper "github.com/cosmos/cosmos-sdk/x/consensus/keeper" + _ "github.com/cosmos/cosmos-sdk/x/crisis" // import for side-effects - crisiskeeper "github.com/cosmos/cosmos-sdk/x/crisis/keeper" + _ "github.com/cosmos/cosmos-sdk/x/distribution" // import for side-effects - distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" - "github.com/cosmos/cosmos-sdk/x/genutil" - genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" - "github.com/cosmos/cosmos-sdk/x/gov" govclient "github.com/cosmos/cosmos-sdk/x/gov/client" - govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - groupkeeper "github.com/cosmos/cosmos-sdk/x/group/keeper" - _ "github.com/cosmos/cosmos-sdk/x/group/module" // import for side-effects - _ "github.com/cosmos/cosmos-sdk/x/mint" // import for side-effects - mintkeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper" - _ "github.com/cosmos/cosmos-sdk/x/params" // import for side-effects 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" - _ "github.com/cosmos/cosmos-sdk/x/slashing" // import for side-effects - slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper" - _ "github.com/cosmos/cosmos-sdk/x/staking" // import for side-effects - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - _ "github.com/cosmos/ibc-go/modules/capability" // import for side-effects - capabilitykeeper "github.com/cosmos/ibc-go/modules/capability/keeper" - _ "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts" // import for side-effects - icacontrollerkeeper "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts/controller/keeper" - icahostkeeper "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts/host/keeper" - _ "github.com/cosmos/ibc-go/v8/modules/apps/29-fee" // import for side-effects - ibcfeekeeper "github.com/cosmos/ibc-go/v8/modules/apps/29-fee/keeper" - ibctransferkeeper "github.com/cosmos/ibc-go/v8/modules/apps/transfer/keeper" - ibckeeper "github.com/cosmos/ibc-go/v8/modules/core/keeper" - - "github.com/onomyprotocol/reserve/docs" - reservemodulekeeper "github.com/onomyprotocol/reserve/x/reserve/keeper" + + psm "github.com/onomyprotocol/reserve/x/psm/module" + + "cosmossdk.io/x/tx/signing" + "github.com/cosmos/cosmos-sdk/codec/address" + "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/std" + "github.com/cosmos/cosmos-sdk/types/msgservice" + sigtypes "github.com/cosmos/cosmos-sdk/types/tx/signing" + "github.com/cosmos/cosmos-sdk/version" + authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" + txmodule "github.com/cosmos/cosmos-sdk/x/auth/tx/config" + "github.com/cosmos/cosmos-sdk/x/crisis" + "github.com/cosmos/gogoproto/proto" + "github.com/onomyprotocol/reserve/app/keepers" + "github.com/spf13/cast" + + autocliv1 "cosmossdk.io/api/cosmos/autocli/v1" + reflectionv1 "cosmossdk.io/api/cosmos/reflection/v1" + autocli "cosmossdk.io/client/v2/autocli" + "cosmossdk.io/core/appmodule" + abci "github.com/cometbft/cometbft/abci/types" + tmjson "github.com/cometbft/cometbft/libs/json" + tmos "github.com/cometbft/cometbft/libs/os" + "github.com/cosmos/cosmos-sdk/client/grpc/cmtservice" + nodeservice "github.com/cosmos/cosmos-sdk/client/grpc/node" + runtimeservices "github.com/cosmos/cosmos-sdk/runtime/services" + "github.com/cosmos/cosmos-sdk/testutil/testdata" + authcodec "github.com/cosmos/cosmos-sdk/x/auth/codec" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" ) const ( AccountAddressPrefix = "cosmos" - Name = "reserve" + AppName = "reserve" ) var ( @@ -98,61 +95,32 @@ var ( // They are exported for convenience in creating helper functions, as object // capabilities aren't needed for testing. type App struct { - *runtime.App + *baseapp.BaseApp + keepers.AppKeepers + legacyAmino *codec.LegacyAmino appCodec codec.Codec txConfig client.TxConfig - interfaceRegistry codectypes.InterfaceRegistry - - // keepers - AccountKeeper authkeeper.AccountKeeper - BankKeeper bankkeeper.Keeper - StakingKeeper *stakingkeeper.Keeper - DistrKeeper distrkeeper.Keeper - ConsensusParamsKeeper consensuskeeper.Keeper - - SlashingKeeper slashingkeeper.Keeper - MintKeeper mintkeeper.Keeper - GovKeeper *govkeeper.Keeper - CrisisKeeper *crisiskeeper.Keeper - UpgradeKeeper *upgradekeeper.Keeper - ParamsKeeper paramskeeper.Keeper - AuthzKeeper authzkeeper.Keeper - EvidenceKeeper evidencekeeper.Keeper - FeeGrantKeeper feegrantkeeper.Keeper - GroupKeeper groupkeeper.Keeper - NFTKeeper nftkeeper.Keeper - CircuitBreakerKeeper circuitkeeper.Keeper - - // IBC - IBCKeeper *ibckeeper.Keeper // IBC Keeper must be a pointer in the app, so we can SetRouter on it correctly - CapabilityKeeper *capabilitykeeper.Keeper - IBCFeeKeeper ibcfeekeeper.Keeper - ICAControllerKeeper icacontrollerkeeper.Keeper - ICAHostKeeper icahostkeeper.Keeper - TransferKeeper ibctransferkeeper.Keeper - - // Scoped IBC - ScopedIBCKeeper capabilitykeeper.ScopedKeeper - ScopedIBCTransferKeeper capabilitykeeper.ScopedKeeper - ScopedICAControllerKeeper capabilitykeeper.ScopedKeeper - ScopedICAHostKeeper capabilitykeeper.ScopedKeeper - ScopedKeepers map[string]capabilitykeeper.ScopedKeeper - - ReserveKeeper reservemodulekeeper.Keeper - // this line is used by starport scaffolding # stargate/app/keeperDeclaration + interfaceRegistry types.InterfaceRegistry + + invCheckPeriod uint + + // the module manager + mm *module.Manager + ModuleBasics module.BasicManager // simulation manager - sm *module.SimulationManager + sm *module.SimulationManager + configurator module.Configurator } func init() { - var err error - clienthelpers.EnvPrefix = Name - DefaultNodeHome, err = clienthelpers.GetNodeHomeDirectory("." + Name) + userHomeDir, err := os.UserHomeDir() if err != nil { panic(err) } + + DefaultNodeHome = filepath.Join(userHomeDir, ".gaia") } // getGovProposalHandlers return the chain proposal handlers. @@ -162,138 +130,198 @@ func getGovProposalHandlers() []govclient.ProposalHandler { govProposalHandlers = append(govProposalHandlers, paramsclient.ProposalHandler, + psm.AddStableCoinProposalHandler, + psm.UpdatesStableCoinProposalHandler, // this line is used by starport scaffolding # stargate/app/govProposalHandler ) return govProposalHandlers } -// AppConfig returns the default app config. -func AppConfig() depinject.Config { - return depinject.Configs( - appConfig, - // Alternatively, load the app config from a YAML file. - // appconfig.LoadYAML(AppConfigYAML), - depinject.Supply( - // supply custom module basics - map[string]module.AppModuleBasic{ - genutiltypes.ModuleName: genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator), - govtypes.ModuleName: gov.NewAppModuleBasic(getGovProposalHandlers()), - // this line is used by starport scaffolding # stargate/appConfig/moduleBasic - }, - ), - ) -} - // New returns a reference to an initialized App. -func New( +// NewGaiaApp returns a reference to an initialized Gaia. +func NewApp( logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, + skipUpgradeHeights map[int64]bool, + homePath string, appOpts servertypes.AppOptions, baseAppOptions ...func(*baseapp.BaseApp), -) (*App, error) { - var ( - app = &App{ScopedKeepers: make(map[string]capabilitykeeper.ScopedKeeper)} - appBuilder *runtime.AppBuilder - - // merge the AppConfig and other configuration in one config - appConfig = depinject.Configs( - AppConfig(), - depinject.Supply( - appOpts, // supply app options - logger, // supply logger - // Supply with IBC keeper getter for the IBC modules with App Wiring. - // The IBC Keeper cannot be passed because it has not been initiated yet. - // Passing the getter, the app IBC Keeper will always be accessible. - // This needs to be removed after IBC supports App Wiring. - app.GetIBCKeeper, - app.GetCapabilityScopedKeeper, - - // here alternative options can be supplied to the DI container. - // those options can be used f.e to override the default behavior of some modules. - // for instance supplying a custom address codec for not using bech32 addresses. - // read the depinject documentation and depinject module wiring for more information - // on available options and how to use them. - ), - ) - ) - - if err := depinject.Inject(appConfig, - &appBuilder, - &app.appCodec, - &app.legacyAmino, - &app.txConfig, - &app.interfaceRegistry, - &app.AccountKeeper, - &app.BankKeeper, - &app.StakingKeeper, - &app.DistrKeeper, - &app.ConsensusParamsKeeper, - &app.SlashingKeeper, - &app.MintKeeper, - &app.GovKeeper, - &app.CrisisKeeper, - &app.UpgradeKeeper, - &app.ParamsKeeper, - &app.AuthzKeeper, - &app.EvidenceKeeper, - &app.FeeGrantKeeper, - &app.NFTKeeper, - &app.GroupKeeper, - &app.CircuitBreakerKeeper, - &app.ReserveKeeper, - ); err != nil { +) *App { + legacyAmino := codec.NewLegacyAmino() + interfaceRegistry, err := types.NewInterfaceRegistryWithOptions(types.InterfaceRegistryOptions{ + ProtoFiles: proto.HybridResolver, + SigningOptions: signing.Options{ + AddressCodec: address.Bech32Codec{ + Bech32Prefix: sdk.GetConfig().GetBech32AccountAddrPrefix(), + }, + ValidatorAddressCodec: address.Bech32Codec{ + Bech32Prefix: sdk.GetConfig().GetBech32ValidatorAddrPrefix(), + }, + }, + }) + if err != nil { panic(err) } + appCodec := codec.NewProtoCodec(interfaceRegistry) + txConfig := authtx.NewTxConfig(appCodec, authtx.DefaultSignModes) + + std.RegisterLegacyAminoCodec(legacyAmino) + std.RegisterInterfaces(interfaceRegistry) + + // App Opts + skipGenesisInvariants := cast.ToBool(appOpts.Get(crisis.FlagSkipGenesisInvariants)) + invCheckPeriod := cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)) + + bApp := baseapp.NewBaseApp( + AppName, + logger, + db, + txConfig.TxDecoder(), + baseAppOptions...) + + bApp.SetCommitMultiStoreTracer(traceStore) + bApp.SetVersion(version.Version) + bApp.SetInterfaceRegistry(interfaceRegistry) + bApp.SetTxEncoder(txConfig.TxEncoder()) + + app := &App{ + BaseApp: bApp, + legacyAmino: legacyAmino, + txConfig: txConfig, + appCodec: appCodec, + interfaceRegistry: interfaceRegistry, + invCheckPeriod: invCheckPeriod, + } - // add to default baseapp options - // enable optimistic execution - baseAppOptions = append(baseAppOptions, baseapp.SetOptimisticExecution()) + moduleAccountAddresses := app.ModuleAccountAddrs() + + // Setup keepers + app.AppKeepers = keepers.NewAppKeeper( + appCodec, + bApp, + legacyAmino, + maccPerms, + moduleAccountAddresses, + app.BlockedModuleAccountAddrs(moduleAccountAddresses), + skipUpgradeHeights, + homePath, + invCheckPeriod, + logger, + appOpts, + ) - // build app - app.App = appBuilder.Build(db, traceStore, baseAppOptions...) + // NOTE: Any module instantiated in the module manager that is later modified + // must be passed by reference here. + // fmt.Println(txConfig.NewTxBuilder() == nil) + app.mm = module.NewManager(appModules(app, appCodec, txConfig, skipGenesisInvariants)...) + app.ModuleBasics = newBasicManagerFromManager(app) - // register legacy modules - if err := app.registerIBCModules(appOpts); err != nil { - return nil, err - } + enabledSignModes := append([]sigtypes.SignMode(nil), authtx.DefaultSignModes...) + enabledSignModes = append(enabledSignModes, sigtypes.SignMode_SIGN_MODE_TEXTUAL) - // register streaming services - if err := app.RegisterStreamingServices(appOpts, app.kvStoreKeys()); err != nil { - return nil, err + txConfigOpts := authtx.ConfigOptions{ + EnabledSignModes: enabledSignModes, + TextualCoinMetadataQueryFn: txmodule.NewBankKeeperCoinMetadataQueryFn(app.BankKeeper), + } + txConfig, err = authtx.NewTxConfigWithOptions( + appCodec, + txConfigOpts, + ) + if err != nil { + panic(err) } + app.txConfig = txConfig + + // NOTE: upgrade module is required to be prioritized + // 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) + // Tell the app's module manager how to set the order of BeginBlockers, which are run at the beginning of every block. + app.mm.SetOrderBeginBlockers(orderBeginBlockers()...) + + app.mm.SetOrderEndBlockers(orderEndBlockers()...) + + // 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. + app.mm.SetOrderInitGenesis(orderInitBlockers()...) + + // Uncomment if you want to set a custom migration order here. + // app.mm.SetOrderMigrations(custom order) + + app.mm.RegisterInvariants(app.CrisisKeeper) + app.configurator = module.NewConfigurator(app.appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter()) + err = app.mm.RegisterServices(app.configurator) + if err != nil { + panic(err) + } + + autocliv1.RegisterQueryServer(app.GRPCQueryRouter(), runtimeservices.NewAutoCLIQueryService(app.mm.Modules)) - /**** Module Options ****/ + reflectionSvc, err := runtimeservices.NewReflectionService() + if err != nil { + panic(err) + } + reflectionv1.RegisterReflectionServiceServer(app.GRPCQueryRouter(), reflectionSvc) - app.ModuleManager.RegisterInvariants(app.CrisisKeeper) + // add test gRPC service for testing gRPC queries in isolation + testdata.RegisterQueryServer(app.GRPCQueryRouter(), testdata.QueryImpl{}) // create the simulation manager and define the order of the modules for deterministic simulations - overrideModules := map[string]module.AppModuleSimulation{ - authtypes.ModuleName: auth.NewAppModule(app.appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts, app.GetSubspace(authtypes.ModuleName)), - } - app.sm = module.NewSimulationManagerFromAppModules(app.ModuleManager.Modules, overrideModules) + // + // NOTE: this is not required apps that don't use the simulator for fuzz testing + // transactions + app.sm = module.NewSimulationManager(simulationModules(app, appCodec, skipGenesisInvariants)...) + app.sm.RegisterStoreDecoders() - // A custom InitChainer sets if extra pre-init-genesis logic is required. - // This is necessary for manually registered modules that do not support app wiring. - // Manually set the module version map as shown below. - // The upgrade module will automatically handle de-duplication of the module version map. - app.SetInitChainer(func(ctx sdk.Context, req *abci.RequestInitChain) (*abci.ResponseInitChain, error) { - if err := app.UpgradeKeeper.SetModuleVersionMap(ctx, app.ModuleManager.GetVersionMap()); err != nil { - return nil, err - } - return app.App.InitChainer(ctx, req) - }) + // initialize stores + app.MountKVStores(app.GetKVStoreKey()) + app.MountTransientStores(app.GetTransientStoreKey()) + app.MountMemoryStores(app.GetMemoryStoreKey()) + + app.SetInitChainer(app.InitChainer) + app.SetPreBlocker(app.PreBlocker) + app.SetBeginBlocker(app.BeginBlocker) + app.SetEndBlocker(app.EndBlocker) + + // app.setupUpgradeHandlers() + app.setupUpgradeStoreLoaders() + + // At startup, after all modules have been registered, check that all prot + // annotations are correct. + protoFiles, err := proto.MergedRegistry() + if err != nil { + panic(err) + } + err = msgservice.ValidateProtoAnnotations(protoFiles) + if err != nil { + // Once we switch to using protoreflect-based antehandlers, we might + // want to panic here instead of logging a warning. + fmt.Fprintln(os.Stderr, err.Error()) + } - if err := app.Load(loadLatest); err != nil { - return nil, err + if loadLatest { + if err := app.LoadLatestVersion(); err != nil { + tmos.Exit(fmt.Sprintf("failed to load latest version: %s", err)) + } } - return app, nil + // fmt.Println("new_app=0", app.ModuleBasics["bank"] == nil) + return app } +// Name returns the name of the App +func (app *App) Name() string { return app.BaseApp.Name() } + // LegacyAmino returns App's amino codec. // // NOTE: This is solely to be used for testing purposes as it may be desirable @@ -312,33 +340,18 @@ func (app *App) AppCodec() codec.Codec { // GetKey returns the KVStoreKey for the provided store key. func (app *App) GetKey(storeKey string) *storetypes.KVStoreKey { - kvStoreKey, ok := app.UnsafeFindStoreKey(storeKey).(*storetypes.KVStoreKey) - if !ok { - return nil - } - return kvStoreKey + return app.AppKeepers.GetKey(storeKey) } // GetMemKey returns the MemoryStoreKey for the provided store key. func (app *App) GetMemKey(storeKey string) *storetypes.MemoryStoreKey { - key, ok := app.UnsafeFindStoreKey(storeKey).(*storetypes.MemoryStoreKey) - if !ok { - return nil - } - - return key + return app.AppKeepers.GetMemKey(storeKey) } // kvStoreKeys returns all the kv store keys registered inside App. func (app *App) kvStoreKeys() map[string]*storetypes.KVStoreKey { - keys := make(map[string]*storetypes.KVStoreKey) - for _, k := range app.GetStoreKeys() { - if kv, ok := k.(*storetypes.KVStoreKey); ok { - keys[kv.Name()] = kv - } - } - return keys + return app.AppKeepers.GetKVStoreKey() } // GetSubspace returns a param subspace for a given module name. @@ -347,20 +360,20 @@ func (app *App) GetSubspace(moduleName string) paramstypes.Subspace { return subspace } -// GetIBCKeeper returns the IBC keeper. -func (app *App) GetIBCKeeper() *ibckeeper.Keeper { - return app.IBCKeeper -} - -// GetCapabilityScopedKeeper returns the capability scoped keeper. -func (app *App) GetCapabilityScopedKeeper(moduleName string) capabilitykeeper.ScopedKeeper { - sk, ok := app.ScopedKeepers[moduleName] - if !ok { - sk = app.CapabilityKeeper.ScopeToModule(moduleName) - app.ScopedKeepers[moduleName] = sk - } - return sk -} +// // GetIBCKeeper returns the IBC keeper. +// func (app *App) GetIBCKeeper() *ibckeeper.Keeper { +// return app.IBCKeeper +// } + +// // GetCapabilityScopedKeeper returns the capability scoped keeper. +// func (app *App) GetCapabilityScopedKeeper(moduleName string) capabilitykeeper.ScopedKeeper { +// sk, ok := app.ScopedKeepers[moduleName] +// if !ok { +// sk = app.CapabilityKeeper.ScopeToModule(moduleName) +// app.ScopedKeepers[moduleName] = sk +// } +// return sk +// } // SimulationManager implements the SimulationApp interface. func (app *App) SimulationManager() *module.SimulationManager { @@ -370,14 +383,22 @@ func (app *App) SimulationManager() *module.SimulationManager { // RegisterAPIRoutes registers all application module routes with the provided // API server. func (app *App) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig) { - app.App.RegisterAPIRoutes(apiSvr, apiConfig) - // register swagger API in app.go so that other applications can override easily + clientCtx := apiSvr.ClientCtx + // Register new tx routes from grpc-gateway. + authtx.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) + // Register new tendermint queries routes from grpc-gateway. + cmtservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) + + // Register legacy and grpc-gateway routes for all modules. + app.ModuleBasics.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) + + // Register nodeservice grpc-gateway routes. + nodeservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) + + // 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) } - - // register app's OpenAPI routes. - docs.RegisterOpenAPIService(Name, apiSvr.Router) } // GetMaccPerms returns a copy of the module account permissions @@ -385,23 +406,151 @@ func (app *App) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig // NOTE: This is solely to be used for testing purposes. func GetMaccPerms() map[string][]string { dup := make(map[string][]string) - for _, perms := range moduleAccPerms { - dup[perms.Account] = perms.Permissions + for k, v := range maccPerms { + dup[k] = v } return dup } -// BlockedAddresses returns all the app's blocked account addresses. -func BlockedAddresses() map[string]bool { - result := make(map[string]bool) - if len(blockAccAddrs) > 0 { - for _, addr := range blockAccAddrs { - result[addr] = true - } - } else { - for addr := range GetMaccPerms() { - result[addr] = true +// // BlockedAddresses returns all the app's blocked account addresses. +// func BlockedAddresses() map[string]bool { +// result := make(map[string]bool) +// if len(blockAccAddrs) > 0 { +// for _, addr := range blockAccAddrs { +// result[addr] = true +// } +// } else { +// for addr := range GetMaccPerms() { +// result[addr] = true +// } +// } +// return result +// } + +// // ModuleAccountAddrs returns all the app's module account addresses. +// func (app *App) ModuleAccountAddrs() map[string]bool { +// modAccAddrs := make(map[string]bool) +// for acc := range maccPerms { +// modAccAddrs[authtypes.NewModuleAddress(acc).String()] = true +// } + +// return modAccAddrs +// } + +func (app *App) BlockedModuleAccountAddrs(modAccAddrs map[string]bool) map[string]bool { + // remove module accounts that are ALLOWED to received funds + delete(modAccAddrs, authtypes.NewModuleAddress(govtypes.ModuleName).String()) + return modAccAddrs +} + +func (app *App) InitChainer(ctx sdk.Context, req *abci.RequestInitChain) (*abci.ResponseInitChain, error) { + var genesisState GenesisState + if err := tmjson.Unmarshal(req.AppStateBytes, &genesisState); err != nil { + panic(err) + } + + if err := app.UpgradeKeeper.SetModuleVersionMap(ctx, app.mm.GetVersionMap()); err != nil { + panic(err) + } + + response, err := app.mm.InitGenesis(ctx, app.appCodec, genesisState) + if err != nil { + panic(err) + } + + return response, nil +} + +func (app *App) PreBlocker(ctx sdk.Context, _ *abci.RequestFinalizeBlock) (*sdk.ResponsePreBlock, error) { + return app.mm.PreBlock(ctx) +} + +func (app *App) BeginBlocker(ctx sdk.Context) (sdk.BeginBlock, error) { + return app.mm.BeginBlock(ctx) +} + +func (app *App) EndBlocker(ctx sdk.Context) (sdk.EndBlock, error) { + return app.mm.EndBlock(ctx) +} + +// func (app *App) setupUpgradeHandlers() { +// for _, upgrade := range Upgrades { +// app.UpgradeKeeper.SetUpgradeHandler( +// upgrade.UpgradeName, +// upgrade.CreateUpgradeHandler( +// app.mm, +// app.configurator, +// &app.AppKeepers, +// ), +// ) +// } +// } + +func (app *App) setupUpgradeStoreLoaders() { + upgradeInfo, err := app.UpgradeKeeper.ReadUpgradeInfoFromDisk() + if err != nil { + panic(fmt.Sprintf("failed to read upgrade info from disk %s", err)) + } + + if app.UpgradeKeeper.IsSkipHeight(upgradeInfo.Height) { + return + } +} + +func (app *App) LoadHeight(height int64) error { + return app.LoadVersion(height) +} + +func (app *App) RegisterNodeService(clientCtx client.Context, cfg config.Config) { + nodeservice.RegisterNodeService(clientCtx, app.GRPCQueryRouter(), cfg) +} + +func (app *App) RegisterTendermintService(clientCtx client.Context) { + cmtservice.RegisterTendermintService( + clientCtx, + app.BaseApp.GRPCQueryRouter(), + app.interfaceRegistry, + app.Query, + ) +} + +func (app *App) RegisterTxService(clientCtx client.Context) { + authtx.RegisterTxService(app.BaseApp.GRPCQueryRouter(), clientCtx, app.BaseApp.Simulate, app.interfaceRegistry) +} + +func (app *App) ModuleAccountAddrs() map[string]bool { + modAccAddrs := make(map[string]bool) + for acc := range maccPerms { + modAccAddrs[authtypes.NewModuleAddress(acc).String()] = true + } + + return modAccAddrs +} + +// AutoCliOpts returns the autocli options for the app. +func (app *App) AutoCliOpts() autocli.AppOptions { + modules := make(map[string]appmodule.AppModule, 0) + for _, m := range app.mm.Modules { + if moduleWithName, ok := m.(module.HasName); ok { + moduleName := moduleWithName.Name() + if appModule, ok := moduleWithName.(appmodule.AppModule); ok { + modules[moduleName] = appModule + } } } - return result + + return autocli.AppOptions{ + Modules: modules, + AddressCodec: authcodec.NewBech32Codec(sdk.GetConfig().GetBech32AccountAddrPrefix()), + ValidatorAddressCodec: authcodec.NewBech32Codec(sdk.GetConfig().GetBech32ValidatorAddrPrefix()), + ConsensusAddressCodec: authcodec.NewBech32Codec(sdk.GetConfig().GetBech32ConsensusAddrPrefix()), + } +} + +func (app *App) GetTxConfig() client.TxConfig { + return app.txConfig +} + +func (app *App) InterfaceRegistry() types.InterfaceRegistry { + return app.interfaceRegistry } diff --git a/app/app_config.go b/app/app_config.go deleted file mode 100644 index be5b21d..0000000 --- a/app/app_config.go +++ /dev/null @@ -1,301 +0,0 @@ -package app - -import ( - "time" - - runtimev1alpha1 "cosmossdk.io/api/cosmos/app/runtime/v1alpha1" - appv1alpha1 "cosmossdk.io/api/cosmos/app/v1alpha1" - authmodulev1 "cosmossdk.io/api/cosmos/auth/module/v1" - authzmodulev1 "cosmossdk.io/api/cosmos/authz/module/v1" - bankmodulev1 "cosmossdk.io/api/cosmos/bank/module/v1" - circuitmodulev1 "cosmossdk.io/api/cosmos/circuit/module/v1" - consensusmodulev1 "cosmossdk.io/api/cosmos/consensus/module/v1" - crisismodulev1 "cosmossdk.io/api/cosmos/crisis/module/v1" - distrmodulev1 "cosmossdk.io/api/cosmos/distribution/module/v1" - evidencemodulev1 "cosmossdk.io/api/cosmos/evidence/module/v1" - feegrantmodulev1 "cosmossdk.io/api/cosmos/feegrant/module/v1" - genutilmodulev1 "cosmossdk.io/api/cosmos/genutil/module/v1" - govmodulev1 "cosmossdk.io/api/cosmos/gov/module/v1" - groupmodulev1 "cosmossdk.io/api/cosmos/group/module/v1" - mintmodulev1 "cosmossdk.io/api/cosmos/mint/module/v1" - nftmodulev1 "cosmossdk.io/api/cosmos/nft/module/v1" - paramsmodulev1 "cosmossdk.io/api/cosmos/params/module/v1" - slashingmodulev1 "cosmossdk.io/api/cosmos/slashing/module/v1" - stakingmodulev1 "cosmossdk.io/api/cosmos/staking/module/v1" - txconfigv1 "cosmossdk.io/api/cosmos/tx/config/v1" - upgrademodulev1 "cosmossdk.io/api/cosmos/upgrade/module/v1" - vestingmodulev1 "cosmossdk.io/api/cosmos/vesting/module/v1" - "cosmossdk.io/depinject/appconfig" - circuittypes "cosmossdk.io/x/circuit/types" - evidencetypes "cosmossdk.io/x/evidence/types" - "cosmossdk.io/x/feegrant" - "cosmossdk.io/x/nft" - upgradetypes "cosmossdk.io/x/upgrade/types" - "github.com/cosmos/cosmos-sdk/runtime" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - "github.com/cosmos/cosmos-sdk/x/authz" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - consensustypes "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" - genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/group" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - 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" - capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types" - icatypes "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts/types" - ibcfeetypes "github.com/cosmos/ibc-go/v8/modules/apps/29-fee/types" - ibctransfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" - ibcexported "github.com/cosmos/ibc-go/v8/modules/core/exported" - _ "github.com/onomyprotocol/reserve/x/reserve/module" - "google.golang.org/protobuf/types/known/durationpb" - - // 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. - reservemoduletypes "github.com/onomyprotocol/reserve/x/reserve/types" -) - -var ( - genesisModuleOrder = []string{ - // cosmos-sdk/ibc modules - capabilitytypes.ModuleName, - authtypes.ModuleName, - banktypes.ModuleName, - distrtypes.ModuleName, - stakingtypes.ModuleName, - slashingtypes.ModuleName, - govtypes.ModuleName, - minttypes.ModuleName, - crisistypes.ModuleName, - ibcexported.ModuleName, - genutiltypes.ModuleName, - evidencetypes.ModuleName, - authz.ModuleName, - ibctransfertypes.ModuleName, - icatypes.ModuleName, - ibcfeetypes.ModuleName, - feegrant.ModuleName, - paramstypes.ModuleName, - upgradetypes.ModuleName, - vestingtypes.ModuleName, - nft.ModuleName, - group.ModuleName, - consensustypes.ModuleName, - circuittypes.ModuleName, - // chain modules - reservemoduletypes.ModuleName, - // this line is used by starport scaffolding # stargate/app/initGenesis - } - - // 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) - beginBlockers = []string{ - // cosmos sdk modules - minttypes.ModuleName, - distrtypes.ModuleName, - slashingtypes.ModuleName, - evidencetypes.ModuleName, - stakingtypes.ModuleName, - authz.ModuleName, - genutiltypes.ModuleName, - // ibc modules - capabilitytypes.ModuleName, - ibcexported.ModuleName, - ibctransfertypes.ModuleName, - icatypes.ModuleName, - ibcfeetypes.ModuleName, - // chain modules - reservemoduletypes.ModuleName, - // this line is used by starport scaffolding # stargate/app/beginBlockers - } - - endBlockers = []string{ - // cosmos sdk modules - crisistypes.ModuleName, - govtypes.ModuleName, - stakingtypes.ModuleName, - feegrant.ModuleName, - group.ModuleName, - genutiltypes.ModuleName, - // ibc modules - ibcexported.ModuleName, - ibctransfertypes.ModuleName, - capabilitytypes.ModuleName, - icatypes.ModuleName, - ibcfeetypes.ModuleName, - // chain modules - reservemoduletypes.ModuleName, - // this line is used by starport scaffolding # stargate/app/endBlockers - } - - preBlockers = []string{ - upgradetypes.ModuleName, - // this line is used by starport scaffolding # stargate/app/preBlockers - } - - // module account permissions - moduleAccPerms = []*authmodulev1.ModuleAccountPermission{ - {Account: authtypes.FeeCollectorName}, - {Account: distrtypes.ModuleName}, - {Account: minttypes.ModuleName, Permissions: []string{authtypes.Minter}}, - {Account: stakingtypes.BondedPoolName, Permissions: []string{authtypes.Burner, stakingtypes.ModuleName}}, - {Account: stakingtypes.NotBondedPoolName, Permissions: []string{authtypes.Burner, stakingtypes.ModuleName}}, - {Account: govtypes.ModuleName, Permissions: []string{authtypes.Burner}}, - {Account: nft.ModuleName}, - {Account: ibctransfertypes.ModuleName, Permissions: []string{authtypes.Minter, authtypes.Burner}}, - {Account: ibcfeetypes.ModuleName}, - {Account: icatypes.ModuleName}, - // this line is used by starport scaffolding # stargate/app/maccPerms - } - - // blocked account addresses - blockAccAddrs = []string{ - authtypes.FeeCollectorName, - distrtypes.ModuleName, - minttypes.ModuleName, - stakingtypes.BondedPoolName, - stakingtypes.NotBondedPoolName, - nft.ModuleName, - // We allow the following module accounts to receive funds: - // govtypes.ModuleName - } - - // appConfig application configuration (used by depinject) - appConfig = appconfig.Compose(&appv1alpha1.Config{ - Modules: []*appv1alpha1.ModuleConfig{ - { - Name: runtime.ModuleName, - Config: appconfig.WrapAny(&runtimev1alpha1.Module{ - AppName: Name, - PreBlockers: preBlockers, - BeginBlockers: beginBlockers, - EndBlockers: endBlockers, - InitGenesis: genesisModuleOrder, - OverrideStoreKeys: []*runtimev1alpha1.StoreKeyConfig{ - { - ModuleName: authtypes.ModuleName, - KvStoreKey: "acc", - }, - }, - // When ExportGenesis is not specified, the export genesis module order - // is equal to the init genesis order - // ExportGenesis: genesisModuleOrder, - // Uncomment if you want to set a custom migration order here. - // OrderMigrations: nil, - }), - }, - { - Name: authtypes.ModuleName, - Config: appconfig.WrapAny(&authmodulev1.Module{ - Bech32Prefix: AccountAddressPrefix, - ModuleAccountPermissions: moduleAccPerms, - // By default modules authority is the governance module. This is configurable with the following: - // Authority: "group", // A custom module authority can be set using a module name - // Authority: "cosmos1cwwv22j5ca08ggdv9c2uky355k908694z577tv", // or a specific address - }), - }, - { - Name: nft.ModuleName, - Config: appconfig.WrapAny(&nftmodulev1.Module{}), - }, - { - Name: vestingtypes.ModuleName, - Config: appconfig.WrapAny(&vestingmodulev1.Module{}), - }, - { - Name: banktypes.ModuleName, - Config: appconfig.WrapAny(&bankmodulev1.Module{ - BlockedModuleAccountsOverride: blockAccAddrs, - }), - }, - { - Name: stakingtypes.ModuleName, - Config: appconfig.WrapAny(&stakingmodulev1.Module{ - // NOTE: specifying a prefix is only necessary when using bech32 addresses - // If not specfied, the auth Bech32Prefix appended with "valoper" and "valcons" is used by default - Bech32PrefixValidator: AccountAddressPrefix + "valoper", - Bech32PrefixConsensus: AccountAddressPrefix + "valcons", - }), - }, - { - Name: slashingtypes.ModuleName, - Config: appconfig.WrapAny(&slashingmodulev1.Module{}), - }, - { - Name: paramstypes.ModuleName, - Config: appconfig.WrapAny(¶msmodulev1.Module{}), - }, - { - Name: "tx", - Config: appconfig.WrapAny(&txconfigv1.Config{}), - }, - { - Name: genutiltypes.ModuleName, - Config: appconfig.WrapAny(&genutilmodulev1.Module{}), - }, - { - Name: authz.ModuleName, - Config: appconfig.WrapAny(&authzmodulev1.Module{}), - }, - { - Name: upgradetypes.ModuleName, - Config: appconfig.WrapAny(&upgrademodulev1.Module{}), - }, - { - Name: distrtypes.ModuleName, - Config: appconfig.WrapAny(&distrmodulev1.Module{}), - }, - { - Name: evidencetypes.ModuleName, - Config: appconfig.WrapAny(&evidencemodulev1.Module{}), - }, - { - Name: minttypes.ModuleName, - Config: appconfig.WrapAny(&mintmodulev1.Module{}), - }, - { - Name: group.ModuleName, - Config: appconfig.WrapAny(&groupmodulev1.Module{ - MaxExecutionPeriod: durationpb.New(time.Second * 1209600), - MaxMetadataLen: 255, - }), - }, - { - Name: feegrant.ModuleName, - Config: appconfig.WrapAny(&feegrantmodulev1.Module{}), - }, - { - Name: govtypes.ModuleName, - Config: appconfig.WrapAny(&govmodulev1.Module{}), - }, - { - Name: crisistypes.ModuleName, - Config: appconfig.WrapAny(&crisismodulev1.Module{}), - }, - { - Name: consensustypes.ModuleName, - Config: appconfig.WrapAny(&consensusmodulev1.Module{}), - }, - { - Name: circuittypes.ModuleName, - Config: appconfig.WrapAny(&circuitmodulev1.Module{}), - }, - { - Name: reservemoduletypes.ModuleName, - Config: appconfig.WrapAny(&reservemoduletypes.Module{}), - }, - // this line is used by starport scaffolding # stargate/app/moduleConfig - }, - }) -) diff --git a/app/export.go b/app/export.go index f6f22f9..7ba5cd8 100644 --- a/app/export.go +++ b/app/export.go @@ -2,11 +2,11 @@ package app import ( "encoding/json" - "fmt" - "log" + + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" storetypes "cosmossdk.io/store/types" - cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + servertypes "github.com/cosmos/cosmos-sdk/server/types" sdk "github.com/cosmos/cosmos-sdk/types" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" @@ -16,19 +16,23 @@ import ( // ExportAppStateAndValidators exports the state of the application for a genesis // file. -func (app *App) ExportAppStateAndValidators(forZeroHeight bool, jailAllowedAddrs, modulesToExport []string) (servertypes.ExportedApp, error) { +func (app *App) ExportAppStateAndValidators( + forZeroHeight bool, + jailAllowedAddrs []string, + modulesToExport []string, +) (servertypes.ExportedApp, error) { // as if they could withdraw from the start of the next block - ctx := app.NewContextLegacy(true, cmtproto.Header{Height: app.LastBlockHeight()}) + ctx := app.NewContextLegacy(true, tmproto.Header{Height: app.LastBlockHeight()}) // We export at last height + 1, because that's the height at which - // CometBFT will start InitChain. + // Tendermint will start InitChain. height := app.LastBlockHeight() + 1 if forZeroHeight { height = 0 app.prepForZeroHeightGenesis(ctx, jailAllowedAddrs) } - genState, err := app.ModuleManager.ExportGenesisForModules(ctx, app.appCodec, modulesToExport) + genState, err := app.mm.ExportGenesisForModules(ctx, app.appCodec, modulesToExport) if err != nil { return servertypes.ExportedApp{}, err } @@ -49,8 +53,7 @@ func (app *App) ExportAppStateAndValidators(forZeroHeight bool, jailAllowedAddrs // prepare for fresh start at zero height // NOTE zero height genesis is a temporary feature which will be deprecated -// -// in favor of export at a block height +// in favour of export at a block height func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []string) { applyAllowedAddrs := false @@ -64,7 +67,7 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str for _, addr := range jailAllowedAddrs { _, err := sdk.ValAddressFromBech32(addr) if err != nil { - log.Fatal(err) + panic(err) } allowedAddrsMap[addr] = true } @@ -76,11 +79,14 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str // withdraw all validator commission err := app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { - valBz, err := app.StakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator()) + valAddr, err := app.StakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator()) if err != nil { - panic(err) + app.Logger().Error(err.Error(), "ValOperatorAddress", val.GetOperator()) + } + _, err = app.DistrKeeper.WithdrawValidatorCommission(ctx, valAddr) + if err != nil { + app.Logger().Error(err.Error(), "ValOperatorAddress", val.GetOperator()) } - _, _ = app.DistrKeeper.WithdrawValidatorCommission(ctx, valBz) return false }) if err != nil { @@ -92,16 +98,21 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str if err != nil { panic(err) } - for _, delegation := range dels { valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) if err != nil { panic(err) } - delAddr := sdk.MustAccAddressFromBech32(delegation.DelegatorAddress) + delAddr, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) + if err != nil { + panic(err) + } - _, _ = app.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr) + _, err = app.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr) + if err != nil { + panic(err) + } } // clear validator slash events @@ -114,14 +125,29 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str height := ctx.BlockHeight() ctx = ctx.WithBlockHeight(0) + // reinitialize all validators (v0.46 version) + // app.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) + // feePool.CommunityPool = feePool.CommunityPool.Add(scraps...) + // app.DistrKeeper.SetFeePool(ctx, feePool) + + // err := app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()) + // if err != nil { + // panic(err) + // } + // return false + // }) + // reinitialize all validators err = app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { - valBz, err := app.StakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator()) + // donate any unwithdrawn outstanding reward fraction tokens to the community pool + valAddr, err := app.StakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator()) if err != nil { panic(err) } - // donate any unwithdrawn outstanding reward fraction tokens to the community pool - scraps, err := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, valBz) + scraps, err := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, valAddr) if err != nil { panic(err) } @@ -130,15 +156,18 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str panic(err) } feePool.CommunityPool = feePool.CommunityPool.Add(scraps...) - if err := app.DistrKeeper.FeePool.Set(ctx, feePool); err != nil { + err = app.DistrKeeper.FeePool.Set(ctx, feePool) + if err != nil { panic(err) } - - if err := app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, valBz); err != nil { + if err := app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, valAddr); err != nil { panic(err) } return false }) + if err != nil { + panic(err) + } // reinitialize all delegations for _, del := range dels { @@ -146,16 +175,15 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str if err != nil { panic(err) } - delAddr := sdk.MustAccAddressFromBech32(del.DelegatorAddress) - + delAddr, err := sdk.AccAddressFromBech32(del.DelegatorAddress) + if err != nil { + panic(err) + } if err := app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr); err != nil { - // never called as BeforeDelegationCreated always returns nil - panic(fmt.Errorf("error while incrementing period: %w", err)) + panic(err) } - if err := app.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)) + panic(err) } } @@ -169,8 +197,7 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str for i := range red.Entries { red.Entries[i].CreationHeight = 0 } - err = app.StakingKeeper.SetRedelegation(ctx, red) - if err != nil { + if err := app.StakingKeeper.SetRedelegation(ctx, red); err != nil { panic(err) } return false @@ -184,8 +211,7 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str for i := range ubd.Entries { ubd.Entries[i].CreationHeight = 0 } - err = app.StakingKeeper.SetUnbondingDelegation(ctx, ubd) - if err != nil { + if err := app.StakingKeeper.SetUnbondingDelegation(ctx, ubd); err != nil { panic(err) } return false @@ -198,48 +224,51 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str // update bond intra-tx counters. store := ctx.KVStore(app.GetKey(stakingtypes.StoreKey)) iter := storetypes.KVStoreReversePrefixIterator(store, stakingtypes.ValidatorsKey) - counter := int16(0) - - for ; iter.Valid(); iter.Next() { - addr := sdk.ValAddress(stakingtypes.AddressFromValidatorsKey(iter.Key())) - validator, err := app.StakingKeeper.GetValidator(ctx, addr) - if err != nil { - panic("expected validator, not found") - } - validator.UnbondingHeight = 0 - if applyAllowedAddrs && !allowedAddrsMap[addr.String()] { - validator.Jailed = true - } + counter := int16(0) - if err := app.StakingKeeper.SetValidator(ctx, validator); err != nil { - panic(err) + // Closure to ensure iterator doesn't leak. + func() { + defer iter.Close() + for ; iter.Valid(); iter.Next() { + addr := sdk.ValAddress(stakingtypes.AddressFromValidatorsKey(iter.Key())) + validator, err := app.StakingKeeper.GetValidator(ctx, addr) + if err != nil { + panic("expected validator, not found") + } + + validator.UnbondingHeight = 0 + if applyAllowedAddrs && !allowedAddrsMap[addr.String()] { + validator.Jailed = true + } + + if err = app.StakingKeeper.SetValidator(ctx, validator); err != nil { + panic(err) + } + + counter++ } - counter++ - } - - if err := iter.Close(); err != nil { - app.Logger().Error("error while closing the key-value store reverse prefix iterator: ", err) - return - } + }() _, err = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) if err != nil { - log.Fatal(err) + panic(err) } /* Handle slashing state. */ // reset start height on signing infos - if err := app.SlashingKeeper.IterateValidatorSigningInfos( + err = app.SlashingKeeper.IterateValidatorSigningInfos( ctx, func(addr sdk.ConsAddress, info slashingtypes.ValidatorSigningInfo) (stop bool) { info.StartHeight = 0 - _ = app.SlashingKeeper.SetValidatorSigningInfo(ctx, addr, info) + if err = app.SlashingKeeper.SetValidatorSigningInfo(ctx, addr, info); err != nil { + panic(err) + } return false }, - ); err != nil { - log.Fatal(err) + ) + if err != nil { + panic(err) } - } diff --git a/app/ibc.go b/app/ibc.go deleted file mode 100644 index 12f9575..0000000 --- a/app/ibc.go +++ /dev/null @@ -1,206 +0,0 @@ -package app - -import ( - "cosmossdk.io/core/appmodule" - storetypes "cosmossdk.io/store/types" - cdctypes "github.com/cosmos/cosmos-sdk/codec/types" - servertypes "github.com/cosmos/cosmos-sdk/server/types" - "github.com/cosmos/cosmos-sdk/types/module" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/cosmos/ibc-go/modules/capability" - capabilitykeeper "github.com/cosmos/ibc-go/modules/capability/keeper" - capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types" - icamodule "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts" - icacontroller "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts/controller" - icacontrollerkeeper "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts/controller/keeper" - icacontrollertypes "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts/controller/types" - icahost "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts/host" - icahostkeeper "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts/host/keeper" - icahosttypes "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts/host/types" - icatypes "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts/types" - ibcfee "github.com/cosmos/ibc-go/v8/modules/apps/29-fee" - ibcfeekeeper "github.com/cosmos/ibc-go/v8/modules/apps/29-fee/keeper" - ibcfeetypes "github.com/cosmos/ibc-go/v8/modules/apps/29-fee/types" - ibctransfer "github.com/cosmos/ibc-go/v8/modules/apps/transfer" - ibctransferkeeper "github.com/cosmos/ibc-go/v8/modules/apps/transfer/keeper" - ibctransfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" - ibc "github.com/cosmos/ibc-go/v8/modules/core" - ibcclienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" // nolint:staticcheck // Deprecated: params key table is needed for params migration - ibcconnectiontypes "github.com/cosmos/ibc-go/v8/modules/core/03-connection/types" - porttypes "github.com/cosmos/ibc-go/v8/modules/core/05-port/types" - ibcexported "github.com/cosmos/ibc-go/v8/modules/core/exported" - ibckeeper "github.com/cosmos/ibc-go/v8/modules/core/keeper" - solomachine "github.com/cosmos/ibc-go/v8/modules/light-clients/06-solomachine" - ibctm "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" -) - -// registerIBCModules register IBC keepers and non dependency inject modules. -func (app *App) registerIBCModules(appOpts servertypes.AppOptions) error { - // set up non depinject support modules store keys - if err := app.RegisterStores( - storetypes.NewKVStoreKey(capabilitytypes.StoreKey), - storetypes.NewKVStoreKey(ibcexported.StoreKey), - storetypes.NewKVStoreKey(ibctransfertypes.StoreKey), - storetypes.NewKVStoreKey(ibcfeetypes.StoreKey), - storetypes.NewKVStoreKey(icahosttypes.StoreKey), - storetypes.NewKVStoreKey(icacontrollertypes.StoreKey), - storetypes.NewMemoryStoreKey(capabilitytypes.MemStoreKey), - storetypes.NewTransientStoreKey(paramstypes.TStoreKey), - ); err != nil { - return err - } - - // register the key tables for legacy param subspaces - keyTable := ibcclienttypes.ParamKeyTable() - keyTable.RegisterParamSet(&ibcconnectiontypes.Params{}) - app.ParamsKeeper.Subspace(ibcexported.ModuleName).WithKeyTable(keyTable) - app.ParamsKeeper.Subspace(ibctransfertypes.ModuleName).WithKeyTable(ibctransfertypes.ParamKeyTable()) - app.ParamsKeeper.Subspace(icacontrollertypes.SubModuleName).WithKeyTable(icacontrollertypes.ParamKeyTable()) - app.ParamsKeeper.Subspace(icahosttypes.SubModuleName).WithKeyTable(icahosttypes.ParamKeyTable()) - - // add capability keeper and ScopeToModule for ibc module - app.CapabilityKeeper = capabilitykeeper.NewKeeper( - app.AppCodec(), - app.GetKey(capabilitytypes.StoreKey), - app.GetMemKey(capabilitytypes.MemStoreKey), - ) - - // add capability keeper and ScopeToModule for ibc module - scopedIBCKeeper := app.CapabilityKeeper.ScopeToModule(ibcexported.ModuleName) - scopedIBCTransferKeeper := app.CapabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName) - scopedICAControllerKeeper := app.CapabilityKeeper.ScopeToModule(icacontrollertypes.SubModuleName) - scopedICAHostKeeper := app.CapabilityKeeper.ScopeToModule(icahosttypes.SubModuleName) - - // Create IBC keeper - app.IBCKeeper = ibckeeper.NewKeeper( - app.appCodec, - app.GetKey(ibcexported.StoreKey), - app.GetSubspace(ibcexported.ModuleName), - app.StakingKeeper, - app.UpgradeKeeper, - scopedIBCKeeper, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - - // 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) - - app.IBCFeeKeeper = ibcfeekeeper.NewKeeper( - app.appCodec, app.GetKey(ibcfeetypes.StoreKey), - app.IBCKeeper.ChannelKeeper, // may be replaced with IBC middleware - app.IBCKeeper.ChannelKeeper, - app.IBCKeeper.PortKeeper, app.AccountKeeper, app.BankKeeper, - ) - - // Create IBC transfer keeper - app.TransferKeeper = ibctransferkeeper.NewKeeper( - app.appCodec, - app.GetKey(ibctransfertypes.StoreKey), - app.GetSubspace(ibctransfertypes.ModuleName), - app.IBCFeeKeeper, - app.IBCKeeper.ChannelKeeper, - app.IBCKeeper.PortKeeper, - app.AccountKeeper, - app.BankKeeper, - scopedIBCTransferKeeper, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - - // Create interchain account keepers - app.ICAHostKeeper = icahostkeeper.NewKeeper( - app.appCodec, - app.GetKey(icahosttypes.StoreKey), - app.GetSubspace(icahosttypes.SubModuleName), - app.IBCFeeKeeper, // use ics29 fee as ics4Wrapper in middleware stack - app.IBCKeeper.ChannelKeeper, - app.IBCKeeper.PortKeeper, - app.AccountKeeper, - scopedICAHostKeeper, - app.MsgServiceRouter(), - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - app.ICAHostKeeper.WithQueryRouter(app.GRPCQueryRouter()) - - app.ICAControllerKeeper = icacontrollerkeeper.NewKeeper( - app.appCodec, - app.GetKey(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(), - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - app.GovKeeper.SetLegacyRouter(govRouter) - - // Create IBC modules with ibcfee middleware - transferIBCModule := ibcfee.NewIBCMiddleware(ibctransfer.NewIBCModule(app.TransferKeeper), app.IBCFeeKeeper) - - // integration point for custom authentication modules - var noAuthzModule porttypes.IBCModule - icaControllerIBCModule := ibcfee.NewIBCMiddleware( - icacontroller.NewIBCMiddleware(noAuthzModule, app.ICAControllerKeeper), - app.IBCFeeKeeper, - ) - - icaHostIBCModule := ibcfee.NewIBCMiddleware(icahost.NewIBCModule(app.ICAHostKeeper), app.IBCFeeKeeper) - - // Create static IBC router, add transfer route, then set and seal it - ibcRouter := porttypes.NewRouter(). - AddRoute(ibctransfertypes.ModuleName, transferIBCModule). - AddRoute(icacontrollertypes.SubModuleName, icaControllerIBCModule). - AddRoute(icahosttypes.SubModuleName, icaHostIBCModule) - - // this line is used by starport scaffolding # ibc/app/module - - app.IBCKeeper.SetRouter(ibcRouter) - - app.ScopedIBCKeeper = scopedIBCKeeper - app.ScopedIBCTransferKeeper = scopedIBCTransferKeeper - app.ScopedICAHostKeeper = scopedICAHostKeeper - app.ScopedICAControllerKeeper = scopedICAControllerKeeper - - // register IBC modules - if err := app.RegisterModules( - ibc.NewAppModule(app.IBCKeeper), - ibctransfer.NewAppModule(app.TransferKeeper), - ibcfee.NewAppModule(app.IBCFeeKeeper), - icamodule.NewAppModule(&app.ICAControllerKeeper, &app.ICAHostKeeper), - capability.NewAppModule(app.appCodec, *app.CapabilityKeeper, false), - ibctm.NewAppModule(), - solomachine.NewAppModule(), - ); err != nil { - return err - } - - return nil -} - -// RegisterIBC Since the IBC modules don't support dependency injection, -// we need to manually register the modules on the client side. -// This needs to be removed after IBC supports App Wiring. -func RegisterIBC(registry cdctypes.InterfaceRegistry) map[string]appmodule.AppModule { - modules := map[string]appmodule.AppModule{ - ibcexported.ModuleName: ibc.AppModule{}, - ibctransfertypes.ModuleName: ibctransfer.AppModule{}, - ibcfeetypes.ModuleName: ibcfee.AppModule{}, - icatypes.ModuleName: icamodule.AppModule{}, - capabilitytypes.ModuleName: capability.AppModule{}, - ibctm.ModuleName: ibctm.AppModule{}, - solomachine.ModuleName: solomachine.AppModule{}, - } - - for name, m := range modules { - module.CoreAppModuleBasicAdaptor(name, m).RegisterInterfaces(registry) - } - - return modules -} diff --git a/app/keepers/keepers.go b/app/keepers/keepers.go new file mode 100644 index 0000000..d1fd745 --- /dev/null +++ b/app/keepers/keepers.go @@ -0,0 +1,346 @@ +package keepers + +import ( + "fmt" + "os" + + "cosmossdk.io/log" + storetypes "cosmossdk.io/store/types" + evidencekeeper "cosmossdk.io/x/evidence/keeper" + evidencetypes "cosmossdk.io/x/evidence/types" + "cosmossdk.io/x/feegrant" + feegrantkeeper "cosmossdk.io/x/feegrant/keeper" + upgradekeeper "cosmossdk.io/x/upgrade/keeper" + upgradetypes "cosmossdk.io/x/upgrade/types" + + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/address" + "github.com/cosmos/cosmos-sdk/runtime" + servertypes "github.com/cosmos/cosmos-sdk/server/types" + sdk "github.com/cosmos/cosmos-sdk/types" + authcodec "github.com/cosmos/cosmos-sdk/x/auth/codec" + 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" + 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" + 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" + mintkeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper" + minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" + "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" + capabilitykeeper "github.com/cosmos/ibc-go/modules/capability/keeper" + capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types" + ibckeeper "github.com/cosmos/ibc-go/v8/modules/core/keeper" + + ibctransfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" + ibcclienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" + ibcconnectiontypes "github.com/cosmos/ibc-go/v8/modules/core/03-connection/types" + ibcexported "github.com/cosmos/ibc-go/v8/modules/core/exported" +) + +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 + BankKeeper bankkeeper.Keeper + 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 + AuthzKeeper authzkeeper.Keeper + ConsensusParamsKeeper consensusparamkeeper.Keeper + + IBCKeeper *ibckeeper.Keeper + + // make scoped keepers public for test purposes + ScopedIBCKeeper capabilitykeeper.ScopedKeeper + ScopedTransferKeeper capabilitykeeper.ScopedKeeper +} + +func NewAppKeeper( + appCodec codec.Codec, + bApp *baseapp.BaseApp, + legacyAmino *codec.LegacyAmino, + maccPerms map[string][]string, + modAccAddrs map[string]bool, + blockedAddress map[string]bool, + skipUpgradeHeights map[int64]bool, + homePath string, + invCheckPeriod uint, + logger log.Logger, + appOpts servertypes.AppOptions, +) AppKeepers { + appKeepers := AppKeepers{} + + // Set keys KVStoreKey, TransientStoreKey, MemoryStoreKey + appKeepers.GenerateKeys() + + /* + configure state listening capabilities using AppOptions + we are doing nothing with the returned streamingServices and waitGroup in this case + */ + // load state streaming if enabled + + if err := bApp.RegisterStreamingServices(appOpts, appKeepers.keys); err != nil { + logger.Error("failed to load state streaming", "err", err) + os.Exit(1) + } + + appKeepers.ParamsKeeper = initParamsKeeper( + appCodec, + legacyAmino, + appKeepers.keys[paramstypes.StoreKey], + appKeepers.tkeys[paramstypes.TStoreKey], + ) + + // set the BaseApp's parameter store + appKeepers.ConsensusParamsKeeper = consensusparamkeeper.NewKeeper( + appCodec, + runtime.NewKVStoreService(appKeepers.keys[consensusparamtypes.StoreKey]), + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + runtime.EventService{}, + ) + bApp.SetParamStore(appKeepers.ConsensusParamsKeeper.ParamsStore) + + // add capability keeper and ScopeToModule for ibc module + appKeepers.CapabilityKeeper = capabilitykeeper.NewKeeper( + appCodec, + appKeepers.keys[capabilitytypes.StoreKey], + appKeepers.memKeys[capabilitytypes.MemStoreKey], + ) + + appKeepers.ScopedIBCKeeper = appKeepers.CapabilityKeeper.ScopeToModule(ibcexported.ModuleName) + appKeepers.ScopedTransferKeeper = appKeepers.CapabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName) + + // Applications that wish to enforce statically created ScopedKeepers should call `Seal` after creating + // their scoped modules in `NewApp` with `ScopeToModule` + appKeepers.CapabilityKeeper.Seal() + + appKeepers.CrisisKeeper = crisiskeeper.NewKeeper( + appCodec, + runtime.NewKVStoreService(appKeepers.keys[crisistypes.StoreKey]), + invCheckPeriod, + appKeepers.BankKeeper, + authtypes.FeeCollectorName, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + appKeepers.AccountKeeper.AddressCodec(), + ) + + // Add normal keepers + appKeepers.AccountKeeper = authkeeper.NewAccountKeeper( + appCodec, + runtime.NewKVStoreService(appKeepers.keys[authtypes.StoreKey]), + authtypes.ProtoBaseAccount, + maccPerms, + address.NewBech32Codec(sdk.GetConfig().GetBech32AccountAddrPrefix()), + sdk.GetConfig().GetBech32AccountAddrPrefix(), + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + + appKeepers.BankKeeper = bankkeeper.NewBaseKeeper( + appCodec, + runtime.NewKVStoreService(appKeepers.keys[banktypes.StoreKey]), + appKeepers.AccountKeeper, + blockedAddress, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + logger, + ) + + appKeepers.AuthzKeeper = authzkeeper.NewKeeper( + runtime.NewKVStoreService(appKeepers.keys[authzkeeper.StoreKey]), + appCodec, + bApp.MsgServiceRouter(), + appKeepers.AccountKeeper, + ) + + appKeepers.FeeGrantKeeper = feegrantkeeper.NewKeeper( + appCodec, + runtime.NewKVStoreService(appKeepers.keys[feegrant.StoreKey]), + appKeepers.AccountKeeper, + ) + + appKeepers.StakingKeeper = stakingkeeper.NewKeeper( + appCodec, + runtime.NewKVStoreService(appKeepers.keys[stakingtypes.StoreKey]), + appKeepers.AccountKeeper, + appKeepers.BankKeeper, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + authcodec.NewBech32Codec(sdk.GetConfig().GetBech32ValidatorAddrPrefix()), + authcodec.NewBech32Codec(sdk.GetConfig().GetBech32ConsensusAddrPrefix()), + ) + + appKeepers.DistrKeeper = distrkeeper.NewKeeper( + appCodec, + runtime.NewKVStoreService(appKeepers.keys[distrtypes.StoreKey]), + appKeepers.AccountKeeper, + appKeepers.BankKeeper, + appKeepers.StakingKeeper, + authtypes.FeeCollectorName, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + + appKeepers.SlashingKeeper = slashingkeeper.NewKeeper( + appCodec, + legacyAmino, + runtime.NewKVStoreService(appKeepers.keys[slashingtypes.StoreKey]), + appKeepers.StakingKeeper, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + + // register the staking hooks + // NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks + appKeepers.StakingKeeper.SetHooks( + stakingtypes.NewMultiStakingHooks( + appKeepers.DistrKeeper.Hooks(), + appKeepers.SlashingKeeper.Hooks(), + ), + ) + + // UpgradeKeeper must be created before IBCKeeper + appKeepers.UpgradeKeeper = upgradekeeper.NewKeeper( + skipUpgradeHeights, + runtime.NewKVStoreService(appKeepers.keys[upgradetypes.StoreKey]), + appCodec, + homePath, + bApp, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + + // UpgradeKeeper must be created before IBCKeeper + appKeepers.IBCKeeper = ibckeeper.NewKeeper( + appCodec, + appKeepers.keys[ibcexported.StoreKey], + appKeepers.GetSubspace(ibcexported.ModuleName), + appKeepers.StakingKeeper, + appKeepers.UpgradeKeeper, + appKeepers.ScopedIBCKeeper, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + + // gov depends on provider, so needs to be set after + govConfig := govtypes.DefaultConfig() + // set the MaxMetadataLen for proposals to the same value as it was pre-sdk v0.47.x + govConfig.MaxMetadataLen = 10200 + appKeepers.GovKeeper = govkeeper.NewKeeper( + appCodec, + runtime.NewKVStoreService(appKeepers.keys[govtypes.StoreKey]), + appKeepers.AccountKeeper, + appKeepers.BankKeeper, + // use the ProviderKeeper as StakingKeeper for gov + // because governance should be based on the consensus-active validators + appKeepers.StakingKeeper, + appKeepers.DistrKeeper, + bApp.MsgServiceRouter(), + govConfig, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + + // mint keeper must be created after provider keeper + appKeepers.MintKeeper = mintkeeper.NewKeeper( + appCodec, + runtime.NewKVStoreService(appKeepers.keys[minttypes.StoreKey]), + appKeepers.StakingKeeper, + appKeepers.AccountKeeper, + appKeepers.BankKeeper, + authtypes.FeeCollectorName, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + + // 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(appKeepers.ParamsKeeper)) + + // Set legacy router for backwards compatibility with gov v1beta1 + appKeepers.GovKeeper.SetLegacyRouter(govRouter) + + evidenceKeeper := evidencekeeper.NewKeeper( + appCodec, + runtime.NewKVStoreService(appKeepers.keys[evidencetypes.StoreKey]), + appKeepers.StakingKeeper, + appKeepers.SlashingKeeper, + appKeepers.AccountKeeper.AddressCodec(), + runtime.ProvideCometInfoService(), + ) + + // If evidence needs to be handled for the app, set routes in router here and seal + appKeepers.EvidenceKeeper = *evidenceKeeper + + return appKeepers +} + +// GetSubspace returns a param subspace for a given module name. +func (appKeepers *AppKeepers) GetSubspace(moduleName string) paramstypes.Subspace { + subspace, ok := appKeepers.ParamsKeeper.GetSubspace(moduleName) + if !ok { + panic("couldn't load subspace for module: " + moduleName) + } + return subspace +} + +// 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) + + keyTable := ibcclienttypes.ParamKeyTable() + keyTable.RegisterParamSet(&ibcconnectiontypes.Params{}) + + paramsKeeper.Subspace(authtypes.ModuleName).WithKeyTable(authtypes.ParamKeyTable()) //nolint: staticcheck + paramsKeeper.Subspace(stakingtypes.ModuleName).WithKeyTable(stakingtypes.ParamKeyTable()) //nolint: staticcheck // SA1019 + paramsKeeper.Subspace(banktypes.ModuleName).WithKeyTable(banktypes.ParamKeyTable()) //nolint: staticcheck // SA1019 + paramsKeeper.Subspace(minttypes.ModuleName).WithKeyTable(minttypes.ParamKeyTable()) //nolint: staticcheck // SA1019 + paramsKeeper.Subspace(distrtypes.ModuleName).WithKeyTable(distrtypes.ParamKeyTable()) //nolint: staticcheck // SA1019 + paramsKeeper.Subspace(slashingtypes.ModuleName).WithKeyTable(slashingtypes.ParamKeyTable()) //nolint: staticcheck // SA1019 + paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govv1.ParamKeyTable()) //nolint: staticcheck // SA1019 + paramsKeeper.Subspace(crisistypes.ModuleName).WithKeyTable(crisistypes.ParamKeyTable()) //nolint: staticcheck // SA1019 + paramsKeeper.Subspace(ibcexported.ModuleName).WithKeyTable(keyTable) + + return paramsKeeper +} + +type DefaultFeemarketDenomResolver struct{} + +func (r *DefaultFeemarketDenomResolver) ConvertToDenom(_ sdk.Context, coin sdk.DecCoin, denom string) (sdk.DecCoin, error) { + if coin.Denom == denom { + return coin, nil + } + + return sdk.DecCoin{}, fmt.Errorf("error resolving denom") +} + +func (r *DefaultFeemarketDenomResolver) ExtraDenoms(_ sdk.Context) ([]string, error) { + return []string{}, nil +} diff --git a/app/keepers/keys.go b/app/keepers/keys.go new file mode 100644 index 0000000..e3ebefb --- /dev/null +++ b/app/keepers/keys.go @@ -0,0 +1,93 @@ +package keepers + +import ( + capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types" + icacontrollertypes "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts/controller/types" + icahosttypes "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts/host/types" + ibcfeetypes "github.com/cosmos/ibc-go/v8/modules/apps/29-fee/types" + ibctransfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" + ibcexported "github.com/cosmos/ibc-go/v8/modules/core/exported" + + storetypes "cosmossdk.io/store/types" + evidencetypes "cosmossdk.io/x/evidence/types" + "cosmossdk.io/x/feegrant" + upgradetypes "cosmossdk.io/x/upgrade/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" + 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" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" + 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" +) + +func (appKeepers *AppKeepers) GenerateKeys() { + // Define what keys will be used in the cosmos-sdk key/value store. + // Cosmos-SDK modules each have a "key" that allows the application to reference what they've stored on the chain. + appKeepers.keys = storetypes.NewKVStoreKeys( + authtypes.StoreKey, + banktypes.StoreKey, + stakingtypes.StoreKey, + crisistypes.StoreKey, + minttypes.StoreKey, + distrtypes.StoreKey, + slashingtypes.StoreKey, + govtypes.StoreKey, + paramstypes.StoreKey, + ibcexported.StoreKey, + upgradetypes.StoreKey, + evidencetypes.StoreKey, + ibctransfertypes.StoreKey, + ibcfeetypes.StoreKey, + icahosttypes.StoreKey, + icacontrollertypes.StoreKey, + capabilitytypes.StoreKey, + feegrant.StoreKey, + authzkeeper.StoreKey, + consensusparamtypes.StoreKey, + ) + + // Define transient store keys + appKeepers.tkeys = storetypes.NewTransientStoreKeys(paramstypes.TStoreKey) + + // MemKeys are for information that is stored only in RAM. + appKeepers.memKeys = storetypes.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] +} diff --git a/app/module.go b/app/module.go new file mode 100644 index 0000000..26a12f5 --- /dev/null +++ b/app/module.go @@ -0,0 +1,230 @@ +package app + +import ( + icatypes "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts/types" + + ibcfeetypes "github.com/cosmos/ibc-go/v8/modules/apps/29-fee/types" + ibctransfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" + + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" + + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" + + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + "github.com/cosmos/ibc-go/modules/capability" + + // ibcfee "github.com/cosmos/ibc-go/v8/modules/apps/29-fee" + + // ibc "github.com/cosmos/ibc-go/v8/modules/core" + + ibctm "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" + + "cosmossdk.io/x/evidence" + + feegrantmodule "cosmossdk.io/x/feegrant/module" + "cosmossdk.io/x/upgrade" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/auth" + // "github.com/cosmos/cosmos-sdk/x/staking" + + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + + 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/consensus" + + "github.com/cosmos/cosmos-sdk/x/crisis" + crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" + distr "github.com/cosmos/cosmos-sdk/x/distribution" + + "github.com/cosmos/cosmos-sdk/x/gov" + + "github.com/cosmos/cosmos-sdk/x/mint" + + sdkparams "github.com/cosmos/cosmos-sdk/x/params" + + "github.com/cosmos/cosmos-sdk/x/slashing" + slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" + + evidencetypes "cosmossdk.io/x/evidence/types" + "cosmossdk.io/x/feegrant" + upgradetypes "cosmossdk.io/x/upgrade/types" + "github.com/cosmos/cosmos-sdk/client" + authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation" + vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" + authz "github.com/cosmos/cosmos-sdk/x/authz" + consensusparamtypes "github.com/cosmos/cosmos-sdk/x/consensus/types" + genutil "github.com/cosmos/cosmos-sdk/x/genutil" + genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" + govclient "github.com/cosmos/cosmos-sdk/x/gov/client" + paramsclient "github.com/cosmos/cosmos-sdk/x/params/client" + paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" + "github.com/cosmos/cosmos-sdk/x/staking" + capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types" + ibc "github.com/cosmos/ibc-go/v8/modules/core" + ibcexported "github.com/cosmos/ibc-go/v8/modules/core/exported" +) + +var maccPerms = map[string][]string{ + authtypes.FeeCollectorName: nil, + distrtypes.ModuleName: nil, + icatypes.ModuleName: nil, + minttypes.ModuleName: {authtypes.Minter}, + stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, + stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, + govtypes.ModuleName: {authtypes.Burner}, + // liquiditytypes.ModuleName: {authtypes.Minter, authtypes.Burner}, + ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, + ibcfeetypes.ModuleName: nil, +} + +func appModules( + app *App, + appCodec codec.Codec, + txConfig client.TxEncodingConfig, + skipGenesisInvariants bool, +) []module.AppModule { + return []module.AppModule{ + auth.NewAppModule(appCodec, app.AccountKeeper, nil, 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), + crisis.NewAppModule(app.CrisisKeeper, skipGenesisInvariants, app.GetSubspace(crisistypes.ModuleName)), + 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), app.interfaceRegistry), + distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.GetSubspace(distrtypes.ModuleName)), + upgrade.NewAppModule(app.UpgradeKeeper, app.AccountKeeper.AddressCodec()), + evidence.NewAppModule(app.EvidenceKeeper), + feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry), + authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), + ibctm.NewAppModule(), + sdkparams.NewAppModule(app.ParamsKeeper), + consensus.NewAppModule(appCodec, app.ConsensusParamsKeeper), + staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(stakingtypes.ModuleName)), + genutil.NewAppModule(app.AccountKeeper, app.StakingKeeper, app, txConfig), + } + +} + +func newBasicManagerFromManager(app *App) module.BasicManager { + basicManager := module.NewBasicManagerFromManager( + app.mm, + map[string]module.AppModuleBasic{ + genutiltypes.ModuleName: genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator), + govtypes.ModuleName: gov.NewAppModuleBasic( + []govclient.ProposalHandler{ + paramsclient.ProposalHandler, + }, + ), + }) + basicManager.RegisterLegacyAminoCodec(app.legacyAmino) + basicManager.RegisterInterfaces(app.interfaceRegistry) + return basicManager +} + +func orderBeginBlockers() []string { + return []string{ + capabilitytypes.ModuleName, + minttypes.ModuleName, + distrtypes.ModuleName, + slashingtypes.ModuleName, + evidencetypes.ModuleName, + stakingtypes.ModuleName, + authtypes.ModuleName, + banktypes.ModuleName, + govtypes.ModuleName, + crisistypes.ModuleName, + ibcexported.ModuleName, + ibctransfertypes.ModuleName, + icatypes.ModuleName, + ibcfeetypes.ModuleName, + genutiltypes.ModuleName, + authz.ModuleName, + feegrant.ModuleName, + paramstypes.ModuleName, + vestingtypes.ModuleName, + consensusparamtypes.ModuleName, + } +} + +func orderEndBlockers() []string { + return []string{ + crisistypes.ModuleName, + govtypes.ModuleName, + stakingtypes.ModuleName, + ibcexported.ModuleName, + ibctransfertypes.ModuleName, + icatypes.ModuleName, + capabilitytypes.ModuleName, + ibcfeetypes.ModuleName, + authtypes.ModuleName, + banktypes.ModuleName, + distrtypes.ModuleName, + slashingtypes.ModuleName, + minttypes.ModuleName, + genutiltypes.ModuleName, + evidencetypes.ModuleName, + authz.ModuleName, + feegrant.ModuleName, + paramstypes.ModuleName, + upgradetypes.ModuleName, + vestingtypes.ModuleName, + consensusparamtypes.ModuleName, + } +} + +func orderInitBlockers() []string { + return []string{ + capabilitytypes.ModuleName, + authtypes.ModuleName, + banktypes.ModuleName, + distrtypes.ModuleName, + govtypes.ModuleName, + stakingtypes.ModuleName, + slashingtypes.ModuleName, + minttypes.ModuleName, + genutiltypes.ModuleName, + ibctransfertypes.ModuleName, + ibcexported.ModuleName, + icatypes.ModuleName, + ibcfeetypes.ModuleName, + evidencetypes.ModuleName, + authz.ModuleName, + feegrant.ModuleName, + paramstypes.ModuleName, + upgradetypes.ModuleName, + vestingtypes.ModuleName, + consensusparamtypes.ModuleName, + crisistypes.ModuleName, + } +} + +func simulationModules( + app *App, + appCodec codec.Codec, + _ bool, +) []module.AppModuleSimulation { + return []module.AppModuleSimulation{ + auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts, app.GetSubspace(authtypes.ModuleName)), + 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)), + staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(stakingtypes.ModuleName)), + distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.GetSubspace(distrtypes.ModuleName)), + slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.GetSubspace(slashingtypes.ModuleName), app.interfaceRegistry), + sdkparams.NewAppModule(app.ParamsKeeper), + evidence.NewAppModule(app.EvidenceKeeper), + authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), + ibc.NewAppModule(app.IBCKeeper), + } +} diff --git a/app/sim_bench_test.go b/app/sim_bench_test.go index 6ae73cf..3d051d2 100644 --- a/app/sim_bench_test.go +++ b/app/sim_bench_test.go @@ -6,6 +6,7 @@ import ( "testing" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/server" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" @@ -43,19 +44,28 @@ func BenchmarkFullAppSimulation(b *testing.B) { appOptions[flags.FlagHome] = app.DefaultNodeHome appOptions[server.FlagInvCheckPeriod] = simcli.FlagPeriodValue - bApp, err := app.New(logger, db, nil, true, appOptions, interBlockCacheOpt()) - require.NoError(b, err) - require.Equal(b, app.Name, bApp.Name()) + bApp := app.NewApp( + logger, + db, + nil, + true, + map[int64]bool{}, + app.DefaultNodeHome, + appOptions, + interBlockCacheOpt(), + baseapp.SetChainID(SimAppChainID), + ) + require.Equal(b, app.AppName, bApp.Name()) // run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( b, os.Stdout, bApp.BaseApp, - simtestutil.AppStateFn(bApp.AppCodec(), bApp.SimulationManager(), bApp.DefaultGenesis()), + simtestutil.AppStateFn(bApp.AppCodec(), bApp.SimulationManager(), bApp.ModuleBasics.DefaultGenesis(bApp.AppCodec())), simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 simtestutil.SimulationOperations(bApp, bApp.AppCodec(), config), - app.BlockedAddresses(), + bApp.ModuleAccountAddrs(), config, bApp.AppCodec(), ) @@ -100,19 +110,28 @@ func BenchmarkInvariants(b *testing.B) { appOptions[flags.FlagHome] = app.DefaultNodeHome appOptions[server.FlagInvCheckPeriod] = simcli.FlagPeriodValue - bApp, err := app.New(logger, db, nil, true, appOptions, interBlockCacheOpt()) - require.NoError(b, err) - require.Equal(b, app.Name, bApp.Name()) + bApp := app.NewApp( + logger, + db, + nil, + true, + map[int64]bool{}, + app.DefaultNodeHome, + appOptions, + interBlockCacheOpt(), + baseapp.SetChainID(SimAppChainID), + ) + require.Equal(b, app.AppName, bApp.Name()) // run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( b, os.Stdout, bApp.BaseApp, - simtestutil.AppStateFn(bApp.AppCodec(), bApp.SimulationManager(), bApp.DefaultGenesis()), + simtestutil.AppStateFn(bApp.AppCodec(), bApp.SimulationManager(), bApp.ModuleBasics.DefaultGenesis(bApp.AppCodec())), simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 simtestutil.SimulationOperations(bApp, bApp.AppCodec(), config), - app.BlockedAddresses(), + bApp.ModuleAccountAddrs(), config, bApp.AppCodec(), ) diff --git a/app/sim_test.go b/app/sim_test.go index 6fa4ec9..f994336 100644 --- a/app/sim_test.go +++ b/app/sim_test.go @@ -13,9 +13,9 @@ import ( "cosmossdk.io/log" "cosmossdk.io/store" - storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/feegrant" abci "github.com/cometbft/cometbft/abci/types" + tmjson "github.com/cometbft/cometbft/libs/json" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" dbm "github.com/cosmos/cosmos-db" "github.com/cosmos/cosmos-sdk/baseapp" @@ -87,19 +87,28 @@ func BenchmarkSimulation(b *testing.B) { appOptions[flags.FlagHome] = app.DefaultNodeHome appOptions[server.FlagInvCheckPeriod] = simcli.FlagPeriodValue - bApp, err := app.New(logger, db, nil, true, appOptions, fauxMerkleModeOpt, baseapp.SetChainID(SimAppChainID)) - require.NoError(b, err) - require.Equal(b, app.Name, bApp.Name()) + bApp := app.NewApp( + logger, + db, + nil, + true, + map[int64]bool{}, + app.DefaultNodeHome, + appOptions, + interBlockCacheOpt(), + baseapp.SetChainID(SimAppChainID), + ) + require.Equal(b, app.AppName, bApp.Name()) // run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( b, os.Stdout, bApp.BaseApp, - simtestutil.AppStateFn(bApp.AppCodec(), bApp.SimulationManager(), bApp.DefaultGenesis()), + simtestutil.AppStateFn(bApp.AppCodec(), bApp.SimulationManager(), bApp.ModuleBasics.DefaultGenesis(bApp.AppCodec())), simulationtypes.RandomAccounts, simtestutil.SimulationOperations(bApp, bApp.AppCodec(), config), - app.BlockedAddresses(), + bApp.ModuleAccountAddrs(), config, bApp.AppCodec(), ) @@ -133,19 +142,28 @@ func TestAppImportExport(t *testing.T) { appOptions[flags.FlagHome] = app.DefaultNodeHome appOptions[server.FlagInvCheckPeriod] = simcli.FlagPeriodValue - bApp, err := app.New(logger, db, nil, true, appOptions, fauxMerkleModeOpt, baseapp.SetChainID(SimAppChainID)) - require.NoError(t, err) - require.Equal(t, app.Name, bApp.Name()) + bApp := app.NewApp( + logger, + db, + nil, + true, + map[int64]bool{}, + app.DefaultNodeHome, + appOptions, + interBlockCacheOpt(), + baseapp.SetChainID(SimAppChainID), + ) + require.Equal(t, app.AppName, bApp.Name()) // Run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( t, os.Stdout, bApp.BaseApp, - simtestutil.AppStateFn(bApp.AppCodec(), bApp.SimulationManager(), bApp.DefaultGenesis()), + simtestutil.AppStateFn(bApp.AppCodec(), bApp.SimulationManager(), bApp.ModuleBasics.DefaultGenesis(bApp.AppCodec())), simulationtypes.RandomAccounts, simtestutil.SimulationOperations(bApp, bApp.AppCodec(), config), - app.BlockedAddresses(), + bApp.ModuleAccountAddrs(), config, bApp.AppCodec(), ) @@ -174,9 +192,18 @@ func TestAppImportExport(t *testing.T) { require.NoError(t, os.RemoveAll(newDir)) }() - newApp, err := app.New(log.NewNopLogger(), newDB, nil, true, appOptions, fauxMerkleModeOpt, baseapp.SetChainID(SimAppChainID)) - require.NoError(t, err) - require.Equal(t, app.Name, newApp.Name()) + newApp := app.NewApp( + logger, + db, + nil, + true, + map[int64]bool{}, + app.DefaultNodeHome, + appOptions, + interBlockCacheOpt(), + baseapp.SetChainID(SimAppChainID), + ) + require.Equal(t, app.AppName, newApp.Name()) var genesisState app.GenesisState err = json.Unmarshal(exported.AppState, &genesisState) @@ -184,7 +211,13 @@ func TestAppImportExport(t *testing.T) { ctxA := bApp.NewContextLegacy(true, cmtproto.Header{Height: bApp.LastBlockHeight()}) ctxB := newApp.NewContextLegacy(true, cmtproto.Header{Height: bApp.LastBlockHeight()}) - _, err = newApp.ModuleManager.InitGenesis(ctxB, bApp.AppCodec(), genesisState) + + bz, err := tmjson.Marshal(genesisState) + require.NoError(t, err) + req := abci.RequestInitChain{ + AppStateBytes: bz, + } + _, err = newApp.InitChainer(ctxB, &req) if err != nil { if strings.Contains(err.Error(), "validator set is empty after InitGenesis") { @@ -210,15 +243,10 @@ func TestAppImportExport(t *testing.T) { slashingtypes.StoreKey: {slashingtypes.ValidatorMissedBlockBitmapKeyPrefix}, } - storeKeys := bApp.GetStoreKeys() + storeKeys := bApp.GetKVStoreKey() require.NotEmpty(t, storeKeys) for _, appKeyA := range storeKeys { - // only compare kvstores - if _, ok := appKeyA.(*storetypes.KVStoreKey); !ok { - continue - } - keyName := appKeyA.Name() appKeyB := newApp.GetKey(keyName) @@ -253,19 +281,28 @@ func TestAppSimulationAfterImport(t *testing.T) { appOptions[flags.FlagHome] = app.DefaultNodeHome appOptions[server.FlagInvCheckPeriod] = simcli.FlagPeriodValue - bApp, err := app.New(logger, db, nil, true, appOptions, fauxMerkleModeOpt, baseapp.SetChainID(SimAppChainID)) - require.NoError(t, err) - require.Equal(t, app.Name, bApp.Name()) + bApp := app.NewApp( + logger, + db, + nil, + true, + map[int64]bool{}, + app.DefaultNodeHome, + appOptions, + interBlockCacheOpt(), + baseapp.SetChainID(SimAppChainID), + ) + require.Equal(t, app.AppName, bApp.Name()) // Run randomized simulation stopEarly, simParams, simErr := simulation.SimulateFromSeed( t, os.Stdout, bApp.BaseApp, - simtestutil.AppStateFn(bApp.AppCodec(), bApp.SimulationManager(), bApp.DefaultGenesis()), + simtestutil.AppStateFn(bApp.AppCodec(), bApp.SimulationManager(), bApp.ModuleBasics.DefaultGenesis(bApp.AppCodec())), simulationtypes.RandomAccounts, simtestutil.SimulationOperations(bApp, bApp.AppCodec(), config), - app.BlockedAddresses(), + bApp.ModuleAccountAddrs(), config, bApp.AppCodec(), ) @@ -299,9 +336,18 @@ func TestAppSimulationAfterImport(t *testing.T) { require.NoError(t, os.RemoveAll(newDir)) }() - newApp, err := app.New(log.NewNopLogger(), newDB, nil, true, appOptions, fauxMerkleModeOpt, baseapp.SetChainID(SimAppChainID)) - require.NoError(t, err) - require.Equal(t, app.Name, newApp.Name()) + newApp := app.NewApp( + logger, + db, + nil, + true, + map[int64]bool{}, + app.DefaultNodeHome, + appOptions, + interBlockCacheOpt(), + baseapp.SetChainID(SimAppChainID), + ) + require.Equal(t, app.AppName, newApp.Name()) _, err = newApp.InitChain(&abci.RequestInitChain{ AppStateBytes: exported.AppState, @@ -313,10 +359,10 @@ func TestAppSimulationAfterImport(t *testing.T) { t, os.Stdout, newApp.BaseApp, - simtestutil.AppStateFn(bApp.AppCodec(), bApp.SimulationManager(), bApp.DefaultGenesis()), + simtestutil.AppStateFn(bApp.AppCodec(), bApp.SimulationManager(), bApp.ModuleBasics.DefaultGenesis(bApp.AppCodec())), simulationtypes.RandomAccounts, simtestutil.SimulationOperations(newApp, newApp.AppCodec(), config), - app.BlockedAddresses(), + bApp.ModuleAccountAddrs(), config, bApp.AppCodec(), ) @@ -375,34 +421,36 @@ func TestAppStateDeterminism(t *testing.T) { } db := dbm.NewMemDB() - bApp, err := app.New( + bApp := app.NewApp( logger, db, nil, true, + map[int64]bool{}, + app.DefaultNodeHome, appOptions, interBlockCacheOpt(), baseapp.SetChainID(SimAppChainID), ) - require.NoError(t, err) + require.Equal(t, app.AppName, bApp.Name()) fmt.Printf( "running non-determinism simulation; seed %d: %d/%d, attempt: %d/%d\n", config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed, ) - _, _, err = simulation.SimulateFromSeed( + _, _, err := simulation.SimulateFromSeed( t, os.Stdout, bApp.BaseApp, simtestutil.AppStateFn( bApp.AppCodec(), bApp.SimulationManager(), - bApp.DefaultGenesis(), + bApp.ModuleBasics.DefaultGenesis(bApp.AppCodec()), ), simulationtypes.RandomAccounts, simtestutil.SimulationOperations(bApp, bApp.AppCodec(), config), - app.BlockedAddresses(), + bApp.ModuleAccountAddrs(), config, bApp.AppCodec(), ) diff --git a/cmd/reserved/cmd/commands.go b/cmd/reserved/cmd/commands.go index 02bcaad..009ae77 100644 --- a/cmd/reserved/cmd/commands.go +++ b/cmd/reserved/cmd/commands.go @@ -2,6 +2,7 @@ package cmd import ( "errors" + // "fmt" "io" "cosmossdk.io/log" @@ -20,6 +21,7 @@ import ( authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" "github.com/cosmos/cosmos-sdk/x/crisis" genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" + "github.com/spf13/cast" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -28,8 +30,8 @@ import ( func initRootCmd( rootCmd *cobra.Command, - txConfig client.TxConfig, basicManager module.BasicManager, + txConfig client.TxConfig, ) { rootCmd.AddCommand( genutilcli.InitCmd(basicManager, app.DefaultNodeHome), @@ -58,6 +60,7 @@ func addModuleInitFlags(startCmd *cobra.Command) { // genesisCommand builds genesis-related `reserved genesis` command. Users may provide application specific commands as a parameter func genesisCommand(txConfig client.TxConfig, basicManager module.BasicManager, cmds ...*cobra.Command) *cobra.Command { + // fmt.Println(basicManager["genutil"] == nil) cmd := genutilcli.Commands(txConfig, basicManager, app.DefaultNodeHome) for _, subCmd := range cmds { @@ -125,15 +128,21 @@ func newApp( ) servertypes.Application { baseappOptions := server.DefaultBaseappOptions(appOpts) - app, err := app.New( - logger, db, traceStore, true, + skipUpgradeHeights := make(map[int64]bool) + for _, h := range cast.ToIntSlice(appOpts.Get(server.FlagUnsafeSkipUpgrades)) { + skipUpgradeHeights[int64(h)] = true + } + + return app.NewApp( + logger, + db, + traceStore, + true, + skipUpgradeHeights, + cast.ToString(appOpts.Get(flags.FlagHome)), appOpts, baseappOptions..., ) - if err != nil { - panic(err) - } - return app } // appExport creates a new app (optionally at a given height) and exports state. @@ -149,7 +158,6 @@ func appExport( ) (servertypes.ExportedApp, error) { var ( bApp *app.App - err error ) // this check is necessary as we use the flag in x/upgrade. @@ -168,20 +176,25 @@ func appExport( viperAppOpts.Set(server.FlagInvCheckPeriod, 1) appOpts = viperAppOpts - if height != -1 { - bApp, err = app.New(logger, db, traceStore, false, appOpts) - if err != nil { - return servertypes.ExportedApp{}, err - } + var loadLatest bool + if height == -1 { + loadLatest = true + } + + bApp = app.NewApp( + logger, + db, + traceStore, + loadLatest, + map[int64]bool{}, + homePath, + appOpts, + ) + if height != -1 { if err := bApp.LoadHeight(height); err != nil { return servertypes.ExportedApp{}, err } - } else { - bApp, err = app.New(logger, db, traceStore, true, appOpts) - if err != nil { - return servertypes.ExportedApp{}, err - } } return bApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs, modulesToExport) diff --git a/cmd/reserved/cmd/root.go b/cmd/reserved/cmd/root.go index fe8e6c1..c42f5cc 100644 --- a/cmd/reserved/cmd/root.go +++ b/cmd/reserved/cmd/root.go @@ -1,73 +1,101 @@ package cmd import ( + // "fmt" + // "fmt" "os" "strings" "cosmossdk.io/client/v2/autocli" - "cosmossdk.io/depinject" "cosmossdk.io/log" + dbm "github.com/cosmos/cosmos-db" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/config" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/types/module" + + // "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth/tx" authtxconfig "github.com/cosmos/cosmos-sdk/x/auth/tx/config" "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/spf13/cobra" "github.com/spf13/pflag" + "github.com/spf13/viper" + + addresscodec "github.com/cosmos/cosmos-sdk/codec/address" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/tx/signing" "github.com/onomyprotocol/reserve/app" ) // NewRootCmd creates a new root command for reserved. It is called once in the main function. func NewRootCmd() *cobra.Command { - var ( - autoCliOpts autocli.AppOptions - moduleBasicManager module.BasicManager - clientCtx client.Context + initAppOptions := viper.New() + tempDir := tempDir() + initAppOptions.Set(flags.FlagHome, tempDir) + tempApplication := app.NewApp( + log.NewNopLogger(), + dbm.NewMemDB(), + nil, + true, + map[int64]bool{}, + tempDir, + initAppOptions, ) + defer func() { + if err := tempApplication.Close(); err != nil { + panic(err) + } + }() - if err := depinject.Inject( - depinject.Configs(app.AppConfig(), - depinject.Supply( - log.NewNopLogger(), - ), - depinject.Provide( - ProvideClientContext, - ), - ), - &autoCliOpts, - &moduleBasicManager, - &clientCtx, - ); err != nil { - panic(err) - } + // fmt.Println(tempApplication.GetTxConfig().NewTxBuilder() == nil) + + initClientCtx := client.Context{}. + WithCodec(tempApplication.AppCodec()). + WithInterfaceRegistry(tempApplication.InterfaceRegistry()). + WithLegacyAmino(tempApplication.LegacyAmino()). + WithInput(os.Stdin). + WithAccountRetriever(types.AccountRetriever{}). + WithHomeDir(app.DefaultNodeHome). + WithViper("") rootCmd := &cobra.Command{ - Use: app.Name + "d", - Short: "Start reserve node", - SilenceErrors: true, + Use: app.AppName + "d", + Short: "Start reserve node", PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { - // set the default command outputs cmd.SetOut(cmd.OutOrStdout()) cmd.SetErr(cmd.ErrOrStderr()) - clientCtx = clientCtx.WithCmdContext(cmd.Context()) - clientCtx, err := client.ReadPersistentCommandFlags(clientCtx, cmd.Flags()) + initClientCtx = initClientCtx.WithCmdContext(cmd.Context()) + initClientCtx, err := client.ReadPersistentCommandFlags(initClientCtx, cmd.Flags()) if err != nil { return err } - clientCtx, err = config.ReadFromClientConfig(clientCtx) + initClientCtx, err = config.ReadFromClientConfig(initClientCtx) if err != nil { return err } - if err := client.SetCmdClientContextHandler(clientCtx, cmd); err != nil { + if !initClientCtx.Offline { + txConfigOpts := tx.ConfigOptions{ + EnabledSignModes: append(tx.DefaultSignModes, signing.SignMode_SIGN_MODE_TEXTUAL), + TextualCoinMetadataQueryFn: authtxconfig.NewGRPCCoinMetadataQueryFn(initClientCtx), + } + txConfigWithTextual, err := tx.NewTxConfigWithOptions( + initClientCtx.Codec, + txConfigOpts, + ) + if err != nil { + return err + } + initClientCtx = initClientCtx.WithTxConfig(txConfigWithTextual) + } + + if err := client.SetCmdClientContextHandler(initClientCtx, cmd); err != nil { return err } @@ -81,19 +109,20 @@ func NewRootCmd() *cobra.Command { // Since the IBC modules don't support dependency injection, we need to // manually register the modules on the client side. // This needs to be removed after IBC supports App Wiring. - ibcModules := app.RegisterIBC(clientCtx.InterfaceRegistry) - for name, mod := range ibcModules { - moduleBasicManager[name] = module.CoreAppModuleBasicAdaptor(name, mod) - autoCliOpts.Modules[name] = mod - } - - initRootCmd(rootCmd, clientCtx.TxConfig, moduleBasicManager) + // ibcModules := app.RegisterIBC(clientCtx.InterfaceRegistry) + // for name, mod := range ibcModules { + // moduleBasicManager[name] = module.CoreAppModuleBasicAdaptor(name, mod) + // autoCliOpts.Modules[name] = mod + // } + // fmt.Println(tempApplication.ModuleBasics["genutil"] == nil) + initRootCmd(rootCmd, tempApplication.ModuleBasics, tempApplication.GetTxConfig()) overwriteFlagDefaults(rootCmd, map[string]string{ - flags.FlagChainID: strings.ReplaceAll(app.Name, "-", ""), + flags.FlagChainID: strings.ReplaceAll(app.AppName, "-", ""), flags.FlagKeyringBackend: "test", }) + autoCliOpts := enrichAutoCliOpts(tempApplication.AutoCliOpts(), initClientCtx) if err := autoCliOpts.EnhanceRootCommand(rootCmd); err != nil { panic(err) } @@ -101,6 +130,16 @@ func NewRootCmd() *cobra.Command { return rootCmd } +func enrichAutoCliOpts(autoCliOpts autocli.AppOptions, clientCtx client.Context) autocli.AppOptions { + autoCliOpts.AddressCodec = addresscodec.NewBech32Codec(sdk.GetConfig().GetBech32AccountAddrPrefix()) + autoCliOpts.ValidatorAddressCodec = addresscodec.NewBech32Codec(sdk.GetConfig().GetBech32ValidatorAddrPrefix()) + autoCliOpts.ConsensusAddressCodec = addresscodec.NewBech32Codec(sdk.GetConfig().GetBech32ConsensusAddrPrefix()) + + autoCliOpts.ClientCtx = clientCtx + + return autoCliOpts +} + func overwriteFlagDefaults(c *cobra.Command, defaults map[string]string) { set := func(s *pflag.FlagSet, key, val string) { if f := s.Lookup(key); f != nil { @@ -130,7 +169,7 @@ func ProvideClientContext( WithInput(os.Stdin). WithAccountRetriever(types.AccountRetriever{}). WithHomeDir(app.DefaultNodeHome). - WithViper(app.Name) // env variable prefix + WithViper(app.AppName) // env variable prefix // Read the config again to overwrite the default values with the values from the config file clientCtx, _ = config.ReadFromClientConfig(clientCtx) @@ -145,3 +184,13 @@ func ProvideClientContext( return clientCtx } + +var tempDir = func() string { + dir, err := os.MkdirTemp("", "."+app.AppName) + if err != nil { + dir = app.DefaultNodeHome + } + defer os.RemoveAll(dir) + + return dir +} diff --git a/docs/static/openapi.yml b/docs/static/openapi.yml index 1d205a8..fb4f8c2 100644 --- a/docs/static/openapi.yml +++ b/docs/static/openapi.yml @@ -1 +1 @@ -{"id":"github.com/onomyprotocol/reserve","consumes":["application/json"],"produces":["application/json"],"swagger":"2.0","info":{"description":"Chain github.com/onomyprotocol/reserve REST API","title":"HTTP API Console","contact":{"name":"github.com/onomyprotocol/reserve"},"version":"version not set"},"paths":{"/reserve.reserve.v1.Msg/UpdateParams":{"post":{"tags":["Msg"],"summary":"UpdateParams defines a (governance) operation for updating the module\nparameters. The authority defaults to the x/gov module account.","operationId":"GithubComonomyprotocolreserveMsg_UpdateParams","parameters":[{"description":"MsgUpdateParams is the Msg/UpdateParams request type.","name":"body","in":"body","required":true,"schema":{"$ref":"#/definitions/reserve.reserve.v1.MsgUpdateParams"}}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/reserve.reserve.v1.MsgUpdateParamsResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}}},"definitions":{"google.protobuf.Any":{"type":"object","properties":{"@type":{"type":"string"}},"additionalProperties":{}},"google.rpc.Status":{"type":"object","properties":{"code":{"type":"integer","format":"int32"},"details":{"type":"array","items":{"type":"object","$ref":"#/definitions/google.protobuf.Any"}},"message":{"type":"string"}}},"reserve.reserve.v1.MsgUpdateParams":{"description":"MsgUpdateParams is the Msg/UpdateParams request type.","type":"object","properties":{"authority":{"description":"authority is the address that controls the module (defaults to x/gov unless overwritten).","type":"string"},"params":{"description":"params defines the module parameters to update.\n\nNOTE: All parameters must be supplied.","$ref":"#/definitions/reserve.reserve.v1.Params"}}},"reserve.reserve.v1.MsgUpdateParamsResponse":{"description":"MsgUpdateParamsResponse defines the response structure for executing a\nMsgUpdateParams message.","type":"object"},"reserve.reserve.v1.Params":{"description":"Params defines the parameters for the module.","type":"object"}},"tags":[{"name":"Msg"}]} \ No newline at end of file +{"id":"github.com/onomyprotocol/reserve","consumes":["application/json"],"produces":["application/json"],"swagger":"2.0","info":{"description":"Chain github.com/onomyprotocol/reserve REST API","title":"HTTP API Console","contact":{"name":"github.com/onomyprotocol/reserve"},"version":"version not set"},"paths":{"/onomyprotocol/reserve/psm/v1/params":{"get":{"tags":["Query"],"summary":"Parameters queries the parameters of the module.","operationId":"GithubComonomyprotocolreserveQuery_Params","responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/reserve.psm.v1.QueryParamsResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/onomyprotocol/reserve/reserve/v1/params":{"get":{"tags":["Query"],"summary":"Parameters queries the parameters of the module.","operationId":"GithubComonomyprotocolreserveQuery_ParamsMixin8","responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/reserve.reserve.v1.QueryParamsResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/reserve.psm.v1.Msg/UpdateParams":{"post":{"tags":["Msg"],"summary":"UpdateParams defines a (governance) operation for updating the module\nparameters. The authority defaults to the x/gov module account.","operationId":"GithubComonomyprotocolreserveMsg_UpdateParams","parameters":[{"description":"MsgUpdateParams is the Msg/UpdateParams request type.","name":"body","in":"body","required":true,"schema":{"$ref":"#/definitions/reserve.psm.v1.MsgUpdateParams"}}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/reserve.psm.v1.MsgUpdateParamsResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}},"/reserve.reserve.v1.Msg/UpdateParams":{"post":{"tags":["Msg"],"summary":"UpdateParams defines a (governance) operation for updating the module\nparameters. The authority defaults to the x/gov module account.","operationId":"GithubComonomyprotocolreserveMsg_UpdateParamsMixin9","parameters":[{"description":"MsgUpdateParams is the Msg/UpdateParams request type.","name":"body","in":"body","required":true,"schema":{"$ref":"#/definitions/reserve.reserve.v1.MsgUpdateParams"}}],"responses":{"200":{"description":"A successful response.","schema":{"$ref":"#/definitions/reserve.reserve.v1.MsgUpdateParamsResponse"}},"default":{"description":"An unexpected error response.","schema":{"$ref":"#/definitions/google.rpc.Status"}}}}}},"definitions":{"google.protobuf.Any":{"type":"object","properties":{"@type":{"type":"string"}},"additionalProperties":{}},"google.rpc.Status":{"type":"object","properties":{"code":{"type":"integer","format":"int32"},"details":{"type":"array","items":{"type":"object","$ref":"#/definitions/google.protobuf.Any"}},"message":{"type":"string"}}},"reserve.psm.v1.MsgUpdateParams":{"description":"MsgUpdateParams is the Msg/UpdateParams request type.","type":"object","properties":{"authority":{"description":"authority is the address that controls the module (defaults to x/gov unless overwritten).","type":"string"},"params":{"description":"params defines the module parameters to update.\n\nNOTE: All parameters must be supplied.","$ref":"#/definitions/reserve.psm.v1.Params"}}},"reserve.psm.v1.MsgUpdateParamsResponse":{"description":"MsgUpdateParamsResponse defines the response structure for executing a\nMsgUpdateParams message.","type":"object"},"reserve.psm.v1.Params":{"type":"object","properties":{"acceptable_price_ratio":{"type":"string","format":"byte"},"limit_total":{"type":"string","format":"byte"}}},"reserve.psm.v1.QueryParamsResponse":{"description":"QueryParamsResponse is response type for the Query/Params RPC method.","type":"object","properties":{"params":{"description":"params holds all the parameters of this module.","$ref":"#/definitions/reserve.psm.v1.Params"}}},"reserve.reserve.v1.MsgUpdateParams":{"description":"MsgUpdateParams is the Msg/UpdateParams request type.","type":"object","properties":{"authority":{"description":"authority is the address that controls the module (defaults to x/gov unless overwritten).","type":"string"},"params":{"description":"params defines the module parameters to update.\n\nNOTE: All parameters must be supplied.","$ref":"#/definitions/reserve.reserve.v1.Params"}}},"reserve.reserve.v1.MsgUpdateParamsResponse":{"description":"MsgUpdateParamsResponse defines the response structure for executing a\nMsgUpdateParams message.","type":"object"},"reserve.reserve.v1.Params":{"description":"Params defines the parameters for the module.","type":"object"},"reserve.reserve.v1.QueryParamsResponse":{"description":"QueryParamsResponse is response type for the Query/Params RPC method.","type":"object","properties":{"params":{"description":"params holds all the parameters of this module.","$ref":"#/definitions/reserve.reserve.v1.Params"}}}},"tags":[{"name":"Query"},{"name":"Msg"}]} \ No newline at end of file diff --git a/go.mod b/go.mod index 2449187..2a506e6 100644 --- a/go.mod +++ b/go.mod @@ -23,7 +23,7 @@ require ( cosmossdk.io/x/circuit v0.1.0 cosmossdk.io/x/evidence v0.1.0 cosmossdk.io/x/feegrant v0.1.0 - cosmossdk.io/x/nft v0.1.0 + cosmossdk.io/x/tx v0.13.4 cosmossdk.io/x/upgrade v0.1.4 github.com/bufbuild/buf v1.32.1 github.com/cometbft/cometbft v0.38.10 @@ -59,7 +59,6 @@ require ( cloud.google.com/go/storage v1.38.0 // indirect connectrpc.com/connect v1.16.1 // indirect connectrpc.com/otelconnect v0.7.0 // indirect - cosmossdk.io/x/tx v0.13.4 // indirect filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect github.com/99designs/keyring v1.2.1 // indirect @@ -256,3 +255,5 @@ require ( pgregory.net/rapid v1.1.0 // indirect sigs.k8s.io/yaml v1.4.0 // indirect ) + +replace github.com/cosmos/cosmos-sdk => /Users/donglieu/cosmos-sdk diff --git a/go.sum b/go.sum index 34a9204..0c2eada 100644 --- a/go.sum +++ b/go.sum @@ -219,8 +219,6 @@ cosmossdk.io/x/evidence v0.1.0 h1:J6OEyDl1rbykksdGynzPKG5R/zm6TacwW2fbLTW4nCk= cosmossdk.io/x/evidence v0.1.0/go.mod h1:hTaiiXsoiJ3InMz1uptgF0BnGqROllAN8mwisOMMsfw= cosmossdk.io/x/feegrant v0.1.0 h1:c7s3oAq/8/UO0EiN1H5BIjwVntujVTkYs35YPvvrdQk= cosmossdk.io/x/feegrant v0.1.0/go.mod h1:4r+FsViJRpcZif/yhTn+E0E6OFfg4n0Lx+6cCtnZElU= -cosmossdk.io/x/nft v0.1.0 h1:VhcsFiEK33ODN27kxKLa0r/CeFd8laBfbDBwYqCyYCM= -cosmossdk.io/x/nft v0.1.0/go.mod h1:ec4j4QAO4mJZ+45jeYRnW7awLHby1JZANqe1hNZ4S3g= cosmossdk.io/x/tx v0.13.4 h1:Eg0PbJgeO0gM8p5wx6xa0fKR7hIV6+8lC56UrsvSo0Y= cosmossdk.io/x/tx v0.13.4/go.mod h1:BkFqrnGGgW50Y6cwTy+JvgAhiffbGEKW6KF9ufcDpvk= cosmossdk.io/x/upgrade v0.1.4 h1:/BWJim24QHoXde8Bc64/2BSEB6W4eTydq0X/2f8+g38= @@ -379,8 +377,6 @@ github.com/cosmos/cosmos-db v1.0.2 h1:hwMjozuY1OlJs/uh6vddqnk9j7VamLv+0DBlbEXbAK github.com/cosmos/cosmos-db v1.0.2/go.mod h1:Z8IXcFJ9PqKK6BIsVOB3QXtkKoqUOp1vRvPT39kOXEA= github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= -github.com/cosmos/cosmos-sdk v0.50.9 h1:gt2usjz0H0qW6KwAxWw7ZJ3XU8uDwmhN+hYG3nTLeSg= -github.com/cosmos/cosmos-sdk v0.50.9/go.mod h1:TMH6wpoYBcg7Cp5BEg8fneLr+8XloNQkf2MRNF9V6JE= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= diff --git a/multinode.sh b/multinode.sh new file mode 100755 index 0000000..bfb9b44 --- /dev/null +++ b/multinode.sh @@ -0,0 +1,164 @@ +#!/bin/bash +set -xeu + +# always returns true so set -e doesn't exit if it is not running. +killall reserved || true +rm -rf $HOME/.reserved/ + +# make four gaia directories +mkdir $HOME/.reserved +cd $HOME/.reserved/ +mkdir $HOME/.reserved/validator1 +mkdir $HOME/.reserved/validator2 +mkdir $HOME/.reserved/validator3 + +# init all three validators +reserved init --chain-id=testing-1 validator1 --home=$HOME/.reserved/validator1 +reserved init --chain-id=testing-1 validator2 --home=$HOME/.reserved/validator2 +reserved init --chain-id=testing-1 validator3 --home=$HOME/.reserved/validator3 + +# create keys for all three validators +# cosmos1wa3u4knw74r598quvzydvca42qsmk6jrzmgy07 +echo $(cat /Users/donglieu/script/keys/mnemonic1)| reserved keys add validator1 --recover --keyring-backend=test --home=$HOME/.reserved/validator1 +# cosmos1w7f3xx7e75p4l7qdym5msqem9rd4dyc4752spg +echo $(cat /Users/donglieu/script/keys/mnemonic2)| reserved keys add validator2 --recover --keyring-backend=test --home=$HOME/.reserved/validator2 +# cosmos1g9v3zjt6rfkwm4s8sw9wu4jgz9me8pn27f8nyc +echo $(cat /Users/donglieu/script/keys/mnemonic3)| reserved keys add validator3 --recover --keyring-backend=test --home=$HOME/.reserved/validator3 + +# create validator node with tokens to transfer to the three other nodes +reserved genesis add-genesis-account cosmos1wa3u4knw74r598quvzydvca42qsmk6jrzmgy07 10000000000000000000000000000000stake,10000000000000000000000000000000gaia --home=$HOME/.reserved/validator1 +reserved genesis add-genesis-account cosmos1w7f3xx7e75p4l7qdym5msqem9rd4dyc4752spg 10000000000000000000000000000000stake,10000000000000000000000000000000gaia --home=$HOME/.reserved/validator1 +reserved genesis add-genesis-account cosmos1g9v3zjt6rfkwm4s8sw9wu4jgz9me8pn27f8nyc 10000000000000000000000000000000stake,10000000000000000000000000000000gaia --home=$HOME/.reserved/validator1 +reserved genesis add-genesis-account cosmos1wa3u4knw74r598quvzydvca42qsmk6jrzmgy07 10000000000000000000000000000000stake,10000000000000000000000000000000gaia --home=$HOME/.reserved/validator2 +reserved genesis add-genesis-account cosmos1w7f3xx7e75p4l7qdym5msqem9rd4dyc4752spg 10000000000000000000000000000000stake,10000000000000000000000000000000gaia --home=$HOME/.reserved/validator2 +reserved genesis add-genesis-account cosmos1g9v3zjt6rfkwm4s8sw9wu4jgz9me8pn27f8nyc 10000000000000000000000000000000stake,10000000000000000000000000000000gaia --home=$HOME/.reserved/validator2 +reserved genesis add-genesis-account cosmos1wa3u4knw74r598quvzydvca42qsmk6jrzmgy07 10000000000000000000000000000000stake,10000000000000000000000000000000gaia --home=$HOME/.reserved/validator3 +reserved genesis add-genesis-account cosmos1w7f3xx7e75p4l7qdym5msqem9rd4dyc4752spg 10000000000000000000000000000000stake,10000000000000000000000000000000gaia --home=$HOME/.reserved/validator3 +reserved genesis add-genesis-account cosmos1g9v3zjt6rfkwm4s8sw9wu4jgz9me8pn27f8nyc 10000000000000000000000000000000stake,10000000000000000000000000000000gaia --home=$HOME/.reserved/validator3 +reserved genesis gentx validator1 1000000000000000000000stake --keyring-backend=test --home=$HOME/.reserved/validator1 --chain-id=testing-1 +reserved genesis gentx validator2 1000000000000000000000stake --keyring-backend=test --home=$HOME/.reserved/validator2 --chain-id=testing-1 +reserved genesis gentx validator3 1000000000000000000000stake --keyring-backend=test --home=$HOME/.reserved/validator3 --chain-id=testing-1 + +cp validator2/config/gentx/*.json $HOME/.reserved/validator1/config/gentx/ +cp validator3/config/gentx/*.json $HOME/.reserved/validator1/config/gentx/ +reserved genesis collect-gentxs --home=$HOME/.reserved/validator1 +reserved genesis collect-gentxs --home=$HOME/.reserved/validator2 +reserved genesis collect-gentxs --home=$HOME/.reserved/validator3 + +cp validator1/config/genesis.json $HOME/.reserved/validator2/config/genesis.json +cp validator1/config/genesis.json $HOME/.reserved/validator3/config/genesis.json + + +# change app.toml values +VALIDATOR1_APP_TOML=$HOME/.reserved/validator1/config/app.toml +VALIDATOR2_APP_TOML=$HOME/.reserved/validator2/config/app.toml +VALIDATOR3_APP_TOML=$HOME/.reserved/validator3/config/app.toml + +# validator1 +sed -i -E 's|localhost:9090|localhost:9050|g' $VALIDATOR1_APP_TOML +sed -i -E 's|minimum-gas-prices = ""|minimum-gas-prices = "0.0001stake"|g' $VALIDATOR1_APP_TOML + +# validator2 +sed -i -E 's|tcp://localhost:1317|tcp://localhost:1316|g' $VALIDATOR2_APP_TOML +# sed -i -E 's|0.0.0.0:9090|0.0.0.0:9088|g' $VALIDATOR2_APP_TOML +sed -i -E 's|localhost:9090|localhost:9088|g' $VALIDATOR2_APP_TOML +# sed -i -E 's|0.0.0.0:9091|0.0.0.0:9089|g' $VALIDATOR2_APP_TOML +sed -i -E 's|localhost:9091|localhost:9089|g' $VALIDATOR2_APP_TOML +sed -i -E 's|minimum-gas-prices = ""|minimum-gas-prices = "0.0001stake"|g' $VALIDATOR2_APP_TOML + +# validator3 +sed -i -E 's|tcp://localhost:1317|tcp://localhost:1315|g' $VALIDATOR3_APP_TOML +# sed -i -E 's|0.0.0.0:9090|0.0.0.0:9086|g' $VALIDATOR3_APP_TOML +sed -i -E 's|localhost:9090|localhost:9086|g' $VALIDATOR3_APP_TOML +# sed -i -E 's|0.0.0.0:9091|0.0.0.0:9087|g' $VALIDATOR3_APP_TOML +sed -i -E 's|localhost:9091|localhost:9087|g' $VALIDATOR3_APP_TOML +sed -i -E 's|minimum-gas-prices = ""|minimum-gas-prices = "0.0001stake"|g' $VALIDATOR3_APP_TOML + +# change config.toml values +VALIDATOR1_CONFIG=$HOME/.reserved/validator1/config/config.toml +VALIDATOR2_CONFIG=$HOME/.reserved/validator2/config/config.toml +VALIDATOR3_CONFIG=$HOME/.reserved/validator3/config/config.toml + + +# validator1 +sed -i -E 's|allow_duplicate_ip = false|allow_duplicate_ip = true|g' $VALIDATOR1_CONFIG +# sed -i -E 's|prometheus = false|prometheus = true|g' $VALIDATOR1_CONFIG + + +# validator2 +sed -i -E 's|tcp://127.0.0.1:26658|tcp://127.0.0.1:26655|g' $VALIDATOR2_CONFIG +sed -i -E 's|tcp://127.0.0.1:26657|tcp://127.0.0.1:26654|g' $VALIDATOR2_CONFIG +sed -i -E 's|tcp://0.0.0.0:26656|tcp://0.0.0.0:26653|g' $VALIDATOR2_CONFIG +sed -i -E 's|allow_duplicate_ip = false|allow_duplicate_ip = true|g' $VALIDATOR2_CONFIG +sed -i -E 's|prometheus = false|prometheus = true|g' $VALIDATOR2_CONFIG +sed -i -E 's|prometheus_listen_addr = ":26660"|prometheus_listen_addr = ":26630"|g' $VALIDATOR2_CONFIG + +# validator3 +sed -i -E 's|tcp://127.0.0.1:26658|tcp://127.0.0.1:26652|g' $VALIDATOR3_CONFIG +sed -i -E 's|tcp://127.0.0.1:26657|tcp://127.0.0.1:26651|g' $VALIDATOR3_CONFIG +sed -i -E 's|tcp://0.0.0.0:26656|tcp://0.0.0.0:26650|g' $VALIDATOR3_CONFIG +sed -i -E 's|allow_duplicate_ip = false|allow_duplicate_ip = true|g' $VALIDATOR3_CONFIG +sed -i -E 's|prometheus = false|prometheus = true|g' $VALIDATOR3_CONFIG +sed -i -E 's|prometheus_listen_addr = ":26660"|prometheus_listen_addr = ":26620"|g' $VALIDATOR3_CONFIG + +# # update +# update_test_genesis () { +# # EX: update_test_genesis '.consensus_params["block"]["max_gas"]="100000000"' +# cat $HOME/.reserved/validator1/config/genesis.json | jq "$1" > tmp.json && mv tmp.json $HOME/.reserved/validator1/config/genesis.json +# cat $HOME/.reserved/validator2/config/genesis.json | jq "$1" > tmp.json && mv tmp.json $HOME/.reserved/validator2/config/genesis.json +# cat $HOME/.reserved/validator3/config/genesis.json | jq "$1" > tmp.json && mv tmp.json $HOME/.reserved/validator3/config/genesis.json +# } + +# update_test_genesis '.app_state["gov"]["voting_params"]["voting_period"] = "30s"' +# update_test_genesis '.app_state["mint"]["params"]["mint_denom"]= "stake"' +# update_test_genesis '.app_state["gov"]["deposit_params"]["min_deposit"]=[{"denom": "stake","amount": "1000000"}]' +# update_test_genesis '.app_state["crisis"]["constant_fee"]={"denom": "stake","amount": "1000"}' +# update_test_genesis '.app_state["staking"]["params"]["bond_denom"]="stake"' + + +# copy validator1 genesis file to validator2-3 +cp $HOME/.reserved/validator1/config/genesis.json $HOME/.reserved/validator2/config/genesis.json +cp $HOME/.reserved/validator1/config/genesis.json $HOME/.reserved/validator3/config/genesis.json + +# copy tendermint node id of validator1 to persistent peers of validator2-3 +node1=$(reserved tendermint show-node-id --home=$HOME/.reserved/validator1) +node2=$(reserved tendermint show-node-id --home=$HOME/.reserved/validator2) +node3=$(reserved tendermint show-node-id --home=$HOME/.reserved/validator3) +sed -i -E "s|persistent_peers = \"\"|persistent_peers = \"$node1@localhost:26656,$node2@localhost:26653,$node3@localhost:26650\"|g" $HOME/.reserved/validator1/config/config.toml +sed -i -E "s|persistent_peers = \"\"|persistent_peers = \"$node1@localhost:26656,$node2@localhost:26653,$node3@localhost:26650\"|g" $HOME/.reserved/validator2/config/config.toml +sed -i -E "s|persistent_peers = \"\"|persistent_peers = \"$node1@localhost:26656,$node2@localhost:26653,$node3@localhost:26650\"|g" $HOME/.reserved/validator3/config/config.toml + + +# # start all three validators/ +# reserved start --home=$HOME/.reserved/validator1 +screen -S gaia1 -t gaia1 -d -m reserved start --home=$HOME/.reserved/validator1 +screen -S gaia2 -t gaia2 -d -m reserved start --home=$HOME/.reserved/validator2 +screen -S gaia3 -t gaia3 -d -m reserved start --home=$HOME/.reserved/validator3 +# reserved start --home=$HOME/.reserved/validator3 + +# screen -r gaia1 + +sleep 7 + +# reserved tx bank send cosmos1wa3u4knw74r598quvzydvca42qsmk6jrzmgy07 cosmos1w7f3xx7e75p4l7qdym5msqem9rd4dyc4752spg 100000stake --keyring-backend=test --chain-id=testing-1 -y --home=$HOME/.reserved/validator1 --fees 10stake + +# sleep 7 +# reserved tx bank send cosmos1f7twgcq4ypzg7y24wuywy06xmdet8pc4473tnq cosmos1qvuhm5m644660nd8377d6l7yz9e9hhm9evmx3x 10000000000000000000000stake --keyring-backend=test --chain-id=testing-1 -y --home=$HOME/.reserved/validator1 --fees 200000stake +# sleep 7 +# reserved tx bank send gaia1f7twgcq4ypzg7y24wuywy06xmdet8pc4hhtf9t gaia16gjg8p5fedy48wf403jwmz2cxlwqtkqlwe0lug 10000000000000000000000stake --keyring-backend=test --chain-id=testing-1 -y --home=$HOME/.reserved/validator1 --fees 10stake + +reserved q staking validators +reserved keys list --keyring-backend=test --home=$HOME/.reserved/validator1 +reserved keys list --keyring-backend=test --home=$HOME/.reserved/validator2 +reserved keys list --keyring-backend=test --home=$HOME/.reserved/validator3 + + +# reserved in-place-testnet testing-1 cosmosvaloper1w7f3xx7e75p4l7qdym5msqem9rd4dyc4mq79dm --home $HOME/.reserved/validator1 +# sleep 30 +# killall reserved || true +# # # cosmosvaloper1wa3u4knw74r598quvzydvca42qsmk6jr80u3rd +# reserved in-place-testnet testing-1 cosmosvaloper1wa3u4knw74r598quvzydvca42qsmk6jr80u3rd --home $HOME/.reserved/validator1 --accounts-to-fund="cosmos1f7twgcq4ypzg7y24wuywy06xmdet8pc4473tnq,cosmos1qvuhm5m644660nd8377d6l7yz9e9hhm9evmx3x" --skip-confirmation +# reserved in-place-testnet testing-1 cosmosvaloper1wa3u4knw74r598quvzydvca42qsmk6jr80u3rd --home $HOME/.reserved/validator1 --accounts-to-fund="cosmos1f7twgcq4ypzg7y24wuywy06xmdet8pc4473tnq,cosmos1qvuhm5m644660nd8377d6l7yz9e9hhm9evmx3x" +# echo "y" | reserved testnet testing-1 cosmosvaloper1wa3u4knw74r598quvzydvca42qsmk6jr80u3rd --home $HOME/.reserved/validator1 --accounts-to-fund="cosmos1f7twgcq4ypzg7y24wuywy06xmdet8pc4473tnq,cosmos1qvuhm5m644660nd8377d6l7yz9e9hhm9evmx3x" + +# reserved testnet in-place-testnet testing-1 cosmosvaloper1w7f3xx7e75p4l7qdym5msqem9rd4dyc4mq79dm --home $HOME/.reserved/validator1 --validator-pukey=xzaD8WNQopfBWPuA4U/WMA+rNLRQATJS3KWspcyigTo= --validator-privkey=6dq+/KHNvyiw2TToCgOpUpQKIzrLs69Rb8Az39xvmxPHNoPxY1Cil8FY+4DhT9YwD6s0tFABMlLcpaylzKKBOg== --accounts-to-fund="cosmos1f7twgcq4ypzg7y24wuywy06xmdet8pc4473tnq,cosmos1qvuhm5m644660nd8377d6l7yz9e9hhm9evmx3x" \ No newline at end of file diff --git a/proto/reserve/psm/module/v1/module.proto b/proto/reserve/psm/module/v1/module.proto new file mode 100644 index 0000000..e6691c0 --- /dev/null +++ b/proto/reserve/psm/module/v1/module.proto @@ -0,0 +1,18 @@ +syntax = "proto3"; +package reserve.psm.module.v1; + +import "cosmos/app/v1alpha1/module.proto"; + +option go_package = "github.com/onomyprotocol/reserve/x/psm/types"; + +// Module is the config object for the module. +message Module { + option (cosmos.app.v1alpha1.module) = { + go_import: "github.com/onomyprotocol/reserve/x/psm" + }; + + // authority defines the custom module authority. If not set, defaults to the governance module. + string authority = 1; + + +} \ No newline at end of file diff --git a/proto/reserve/psm/v1/genesis.proto b/proto/reserve/psm/v1/genesis.proto new file mode 100644 index 0000000..67ea474 --- /dev/null +++ b/proto/reserve/psm/v1/genesis.proto @@ -0,0 +1,17 @@ +syntax = "proto3"; +package reserve.psm.v1; + +import "amino/amino.proto"; +import "gogoproto/gogo.proto"; +import "reserve/psm/v1/params.proto"; + +option go_package = "github.com/onomyprotocol/reserve/x/psm/types"; + +// GenesisState defines the psm module's genesis state. +message GenesisState { + // params defines all the parameters of the module. + Params params = 1 [ + (gogoproto.nullable) = false, + (amino.dont_omitempty) = true + ]; +} diff --git a/proto/reserve/psm/v1/params.proto b/proto/reserve/psm/v1/params.proto new file mode 100644 index 0000000..1aa4903 --- /dev/null +++ b/proto/reserve/psm/v1/params.proto @@ -0,0 +1,23 @@ +syntax = "proto3"; +package reserve.psm.v1; + +import "amino/amino.proto"; +import "gogoproto/gogo.proto"; +import "cosmos_proto/cosmos.proto"; + +option go_package = "github.com/onomyprotocol/reserve/x/psm/types"; + +message Params { + bytes limit_total = 1 [ + (cosmos_proto.scalar) = "cosmos.Int", + (gogoproto.customtype) = "cosmossdk.io/math.Int", + (gogoproto.nullable) = false, + (amino.dont_omitempty) = true + ]; + + bytes acceptable_price_ratio = 2 [ + (cosmos_proto.scalar) = "cosmos.Dec", + (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", + (gogoproto.nullable) = false + ]; +} \ No newline at end of file diff --git a/proto/reserve/psm/v1/proposals.proto b/proto/reserve/psm/v1/proposals.proto new file mode 100644 index 0000000..ac48bde --- /dev/null +++ b/proto/reserve/psm/v1/proposals.proto @@ -0,0 +1,62 @@ +syntax = "proto3"; +package reserve.psm.v1; + +import "gogoproto/gogo.proto"; +import "cosmos_proto/cosmos.proto"; +import "amino/amino.proto"; + +option go_package = "github.com/onomyprotocol/reserve/x/psm/types"; + +message AddStableCoinProposal { + string title = 1; + string description = 2; + string denom = 3; + bytes limit_total = 4 [ + (cosmos_proto.scalar) = "cosmos.Int", + (gogoproto.customtype) = "cosmossdk.io/math.Int", + (gogoproto.nullable) = false, + (amino.dont_omitempty) = true + ]; + bytes price = 5 [ + (cosmos_proto.scalar) = "cosmos.Dec", + (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", + (gogoproto.nullable) = false + ]; + bytes fee_in = 6 [ + (cosmos_proto.scalar) = "cosmos.Dec", + (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", + (gogoproto.nullable) = false + ]; + bytes fee_out = 7 [ + (cosmos_proto.scalar) = "cosmos.Dec", + (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", + (gogoproto.nullable) = false + ]; +} + +message UpdatesStableCoinProposal { + string title = 1; + string description = 2; + string denom = 3; + bytes updates_limit_total = 4 [ + (cosmos_proto.scalar) = "cosmos.Int", + (gogoproto.customtype) = "cosmossdk.io/math.Int", + (gogoproto.nullable) = false, + (amino.dont_omitempty) = true + ]; + bytes price = 5 [ + (cosmos_proto.scalar) = "cosmos.Dec", + (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", + (gogoproto.nullable) = false + ]; + bytes fee_in = 6 [ + (cosmos_proto.scalar) = "cosmos.Dec", + (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", + (gogoproto.nullable) = false + ]; + bytes fee_out = 7 [ + (cosmos_proto.scalar) = "cosmos.Dec", + (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", + (gogoproto.nullable) = false + ]; +} \ No newline at end of file diff --git a/proto/reserve/psm/v1/psm.proto b/proto/reserve/psm/v1/psm.proto new file mode 100644 index 0000000..1fba146 --- /dev/null +++ b/proto/reserve/psm/v1/psm.proto @@ -0,0 +1,35 @@ +syntax = "proto3"; +package reserve.psm.v1; + +import "gogoproto/gogo.proto"; +import "cosmos_proto/cosmos.proto"; +import "amino/amino.proto"; + +option go_package = "github.com/onomyprotocol/reserve/x/psm/types"; + +message Stablecoin { + string denom = 1; + // limit total stablecoin module support + bytes limit_total = 2 [ + (cosmos_proto.scalar) = "cosmos.Int", + (gogoproto.customtype) = "cosmossdk.io/math.Int", + (gogoproto.nullable) = false, + (amino.dont_omitempty) = true + ]; + // price is the amount of stablecoin to exchange for 1 unit of nomUSD (very close to 1) + bytes price = 3 [ + (cosmos_proto.scalar) = "cosmos.Dec", + (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", + (gogoproto.nullable) = false + ]; + bytes fee_in = 4 [ + (cosmos_proto.scalar) = "cosmos.Dec", + (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", + (gogoproto.nullable) = false + ]; + bytes fee_out = 5 [ + (cosmos_proto.scalar) = "cosmos.Dec", + (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", + (gogoproto.nullable) = false + ]; +} \ No newline at end of file diff --git a/proto/reserve/psm/v1/query.proto b/proto/reserve/psm/v1/query.proto new file mode 100644 index 0000000..2ab143f --- /dev/null +++ b/proto/reserve/psm/v1/query.proto @@ -0,0 +1,30 @@ +syntax = "proto3"; +package reserve.psm.v1; + +import "amino/amino.proto"; +import "gogoproto/gogo.proto"; +import "google/api/annotations.proto"; +import "cosmos/base/query/v1beta1/pagination.proto"; +import "reserve/psm/v1/params.proto"; + +option go_package = "github.com/onomyprotocol/reserve/x/psm/types"; + +// Query defines the gRPC querier service. +service Query { + // Parameters queries the parameters of the module. + rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { + option (google.api.http).get = "/onomyprotocol/reserve/psm/v1/params"; + } +} + +// QueryParamsRequest is request type for the Query/Params RPC method. +message QueryParamsRequest {} + +// QueryParamsResponse is response type for the Query/Params RPC method. +message QueryParamsResponse { + // params holds all the parameters of this module. + Params params = 1 [ + (gogoproto.nullable) = false, + (amino.dont_omitempty) = true + ]; +} \ No newline at end of file diff --git a/proto/reserve/psm/v1/tx.proto b/proto/reserve/psm/v1/tx.proto new file mode 100644 index 0000000..4bf57e0 --- /dev/null +++ b/proto/reserve/psm/v1/tx.proto @@ -0,0 +1,40 @@ +syntax = "proto3"; +package reserve.psm.v1; + +import "amino/amino.proto"; +import "cosmos/msg/v1/msg.proto"; +import "cosmos_proto/cosmos.proto"; +import "gogoproto/gogo.proto"; +import "reserve/psm/v1/params.proto"; + +option go_package = "github.com/onomyprotocol/reserve/x/psm/types"; + +// Msg defines the Msg service. +service Msg { + option (cosmos.msg.v1.service) = true; + + // UpdateParams defines a (governance) operation for updating the module + // parameters. The authority defaults to the x/gov module account. + rpc UpdateParams(MsgUpdateParams) returns (MsgUpdateParamsResponse); +} + +// MsgUpdateParams is the Msg/UpdateParams request type. +message MsgUpdateParams { + option (cosmos.msg.v1.signer) = "authority"; + option (amino.name) = "reserve/x/psm/MsgUpdateParams"; + + // authority is the address that controls the module (defaults to x/gov unless overwritten). + string authority = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + + // params defines the module parameters to update. + // + // NOTE: All parameters must be supplied. + Params params = 2 [ + (gogoproto.nullable) = false, + (amino.dont_omitempty) = true + ]; +} + +// MsgUpdateParamsResponse defines the response structure for executing a +// MsgUpdateParams message. +message MsgUpdateParamsResponse {} \ No newline at end of file diff --git a/testutil/keeper/psm.go b/testutil/keeper/psm.go new file mode 100644 index 0000000..8e044ed --- /dev/null +++ b/testutil/keeper/psm.go @@ -0,0 +1,56 @@ +package keeper + +import ( + "testing" + + "cosmossdk.io/core/address" + "cosmossdk.io/log" + "cosmossdk.io/store" + "cosmossdk.io/store/metrics" + storetypes "cosmossdk.io/store/types" + cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + dbm "github.com/cosmos/cosmos-db" + "github.com/cosmos/cosmos-sdk/codec" + addresscodec "github.com/cosmos/cosmos-sdk/codec/address" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/runtime" + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/stretchr/testify/require" + + "github.com/onomyprotocol/reserve/x/psm/keeper" + "github.com/onomyprotocol/reserve/x/psm/types" +) + +func PsmKeeper(t testing.TB) (keeper.Keeper, sdk.Context, address.Codec) { + storeKey := storetypes.NewKVStoreKey(types.StoreKey) + + db := dbm.NewMemDB() + stateStore := store.NewCommitMultiStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) + stateStore.MountStoreWithDB(storeKey, storetypes.StoreTypeIAVL, db) + require.NoError(t, stateStore.LoadLatestVersion()) + + registry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(registry) + authority := authtypes.NewModuleAddress(govtypes.ModuleName) + addressCodec := addresscodec.NewBech32Codec(sdk.GetConfig().GetBech32AccountAddrPrefix()) + + k := keeper.NewKeeper( + cdc, + addressCodec, + runtime.NewKVStoreService(storeKey), + log.NewNopLogger(), + authority.String(), + nil, + ) + + ctx := sdk.NewContext(stateStore, cmtproto.Header{}, false, log.NewNopLogger()) + + // Initialize params + if err := k.Params.Set(ctx, types.DefaultParams()); err != nil { + t.Fatalf("failed to set params: %v", err) + } + + return k, ctx, addressCodec +} diff --git a/testutil/network/network.go b/testutil/network/network.go index 29c13c7..072c95c 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -1,80 +1,80 @@ package network -import ( - "fmt" - "testing" +// import ( +// "fmt" +// "testing" - "github.com/cosmos/cosmos-sdk/testutil/network" - "github.com/stretchr/testify/require" +// "github.com/cosmos/cosmos-sdk/testutil/network" +// "github.com/stretchr/testify/require" - "github.com/onomyprotocol/reserve/app" -) +// "github.com/onomyprotocol/reserve/app" +// ) -type ( - Network = network.Network - Config = network.Config -) +// type ( +// Network = network.Network +// Config = network.Config +// ) -// New creates instance with fully configured cosmos network. -// Accepts optional config, that will be used in place of the DefaultConfig() if provided. -func New(t *testing.T, configs ...Config) *Network { - t.Helper() - if len(configs) > 1 { - panic("at most one config should be provided") - } - var cfg network.Config - if len(configs) == 0 { - cfg = DefaultConfig() - } else { - cfg = configs[0] - } - net, err := network.New(t, t.TempDir(), cfg) - require.NoError(t, err) - _, err = net.WaitForHeight(1) - require.NoError(t, err) - t.Cleanup(net.Cleanup) - return net -} +// // New creates instance with fully configured cosmos network. +// // Accepts optional config, that will be used in place of the DefaultConfig() if provided. +// func New(t *testing.T, configs ...Config) *Network { +// t.Helper() +// if len(configs) > 1 { +// panic("at most one config should be provided") +// } +// var cfg network.Config +// if len(configs) == 0 { +// cfg = DefaultConfig() +// } else { +// cfg = configs[0] +// } +// net, err := network.New(t, t.TempDir(), cfg) +// require.NoError(t, err) +// _, err = net.WaitForHeight(1) +// require.NoError(t, err) +// t.Cleanup(net.Cleanup) +// return net +// } -// DefaultConfig will initialize config for the network with custom application, -// genesis and single validator. All other parameters are inherited from cosmos-sdk/testutil/network.DefaultConfig -func DefaultConfig() network.Config { - cfg, err := network.DefaultConfigWithAppConfig(app.AppConfig()) - if err != nil { - panic(err) - } - ports, err := freePorts(3) - if err != nil { - panic(err) - } - if cfg.APIAddress == "" { - cfg.APIAddress = fmt.Sprintf("tcp://0.0.0.0:%s", ports[0]) - } - if cfg.RPCAddress == "" { - cfg.RPCAddress = fmt.Sprintf("tcp://0.0.0.0:%s", ports[1]) - } - if cfg.GRPCAddress == "" { - cfg.GRPCAddress = fmt.Sprintf("0.0.0.0:%s", ports[2]) - } - return cfg -} +// // DefaultConfig will initialize config for the network with custom application, +// // genesis and single validator. All other parameters are inherited from cosmos-sdk/testutil/network.DefaultConfig +// func DefaultConfig() network.Config { +// cfg, err := network.DefaultConfigWithAppConfig(app.AppConfig()) +// if err != nil { +// panic(err) +// } +// ports, err := freePorts(3) +// if err != nil { +// panic(err) +// } +// if cfg.APIAddress == "" { +// cfg.APIAddress = fmt.Sprintf("tcp://0.0.0.0:%s", ports[0]) +// } +// if cfg.RPCAddress == "" { +// cfg.RPCAddress = fmt.Sprintf("tcp://0.0.0.0:%s", ports[1]) +// } +// if cfg.GRPCAddress == "" { +// cfg.GRPCAddress = fmt.Sprintf("0.0.0.0:%s", ports[2]) +// } +// return cfg +// } -// freePorts return the available ports based on the number of requested ports. -func freePorts(n int) ([]string, error) { - closeFns := make([]func() error, n) - ports := make([]string, n) - for i := 0; i < n; i++ { - _, port, closeFn, err := network.FreeTCPAddr() - if err != nil { - return nil, err - } - ports[i] = port - closeFns[i] = closeFn - } - for _, closeFn := range closeFns { - if err := closeFn(); err != nil { - return nil, err - } - } - return ports, nil -} +// // freePorts return the available ports based on the number of requested ports. +// func freePorts(n int) ([]string, error) { +// closeFns := make([]func() error, n) +// ports := make([]string, n) +// for i := 0; i < n; i++ { +// _, port, closeFn, err := network.FreeTCPAddr() +// if err != nil { +// return nil, err +// } +// ports[i] = port +// closeFns[i] = closeFn +// } +// for _, closeFn := range closeFns { +// if err := closeFn(); err != nil { +// return nil, err +// } +// } +// return ports, nil +// } diff --git a/x/psm/client/cli/tx.go b/x/psm/client/cli/tx.go new file mode 100644 index 0000000..97ef6b4 --- /dev/null +++ b/x/psm/client/cli/tx.go @@ -0,0 +1,103 @@ +package cli + +import ( + "fmt" + + "cosmossdk.io/math" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/tx" + sdk "github.com/cosmos/cosmos-sdk/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" + "github.com/spf13/cobra" + + "github.com/onomyprotocol/reserve/x/psm/types" +) + +func NewCmdSubmitAddStableCoinProposal() *cobra.Command { + cmd := &cobra.Command{ + Use: "add-stable-coin [title] [description] [denom] [limit-total] [price] [fee_in] [fee_out] [proposer] [deposit]", + Args: cobra.ExactArgs(9), + Short: "Submit an add stable coin proposal", + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + limitTotal, ok := math.NewIntFromString(args[3]) + if !ok { + return fmt.Errorf("value %s cannot constructs Int from string", args[3]) + } + + price, err := math.LegacyNewDecFromStr(args[4]) + if err != nil { + return err + } + feeIn, err := math.LegacyNewDecFromStr(args[5]) + if err != nil { + return err + } + feeOut, err := math.LegacyNewDecFromStr(args[6]) + if err != nil { + return err + } + from := sdk.MustAccAddressFromBech32(args[7]) + + content := types.NewAddStableCoinProposal( + args[0], args[1], args[2], limitTotal, price, feeIn, feeOut, + ) + + deposit, err := sdk.ParseCoinsNormalized(args[8]) + if err != nil { + return err + } + + msg, err := govtypes.NewMsgSubmitProposal(&content, deposit, from) + if err != nil { + return err + } + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) + }, + } + return cmd +} +func NewCmdUpdatesStableCoinProposal() *cobra.Command { + cmd := &cobra.Command{ + Use: "update-limit-total-stable-coin [title] [description] [denom] [limit-total-update] [price] [fee_in] [fee_out] [deposit]", + Args: cobra.ExactArgs(8), + Short: "Submit update limit total stable coin proposal", + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + limitTotalUpdate, ok := math.NewIntFromString(args[3]) + if !ok { + return fmt.Errorf("value %s cannot constructs Int from string", args[3]) + } + price, err := math.LegacyNewDecFromStr(args[4]) + feeIn, err := math.LegacyNewDecFromStr(args[5]) + feeOut, err := math.LegacyNewDecFromStr(args[6]) + from := clientCtx.GetFromAddress() + content := types.NewUpdatesStableCoinProposal( + args[0], args[1], args[2], limitTotalUpdate, price, feeIn, feeOut, + ) + + deposit, err := sdk.ParseCoinsNormalized(args[7]) + if err != nil { + return err + } + + msg, err := govtypes.NewMsgSubmitProposal(&content, deposit, from) + if err != nil { + return err + } + + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) + }, + } + + return cmd +} diff --git a/x/psm/keeper/keeper.go b/x/psm/keeper/keeper.go new file mode 100644 index 0000000..84895b3 --- /dev/null +++ b/x/psm/keeper/keeper.go @@ -0,0 +1,125 @@ +package keeper + +import ( + "context" + "fmt" + + "cosmossdk.io/collections" + "cosmossdk.io/core/address" + "cosmossdk.io/core/store" + "cosmossdk.io/log" + storetypes "cosmossdk.io/store/types" + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/onomyprotocol/reserve/x/psm/types" +) + +type ( + Keeper struct { + cdc codec.BinaryCodec + addressCodec address.Codec + storeService store.KVStoreService + logger log.Logger + + // the address capable of executing a MsgUpdateParams message. + // Typically, this should be the x/gov module account. + authority string + + Schema collections.Schema + Params collections.Item[types.Params] + // this line is used by starport scaffolding # collection/type + + bankKeeper types.BankKeeper + } +) + +func NewKeeper( + cdc codec.BinaryCodec, + addressCodec address.Codec, + storeService store.KVStoreService, + logger log.Logger, + authority string, + + bankKeeper types.BankKeeper, +) Keeper { + if _, err := addressCodec.StringToBytes(authority); err != nil { + panic(fmt.Sprintf("invalid authority address %s: %s", authority, err)) + } + + sb := collections.NewSchemaBuilder(storeService) + + k := Keeper{ + cdc: cdc, + addressCodec: addressCodec, + storeService: storeService, + authority: authority, + logger: logger, + + bankKeeper: bankKeeper, + Params: collections.NewItem(sb, types.ParamsKey, "params", codec.CollValue[types.Params](cdc)), + // this line is used by starport scaffolding # collection/instantiate + } + + schema, err := sb.Build() + if err != nil { + panic(err) + } + k.Schema = schema + + return k +} + +// GetAuthority returns the module's authority. +func (k Keeper) GetAuthority() string { + return k.authority +} + +// Logger returns a module-specific logger. +func (k Keeper) Logger() log.Logger { + return k.logger.With("module", fmt.Sprintf("x/%s", types.ModuleName)) +} + +func (k Keeper) SetStablecoin(ctx context.Context, s types.Stablecoin) { + store := k.storeService.OpenKVStore(ctx) + + key := types.GetKeyStableCoin(s.Denom) + bz := k.cdc.MustMarshal(&s) + + store.Set(key, bz) +} + +func (k Keeper) GetStablecoin(ctx context.Context, denom string) (types.Stablecoin, bool) { + store := k.storeService.OpenKVStore(ctx) + + key := types.GetKeyStableCoin(denom) + + bz, err := store.Get(key) + if bz == nil || err != nil { + return types.Stablecoin{}, false + } + + var token types.Stablecoin + k.cdc.MustUnmarshal(bz, &token) + + return token, true +} + +func (k Keeper) IterateStablecoin(ctx context.Context, cb func(red types.Stablecoin) (stop bool)) error { + store := k.storeService.OpenKVStore(ctx) + + iterator, err := store.Iterator(types.KeyStableCoin, storetypes.PrefixEndBytes(types.KeyStableCoin)) + if err != nil { + return err + } + + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + var token types.Stablecoin + k.cdc.MustUnmarshal(iterator.Value(), &token) + if cb(token) { + break + } + } + return nil +} diff --git a/x/psm/keeper/msg_server.go b/x/psm/keeper/msg_server.go new file mode 100644 index 0000000..dcdec19 --- /dev/null +++ b/x/psm/keeper/msg_server.go @@ -0,0 +1,17 @@ +package keeper + +import ( + "github.com/onomyprotocol/reserve/x/psm/types" +) + +type msgServer struct { + Keeper +} + +// NewMsgServerImpl returns an implementation of the MsgServer interface +// for the provided Keeper. +func NewMsgServerImpl(keeper Keeper) types.MsgServer { + return &msgServer{Keeper: keeper} +} + +var _ types.MsgServer = msgServer{} diff --git a/x/psm/keeper/msg_update_params.go b/x/psm/keeper/msg_update_params.go new file mode 100644 index 0000000..93e477b --- /dev/null +++ b/x/psm/keeper/msg_update_params.go @@ -0,0 +1,29 @@ +package keeper + +import ( + "context" + + errorsmod "cosmossdk.io/errors" + + "github.com/onomyprotocol/reserve/x/psm/types" +) + +func (k msgServer) UpdateParams(ctx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { + if _, err := k.addressCodec.StringToBytes(req.Authority); err != nil { + return nil, errorsmod.Wrap(err, "invalid authority address") + } + + if k.GetAuthority() != req.Authority { + return nil, errorsmod.Wrapf(types.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.GetAuthority(), req.Authority) + } + + if err := req.Params.Validate(); err != nil { + return nil, err + } + + if err := k.SetParams(ctx, req.Params); err != nil { + return nil, err + } + + return &types.MsgUpdateParamsResponse{}, nil +} diff --git a/x/psm/keeper/msg_update_params_test.go b/x/psm/keeper/msg_update_params_test.go new file mode 100644 index 0000000..747ee28 --- /dev/null +++ b/x/psm/keeper/msg_update_params_test.go @@ -0,0 +1,66 @@ +package keeper_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + + keepertest "github.com/onomyprotocol/reserve/testutil/keeper" + "github.com/onomyprotocol/reserve/x/psm/keeper" + "github.com/onomyprotocol/reserve/x/psm/types" +) + +func TestMsgUpdateParams(t *testing.T) { + k, ctx, _ := keepertest.PsmKeeper(t) + ms := keeper.NewMsgServerImpl(k) + + params := types.DefaultParams() + require.NoError(t, k.Params.Set(ctx, params)) + + // default params + testCases := []struct { + name string + input *types.MsgUpdateParams + expErr bool + expErrMsg string + }{ + { + name: "invalid authority", + input: &types.MsgUpdateParams{ + Authority: "invalid", + Params: params, + }, + expErr: true, + expErrMsg: "invalid authority", + }, + { + name: "send enabled param", + input: &types.MsgUpdateParams{ + Authority: k.GetAuthority(), + Params: types.Params{}, + }, + expErr: false, + }, + { + name: "all good", + input: &types.MsgUpdateParams{ + Authority: k.GetAuthority(), + Params: params, + }, + expErr: false, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + _, err := ms.UpdateParams(ctx, tc.input) + + if tc.expErr { + require.Error(t, err) + require.Contains(t, err.Error(), tc.expErrMsg) + } else { + require.NoError(t, err) + } + }) + } +} diff --git a/x/psm/keeper/params.go b/x/psm/keeper/params.go new file mode 100644 index 0000000..c84c2e7 --- /dev/null +++ b/x/psm/keeper/params.go @@ -0,0 +1,33 @@ +package keeper + +import ( + "context" + // sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/onomyprotocol/reserve/x/psm/types" +) + +func (k Keeper) SetParams(ctx context.Context, params types.Params) error { + store := k.storeService.OpenKVStore(ctx) + bz, err := k.cdc.Marshal(¶ms) + if err != nil { + return err + } + return store.Set(types.ParamsKey, bz) +} + +// GetParams gets the x/staking module parameters. +func (k Keeper) GetParams(ctx context.Context) (params types.Params, err error) { + store := k.storeService.OpenKVStore(ctx) + bz, err := store.Get(types.ParamsKey) + if err != nil { + return params, err + } + + if bz == nil { + return params, nil + } + + err = k.cdc.Unmarshal(bz, ¶ms) + return params, err +} diff --git a/x/psm/keeper/proposals.go b/x/psm/keeper/proposals.go new file mode 100644 index 0000000..17bbe65 --- /dev/null +++ b/x/psm/keeper/proposals.go @@ -0,0 +1,50 @@ +package keeper + +import ( + "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/onomyprotocol/reserve/x/psm/types" +) + +func (k Keeper) AddStableCoinProposal(ctx sdk.Context, c *types.AddStableCoinProposal) error { + if err := c.ValidateBasic(); err != nil { + return err + } + + _, found := k.GetStablecoin(ctx, c.Denom) + if found { + return fmt.Errorf("%s has existed", c.Denom) + } + + k.SetStablecoin(ctx, types.ConvertAddStableCoinToStablecoin(*c)) + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventAddStablecoin, + sdk.NewAttribute(types.AttributeStablecoinName, c.Denom), + ), + ) + return nil +} + +func (k Keeper) UpdatesStableCoinProposal(ctx sdk.Context, c *types.UpdatesStableCoinProposal) error { + if err := c.ValidateBasic(); err != nil { + return err + } + + _, found := k.GetStablecoin(ctx, c.Denom) + if !found { + return fmt.Errorf("%s not existed", c.Denom) + } + + k.SetStablecoin(ctx, types.ConvertUpdateStableCoinToStablecoin(*c)) + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventAddStablecoin, + sdk.NewAttribute(types.AttributeStablecoinName, c.Denom), + ), + ) + return nil +} diff --git a/x/psm/keeper/query.go b/x/psm/keeper/query.go new file mode 100644 index 0000000..61f32c7 --- /dev/null +++ b/x/psm/keeper/query.go @@ -0,0 +1,17 @@ +package keeper + +import ( + "github.com/onomyprotocol/reserve/x/psm/types" +) + +var _ types.QueryServer = queryServer{} + +// NewQueryServerImpl returns an implementation of the QueryServer interface +// for the provided Keeper. +func NewQueryServerImpl(k Keeper) types.QueryServer { + return queryServer{k} +} + +type queryServer struct { + k Keeper +} diff --git a/x/psm/keeper/query_params.go b/x/psm/keeper/query_params.go new file mode 100644 index 0000000..5c3e909 --- /dev/null +++ b/x/psm/keeper/query_params.go @@ -0,0 +1,30 @@ +package keeper + +import ( + "context" + "errors" + + "cosmossdk.io/collections" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/onomyprotocol/reserve/x/psm/types" +) + +func (q queryServer) Params(ctx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "invalid request") + } + + params, err := q.k.GetParams(ctx) + if err != nil { + if errors.Is(err, collections.ErrNotFound) { + return nil, status.Error(codes.NotFound, "not found") + } + + return nil, status.Error(codes.Internal, "internal error") + } + + return &types.QueryParamsResponse{Params: params}, nil +} diff --git a/x/psm/keeper/query_params_test.go b/x/psm/keeper/query_params_test.go new file mode 100644 index 0000000..c4c88b4 --- /dev/null +++ b/x/psm/keeper/query_params_test.go @@ -0,0 +1,23 @@ +package keeper_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + + keepertest "github.com/onomyprotocol/reserve/testutil/keeper" + "github.com/onomyprotocol/reserve/x/psm/keeper" + "github.com/onomyprotocol/reserve/x/psm/types" +) + +func TestParamsQuery(t *testing.T) { + k, ctx, _ := keepertest.PsmKeeper(t) + + qs := keeper.NewQueryServerImpl(k) + params := types.DefaultParams() + require.NoError(t, k.Params.Set(ctx, params)) + + response, err := qs.Params(ctx, &types.QueryParamsRequest{}) + require.NoError(t, err) + require.Equal(t, &types.QueryParamsResponse{Params: params}, response) +} diff --git a/x/psm/module/autocli.go b/x/psm/module/autocli.go new file mode 100644 index 0000000..c53a3e2 --- /dev/null +++ b/x/psm/module/autocli.go @@ -0,0 +1,35 @@ +package psm + +import ( + autocliv1 "cosmossdk.io/api/cosmos/autocli/v1" + + "github.com/onomyprotocol/reserve/x/psm/types" +) + +// AutoCLIOptions implements the autocli.HasAutoCLIConfig interface. +func (am AppModule) AutoCLIOptions() *autocliv1.ModuleOptions { + return &autocliv1.ModuleOptions{ + Query: &autocliv1.ServiceCommandDescriptor{ + Service: types.Query_serviceDesc.ServiceName, + RpcCommandOptions: []*autocliv1.RpcCommandOptions{ + { + RpcMethod: "Params", + Use: "params", + Short: "Shows the parameters of the module", + }, + // this line is used by ignite scaffolding # autocli/query + }, + }, + Tx: &autocliv1.ServiceCommandDescriptor{ + Service: types.Msg_serviceDesc.ServiceName, + EnhanceCustomCommand: true, // only required if you want to use the custom command + RpcCommandOptions: []*autocliv1.RpcCommandOptions{ + { + RpcMethod: "UpdateParams", + Skip: true, // skipped because authority gated + }, + // this line is used by ignite scaffolding # autocli/tx + }, + }, + } +} diff --git a/x/psm/module/genesis.go b/x/psm/module/genesis.go new file mode 100644 index 0000000..d81d945 --- /dev/null +++ b/x/psm/module/genesis.go @@ -0,0 +1,29 @@ +package psm + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/onomyprotocol/reserve/x/psm/keeper" + "github.com/onomyprotocol/reserve/x/psm/types" +) + +// InitGenesis initializes the module's state from a provided genesis state. +func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) error { + // this line is used by starport scaffolding # genesis/module/init + return k.Params.Set(ctx, genState.Params) +} + +// ExportGenesis returns the module's exported genesis. +func ExportGenesis(ctx sdk.Context, k keeper.Keeper) (*types.GenesisState, error) { + var err error + + genesis := types.DefaultGenesis() + genesis.Params, err = k.Params.Get(ctx) + if err != nil { + return nil, err + } + + // this line is used by starport scaffolding # genesis/module/export + + return genesis, nil +} diff --git a/x/psm/module/genesis_test.go b/x/psm/module/genesis_test.go new file mode 100644 index 0000000..dff81c4 --- /dev/null +++ b/x/psm/module/genesis_test.go @@ -0,0 +1,31 @@ +package psm_test + +import ( + "testing" + + keepertest "github.com/onomyprotocol/reserve/testutil/keeper" + "github.com/onomyprotocol/reserve/testutil/nullify" + psm "github.com/onomyprotocol/reserve/x/psm/module" + "github.com/onomyprotocol/reserve/x/psm/types" + "github.com/stretchr/testify/require" +) + +func TestGenesis(t *testing.T) { + genesisState := types.GenesisState{ + Params: types.DefaultParams(), + + // this line is used by starport scaffolding # genesis/test/state + } + + k, ctx, _ := keepertest.PsmKeeper(t) + err := psm.InitGenesis(ctx, k, genesisState) + require.NoError(t, err) + got, err := psm.ExportGenesis(ctx, k) + require.NoError(t, err) + require.NotNil(t, got) + + nullify.Fill(&genesisState) + nullify.Fill(got) + + // this line is used by starport scaffolding # genesis/test/assert +} diff --git a/x/psm/module/module.go b/x/psm/module/module.go new file mode 100644 index 0000000..8b99271 --- /dev/null +++ b/x/psm/module/module.go @@ -0,0 +1,227 @@ +package psm + +import ( + "context" + "encoding/json" + "fmt" + + "cosmossdk.io/core/address" + "cosmossdk.io/core/appmodule" + "cosmossdk.io/core/store" + "cosmossdk.io/depinject" + // "cosmossdk.io/depinject/appconfig" + "cosmossdk.io/log" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + + // this line is used by starport scaffolding # 1 + govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" + + "github.com/onomyprotocol/reserve/x/psm/keeper" + "github.com/onomyprotocol/reserve/x/psm/types" +) + +var ( + _ module.AppModuleBasic = (*AppModule)(nil) + _ module.AppModuleSimulation = (*AppModule)(nil) + _ module.HasGenesis = (*AppModule)(nil) + _ module.HasInvariants = (*AppModule)(nil) + _ module.HasConsensusVersion = (*AppModule)(nil) + + _ appmodule.AppModule = (*AppModule)(nil) + _ appmodule.HasBeginBlocker = (*AppModule)(nil) + _ appmodule.HasEndBlocker = (*AppModule)(nil) +) + +// ---------------------------------------------------------------------------- +// AppModuleBasic +// ---------------------------------------------------------------------------- + +// AppModuleBasic implements the AppModuleBasic interface that defines the +// independent methods a Cosmos SDK module needs to implement. +type AppModuleBasic struct { + cdc codec.BinaryCodec +} + +func NewAppModuleBasic(cdc codec.BinaryCodec) AppModuleBasic { + return AppModuleBasic{cdc: cdc} +} + +// Name returns the name of the module as a string. +func (AppModuleBasic) Name() string { + return types.ModuleName +} + +// RegisterLegacyAminoCodec registers the amino codec for the module, which is used +// to marshal and unmarshal structs to/from []byte in order to persist them in the module's KVStore. +func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {} + +// RegisterInterfaces registers a module's interface types and their concrete implementations as proto.Message. +func (a AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry) { + types.RegisterInterfaces(reg) +} + +// DefaultGenesis returns a default GenesisState for the module, marshalled to json.RawMessage. +// The default GenesisState need to be defined by the module developer and is primarily used for testing. +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { + return cdc.MustMarshalJSON(types.DefaultGenesis()) +} + +// ValidateGenesis used to validate the GenesisState, given in its json.RawMessage form. +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { + var genState types.GenesisState + if err := cdc.UnmarshalJSON(bz, &genState); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + return genState.Validate() +} + +// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module. +func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { + if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { + panic(err) + } +} + +// ---------------------------------------------------------------------------- +// AppModule +// ---------------------------------------------------------------------------- + +// AppModule implements the AppModule interface that defines the inter-dependent methods that modules need to implement +type AppModule struct { + AppModuleBasic + + keeper keeper.Keeper + accountKeeper types.AccountKeeper + bankKeeper types.BankKeeper +} + +func NewAppModule( + cdc codec.Codec, + keeper keeper.Keeper, + accountKeeper types.AccountKeeper, + bankKeeper types.BankKeeper, +) AppModule { + return AppModule{ + AppModuleBasic: NewAppModuleBasic(cdc), + keeper: keeper, + accountKeeper: accountKeeper, + bankKeeper: bankKeeper, + } +} + +// RegisterServices registers a gRPC query service to respond to the module-specific gRPC queries +func (am AppModule) RegisterServices(cfg module.Configurator) { + types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) + types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) +} + +// RegisterInvariants registers the invariants of the module. If an invariant deviates from its predicted value, the InvariantRegistry triggers appropriate logic (most often the chain will be halted) +func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} + +// InitGenesis performs the module's genesis initialization. It returns no validator updates. +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) { + var genState types.GenesisState + // Initialize global index to index in genesis state + cdc.MustUnmarshalJSON(gs, &genState) + + if err := InitGenesis(ctx, am.keeper, genState); err != nil { + panic(err) + } +} + +// ExportGenesis returns the module's exported genesis state as raw JSON bytes. +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { + genState, err := ExportGenesis(ctx, am.keeper) + if err != nil { + panic(err) + } + return cdc.MustMarshalJSON(genState) +} + +// ConsensusVersion is a sequence number for state-breaking change of the module. +// It should be incremented on each consensus-breaking change introduced by the module. +// To avoid wrong/empty versions, the initial version should be set to 1. +func (AppModule) ConsensusVersion() uint64 { return 1 } + +// BeginBlock contains the logic that is automatically triggered at the beginning of each block. +// The begin block implementation is optional. +func (am AppModule) BeginBlock(_ context.Context) error { + return nil +} + +// EndBlock contains the logic that is automatically triggered at the end of each block. +// The end block implementation is optional. +func (am AppModule) EndBlock(_ context.Context) error { + return nil +} + +// IsOnePerModuleType implements the depinject.OnePerModuleType interface. +func (am AppModule) IsOnePerModuleType() {} + +// IsAppModule implements the appmodule.AppModule interface. +func (am AppModule) IsAppModule() {} + +// ---------------------------------------------------------------------------- +// App Wiring Setup +// ---------------------------------------------------------------------------- + +func init() { + appmodule.Register( + &types.Module{}, + appmodule.Provide(ProvideModule), + ) +} + +type ModuleInputs struct { + depinject.In + + AddressCodec address.Codec + StoreService store.KVStoreService + Cdc codec.Codec + Config *types.Module + Logger log.Logger + + AccountKeeper types.AccountKeeper + BankKeeper types.BankKeeper +} + +type ModuleOutputs struct { + depinject.Out + + PsmKeeper keeper.Keeper + Module appmodule.AppModule + GovHandler govv1beta1.HandlerRoute +} + +func ProvideModule(in ModuleInputs) ModuleOutputs { + // default to governance authority if not provided + authority := authtypes.NewModuleAddress(govtypes.ModuleName) + if in.Config.Authority != "" { + authority = authtypes.NewModuleAddressOrBech32Address(in.Config.Authority) + } + k := keeper.NewKeeper( + in.Cdc, + in.AddressCodec, + in.StoreService, + in.Logger, + authority.String(), + in.BankKeeper, + ) + m := NewAppModule( + in.Cdc, + k, + in.AccountKeeper, + in.BankKeeper, + ) + + govHandler := govv1beta1.HandlerRoute{RouteKey: types.RouterKey, Handler: NewStablecoinProposalHandler(&k)} + + return ModuleOutputs{PsmKeeper: k, Module: m, GovHandler: govHandler} +} diff --git a/x/psm/module/proposal_handler.go b/x/psm/module/proposal_handler.go new file mode 100644 index 0000000..78039e8 --- /dev/null +++ b/x/psm/module/proposal_handler.go @@ -0,0 +1,32 @@ +package psm + +import ( + errorsmod "cosmossdk.io/errors" + + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + govclient "github.com/cosmos/cosmos-sdk/x/gov/client" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" + + "github.com/onomyprotocol/reserve/x/psm/client/cli" + "github.com/onomyprotocol/reserve/x/psm/keeper" + "github.com/onomyprotocol/reserve/x/psm/types" +) + +var ( + AddStableCoinProposalHandler = govclient.NewProposalHandler(cli.NewCmdSubmitAddStableCoinProposal) + UpdatesStableCoinProposalHandler = govclient.NewProposalHandler(cli.NewCmdUpdatesStableCoinProposal) +) + +func NewStablecoinProposalHandler(k *keeper.Keeper) govtypes.Handler { + return func(ctx sdk.Context, content govtypes.Content) error { + switch c := content.(type) { + case *types.AddStableCoinProposal: + return k.AddStableCoinProposal(ctx, c) + case *types.UpdatesStableCoinProposal: + return k.UpdatesStableCoinProposal(ctx, c) + default: + return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized %s proposal content type: %T", types.ModuleName, c) + } + } +} diff --git a/x/psm/module/simulation.go b/x/psm/module/simulation.go new file mode 100644 index 0000000..0ca2429 --- /dev/null +++ b/x/psm/module/simulation.go @@ -0,0 +1,59 @@ +package psm + +import ( + "math/rand" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/simulation" + + "github.com/onomyprotocol/reserve/testutil/sample" + psmsimulation "github.com/onomyprotocol/reserve/x/psm/simulation" + "github.com/onomyprotocol/reserve/x/psm/types" +) + +// avoid unused import issue +var ( + _ = psmsimulation.FindAccount + _ = rand.Rand{} + _ = sample.AccAddress + _ = sdk.AccAddress{} + _ = simulation.MsgEntryKind +) + +const ( +// this line is used by starport scaffolding # simapp/module/const +) + +// GenerateGenesisState creates a randomized GenState of the module. +func (AppModule) GenerateGenesisState(simState *module.SimulationState) { + accs := make([]string, len(simState.Accounts)) + for i, acc := range simState.Accounts { + accs[i] = acc.Address.String() + } + psmGenesis := types.GenesisState{ + Params: types.DefaultParams(), + // this line is used by starport scaffolding # simapp/module/genesisState + } + simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(&psmGenesis) +} + +// RegisterStoreDecoder registers a decoder. +func (am AppModule) RegisterStoreDecoder(_ simtypes.StoreDecoderRegistry) {} + +// WeightedOperations returns the all the gov module operations with their respective weights. +func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { + operations := make([]simtypes.WeightedOperation, 0) + + // this line is used by starport scaffolding # simapp/module/operation + + return operations +} + +// ProposalMsgs returns msgs used for governance proposals for simulations. +func (am AppModule) ProposalMsgs(simState module.SimulationState) []simtypes.WeightedProposalMsg { + return []simtypes.WeightedProposalMsg{ + // this line is used by starport scaffolding # simapp/module/OpMsg + } +} diff --git a/x/psm/simulation/helpers.go b/x/psm/simulation/helpers.go new file mode 100644 index 0000000..92c437c --- /dev/null +++ b/x/psm/simulation/helpers.go @@ -0,0 +1,15 @@ +package simulation + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" +) + +// FindAccount find a specific address from an account list +func FindAccount(accs []simtypes.Account, address string) (simtypes.Account, bool) { + creator, err := sdk.AccAddressFromBech32(address) + if err != nil { + panic(err) + } + return simtypes.FindAccount(accs, creator) +} diff --git a/x/psm/types/codec.go b/x/psm/types/codec.go new file mode 100644 index 0000000..ac55263 --- /dev/null +++ b/x/psm/types/codec.go @@ -0,0 +1,17 @@ +package types + +import ( + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/msgservice" + // this line is used by starport scaffolding # 1 +) + +func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { + // this line is used by starport scaffolding # 3 + + registry.RegisterImplementations((*sdk.Msg)(nil), + &MsgUpdateParams{}, + ) + msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +} diff --git a/x/psm/types/errors.go b/x/psm/types/errors.go new file mode 100644 index 0000000..cdeaea4 --- /dev/null +++ b/x/psm/types/errors.go @@ -0,0 +1,14 @@ +package types + +// DONTCOVER + +import ( + sdkerrors "cosmossdk.io/errors" +) + +// x/psm module sentinel errors +var ( + ErrInvalidSigner = sdkerrors.Register(ModuleName, 1100, "expected gov account as only signer for proposal message") + ErrSample = sdkerrors.Register(ModuleName, 1101, "sample error") + ErrInvalidAddStableCoinProposal = sdkerrors.Register(ModuleName, 2, "invalid add stable coin proposal") +) diff --git a/x/psm/types/event.go b/x/psm/types/event.go new file mode 100644 index 0000000..c1a72f9 --- /dev/null +++ b/x/psm/types/event.go @@ -0,0 +1,10 @@ +package types + +const ( + EventAddStablecoin = "add_stablecoin" + EventSwapToIST = "swap_to_ist" + + AttributeAmount = "amount" + AttributeStablecoinName = "stablecoin_name" + AttributeReceive = "receive" +) diff --git a/x/psm/types/expected_keepers.go b/x/psm/types/expected_keepers.go new file mode 100644 index 0000000..4a50d01 --- /dev/null +++ b/x/psm/types/expected_keepers.go @@ -0,0 +1,25 @@ +package types + +import ( + "context" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// AccountKeeper defines the expected interface for the Account module. +type AccountKeeper interface { + GetAccount(context.Context, sdk.AccAddress) sdk.AccountI // only used for simulation + // Methods imported from account should be defined here +} + +// BankKeeper defines the expected interface for the Bank module. +type BankKeeper interface { + SpendableCoins(context.Context, sdk.AccAddress) sdk.Coins + // Methods imported from bank should be defined here +} + +// ParamSubspace defines the expected Subspace interface for parameters. +type ParamSubspace interface { + Get(context.Context, []byte, interface{}) + Set(context.Context, []byte, interface{}) +} diff --git a/x/psm/types/genesis.go b/x/psm/types/genesis.go new file mode 100644 index 0000000..f2689b7 --- /dev/null +++ b/x/psm/types/genesis.go @@ -0,0 +1,20 @@ +package types + +// DefaultIndex is the default global index +const DefaultIndex uint64 = 1 + +// DefaultGenesis returns the default genesis state +func DefaultGenesis() *GenesisState { + return &GenesisState{ + // this line is used by starport scaffolding # genesis/types/default + Params: DefaultParams(), + } +} + +// Validate performs basic genesis state validation returning an error upon any +// failure. +func (gs GenesisState) Validate() error { + // this line is used by starport scaffolding # genesis/types/validate + + return gs.Params.Validate() +} diff --git a/x/psm/types/genesis.pb.go b/x/psm/types/genesis.pb.go new file mode 100644 index 0000000..e3de6e6 --- /dev/null +++ b/x/psm/types/genesis.pb.go @@ -0,0 +1,324 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: reserve/psm/v1/genesis.proto + +package types + +import ( + fmt "fmt" + _ "github.com/cosmos/cosmos-sdk/types/tx/amino" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// GenesisState defines the psm module's genesis state. +type GenesisState struct { + // params defines all the parameters of the module. + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` +} + +func (m *GenesisState) Reset() { *m = GenesisState{} } +func (m *GenesisState) String() string { return proto.CompactTextString(m) } +func (*GenesisState) ProtoMessage() {} +func (*GenesisState) Descriptor() ([]byte, []int) { + return fileDescriptor_fbe4ca1f3927cde8, []int{0} +} +func (m *GenesisState) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *GenesisState) XXX_Merge(src proto.Message) { + xxx_messageInfo_GenesisState.Merge(m, src) +} +func (m *GenesisState) XXX_Size() int { + return m.Size() +} +func (m *GenesisState) XXX_DiscardUnknown() { + xxx_messageInfo_GenesisState.DiscardUnknown(m) +} + +var xxx_messageInfo_GenesisState proto.InternalMessageInfo + +func (m *GenesisState) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +func init() { + proto.RegisterType((*GenesisState)(nil), "reserve.psm.v1.GenesisState") +} + +func init() { proto.RegisterFile("reserve/psm/v1/genesis.proto", fileDescriptor_fbe4ca1f3927cde8) } + +var fileDescriptor_fbe4ca1f3927cde8 = []byte{ + // 214 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x29, 0x4a, 0x2d, 0x4e, + 0x2d, 0x2a, 0x4b, 0xd5, 0x2f, 0x28, 0xce, 0xd5, 0x2f, 0x33, 0xd4, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, + 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x83, 0xca, 0xea, 0x15, 0x14, 0xe7, + 0xea, 0x95, 0x19, 0x4a, 0x09, 0x26, 0xe6, 0x66, 0xe6, 0xe5, 0xeb, 0x83, 0x49, 0x88, 0x12, 0x29, + 0x91, 0xf4, 0xfc, 0xf4, 0x7c, 0x30, 0x53, 0x1f, 0xc4, 0x82, 0x8a, 0x4a, 0xa3, 0x19, 0x5b, 0x90, + 0x58, 0x94, 0x98, 0x0b, 0x35, 0x55, 0xc9, 0x93, 0x8b, 0xc7, 0x1d, 0x62, 0x4d, 0x70, 0x49, 0x62, + 0x49, 0xaa, 0x90, 0x25, 0x17, 0x1b, 0x44, 0x5e, 0x82, 0x51, 0x81, 0x51, 0x83, 0xdb, 0x48, 0x4c, + 0x0f, 0xd5, 0x5a, 0xbd, 0x00, 0xb0, 0xac, 0x13, 0xe7, 0x89, 0x7b, 0xf2, 0x0c, 0x2b, 0x9e, 0x6f, + 0xd0, 0x62, 0x0c, 0x82, 0x6a, 0x70, 0x72, 0x3b, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, + 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, + 0x86, 0x28, 0x9d, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0xfd, 0xfc, 0xbc, + 0xfc, 0xdc, 0x4a, 0xb0, 0xdd, 0xc9, 0xf9, 0x39, 0xfa, 0x30, 0xa7, 0x55, 0x80, 0x1d, 0x57, 0x52, + 0x59, 0x90, 0x5a, 0x9c, 0xc4, 0x06, 0x96, 0x35, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x48, 0x74, + 0xe4, 0x5a, 0x0f, 0x01, 0x00, 0x00, +} + +func (m *GenesisState) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { + offset -= sovGenesis(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *GenesisState) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Params.Size() + n += 1 + l + sovGenesis(uint64(l)) + return n +} + +func sovGenesis(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozGenesis(x uint64) (n int) { + return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *GenesisState) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenesis(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipGenesis(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenesis + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenesis + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenesis + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthGenesis + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupGenesis + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthGenesis + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/psm/types/genesis_test.go b/x/psm/types/genesis_test.go new file mode 100644 index 0000000..8cc7097 --- /dev/null +++ b/x/psm/types/genesis_test.go @@ -0,0 +1,41 @@ +package types_test + +import ( + "testing" + + "github.com/onomyprotocol/reserve/x/psm/types" + "github.com/stretchr/testify/require" +) + +func TestGenesisState_Validate(t *testing.T) { + tests := []struct { + desc string + genState *types.GenesisState + valid bool + }{ + { + desc: "default is valid", + genState: types.DefaultGenesis(), + valid: true, + }, + { + desc: "valid genesis state", + genState: &types.GenesisState{ + + // this line is used by starport scaffolding # types/genesis/validField + }, + valid: true, + }, + // this line is used by starport scaffolding # types/genesis/testcase + } + for _, tc := range tests { + t.Run(tc.desc, func(t *testing.T) { + err := tc.genState.Validate() + if tc.valid { + require.NoError(t, err) + } else { + require.Error(t, err) + } + }) + } +} diff --git a/x/psm/types/keys.go b/x/psm/types/keys.go new file mode 100644 index 0000000..0652323 --- /dev/null +++ b/x/psm/types/keys.go @@ -0,0 +1,32 @@ +package types + +const ( + // ModuleName defines the module name. + ModuleName = "psm" + + // StoreKey defines the primary module store key. + StoreKey = ModuleName + + // RouterKey is the message route for slashing. + RouterKey = ModuleName + + // QuerierRoute defines the module's query routing key. + QuerierRoute = ModuleName + + // MemStoreKey defines the in-memory store key. + MemStoreKey = "mem_psm" + + // Inter Stable Token (IST). + InterStableToken = "ist" +) + +var ( + KeyStableCoin = []byte{0x01} + KeyLockStableCoin = []byte{0x02} + KeyUnlockStableCoin = []byte{0x03} + ParamsKey = []byte{0x4} +) + +func GetKeyStableCoin(denom string) []byte { + return append(KeyStableCoin, []byte(denom)...) +} diff --git a/x/psm/types/module.pb.go b/x/psm/types/module.pb.go new file mode 100644 index 0000000..5e6465b --- /dev/null +++ b/x/psm/types/module.pb.go @@ -0,0 +1,322 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: reserve/psm/module/v1/module.proto + +package types + +import ( + _ "cosmossdk.io/api/cosmos/app/v1alpha1" + fmt "fmt" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// Module is the config object for the module. +type Module struct { + // authority defines the custom module authority. If not set, defaults to the governance module. + Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` +} + +func (m *Module) Reset() { *m = Module{} } +func (m *Module) String() string { return proto.CompactTextString(m) } +func (*Module) ProtoMessage() {} +func (*Module) Descriptor() ([]byte, []int) { + return fileDescriptor_032677de36312ba3, []int{0} +} +func (m *Module) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Module) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Module.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Module) XXX_Merge(src proto.Message) { + xxx_messageInfo_Module.Merge(m, src) +} +func (m *Module) XXX_Size() int { + return m.Size() +} +func (m *Module) XXX_DiscardUnknown() { + xxx_messageInfo_Module.DiscardUnknown(m) +} + +var xxx_messageInfo_Module proto.InternalMessageInfo + +func (m *Module) GetAuthority() string { + if m != nil { + return m.Authority + } + return "" +} + +func init() { + proto.RegisterType((*Module)(nil), "reserve.psm.module.v1.Module") +} + +func init() { + proto.RegisterFile("reserve/psm/module/v1/module.proto", fileDescriptor_032677de36312ba3) +} + +var fileDescriptor_032677de36312ba3 = []byte{ + // 199 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x2a, 0x4a, 0x2d, 0x4e, + 0x2d, 0x2a, 0x4b, 0xd5, 0x2f, 0x28, 0xce, 0xd5, 0xcf, 0xcd, 0x4f, 0x29, 0xcd, 0x49, 0xd5, 0x2f, + 0x33, 0x84, 0xb2, 0xf4, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x44, 0xa1, 0x6a, 0xf4, 0x0a, 0x8a, + 0x73, 0xf5, 0xa0, 0x32, 0x65, 0x86, 0x52, 0x0a, 0xc9, 0xf9, 0xc5, 0xb9, 0xf9, 0xc5, 0xfa, 0x89, + 0x05, 0x05, 0xfa, 0x65, 0x86, 0x89, 0x39, 0x05, 0x19, 0x89, 0xa8, 0x1a, 0x95, 0xc2, 0xb8, 0xd8, + 0x7c, 0xc1, 0x7c, 0x21, 0x19, 0x2e, 0xce, 0xc4, 0xd2, 0x92, 0x8c, 0xfc, 0xa2, 0xcc, 0x92, 0x4a, + 0x09, 0x46, 0x05, 0x46, 0x0d, 0xce, 0x20, 0x84, 0x80, 0x95, 0xde, 0xae, 0x03, 0xd3, 0x6e, 0x31, + 0x6a, 0x70, 0xa9, 0xa5, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0xe7, 0xe7, + 0xe5, 0xe7, 0x56, 0x82, 0x8d, 0x49, 0xce, 0xcf, 0xd1, 0x87, 0xb9, 0xb2, 0x02, 0xe4, 0x4e, 0x27, + 0xb7, 0x13, 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, + 0x39, 0x86, 0x0b, 0x8f, 0xe5, 0x18, 0x6e, 0x3c, 0x96, 0x63, 0x88, 0xd2, 0x21, 0xce, 0x04, 0xfd, + 0x92, 0xca, 0x82, 0xd4, 0xe2, 0x24, 0x36, 0xb0, 0xac, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x85, + 0xe3, 0xe1, 0xd5, 0x05, 0x01, 0x00, 0x00, +} + +func (m *Module) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Module) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Module) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Authority) > 0 { + i -= len(m.Authority) + copy(dAtA[i:], m.Authority) + i = encodeVarintModule(dAtA, i, uint64(len(m.Authority))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintModule(dAtA []byte, offset int, v uint64) int { + offset -= sovModule(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Module) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Authority) + if l > 0 { + n += 1 + l + sovModule(uint64(l)) + } + return n +} + +func sovModule(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozModule(x uint64) (n int) { + return sovModule(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Module) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Module: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Module: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowModule + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthModule + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthModule + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Authority = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipModule(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthModule + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipModule(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowModule + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowModule + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowModule + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthModule + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupModule + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthModule + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthModule = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowModule = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupModule = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/psm/types/params.go b/x/psm/types/params.go new file mode 100644 index 0000000..35bbfee --- /dev/null +++ b/x/psm/types/params.go @@ -0,0 +1,53 @@ +package types + +import ( + "cosmossdk.io/math" + "fmt" +) + +var ( + DefaultLimitTotal = math.NewInt(100_000_000) + DefaultAcceptablePriceRatio = math.LegacyMustNewDecFromStr("0.001") +) + +// NewParams creates a new Params instance. +func NewParams( + limitTotal math.Int, + AcceptablePriceRatio math.LegacyDec, +) Params { + return Params{ + LimitTotal: limitTotal, + AcceptablePriceRatio: AcceptablePriceRatio, + } +} + +// DefaultParams returns a default set of parameters. +func DefaultParams() Params { + return NewParams( + DefaultLimitTotal, DefaultAcceptablePriceRatio, + ) +} + +// Validate validates the set of params. +func (m Params) Validate() error { + if err := validateLimitTotal(m.LimitTotal); err != nil { + return err + } + if m.AcceptablePriceRatio.LTE(math.LegacyZeroDec()) { + return fmt.Errorf("AcceptablePriceRatio must be positive") + } + return nil +} + +func validateLimitTotal(i interface{}) error { + v, ok := i.(math.Int) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if v.IsNil() || v.IsNegative() { + return fmt.Errorf("total limit rate cannot be negative or nil: %s", v) + } + + return nil +} diff --git a/x/psm/types/params.pb.go b/x/psm/types/params.pb.go new file mode 100644 index 0000000..b265949 --- /dev/null +++ b/x/psm/types/params.pb.go @@ -0,0 +1,369 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: reserve/psm/v1/params.proto + +package types + +import ( + cosmossdk_io_math "cosmossdk.io/math" + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + _ "github.com/cosmos/cosmos-sdk/types/tx/amino" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type Params struct { + LimitTotal cosmossdk_io_math.Int `protobuf:"bytes,1,opt,name=limit_total,json=limitTotal,proto3,customtype=cosmossdk.io/math.Int" json:"limit_total"` + AcceptablePriceRatio cosmossdk_io_math.LegacyDec `protobuf:"bytes,2,opt,name=acceptable_price_ratio,json=acceptablePriceRatio,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"acceptable_price_ratio"` +} + +func (m *Params) Reset() { *m = Params{} } +func (m *Params) String() string { return proto.CompactTextString(m) } +func (*Params) ProtoMessage() {} +func (*Params) Descriptor() ([]byte, []int) { + return fileDescriptor_e516259d7293aa1e, []int{0} +} +func (m *Params) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Params.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Params) XXX_Merge(src proto.Message) { + xxx_messageInfo_Params.Merge(m, src) +} +func (m *Params) XXX_Size() int { + return m.Size() +} +func (m *Params) XXX_DiscardUnknown() { + xxx_messageInfo_Params.DiscardUnknown(m) +} + +var xxx_messageInfo_Params proto.InternalMessageInfo + +func init() { + proto.RegisterType((*Params)(nil), "reserve.psm.v1.Params") +} + +func init() { proto.RegisterFile("reserve/psm/v1/params.proto", fileDescriptor_e516259d7293aa1e) } + +var fileDescriptor_e516259d7293aa1e = []byte{ + // 306 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x64, 0xd0, 0xb1, 0x4a, 0x03, 0x31, + 0x18, 0x07, 0xf0, 0x8b, 0x43, 0x87, 0x28, 0x82, 0xa5, 0x4a, 0x6d, 0x21, 0x15, 0x27, 0x11, 0x4d, + 0x2c, 0xbe, 0x41, 0x29, 0x42, 0xc1, 0xa1, 0x16, 0x27, 0x97, 0x23, 0x8d, 0xe1, 0x1a, 0xbc, 0xdc, + 0x17, 0x92, 0x58, 0xec, 0x5b, 0xf8, 0x18, 0x8e, 0x0e, 0x3e, 0x82, 0x43, 0xc7, 0xe2, 0x24, 0x0e, + 0x45, 0xee, 0x06, 0x5f, 0x43, 0x2e, 0x77, 0xa2, 0xe0, 0x12, 0xbe, 0xe4, 0x9f, 0xfc, 0x3e, 0xf2, + 0xe1, 0xae, 0x95, 0x4e, 0xda, 0xb9, 0x64, 0xc6, 0x69, 0x36, 0xef, 0x33, 0xc3, 0x2d, 0xd7, 0x8e, + 0x1a, 0x0b, 0x1e, 0x9a, 0xdb, 0x75, 0x48, 0x8d, 0xd3, 0x74, 0xde, 0xef, 0xec, 0x70, 0xad, 0x32, + 0x60, 0x61, 0xad, 0xae, 0x74, 0x5a, 0x09, 0x24, 0x10, 0x4a, 0x56, 0x56, 0xf5, 0xe9, 0xbe, 0x00, + 0xa7, 0xc1, 0xc5, 0x55, 0x50, 0x6d, 0xaa, 0xe8, 0xf0, 0x15, 0xe1, 0xc6, 0x38, 0x34, 0x69, 0x5e, + 0xe1, 0xcd, 0x54, 0x69, 0xe5, 0x63, 0x0f, 0x9e, 0xa7, 0x6d, 0x74, 0x80, 0x8e, 0xb6, 0x06, 0x67, + 0xcb, 0x75, 0x2f, 0xfa, 0x58, 0xf7, 0x76, 0xab, 0x57, 0xee, 0xf6, 0x8e, 0x2a, 0x60, 0x9a, 0xfb, + 0x19, 0x1d, 0x65, 0xfe, 0xed, 0xe5, 0x14, 0xd7, 0xdc, 0x28, 0xf3, 0x4f, 0x5f, 0xcf, 0xc7, 0x68, + 0x82, 0x03, 0x72, 0x5d, 0x1a, 0xcd, 0x04, 0xef, 0x71, 0x21, 0xa4, 0xf1, 0x7c, 0x9a, 0xca, 0xd8, + 0x58, 0x25, 0x64, 0x6c, 0xb9, 0x57, 0xd0, 0xde, 0x08, 0x7a, 0xbf, 0xd6, 0xbb, 0xff, 0xf5, 0x4b, + 0x99, 0x70, 0xb1, 0x18, 0x4a, 0xf1, 0xa7, 0xc7, 0x50, 0x8a, 0x49, 0xeb, 0x17, 0x1c, 0x97, 0xde, + 0xa4, 0xe4, 0x06, 0x17, 0xcb, 0x9c, 0xa0, 0x55, 0x4e, 0xd0, 0x67, 0x4e, 0xd0, 0x63, 0x41, 0xa2, + 0x55, 0x41, 0xa2, 0xf7, 0x82, 0x44, 0x37, 0x27, 0x89, 0xf2, 0xb3, 0xfb, 0x29, 0x15, 0xa0, 0x19, + 0x64, 0xa0, 0x17, 0xe1, 0xdf, 0x02, 0x52, 0xf6, 0x33, 0xea, 0x87, 0x30, 0x6c, 0xbf, 0x30, 0xd2, + 0x4d, 0x1b, 0x21, 0x3d, 0xff, 0x0e, 0x00, 0x00, 0xff, 0xff, 0x82, 0xec, 0xd9, 0x9a, 0x88, 0x01, + 0x00, 0x00, +} + +func (m *Params) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Params) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size := m.AcceptablePriceRatio.Size() + i -= size + if _, err := m.AcceptablePriceRatio.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintParams(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + { + size := m.LimitTotal.Size() + i -= size + if _, err := m.LimitTotal.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintParams(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func encodeVarintParams(dAtA []byte, offset int, v uint64) int { + offset -= sovParams(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Params) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.LimitTotal.Size() + n += 1 + l + sovParams(uint64(l)) + l = m.AcceptablePriceRatio.Size() + n += 1 + l + sovParams(uint64(l)) + return n +} + +func sovParams(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozParams(x uint64) (n int) { + return sovParams(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Params) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Params: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LimitTotal", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthParams + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthParams + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.LimitTotal.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AcceptablePriceRatio", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthParams + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthParams + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.AcceptablePriceRatio.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipParams(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthParams + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipParams(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowParams + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowParams + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowParams + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthParams + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupParams + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthParams + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthParams = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowParams = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupParams = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/psm/types/proposals.go b/x/psm/types/proposals.go new file mode 100644 index 0000000..b5e5449 --- /dev/null +++ b/x/psm/types/proposals.go @@ -0,0 +1,95 @@ +package types + +import ( + // "fmt" + + sdkerrors "cosmossdk.io/errors" + "cosmossdk.io/math" + + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" +) + +const ( + ProposalTypeAddStableCoinProposal string = "AddStableCoinProposal" + ProposalTypeUpdatesStableCoinProposal string = "UpdatesStableCoinProposal" +) + +var ( + _ govtypes.Content = &AddStableCoinProposal{} + _ govtypes.Content = &UpdatesStableCoinProposal{} +) + +func init() { + govtypes.RegisterProposalType(ProposalTypeAddStableCoinProposal) + govtypes.RegisterProposalType(ProposalTypeUpdatesStableCoinProposal) + +} + +func NewAddStableCoinProposal(title, description, denom string, limitTotal math.Int, price, feeIn, feeOut math.LegacyDec) AddStableCoinProposal { + return AddStableCoinProposal{ + Title: title, + Description: description, + Denom: denom, + LimitTotal: limitTotal, + Price: price, + FeeIn: feeIn, + FeeOut: feeOut, + } +} + +func NewUpdatesStableCoinProposal(title, description, denom string, updateLimitTotal math.Int, price, feeIn, feeOut math.LegacyDec) UpdatesStableCoinProposal { + return UpdatesStableCoinProposal{ + Title: title, + Description: description, + Denom: denom, + UpdatesLimitTotal: updateLimitTotal, + Price: price, + FeeIn: feeIn, + FeeOut: feeOut, + } +} + +func (a *AddStableCoinProposal) ProposalRoute() string { return RouterKey } + +func (a *AddStableCoinProposal) ProposalType() string { + return ProposalTypeAddStableCoinProposal +} + +func (a *AddStableCoinProposal) ValidateBasic() error { + err := govtypes.ValidateAbstract(a) + if err != nil { + return err + } + + if a.Denom == "" { + return sdkerrors.Wrap(ErrInvalidAddStableCoinProposal, "empty denom") + } + if a.LimitTotal.LT(math.ZeroInt()) { + return sdkerrors.Wrap(ErrInvalidAddStableCoinProposal, "less than zero") + } + return nil +} + +// func (a AddStableCoinProposal) +// func (a AddStableCoinProposal) + +func (u *UpdatesStableCoinProposal) ProposalRoute() string { return RouterKey } + +func (u *UpdatesStableCoinProposal) ProposalType() string { + return ProposalTypeUpdatesStableCoinProposal +} + +func (u *UpdatesStableCoinProposal) ValidateBasic() error { + err := govtypes.ValidateAbstract(u) + if err != nil { + return err + } + + if u.Denom == "" { + return sdkerrors.Wrap(ErrInvalidAddStableCoinProposal, "empty denom") + } + if u.UpdatesLimitTotal.LT(math.ZeroInt()) { + return sdkerrors.Wrap(ErrInvalidAddStableCoinProposal, "less than zero") + } + return nil +} diff --git a/x/psm/types/proposals.pb.go b/x/psm/types/proposals.pb.go new file mode 100644 index 0000000..ae228a8 --- /dev/null +++ b/x/psm/types/proposals.pb.go @@ -0,0 +1,1076 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: reserve/psm/v1/proposals.proto + +package types + +import ( + cosmossdk_io_math "cosmossdk.io/math" + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + _ "github.com/cosmos/cosmos-sdk/types/tx/amino" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type AddStableCoinProposal struct { + Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` + Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` + Denom string `protobuf:"bytes,3,opt,name=denom,proto3" json:"denom,omitempty"` + LimitTotal cosmossdk_io_math.Int `protobuf:"bytes,4,opt,name=limit_total,json=limitTotal,proto3,customtype=cosmossdk.io/math.Int" json:"limit_total"` + Price cosmossdk_io_math.LegacyDec `protobuf:"bytes,5,opt,name=price,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"price"` + FeeIn cosmossdk_io_math.LegacyDec `protobuf:"bytes,6,opt,name=fee_in,json=feeIn,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"fee_in"` + FeeOut cosmossdk_io_math.LegacyDec `protobuf:"bytes,7,opt,name=fee_out,json=feeOut,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"fee_out"` +} + +func (m *AddStableCoinProposal) Reset() { *m = AddStableCoinProposal{} } +func (m *AddStableCoinProposal) String() string { return proto.CompactTextString(m) } +func (*AddStableCoinProposal) ProtoMessage() {} +func (*AddStableCoinProposal) Descriptor() ([]byte, []int) { + return fileDescriptor_acdb9fbbcb940001, []int{0} +} +func (m *AddStableCoinProposal) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *AddStableCoinProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_AddStableCoinProposal.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *AddStableCoinProposal) XXX_Merge(src proto.Message) { + xxx_messageInfo_AddStableCoinProposal.Merge(m, src) +} +func (m *AddStableCoinProposal) XXX_Size() int { + return m.Size() +} +func (m *AddStableCoinProposal) XXX_DiscardUnknown() { + xxx_messageInfo_AddStableCoinProposal.DiscardUnknown(m) +} + +var xxx_messageInfo_AddStableCoinProposal proto.InternalMessageInfo + +func (m *AddStableCoinProposal) GetTitle() string { + if m != nil { + return m.Title + } + return "" +} + +func (m *AddStableCoinProposal) GetDescription() string { + if m != nil { + return m.Description + } + return "" +} + +func (m *AddStableCoinProposal) GetDenom() string { + if m != nil { + return m.Denom + } + return "" +} + +type UpdatesStableCoinProposal struct { + Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` + Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` + Denom string `protobuf:"bytes,3,opt,name=denom,proto3" json:"denom,omitempty"` + UpdatesLimitTotal cosmossdk_io_math.Int `protobuf:"bytes,4,opt,name=updates_limit_total,json=updatesLimitTotal,proto3,customtype=cosmossdk.io/math.Int" json:"updates_limit_total"` + Price cosmossdk_io_math.LegacyDec `protobuf:"bytes,5,opt,name=price,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"price"` + FeeIn cosmossdk_io_math.LegacyDec `protobuf:"bytes,6,opt,name=fee_in,json=feeIn,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"fee_in"` + FeeOut cosmossdk_io_math.LegacyDec `protobuf:"bytes,7,opt,name=fee_out,json=feeOut,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"fee_out"` +} + +func (m *UpdatesStableCoinProposal) Reset() { *m = UpdatesStableCoinProposal{} } +func (m *UpdatesStableCoinProposal) String() string { return proto.CompactTextString(m) } +func (*UpdatesStableCoinProposal) ProtoMessage() {} +func (*UpdatesStableCoinProposal) Descriptor() ([]byte, []int) { + return fileDescriptor_acdb9fbbcb940001, []int{1} +} +func (m *UpdatesStableCoinProposal) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *UpdatesStableCoinProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_UpdatesStableCoinProposal.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *UpdatesStableCoinProposal) XXX_Merge(src proto.Message) { + xxx_messageInfo_UpdatesStableCoinProposal.Merge(m, src) +} +func (m *UpdatesStableCoinProposal) XXX_Size() int { + return m.Size() +} +func (m *UpdatesStableCoinProposal) XXX_DiscardUnknown() { + xxx_messageInfo_UpdatesStableCoinProposal.DiscardUnknown(m) +} + +var xxx_messageInfo_UpdatesStableCoinProposal proto.InternalMessageInfo + +func (m *UpdatesStableCoinProposal) GetTitle() string { + if m != nil { + return m.Title + } + return "" +} + +func (m *UpdatesStableCoinProposal) GetDescription() string { + if m != nil { + return m.Description + } + return "" +} + +func (m *UpdatesStableCoinProposal) GetDenom() string { + if m != nil { + return m.Denom + } + return "" +} + +func init() { + proto.RegisterType((*AddStableCoinProposal)(nil), "reserve.psm.v1.AddStableCoinProposal") + proto.RegisterType((*UpdatesStableCoinProposal)(nil), "reserve.psm.v1.UpdatesStableCoinProposal") +} + +func init() { proto.RegisterFile("reserve/psm/v1/proposals.proto", fileDescriptor_acdb9fbbcb940001) } + +var fileDescriptor_acdb9fbbcb940001 = []byte{ + // 415 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe4, 0x93, 0x41, 0x6b, 0xd4, 0x40, + 0x14, 0x80, 0x13, 0xd7, 0xdd, 0xe2, 0x54, 0x84, 0xc6, 0x16, 0xd2, 0x0a, 0xe9, 0xd2, 0x53, 0x11, + 0xcd, 0xb8, 0xf8, 0x0b, 0xac, 0x45, 0x5d, 0x29, 0xa8, 0xab, 0x5e, 0xbc, 0xc4, 0xec, 0xe4, 0x35, + 0x1d, 0xcc, 0xcc, 0x1b, 0x32, 0x2f, 0x8b, 0xfb, 0x2f, 0xbc, 0xf9, 0x17, 0xc4, 0x93, 0x07, 0x7f, + 0x44, 0x8f, 0xc5, 0x93, 0x78, 0x28, 0xb2, 0x7b, 0xf0, 0x6f, 0x48, 0x66, 0x22, 0x14, 0xbc, 0x2d, + 0x7a, 0xea, 0x25, 0xe4, 0xbd, 0x6f, 0xde, 0xf7, 0x1e, 0x3c, 0x1e, 0x4b, 0x6a, 0xb0, 0x50, 0xcf, + 0x80, 0x1b, 0xab, 0xf8, 0x6c, 0xc4, 0x4d, 0x8d, 0x06, 0x6d, 0x5e, 0xd9, 0xd4, 0xd4, 0x48, 0x18, + 0xdd, 0xe8, 0x78, 0x6a, 0xac, 0x4a, 0x67, 0xa3, 0x9d, 0xcd, 0x12, 0x4b, 0x74, 0x88, 0xb7, 0x7f, + 0xfe, 0xd5, 0xce, 0xb6, 0x40, 0xab, 0xd0, 0x66, 0x1e, 0xf8, 0xa0, 0x43, 0x1b, 0xb9, 0x92, 0x1a, + 0xb9, 0xfb, 0xfa, 0xd4, 0xde, 0xc7, 0x1e, 0xdb, 0x7a, 0x50, 0x14, 0x2f, 0x29, 0x9f, 0x56, 0xf0, + 0x10, 0xa5, 0x7e, 0xde, 0x35, 0x8d, 0x36, 0x59, 0x9f, 0x24, 0x55, 0x10, 0x87, 0xc3, 0x70, 0xff, + 0xda, 0xc4, 0x07, 0xd1, 0x90, 0xad, 0x17, 0x60, 0x45, 0x2d, 0x0d, 0x49, 0xd4, 0xf1, 0x15, 0xc7, + 0x2e, 0xa6, 0xda, 0xba, 0x02, 0x34, 0xaa, 0xb8, 0xe7, 0xeb, 0x5c, 0x10, 0xbd, 0x60, 0xeb, 0x95, + 0x54, 0x92, 0x32, 0x42, 0xca, 0xab, 0xf8, 0xea, 0x30, 0xdc, 0xbf, 0x7e, 0x70, 0xef, 0xf4, 0x7c, + 0x37, 0xf8, 0x71, 0xbe, 0xbb, 0xe5, 0xa7, 0xb4, 0xc5, 0xbb, 0x54, 0x22, 0x57, 0x39, 0x9d, 0xa4, + 0x63, 0x4d, 0xdf, 0xbe, 0xde, 0x65, 0xdd, 0xf8, 0x63, 0x4d, 0x9f, 0x7e, 0x7d, 0xb9, 0x1d, 0x4e, + 0x98, 0x93, 0xbc, 0x6a, 0x1d, 0xd1, 0x63, 0xd6, 0x37, 0xb5, 0x14, 0x10, 0xf7, 0x9d, 0x6c, 0xd4, + 0xc9, 0x6e, 0xfd, 0x2d, 0x3b, 0x82, 0x32, 0x17, 0xf3, 0x43, 0x10, 0x17, 0x94, 0x87, 0x20, 0x26, + 0xbe, 0x3e, 0x7a, 0xc2, 0x06, 0xc7, 0x00, 0x99, 0xd4, 0xf1, 0x60, 0x65, 0xd3, 0x31, 0xc0, 0x58, + 0x47, 0x4f, 0xd9, 0x5a, 0x6b, 0xc2, 0x86, 0xe2, 0xb5, 0x55, 0x55, 0xed, 0x2c, 0xcf, 0x1a, 0xda, + 0xfb, 0xdc, 0x63, 0xdb, 0xaf, 0x4d, 0x91, 0x13, 0xd8, 0xff, 0xbe, 0x9d, 0xb7, 0xec, 0x66, 0xe3, + 0x5b, 0x65, 0xff, 0x62, 0x4b, 0x1b, 0x9d, 0xec, 0xe8, 0xb2, 0x2c, 0xeb, 0xe0, 0xd1, 0xe9, 0x22, + 0x09, 0xcf, 0x16, 0x49, 0xf8, 0x73, 0x91, 0x84, 0x1f, 0x96, 0x49, 0x70, 0xb6, 0x4c, 0x82, 0xef, + 0xcb, 0x24, 0x78, 0x73, 0xa7, 0x94, 0x74, 0xd2, 0x4c, 0x53, 0x81, 0x8a, 0xa3, 0x46, 0x35, 0x77, + 0x77, 0x27, 0xb0, 0xe2, 0x7f, 0xae, 0xfd, 0xbd, 0xbb, 0x77, 0x9a, 0x1b, 0xb0, 0xd3, 0x81, 0xa3, + 0xf7, 0x7f, 0x07, 0x00, 0x00, 0xff, 0xff, 0xd6, 0xef, 0x51, 0x17, 0x0b, 0x04, 0x00, 0x00, +} + +func (m *AddStableCoinProposal) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *AddStableCoinProposal) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *AddStableCoinProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size := m.FeeOut.Size() + i -= size + if _, err := m.FeeOut.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintProposals(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x3a + { + size := m.FeeIn.Size() + i -= size + if _, err := m.FeeIn.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintProposals(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + { + size := m.Price.Size() + i -= size + if _, err := m.Price.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintProposals(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + { + size := m.LimitTotal.Size() + i -= size + if _, err := m.LimitTotal.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintProposals(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + if len(m.Denom) > 0 { + i -= len(m.Denom) + copy(dAtA[i:], m.Denom) + i = encodeVarintProposals(dAtA, i, uint64(len(m.Denom))) + i-- + dAtA[i] = 0x1a + } + if len(m.Description) > 0 { + i -= len(m.Description) + copy(dAtA[i:], m.Description) + i = encodeVarintProposals(dAtA, i, uint64(len(m.Description))) + i-- + dAtA[i] = 0x12 + } + if len(m.Title) > 0 { + i -= len(m.Title) + copy(dAtA[i:], m.Title) + i = encodeVarintProposals(dAtA, i, uint64(len(m.Title))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *UpdatesStableCoinProposal) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *UpdatesStableCoinProposal) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *UpdatesStableCoinProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size := m.FeeOut.Size() + i -= size + if _, err := m.FeeOut.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintProposals(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x3a + { + size := m.FeeIn.Size() + i -= size + if _, err := m.FeeIn.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintProposals(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + { + size := m.Price.Size() + i -= size + if _, err := m.Price.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintProposals(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + { + size := m.UpdatesLimitTotal.Size() + i -= size + if _, err := m.UpdatesLimitTotal.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintProposals(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + if len(m.Denom) > 0 { + i -= len(m.Denom) + copy(dAtA[i:], m.Denom) + i = encodeVarintProposals(dAtA, i, uint64(len(m.Denom))) + i-- + dAtA[i] = 0x1a + } + if len(m.Description) > 0 { + i -= len(m.Description) + copy(dAtA[i:], m.Description) + i = encodeVarintProposals(dAtA, i, uint64(len(m.Description))) + i-- + dAtA[i] = 0x12 + } + if len(m.Title) > 0 { + i -= len(m.Title) + copy(dAtA[i:], m.Title) + i = encodeVarintProposals(dAtA, i, uint64(len(m.Title))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintProposals(dAtA []byte, offset int, v uint64) int { + offset -= sovProposals(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *AddStableCoinProposal) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Title) + if l > 0 { + n += 1 + l + sovProposals(uint64(l)) + } + l = len(m.Description) + if l > 0 { + n += 1 + l + sovProposals(uint64(l)) + } + l = len(m.Denom) + if l > 0 { + n += 1 + l + sovProposals(uint64(l)) + } + l = m.LimitTotal.Size() + n += 1 + l + sovProposals(uint64(l)) + l = m.Price.Size() + n += 1 + l + sovProposals(uint64(l)) + l = m.FeeIn.Size() + n += 1 + l + sovProposals(uint64(l)) + l = m.FeeOut.Size() + n += 1 + l + sovProposals(uint64(l)) + return n +} + +func (m *UpdatesStableCoinProposal) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Title) + if l > 0 { + n += 1 + l + sovProposals(uint64(l)) + } + l = len(m.Description) + if l > 0 { + n += 1 + l + sovProposals(uint64(l)) + } + l = len(m.Denom) + if l > 0 { + n += 1 + l + sovProposals(uint64(l)) + } + l = m.UpdatesLimitTotal.Size() + n += 1 + l + sovProposals(uint64(l)) + l = m.Price.Size() + n += 1 + l + sovProposals(uint64(l)) + l = m.FeeIn.Size() + n += 1 + l + sovProposals(uint64(l)) + l = m.FeeOut.Size() + n += 1 + l + sovProposals(uint64(l)) + return n +} + +func sovProposals(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozProposals(x uint64) (n int) { + return sovProposals(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *AddStableCoinProposal) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposals + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: AddStableCoinProposal: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AddStableCoinProposal: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposals + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProposals + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProposals + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Title = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposals + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProposals + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProposals + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Description = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposals + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProposals + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProposals + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Denom = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LimitTotal", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposals + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProposals + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProposals + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.LimitTotal.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Price", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposals + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProposals + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProposals + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Price.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field FeeIn", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposals + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProposals + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProposals + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.FeeIn.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field FeeOut", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposals + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProposals + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProposals + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.FeeOut.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipProposals(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthProposals + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *UpdatesStableCoinProposal) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposals + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: UpdatesStableCoinProposal: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: UpdatesStableCoinProposal: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposals + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProposals + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProposals + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Title = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposals + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProposals + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProposals + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Description = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposals + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProposals + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProposals + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Denom = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field UpdatesLimitTotal", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposals + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProposals + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProposals + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.UpdatesLimitTotal.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Price", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposals + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProposals + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProposals + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Price.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field FeeIn", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposals + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProposals + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProposals + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.FeeIn.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field FeeOut", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposals + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProposals + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProposals + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.FeeOut.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipProposals(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthProposals + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipProposals(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowProposals + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowProposals + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowProposals + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthProposals + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupProposals + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthProposals + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthProposals = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowProposals = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupProposals = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/psm/types/psm.go b/x/psm/types/psm.go new file mode 100644 index 0000000..1f26db6 --- /dev/null +++ b/x/psm/types/psm.go @@ -0,0 +1,21 @@ +package types + +func ConvertAddStableCoinToStablecoin(s AddStableCoinProposal) Stablecoin { + return Stablecoin{ + Denom: s.Denom, + LimitTotal: s.LimitTotal, + Price: s.Price, + FeeIn: s.FeeIn, + FeeOut: s.FeeOut, + } +} + +func ConvertUpdateStableCoinToStablecoin(s UpdatesStableCoinProposal) Stablecoin { + return Stablecoin{ + Denom: s.Denom, + LimitTotal: s.UpdatesLimitTotal, + Price: s.Price, + FeeIn: s.FeeIn, + FeeOut: s.FeeOut, + } +} diff --git a/x/psm/types/psm.pb.go b/x/psm/types/psm.pb.go new file mode 100644 index 0000000..5e65d99 --- /dev/null +++ b/x/psm/types/psm.pb.go @@ -0,0 +1,516 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: reserve/psm/v1/psm.proto + +package types + +import ( + cosmossdk_io_math "cosmossdk.io/math" + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + _ "github.com/cosmos/cosmos-sdk/types/tx/amino" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type Stablecoin struct { + Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` + // limit total stablecoin module support + LimitTotal cosmossdk_io_math.Int `protobuf:"bytes,2,opt,name=limit_total,json=limitTotal,proto3,customtype=cosmossdk.io/math.Int" json:"limit_total"` + // price is the amount of stablecoin to exchange for 1 unit of nomUSD (very close to 1) + Price cosmossdk_io_math.LegacyDec `protobuf:"bytes,3,opt,name=price,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"price"` + FeeIn cosmossdk_io_math.LegacyDec `protobuf:"bytes,4,opt,name=fee_in,json=feeIn,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"fee_in"` + FeeOut cosmossdk_io_math.LegacyDec `protobuf:"bytes,5,opt,name=fee_out,json=feeOut,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"fee_out"` +} + +func (m *Stablecoin) Reset() { *m = Stablecoin{} } +func (m *Stablecoin) String() string { return proto.CompactTextString(m) } +func (*Stablecoin) ProtoMessage() {} +func (*Stablecoin) Descriptor() ([]byte, []int) { + return fileDescriptor_59572214fa05fb2f, []int{0} +} +func (m *Stablecoin) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Stablecoin) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Stablecoin.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Stablecoin) XXX_Merge(src proto.Message) { + xxx_messageInfo_Stablecoin.Merge(m, src) +} +func (m *Stablecoin) XXX_Size() int { + return m.Size() +} +func (m *Stablecoin) XXX_DiscardUnknown() { + xxx_messageInfo_Stablecoin.DiscardUnknown(m) +} + +var xxx_messageInfo_Stablecoin proto.InternalMessageInfo + +func (m *Stablecoin) GetDenom() string { + if m != nil { + return m.Denom + } + return "" +} + +func init() { + proto.RegisterType((*Stablecoin)(nil), "reserve.psm.v1.Stablecoin") +} + +func init() { proto.RegisterFile("reserve/psm/v1/psm.proto", fileDescriptor_59572214fa05fb2f) } + +var fileDescriptor_59572214fa05fb2f = []byte{ + // 339 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x91, 0x41, 0x4a, 0x33, 0x31, + 0x14, 0xc7, 0x67, 0xfa, 0x7d, 0xad, 0x18, 0x45, 0x70, 0xa8, 0x30, 0x56, 0x98, 0x16, 0x57, 0x45, + 0x74, 0x62, 0xf1, 0x06, 0xa5, 0xa8, 0x15, 0x41, 0xac, 0xae, 0xdc, 0x94, 0x69, 0xfa, 0x3a, 0x0d, + 0x4e, 0xf2, 0x86, 0x99, 0xb4, 0xd8, 0x5b, 0x78, 0x0c, 0x97, 0x2e, 0x3c, 0x44, 0x97, 0x45, 0x5c, + 0x88, 0x8b, 0x22, 0xed, 0xc2, 0x6b, 0xc8, 0x24, 0x23, 0x08, 0xee, 0xba, 0x49, 0xf2, 0xde, 0x2f, + 0xf9, 0xbd, 0xc0, 0x9f, 0xb8, 0x09, 0xa4, 0x90, 0x8c, 0x81, 0xc6, 0xa9, 0xa0, 0xe3, 0x46, 0xb6, + 0xf9, 0x71, 0x82, 0x0a, 0x9d, 0xad, 0x9c, 0xf8, 0x59, 0x6b, 0xdc, 0xa8, 0x94, 0x43, 0x0c, 0x51, + 0x23, 0x9a, 0x9d, 0xcc, 0xad, 0xca, 0x2e, 0xc3, 0x54, 0x60, 0xda, 0x35, 0xc0, 0x14, 0x39, 0xda, + 0x0e, 0x04, 0x97, 0x48, 0xf5, 0x6a, 0x5a, 0xfb, 0x6f, 0x05, 0x42, 0x6e, 0x54, 0xd0, 0x8b, 0x80, + 0x21, 0x97, 0x4e, 0x99, 0x14, 0xfb, 0x20, 0x51, 0xb8, 0x76, 0xcd, 0xae, 0xaf, 0x77, 0x4c, 0xe1, + 0x5c, 0x93, 0x8d, 0x88, 0x0b, 0xae, 0xba, 0x0a, 0x55, 0x10, 0xb9, 0x85, 0x9a, 0x5d, 0xdf, 0x6c, + 0x1e, 0x4f, 0xe7, 0x55, 0xeb, 0x63, 0x5e, 0xdd, 0x31, 0x23, 0xd2, 0xfe, 0xbd, 0xcf, 0x91, 0x8a, + 0x40, 0x0d, 0xfd, 0xb6, 0x54, 0xaf, 0x2f, 0x47, 0x24, 0x9f, 0xdd, 0x96, 0xea, 0xe9, 0xeb, 0xf9, + 0xc0, 0xee, 0x10, 0x2d, 0xb9, 0xcd, 0x1c, 0xce, 0x19, 0x29, 0xc6, 0x09, 0x67, 0xe0, 0xfe, 0xd3, + 0xb2, 0x46, 0x2e, 0xdb, 0xfb, 0x2b, 0xbb, 0x84, 0x30, 0x60, 0x93, 0x16, 0xb0, 0x5f, 0xca, 0x16, + 0xb0, 0x8e, 0x79, 0xef, 0x9c, 0x93, 0xd2, 0x00, 0xa0, 0xcb, 0xa5, 0xfb, 0x7f, 0x65, 0xd3, 0x00, + 0xa0, 0x2d, 0x9d, 0x0b, 0xb2, 0x96, 0x99, 0x70, 0xa4, 0xdc, 0xe2, 0xaa, 0xaa, 0xec, 0x2f, 0x57, + 0x23, 0xd5, 0x3c, 0x9d, 0x2e, 0x3c, 0x7b, 0xb6, 0xf0, 0xec, 0xcf, 0x85, 0x67, 0x3f, 0x2e, 0x3d, + 0x6b, 0xb6, 0xf4, 0xac, 0xf7, 0xa5, 0x67, 0xdd, 0x1d, 0x86, 0x5c, 0x0d, 0x47, 0x3d, 0x9f, 0xa1, + 0xa0, 0x28, 0x51, 0x4c, 0x74, 0x0e, 0x0c, 0x23, 0xfa, 0x93, 0xfb, 0x83, 0x4e, 0x5e, 0x4d, 0x62, + 0x48, 0x7b, 0x25, 0x4d, 0x4f, 0xbe, 0x03, 0x00, 0x00, 0xff, 0xff, 0xe1, 0x3d, 0xb5, 0x70, 0x15, + 0x02, 0x00, 0x00, +} + +func (m *Stablecoin) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Stablecoin) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Stablecoin) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size := m.FeeOut.Size() + i -= size + if _, err := m.FeeOut.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintPsm(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + { + size := m.FeeIn.Size() + i -= size + if _, err := m.FeeIn.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintPsm(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + { + size := m.Price.Size() + i -= size + if _, err := m.Price.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintPsm(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + { + size := m.LimitTotal.Size() + i -= size + if _, err := m.LimitTotal.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintPsm(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if len(m.Denom) > 0 { + i -= len(m.Denom) + copy(dAtA[i:], m.Denom) + i = encodeVarintPsm(dAtA, i, uint64(len(m.Denom))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintPsm(dAtA []byte, offset int, v uint64) int { + offset -= sovPsm(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Stablecoin) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Denom) + if l > 0 { + n += 1 + l + sovPsm(uint64(l)) + } + l = m.LimitTotal.Size() + n += 1 + l + sovPsm(uint64(l)) + l = m.Price.Size() + n += 1 + l + sovPsm(uint64(l)) + l = m.FeeIn.Size() + n += 1 + l + sovPsm(uint64(l)) + l = m.FeeOut.Size() + n += 1 + l + sovPsm(uint64(l)) + return n +} + +func sovPsm(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozPsm(x uint64) (n int) { + return sovPsm(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Stablecoin) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPsm + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Stablecoin: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Stablecoin: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPsm + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthPsm + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthPsm + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Denom = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LimitTotal", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPsm + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthPsm + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthPsm + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.LimitTotal.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Price", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPsm + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthPsm + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthPsm + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Price.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field FeeIn", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPsm + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthPsm + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthPsm + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.FeeIn.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field FeeOut", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPsm + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthPsm + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthPsm + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.FeeOut.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipPsm(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthPsm + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipPsm(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowPsm + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowPsm + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowPsm + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthPsm + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupPsm + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthPsm + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthPsm = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowPsm = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupPsm = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/psm/types/query.pb.go b/x/psm/types/query.pb.go new file mode 100644 index 0000000..95319d7 --- /dev/null +++ b/x/psm/types/query.pb.go @@ -0,0 +1,541 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: reserve/psm/v1/query.proto + +package types + +import ( + context "context" + fmt "fmt" + _ "github.com/cosmos/cosmos-sdk/types/query" + _ "github.com/cosmos/cosmos-sdk/types/tx/amino" + _ "github.com/cosmos/gogoproto/gogoproto" + grpc1 "github.com/cosmos/gogoproto/grpc" + proto "github.com/cosmos/gogoproto/proto" + _ "google.golang.org/genproto/googleapis/api/annotations" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// QueryParamsRequest is request type for the Query/Params RPC method. +type QueryParamsRequest struct { +} + +func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } +func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } +func (*QueryParamsRequest) ProtoMessage() {} +func (*QueryParamsRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_46bfc761c6109b8c, []int{0} +} +func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryParamsRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryParamsRequest.Merge(m, src) +} +func (m *QueryParamsRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryParamsRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo + +// QueryParamsResponse is response type for the Query/Params RPC method. +type QueryParamsResponse struct { + // params holds all the parameters of this module. + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` +} + +func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } +func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } +func (*QueryParamsResponse) ProtoMessage() {} +func (*QueryParamsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_46bfc761c6109b8c, []int{1} +} +func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryParamsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryParamsResponse.Merge(m, src) +} +func (m *QueryParamsResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryParamsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo + +func (m *QueryParamsResponse) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +func init() { + proto.RegisterType((*QueryParamsRequest)(nil), "reserve.psm.v1.QueryParamsRequest") + proto.RegisterType((*QueryParamsResponse)(nil), "reserve.psm.v1.QueryParamsResponse") +} + +func init() { proto.RegisterFile("reserve/psm/v1/query.proto", fileDescriptor_46bfc761c6109b8c) } + +var fileDescriptor_46bfc761c6109b8c = []byte{ + // 321 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x8f, 0x3f, 0x4b, 0xc3, 0x40, + 0x18, 0xc6, 0x73, 0x82, 0x05, 0x23, 0x08, 0xc6, 0x22, 0x12, 0x25, 0x4a, 0x14, 0x91, 0x52, 0xf2, + 0x92, 0x3a, 0xb9, 0x76, 0x70, 0xae, 0x1d, 0xdd, 0x2e, 0xe5, 0x88, 0x81, 0xde, 0xbd, 0xd7, 0xdc, + 0x35, 0xd8, 0x49, 0x70, 0x72, 0x14, 0xfc, 0x12, 0x8e, 0x7e, 0x8c, 0x8e, 0x05, 0x17, 0x27, 0x91, + 0x46, 0xf0, 0x6b, 0x48, 0xef, 0x6e, 0x69, 0xfd, 0xb3, 0x1c, 0x2f, 0xef, 0xfb, 0x7b, 0x9e, 0x7b, + 0x1e, 0x3f, 0x2c, 0x99, 0x62, 0x65, 0xc5, 0x40, 0x2a, 0x0e, 0x55, 0x0a, 0xa3, 0x31, 0x2b, 0x27, + 0x89, 0x2c, 0x51, 0x63, 0xb0, 0xe5, 0x6e, 0x89, 0x54, 0x3c, 0xa9, 0xd2, 0x70, 0x9b, 0xf2, 0x42, + 0x20, 0x98, 0xd7, 0x22, 0x61, 0x33, 0xc7, 0x1c, 0xcd, 0x08, 0x8b, 0xc9, 0x6d, 0x0f, 0x72, 0xc4, + 0x7c, 0xc8, 0x80, 0xca, 0x02, 0xa8, 0x10, 0xa8, 0xa9, 0x2e, 0x50, 0x28, 0x77, 0x6d, 0x0d, 0x50, + 0x71, 0x54, 0x90, 0x51, 0xc5, 0xec, 0x7f, 0x50, 0xa5, 0x19, 0xd3, 0x34, 0x05, 0x49, 0xf3, 0x42, + 0x18, 0xd8, 0xb1, 0xfb, 0x2b, 0xf1, 0x24, 0x2d, 0x29, 0x77, 0x46, 0x71, 0xd3, 0x0f, 0xae, 0x16, + 0xf2, 0x9e, 0x59, 0xf6, 0xd9, 0x68, 0xcc, 0x94, 0x8e, 0x7b, 0xfe, 0xce, 0xd2, 0x56, 0x49, 0x14, + 0x8a, 0x05, 0x17, 0x7e, 0xc3, 0x8a, 0xf7, 0xc8, 0x11, 0x39, 0xdb, 0xec, 0xec, 0x26, 0xcb, 0xed, + 0x12, 0xcb, 0x77, 0x37, 0xa6, 0xef, 0x87, 0xde, 0xf3, 0xd7, 0x4b, 0x8b, 0xf4, 0x9d, 0xa0, 0xf3, + 0x40, 0xfc, 0x75, 0x63, 0x19, 0xdc, 0xf9, 0x0d, 0x8b, 0x05, 0xf1, 0xaa, 0xfc, 0x67, 0x92, 0xf0, + 0xf8, 0x5f, 0xc6, 0xe6, 0x8a, 0xdb, 0xf7, 0xaf, 0x9f, 0x4f, 0x6b, 0xa7, 0xc1, 0x09, 0xa0, 0x40, + 0x3e, 0x31, 0xcd, 0x06, 0x38, 0x84, 0x5f, 0x8b, 0x77, 0x2f, 0xa7, 0xf3, 0x88, 0xcc, 0xe6, 0x11, + 0xf9, 0x98, 0x47, 0xe4, 0xb1, 0x8e, 0xbc, 0x59, 0x1d, 0x79, 0x6f, 0x75, 0xe4, 0x5d, 0xb7, 0xf3, + 0x42, 0xdf, 0x8c, 0xb3, 0x64, 0x80, 0xfc, 0x0f, 0xa7, 0x5b, 0xe3, 0xa5, 0x27, 0x92, 0xa9, 0xac, + 0x61, 0xae, 0xe7, 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0xfd, 0xad, 0x02, 0x23, 0xff, 0x01, 0x00, + 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// QueryClient is the client API for Query service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type QueryClient interface { + // Parameters queries the parameters of the module. + Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) +} + +type queryClient struct { + cc grpc1.ClientConn +} + +func NewQueryClient(cc grpc1.ClientConn) QueryClient { + return &queryClient{cc} +} + +func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { + out := new(QueryParamsResponse) + err := c.cc.Invoke(ctx, "/reserve.psm.v1.Query/Params", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// QueryServer is the server API for Query service. +type QueryServer interface { + // Parameters queries the parameters of the module. + Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) +} + +// UnimplementedQueryServer can be embedded to have forward compatible implementations. +type UnimplementedQueryServer struct { +} + +func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") +} + +func RegisterQueryServer(s grpc1.Server, srv QueryServer) { + s.RegisterService(&_Query_serviceDesc, srv) +} + +func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryParamsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Params(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/reserve.psm.v1.Query/Params", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +var Query_serviceDesc = _Query_serviceDesc +var _Query_serviceDesc = grpc.ServiceDesc{ + ServiceName: "reserve.psm.v1.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Params", + Handler: _Query_Params_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "reserve/psm/v1/query.proto", +} + +func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { + offset -= sovQuery(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *QueryParamsRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *QueryParamsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Params.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + +func sovQuery(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozQuery(x uint64) (n int) { + return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipQuery(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthQuery + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupQuery + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthQuery + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/psm/types/query.pb.gw.go b/x/psm/types/query.pb.gw.go new file mode 100644 index 0000000..099b0f4 --- /dev/null +++ b/x/psm/types/query.pb.gw.go @@ -0,0 +1,153 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: reserve/psm/v1/query.proto + +/* +Package types is a reverse proxy. + +It translates gRPC into RESTful JSON APIs. +*/ +package types + +import ( + "context" + "io" + "net/http" + + "github.com/golang/protobuf/descriptor" + "github.com/golang/protobuf/proto" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/grpc-ecosystem/grpc-gateway/utilities" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +// Suppress "imported and not used" errors +var _ codes.Code +var _ io.Reader +var _ status.Status +var _ = runtime.String +var _ = utilities.NewDoubleArray +var _ = descriptor.ForMessage +var _ = metadata.Join + +func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryParamsRequest + var metadata runtime.ServerMetadata + + msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryParamsRequest + var metadata runtime.ServerMetadata + + msg, err := server.Params(ctx, &protoReq) + return msg, metadata, err + +} + +// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". +// UnaryRPC :call QueryServer directly. +// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. +// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. +func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { + + mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but +// automatically dials to "endpoint" and closes the connection when "ctx" gets done. +func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { + conn, err := grpc.Dial(endpoint, opts...) + if err != nil { + return err + } + defer func() { + if err != nil { + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + return + } + go func() { + <-ctx.Done() + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + }() + }() + + return RegisterQueryHandler(ctx, mux, conn) +} + +// RegisterQueryHandler registers the http handlers for service Query to "mux". +// The handlers forward requests to the grpc endpoint over "conn". +func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { + return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) +} + +// RegisterQueryHandlerClient registers the http handlers for service Query +// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". +// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" +// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in +// "QueryClient" to call the correct interceptors. +func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { + + mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +var ( + pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"onomyprotocol", "reserve", "psm", "v1", "params"}, "", runtime.AssumeColonVerbOpt(false))) +) + +var ( + forward_Query_Params_0 = runtime.ForwardResponseMessage +) diff --git a/x/psm/types/tx.pb.go b/x/psm/types/tx.pb.go new file mode 100644 index 0000000..73ec205 --- /dev/null +++ b/x/psm/types/tx.pb.go @@ -0,0 +1,599 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: reserve/psm/v1/tx.proto + +package types + +import ( + context "context" + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + _ "github.com/cosmos/cosmos-sdk/types/msgservice" + _ "github.com/cosmos/cosmos-sdk/types/tx/amino" + _ "github.com/cosmos/gogoproto/gogoproto" + grpc1 "github.com/cosmos/gogoproto/grpc" + proto "github.com/cosmos/gogoproto/proto" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// MsgUpdateParams is the Msg/UpdateParams request type. +type MsgUpdateParams struct { + // authority is the address that controls the module (defaults to x/gov unless overwritten). + Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` + // params defines the module parameters to update. + // + // NOTE: All parameters must be supplied. + Params Params `protobuf:"bytes,2,opt,name=params,proto3" json:"params"` +} + +func (m *MsgUpdateParams) Reset() { *m = MsgUpdateParams{} } +func (m *MsgUpdateParams) String() string { return proto.CompactTextString(m) } +func (*MsgUpdateParams) ProtoMessage() {} +func (*MsgUpdateParams) Descriptor() ([]byte, []int) { + return fileDescriptor_d0ff2d5421e71e2a, []int{0} +} +func (m *MsgUpdateParams) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUpdateParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUpdateParams.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgUpdateParams) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateParams.Merge(m, src) +} +func (m *MsgUpdateParams) XXX_Size() int { + return m.Size() +} +func (m *MsgUpdateParams) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateParams.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUpdateParams proto.InternalMessageInfo + +func (m *MsgUpdateParams) GetAuthority() string { + if m != nil { + return m.Authority + } + return "" +} + +func (m *MsgUpdateParams) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +// MsgUpdateParamsResponse defines the response structure for executing a +// MsgUpdateParams message. +type MsgUpdateParamsResponse struct { +} + +func (m *MsgUpdateParamsResponse) Reset() { *m = MsgUpdateParamsResponse{} } +func (m *MsgUpdateParamsResponse) String() string { return proto.CompactTextString(m) } +func (*MsgUpdateParamsResponse) ProtoMessage() {} +func (*MsgUpdateParamsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_d0ff2d5421e71e2a, []int{1} +} +func (m *MsgUpdateParamsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUpdateParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUpdateParamsResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgUpdateParamsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateParamsResponse.Merge(m, src) +} +func (m *MsgUpdateParamsResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgUpdateParamsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateParamsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUpdateParamsResponse proto.InternalMessageInfo + +func init() { + proto.RegisterType((*MsgUpdateParams)(nil), "reserve.psm.v1.MsgUpdateParams") + proto.RegisterType((*MsgUpdateParamsResponse)(nil), "reserve.psm.v1.MsgUpdateParamsResponse") +} + +func init() { proto.RegisterFile("reserve/psm/v1/tx.proto", fileDescriptor_d0ff2d5421e71e2a) } + +var fileDescriptor_d0ff2d5421e71e2a = []byte{ + // 347 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x2f, 0x4a, 0x2d, 0x4e, + 0x2d, 0x2a, 0x4b, 0xd5, 0x2f, 0x28, 0xce, 0xd5, 0x2f, 0x33, 0xd4, 0x2f, 0xa9, 0xd0, 0x2b, 0x28, + 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x83, 0x4a, 0xe8, 0x15, 0x14, 0xe7, 0xea, 0x95, 0x19, 0x4a, 0x09, + 0x26, 0xe6, 0x66, 0xe6, 0xe5, 0xeb, 0x83, 0x49, 0x88, 0x12, 0x29, 0xf1, 0xe4, 0xfc, 0xe2, 0xdc, + 0xfc, 0x62, 0xfd, 0xdc, 0xe2, 0x74, 0x90, 0xd6, 0xdc, 0xe2, 0x74, 0xa8, 0x84, 0x24, 0x44, 0x22, + 0x1e, 0xcc, 0xd3, 0x87, 0x70, 0xa0, 0x52, 0x22, 0xe9, 0xf9, 0xe9, 0xf9, 0x10, 0x71, 0x10, 0x0b, + 0x2a, 0x2a, 0x8d, 0xe6, 0x8a, 0x82, 0xc4, 0xa2, 0xc4, 0x5c, 0xa8, 0x16, 0xa5, 0x6d, 0x8c, 0x5c, + 0xfc, 0xbe, 0xc5, 0xe9, 0xa1, 0x05, 0x29, 0x89, 0x25, 0xa9, 0x01, 0x60, 0x19, 0x21, 0x33, 0x2e, + 0xce, 0xc4, 0xd2, 0x92, 0x8c, 0xfc, 0xa2, 0xcc, 0x92, 0x4a, 0x09, 0x46, 0x05, 0x46, 0x0d, 0x4e, + 0x27, 0x89, 0x4b, 0x5b, 0x74, 0x45, 0xa0, 0x76, 0x39, 0xa6, 0xa4, 0x14, 0xa5, 0x16, 0x17, 0x07, + 0x97, 0x14, 0x65, 0xe6, 0xa5, 0x07, 0x21, 0x94, 0x0a, 0x59, 0x72, 0xb1, 0x41, 0xcc, 0x96, 0x60, + 0x52, 0x60, 0xd4, 0xe0, 0x36, 0x12, 0xd3, 0x43, 0xf5, 0xa6, 0x1e, 0xc4, 0x7c, 0x27, 0xce, 0x13, + 0xf7, 0xe4, 0x19, 0x56, 0x3c, 0xdf, 0xa0, 0xc5, 0x18, 0x04, 0xd5, 0x60, 0x65, 0xd0, 0xf4, 0x7c, + 0x83, 0x16, 0xc2, 0xa8, 0xae, 0xe7, 0x1b, 0xb4, 0x64, 0x61, 0xce, 0xae, 0x00, 0x3b, 0x1c, 0xcd, + 0x91, 0x4a, 0x92, 0x5c, 0xe2, 0x68, 0x42, 0x41, 0xa9, 0xc5, 0x05, 0xf9, 0x79, 0xc5, 0xa9, 0x46, + 0x69, 0x5c, 0xcc, 0xbe, 0xc5, 0xe9, 0x42, 0x11, 0x5c, 0x3c, 0x28, 0xde, 0x92, 0x47, 0x77, 0x0e, + 0x9a, 0x7e, 0x29, 0x75, 0x02, 0x0a, 0x60, 0x16, 0x48, 0xb1, 0x36, 0x80, 0x1c, 0xef, 0xe4, 0x76, + 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, + 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x51, 0x3a, 0xe9, 0x99, 0x25, 0x19, 0xa5, + 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0xf9, 0x79, 0xf9, 0xb9, 0x95, 0xe0, 0xc0, 0x4e, 0xce, 0xcf, + 0xd1, 0x47, 0xf5, 0x54, 0x49, 0x65, 0x41, 0x6a, 0x71, 0x12, 0x1b, 0x58, 0xd6, 0x18, 0x10, 0x00, + 0x00, 0xff, 0xff, 0x54, 0xeb, 0x6a, 0x99, 0x2f, 0x02, 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// MsgClient is the client API for Msg service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type MsgClient interface { + // UpdateParams defines a (governance) operation for updating the module + // parameters. The authority defaults to the x/gov module account. + UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) +} + +type msgClient struct { + cc grpc1.ClientConn +} + +func NewMsgClient(cc grpc1.ClientConn) MsgClient { + return &msgClient{cc} +} + +func (c *msgClient) UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) { + out := new(MsgUpdateParamsResponse) + err := c.cc.Invoke(ctx, "/reserve.psm.v1.Msg/UpdateParams", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// MsgServer is the server API for Msg service. +type MsgServer interface { + // UpdateParams defines a (governance) operation for updating the module + // parameters. The authority defaults to the x/gov module account. + UpdateParams(context.Context, *MsgUpdateParams) (*MsgUpdateParamsResponse, error) +} + +// UnimplementedMsgServer can be embedded to have forward compatible implementations. +type UnimplementedMsgServer struct { +} + +func (*UnimplementedMsgServer) UpdateParams(ctx context.Context, req *MsgUpdateParams) (*MsgUpdateParamsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method UpdateParams not implemented") +} + +func RegisterMsgServer(s grpc1.Server, srv MsgServer) { + s.RegisterService(&_Msg_serviceDesc, srv) +} + +func _Msg_UpdateParams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgUpdateParams) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).UpdateParams(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/reserve.psm.v1.Msg/UpdateParams", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).UpdateParams(ctx, req.(*MsgUpdateParams)) + } + return interceptor(ctx, in, info, handler) +} + +var Msg_serviceDesc = _Msg_serviceDesc +var _Msg_serviceDesc = grpc.ServiceDesc{ + ServiceName: "reserve.psm.v1.Msg", + HandlerType: (*MsgServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "UpdateParams", + Handler: _Msg_UpdateParams_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "reserve/psm/v1/tx.proto", +} + +func (m *MsgUpdateParams) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgUpdateParams) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUpdateParams) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if len(m.Authority) > 0 { + i -= len(m.Authority) + copy(dAtA[i:], m.Authority) + i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgUpdateParamsResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgUpdateParamsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUpdateParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func encodeVarintTx(dAtA []byte, offset int, v uint64) int { + offset -= sovTx(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *MsgUpdateParams) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Authority) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = m.Params.Size() + n += 1 + l + sovTx(uint64(l)) + return n +} + +func (m *MsgUpdateParamsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func sovTx(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTx(x uint64) (n int) { + return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *MsgUpdateParams) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgUpdateParams: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgUpdateParams: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Authority = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgUpdateParamsResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgUpdateParamsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgUpdateParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTx(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTx + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTx + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTx + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTx + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTx + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTx + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/psm/types/types.go b/x/psm/types/types.go new file mode 100644 index 0000000..ab1254f --- /dev/null +++ b/x/psm/types/types.go @@ -0,0 +1 @@ +package types diff --git a/x/reserve/types/genesis.pb.go b/x/reserve/types/genesis.pb.go index 681d224..e5a118e 100644 --- a/x/reserve/types/genesis.pb.go +++ b/x/reserve/types/genesis.pb.go @@ -5,13 +5,12 @@ package types import ( fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" _ "github.com/cosmos/gogoproto/gogoproto" proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/reserve/types/module.pb.go b/x/reserve/types/module.pb.go index 7ecae3f..1adf5b5 100644 --- a/x/reserve/types/module.pb.go +++ b/x/reserve/types/module.pb.go @@ -4,13 +4,12 @@ package types import ( + _ "cosmossdk.io/api/cosmos/app/v1alpha1" fmt "fmt" + proto "github.com/cosmos/gogoproto/proto" io "io" math "math" math_bits "math/bits" - - _ "cosmossdk.io/api/cosmos/app/v1alpha1" - proto "github.com/cosmos/gogoproto/proto" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/reserve/types/params.pb.go b/x/reserve/types/params.pb.go index 8583cb6..1581b9c 100644 --- a/x/reserve/types/params.pb.go +++ b/x/reserve/types/params.pb.go @@ -5,13 +5,12 @@ package types import ( fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" _ "github.com/cosmos/gogoproto/gogoproto" proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/reserve/types/query.pb.go b/x/reserve/types/query.pb.go index 6823e13..c5adc33 100644 --- a/x/reserve/types/query.pb.go +++ b/x/reserve/types/query.pb.go @@ -6,10 +6,6 @@ package types import ( context "context" fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - _ "github.com/cosmos/cosmos-sdk/types/query" _ "github.com/cosmos/cosmos-sdk/types/tx/amino" _ "github.com/cosmos/gogoproto/gogoproto" @@ -19,6 +15,9 @@ import ( grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" + io "io" + math "math" + math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/reserve/types/tx.pb.go b/x/reserve/types/tx.pb.go index 071da8c..d6b59c5 100644 --- a/x/reserve/types/tx.pb.go +++ b/x/reserve/types/tx.pb.go @@ -6,10 +6,6 @@ package types import ( context "context" fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - _ "github.com/cosmos/cosmos-proto" _ "github.com/cosmos/cosmos-sdk/types/msgservice" _ "github.com/cosmos/cosmos-sdk/types/tx/amino" @@ -19,6 +15,9 @@ import ( grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" + io "io" + math "math" + math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used.