From dc0d2d667e11b83fa7e3e156c55e4d96b6401891 Mon Sep 17 00:00:00 2001 From: C H Date: Fri, 26 Apr 2024 16:22:41 +0800 Subject: [PATCH] Added liquidity module --- app/app.go | 6 +- app/keepers/keepers.go | 35 +- app/keepers/keys.go | 4 +- app/modules.go | 14 +- app/upgrades/v4/constants.go | 1 + app/upgrades/v4/upgrades.go | 4 +- docs/proto/proto-docs.md | 866 +++ go.mod | 5 +- plugins/liquidity.go | 386 +- plugins/msg_binding.go | 4 +- plugins/query_binding.go | 4 +- plugins/wasm.go | 8 +- proto/buf.yaml | 3 + proto/cyber/liquidity/v1beta1/genesis.proto | 45 + proto/cyber/liquidity/v1beta1/liquidity.proto | 300 + proto/cyber/liquidity/v1beta1/query.proto | 252 + proto/cyber/liquidity/v1beta1/tx.proto | 198 + x/liquidity/abci.go | 25 + x/liquidity/client/cli/flags.go | 21 + x/liquidity/client/cli/query.go | 577 ++ x/liquidity/client/cli/tx.go | 336 ++ x/liquidity/exported/exported.go | 22 + x/liquidity/genesis.go | 18 + x/liquidity/handler.go | 37 + x/liquidity/keeper/batch.go | 285 + x/liquidity/keeper/genesis.go | 61 + x/liquidity/keeper/grpc_query.go | 327 ++ x/liquidity/keeper/invariants.go | 389 ++ x/liquidity/keeper/keeper.go | 85 + x/liquidity/keeper/liquidity_pool.go | 918 +++ x/liquidity/keeper/migrator.go | 27 + x/liquidity/keeper/msg_server.go | 167 + x/liquidity/keeper/store.go | 600 ++ x/liquidity/keeper/swap.go | 147 + x/liquidity/migrations/v2/migrate.go | 28 + x/liquidity/module.go | 168 + x/liquidity/spec/01_concepts.md | 67 + x/liquidity/spec/02_state.md | 123 + x/liquidity/spec/03_state_transitions.md | 250 + x/liquidity/spec/04_messages.md | 104 + x/liquidity/spec/05_begin_block.md | 18 + x/liquidity/spec/06_end_block.md | 32 + x/liquidity/spec/07_events.md | 118 + x/liquidity/spec/08_params.md | 92 + x/liquidity/spec/README.md | 27 + x/liquidity/types/codec.go | 54 + x/liquidity/types/errors.go | 50 + x/liquidity/types/events.go | 53 + x/liquidity/types/expected_keepers.go | 33 + x/liquidity/types/genesis.go | 44 + x/liquidity/types/genesis.pb.go | 875 +++ x/liquidity/types/keys.go | 111 + x/liquidity/types/liquidity.pb.go | 3486 +++++++++++ x/liquidity/types/liquidity_pool.go | 190 + x/liquidity/types/msgs.go | 230 + x/liquidity/types/params.go | 299 + x/liquidity/types/params_legacy.go | 24 + x/liquidity/types/querier.go | 33 + x/liquidity/types/query.pb.go | 5087 +++++++++++++++++ x/liquidity/types/query.pb.gw.go | 1310 +++++ x/liquidity/types/swap.go | 619 ++ x/liquidity/types/tx.pb.go | 2116 +++++++ x/liquidity/types/utils.go | 126 + 63 files changed, 21710 insertions(+), 234 deletions(-) create mode 100644 proto/cyber/liquidity/v1beta1/genesis.proto create mode 100644 proto/cyber/liquidity/v1beta1/liquidity.proto create mode 100644 proto/cyber/liquidity/v1beta1/query.proto create mode 100644 proto/cyber/liquidity/v1beta1/tx.proto create mode 100644 x/liquidity/abci.go create mode 100644 x/liquidity/client/cli/flags.go create mode 100644 x/liquidity/client/cli/query.go create mode 100644 x/liquidity/client/cli/tx.go create mode 100644 x/liquidity/exported/exported.go create mode 100644 x/liquidity/genesis.go create mode 100644 x/liquidity/handler.go create mode 100644 x/liquidity/keeper/batch.go create mode 100644 x/liquidity/keeper/genesis.go create mode 100644 x/liquidity/keeper/grpc_query.go create mode 100644 x/liquidity/keeper/invariants.go create mode 100644 x/liquidity/keeper/keeper.go create mode 100644 x/liquidity/keeper/liquidity_pool.go create mode 100644 x/liquidity/keeper/migrator.go create mode 100644 x/liquidity/keeper/msg_server.go create mode 100644 x/liquidity/keeper/store.go create mode 100644 x/liquidity/keeper/swap.go create mode 100644 x/liquidity/migrations/v2/migrate.go create mode 100644 x/liquidity/module.go create mode 100644 x/liquidity/spec/01_concepts.md create mode 100644 x/liquidity/spec/02_state.md create mode 100644 x/liquidity/spec/03_state_transitions.md create mode 100644 x/liquidity/spec/04_messages.md create mode 100644 x/liquidity/spec/05_begin_block.md create mode 100644 x/liquidity/spec/06_end_block.md create mode 100644 x/liquidity/spec/07_events.md create mode 100644 x/liquidity/spec/08_params.md create mode 100644 x/liquidity/spec/README.md create mode 100644 x/liquidity/types/codec.go create mode 100644 x/liquidity/types/errors.go create mode 100644 x/liquidity/types/events.go create mode 100644 x/liquidity/types/expected_keepers.go create mode 100644 x/liquidity/types/genesis.go create mode 100644 x/liquidity/types/genesis.pb.go create mode 100644 x/liquidity/types/keys.go create mode 100644 x/liquidity/types/liquidity.pb.go create mode 100644 x/liquidity/types/liquidity_pool.go create mode 100644 x/liquidity/types/msgs.go create mode 100644 x/liquidity/types/params.go create mode 100644 x/liquidity/types/params_legacy.go create mode 100644 x/liquidity/types/querier.go create mode 100644 x/liquidity/types/query.pb.go create mode 100644 x/liquidity/types/query.pb.gw.go create mode 100644 x/liquidity/types/swap.go create mode 100644 x/liquidity/types/tx.pb.go create mode 100644 x/liquidity/types/utils.go diff --git a/app/app.go b/app/app.go index 3545a59f..6bf04d21 100644 --- a/app/app.go +++ b/app/app.go @@ -344,9 +344,9 @@ func (app *App) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.Res } // custom initialization - //var bankGenesisState banktypes.GenesisState - //app.appCodec.MustUnmarshalJSON(genesisState["bank"], &bankGenesisState) - //app.BandwidthMeter.AddToDesirableBandwidth(ctx, bankGenesisState.Supply.AmountOf(ctypes.VOLT).Uint64()) + // var bankGenesisState banktypes.GenesisState + // app.appCodec.MustUnmarshalJSON(genesisState["bank"], &bankGenesisState) + // app.BandwidthMeter.AddToDesirableBandwidth(ctx, bankGenesisState.Supply.AmountOf(ctypes.VOLT).Uint64()) app.UpgradeKeeper.SetModuleVersionMap(ctx, app.ModuleManager.GetVersionMap()) resp := app.ModuleManager.InitGenesis(ctx, app.appCodec, genesisState) diff --git a/app/keepers/keepers.go b/app/keepers/keepers.go index d94ce764..23407fc4 100644 --- a/app/keepers/keepers.go +++ b/app/keepers/keepers.go @@ -57,10 +57,11 @@ import ( //"github.com/cybercongress/go-cyber/v4/app" - // liquiditykeeper "github.com/gravity-devs/liquidity/x/liquidity/keeper" - // liquiditytypes "github.com/gravity-devs/liquidity/x/liquidity/types" "github.com/spf13/cast" + liquiditykeeper "github.com/cybercongress/go-cyber/v4/x/liquidity/keeper" + liquiditytypes "github.com/cybercongress/go-cyber/v4/x/liquidity/types" + wasmplugins "github.com/cybercongress/go-cyber/v4/plugins" "github.com/cybercongress/go-cyber/v4/x/bandwidth" bandwidthkeeper "github.com/cybercongress/go-cyber/v4/x/bandwidth/keeper" @@ -97,9 +98,9 @@ var maccPerms = map[string][]string{ ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, ibcfeetypes.ModuleName: nil, wasmtypes.ModuleName: {authtypes.Burner}, - // liquiditytypes.ModuleName: {authtypes.Minter, authtypes.Burner}, - gridtypes.GridPoolName: nil, - resourcestypes.ResourcesName: {authtypes.Minter, authtypes.Burner}, + liquiditytypes.ModuleName: {authtypes.Minter, authtypes.Burner}, + gridtypes.GridPoolName: nil, + resourcestypes.ResourcesName: {authtypes.Minter, authtypes.Burner}, } type AppKeepers struct { @@ -129,8 +130,8 @@ type AppKeepers struct { ConsensusParamsKeeper consensusparamkeeper.Keeper - WasmKeeper wasmkeeper.Keeper - // LiquidityKeeper liquiditykeeper.Keeper + WasmKeeper wasmkeeper.Keeper + LiquidityKeeper liquiditykeeper.Keeper BandwidthMeter *bandwidthkeeper.BandwidthMeter CyberbankKeeper *cyberbankkeeper.IndexedKeeper GraphKeeper *graphkeeper.GraphKeeper @@ -354,14 +355,14 @@ func NewAppKeepers( govModAddress, ) - //appKeepers.LiquidityKeeper = liquiditykeeper.NewKeeper( - // appCodec, - // keys[liquiditytypes.StoreKey], - // appKeepers.GetSubspace(liquiditytypes.ModuleName), - // appKeepers.CyberbankKeeper.Proxy, - // appKeepers.AccountKeeper, - // appKeepers.DistrKeeper, - //) + appKeepers.LiquidityKeeper = liquiditykeeper.NewKeeper( + appCodec, + keys[liquiditytypes.StoreKey], + appKeepers.CyberbankKeeper.Proxy, + appKeepers.AccountKeeper, + appKeepers.DistrKeeper, + govModAddress, + ) // End cyber's keepers configuration @@ -462,7 +463,7 @@ func NewAppKeepers( appKeepers.DmnKeeper, appKeepers.GridKeeper, appKeepers.BandwidthMeter, - // appKeepers.LiquidityKeeper, + appKeepers.LiquidityKeeper, ) wasmOpts = append(wasmOpts, cyberOpts...) @@ -536,7 +537,7 @@ func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino paramsKeeper.Subspace(gridtypes.ModuleName) paramsKeeper.Subspace(dmntypes.ModuleName) paramsKeeper.Subspace(resourcestypes.ModuleName) - // paramsKeeper.Subspace(liquiditytypes.ModuleName) + paramsKeeper.Subspace(liquiditytypes.ModuleName) return paramsKeeper } diff --git a/app/keepers/keys.go b/app/keepers/keys.go index f24e81b6..c418716e 100644 --- a/app/keepers/keys.go +++ b/app/keepers/keys.go @@ -23,7 +23,7 @@ import ( ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" - // liquiditytypes "github.com/gravity-devs/liquidity/x/liquidity/types" + liquiditytypes "github.com/cybercongress/go-cyber/v4/x/liquidity/types" bandwidthtypes "github.com/cybercongress/go-cyber/v4/x/bandwidth/types" dmntypes "github.com/cybercongress/go-cyber/v4/x/dmn/types" @@ -48,7 +48,7 @@ func (appKeepers *AppKeepers) GenerateKeys() { ibcfeetypes.StoreKey, wasmtypes.StoreKey, // our additions - // liquiditytypes.StoreKey, + liquiditytypes.StoreKey, bandwidthtypes.StoreKey, graphtypes.StoreKey, ranktypes.StoreKey, diff --git a/app/modules.go b/app/modules.go index 4e37620d..b732ada2 100644 --- a/app/modules.go +++ b/app/modules.go @@ -45,8 +45,8 @@ import ( ibc "github.com/cosmos/ibc-go/v7/modules/core" ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" - //"github.com/gravity-devs/liquidity/x/liquidity" - //liquiditytypes "github.com/gravity-devs/liquidity/x/liquidity/types" + "github.com/cybercongress/go-cyber/v4/x/liquidity" + liquiditytypes "github.com/cybercongress/go-cyber/v4/x/liquidity/types" "github.com/cybercongress/go-cyber/v4/app/params" "github.com/cybercongress/go-cyber/v4/x/bandwidth" @@ -93,7 +93,7 @@ var ModuleBasics = module.NewBasicManager( ibcfee.AppModuleBasic{}, transfer.AppModuleBasic{}, consensus.AppModuleBasic{}, - // liquidity.AppModuleBasic{}, + liquidity.AppModuleBasic{}, wasm.AppModuleBasic{}, bandwidth.AppModuleBasic{}, cyberbank.AppModuleBasic{}, @@ -137,7 +137,7 @@ func appModules( crisis.NewAppModule(app.AppKeepers.CrisisKeeper, skipGenesisInvariants, app.GetSubspace(crisistypes.ModuleName)), wasm.NewAppModule(appCodec, &app.WasmKeeper, app.StakingKeeper, app.AccountKeeper, app.CyberbankKeeper.Proxy, app.MsgServiceRouter(), app.GetSubspace(wasmtypes.ModuleName)), consensus.NewAppModule(appCodec, app.AppKeepers.ConsensusParamsKeeper), - // liquidity.NewAppModule(appCodec, app.LiquidityKeeper, app.AccountKeeper, app.CyberbankKeeper.Proxy, app.DistrKeeper), + liquidity.NewAppModule(appCodec, app.LiquidityKeeper, app.AccountKeeper, app.CyberbankKeeper.Proxy, app.DistrKeeper, app.GetSubspace(liquiditytypes.ModuleName)), cyberbank.NewAppModule(appCodec, app.CyberbankKeeper), bandwidth.NewAppModule(appCodec, app.AccountKeeper, app.BandwidthMeter, app.GetSubspace(bandwidthtypes.ModuleName)), graph.NewAppModule( @@ -189,7 +189,7 @@ func orderBeginBlockers() []string { upgradetypes.ModuleName, capabilitytypes.ModuleName, stakingtypes.ModuleName, - // liquiditytypes.ModuleName, + liquiditytypes.ModuleName, distrtypes.ModuleName, slashingtypes.ModuleName, minttypes.ModuleName, @@ -223,7 +223,7 @@ func orderEndBlockers() []string { crisistypes.ModuleName, govtypes.ModuleName, stakingtypes.ModuleName, - // liquiditytypes.ModuleName, + liquiditytypes.ModuleName, cyberbanktypes.ModuleName, bandwidthtypes.ModuleName, graphtypes.ModuleName, @@ -266,7 +266,7 @@ func orderInitBlockers() []string { ibcexported.ModuleName, evidencetypes.ModuleName, consensusparamtypes.ModuleName, - // liquiditytypes.ModuleName, + liquiditytypes.ModuleName, feegrant.ModuleName, authz.ModuleName, authtypes.ModuleName, diff --git a/app/upgrades/v4/constants.go b/app/upgrades/v4/constants.go index f5acf0b1..70b8d42b 100644 --- a/app/upgrades/v4/constants.go +++ b/app/upgrades/v4/constants.go @@ -4,6 +4,7 @@ import ( store "github.com/cosmos/cosmos-sdk/store/types" consensustypes "github.com/cosmos/cosmos-sdk/x/consensus/types" crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" + resourcestypes "github.com/cybercongress/go-cyber/v4/x/resources/types" "github.com/cybercongress/go-cyber/v4/app/upgrades" diff --git a/app/upgrades/v4/upgrades.go b/app/upgrades/v4/upgrades.go index fb8a67fd..aaec5f8d 100644 --- a/app/upgrades/v4/upgrades.go +++ b/app/upgrades/v4/upgrades.go @@ -2,6 +2,7 @@ package v3 import ( "fmt" + liquiditytypes "github.com/cybercongress/go-cyber/v4/x/liquidity/types" "time" wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" @@ -83,8 +84,9 @@ func CreateV4UpgradeHandler( keyTable = ranktypes.ParamKeyTable() //nolint:staticcheck case resourcestypes.ModuleName: keyTable = resourcestypes.ParamKeyTable() //nolint:staticcheck + case liquiditytypes.ModuleName: + keyTable = liquiditytypes.ParamKeyTable() } - if !subspace.HasKeyTable() { subspace.WithKeyTable(keyTable) } diff --git a/docs/proto/proto-docs.md b/docs/proto/proto-docs.md index e3114236..af787534 100644 --- a/docs/proto/proto-docs.md +++ b/docs/proto/proto-docs.md @@ -127,6 +127,58 @@ - [Msg](#cyber.grid.v1beta1.Msg) +- [cyber/liquidity/v1beta1/tx.proto](#cyber/liquidity/v1beta1/tx.proto) + - [MsgCreatePool](#cyber.liquidity.v1beta1.MsgCreatePool) + - [MsgCreatePoolResponse](#cyber.liquidity.v1beta1.MsgCreatePoolResponse) + - [MsgDepositWithinBatch](#cyber.liquidity.v1beta1.MsgDepositWithinBatch) + - [MsgDepositWithinBatchResponse](#cyber.liquidity.v1beta1.MsgDepositWithinBatchResponse) + - [MsgSwapWithinBatch](#cyber.liquidity.v1beta1.MsgSwapWithinBatch) + - [MsgSwapWithinBatchResponse](#cyber.liquidity.v1beta1.MsgSwapWithinBatchResponse) + - [MsgWithdrawWithinBatch](#cyber.liquidity.v1beta1.MsgWithdrawWithinBatch) + - [MsgWithdrawWithinBatchResponse](#cyber.liquidity.v1beta1.MsgWithdrawWithinBatchResponse) + + - [Msg](#cyber.liquidity.v1beta1.Msg) + +- [cyber/liquidity/v1beta1/liquidity.proto](#cyber/liquidity/v1beta1/liquidity.proto) + - [DepositMsgState](#cyber.liquidity.v1beta1.DepositMsgState) + - [Params](#cyber.liquidity.v1beta1.Params) + - [Pool](#cyber.liquidity.v1beta1.Pool) + - [PoolBatch](#cyber.liquidity.v1beta1.PoolBatch) + - [PoolMetadata](#cyber.liquidity.v1beta1.PoolMetadata) + - [PoolType](#cyber.liquidity.v1beta1.PoolType) + - [SwapMsgState](#cyber.liquidity.v1beta1.SwapMsgState) + - [WithdrawMsgState](#cyber.liquidity.v1beta1.WithdrawMsgState) + +- [cyber/liquidity/v1beta1/genesis.proto](#cyber/liquidity/v1beta1/genesis.proto) + - [GenesisState](#cyber.liquidity.v1beta1.GenesisState) + - [PoolRecord](#cyber.liquidity.v1beta1.PoolRecord) + +- [cyber/liquidity/v1beta1/query.proto](#cyber/liquidity/v1beta1/query.proto) + - [QueryLiquidityPoolBatchRequest](#cyber.liquidity.v1beta1.QueryLiquidityPoolBatchRequest) + - [QueryLiquidityPoolBatchResponse](#cyber.liquidity.v1beta1.QueryLiquidityPoolBatchResponse) + - [QueryLiquidityPoolByPoolCoinDenomRequest](#cyber.liquidity.v1beta1.QueryLiquidityPoolByPoolCoinDenomRequest) + - [QueryLiquidityPoolByReserveAccRequest](#cyber.liquidity.v1beta1.QueryLiquidityPoolByReserveAccRequest) + - [QueryLiquidityPoolRequest](#cyber.liquidity.v1beta1.QueryLiquidityPoolRequest) + - [QueryLiquidityPoolResponse](#cyber.liquidity.v1beta1.QueryLiquidityPoolResponse) + - [QueryLiquidityPoolsRequest](#cyber.liquidity.v1beta1.QueryLiquidityPoolsRequest) + - [QueryLiquidityPoolsResponse](#cyber.liquidity.v1beta1.QueryLiquidityPoolsResponse) + - [QueryParamsRequest](#cyber.liquidity.v1beta1.QueryParamsRequest) + - [QueryParamsResponse](#cyber.liquidity.v1beta1.QueryParamsResponse) + - [QueryPoolBatchDepositMsgRequest](#cyber.liquidity.v1beta1.QueryPoolBatchDepositMsgRequest) + - [QueryPoolBatchDepositMsgResponse](#cyber.liquidity.v1beta1.QueryPoolBatchDepositMsgResponse) + - [QueryPoolBatchDepositMsgsRequest](#cyber.liquidity.v1beta1.QueryPoolBatchDepositMsgsRequest) + - [QueryPoolBatchDepositMsgsResponse](#cyber.liquidity.v1beta1.QueryPoolBatchDepositMsgsResponse) + - [QueryPoolBatchSwapMsgRequest](#cyber.liquidity.v1beta1.QueryPoolBatchSwapMsgRequest) + - [QueryPoolBatchSwapMsgResponse](#cyber.liquidity.v1beta1.QueryPoolBatchSwapMsgResponse) + - [QueryPoolBatchSwapMsgsRequest](#cyber.liquidity.v1beta1.QueryPoolBatchSwapMsgsRequest) + - [QueryPoolBatchSwapMsgsResponse](#cyber.liquidity.v1beta1.QueryPoolBatchSwapMsgsResponse) + - [QueryPoolBatchWithdrawMsgRequest](#cyber.liquidity.v1beta1.QueryPoolBatchWithdrawMsgRequest) + - [QueryPoolBatchWithdrawMsgResponse](#cyber.liquidity.v1beta1.QueryPoolBatchWithdrawMsgResponse) + - [QueryPoolBatchWithdrawMsgsRequest](#cyber.liquidity.v1beta1.QueryPoolBatchWithdrawMsgsRequest) + - [QueryPoolBatchWithdrawMsgsResponse](#cyber.liquidity.v1beta1.QueryPoolBatchWithdrawMsgsResponse) + + - [Query](#cyber.liquidity.v1beta1.Query) + - [cyber/rank/v1beta1/types.proto](#cyber/rank/v1beta1/types.proto) - [Params](#cyber.rank.v1beta1.Params) - [RankedParticle](#cyber.rank.v1beta1.RankedParticle) @@ -1623,6 +1675,820 @@ + +

Top

+ +## cyber/liquidity/v1beta1/tx.proto + + + + + +### MsgCreatePool +MsgCreatePool defines an sdk.Msg type that supports submitting a create +liquidity pool tx. + +See: +https://github.com/gravity-devs/liquidity/blob/develop/x/liquidity/spec/04_messages.md + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `pool_creator_address` | [string](#string) | | | +| `pool_type_id` | [uint32](#uint32) | | id of the target pool type, must match the value in the pool. Only pool-type-id 1 is supported. | +| `deposit_coins` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | repeated | reserve coin pair of the pool to deposit. | + + + + + + + + +### MsgCreatePoolResponse +MsgCreatePoolResponse defines the Msg/CreatePool response type. + + + + + + + + +### MsgDepositWithinBatch +`MsgDepositWithinBatch defines` an `sdk.Msg` type that supports submitting +a deposit request to the batch of the liquidity pool. +Deposit is submitted to the batch of the Liquidity pool with the specified +`pool_id`, `deposit_coins` for reserve. +This request is stacked in the batch of the liquidity pool, is not processed +immediately, and is processed in the `endblock` at the same time as other +requests. + +See: +https://github.com/gravity-devs/liquidity/blob/develop/x/liquidity/spec/04_messages.md + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `depositor_address` | [string](#string) | | | +| `pool_id` | [uint64](#uint64) | | id of the target pool | +| `deposit_coins` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | repeated | reserve coin pair of the pool to deposit | + + + + + + + + +### MsgDepositWithinBatchResponse +MsgDepositWithinBatchResponse defines the Msg/DepositWithinBatch response +type. + + + + + + + + +### MsgSwapWithinBatch +`MsgSwapWithinBatch` defines an sdk.Msg type that supports submitting a swap +offer request to the batch of the liquidity pool. Submit swap offer to the +liquidity pool batch with the specified the `pool_id`, `swap_type_id`, +`demand_coin_denom` with the coin and the price you're offering +and `offer_coin_fee` must be half of offer coin amount * current +`params.swap_fee_rate` and ceil for reservation to pay fees. This request is +stacked in the batch of the liquidity pool, is not processed immediately, and +is processed in the `endblock` at the same time as other requests. You must +request the same fields as the pool. Only the default `swap_type_id` 1 is +supported. + +See: https://github.com/gravity-devs/liquidity/tree/develop/doc +https://github.com/gravity-devs/liquidity/blob/develop/x/liquidity/spec/04_messages.md + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `swap_requester_address` | [string](#string) | | address of swap requester | +| `pool_id` | [uint64](#uint64) | | id of swap type, must match the value in the pool. Only `swap_type_id` 1 is supported. | +| `swap_type_id` | [uint32](#uint32) | | id of swap type. Must match the value in the pool. | +| `offer_coin` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | | offer sdk.coin for the swap request, must match the denom in the pool. | +| `demand_coin_denom` | [string](#string) | | denom of demand coin to be exchanged on the swap request, must match the denom in the pool. | +| `offer_coin_fee` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | | half of offer coin amount * params.swap_fee_rate and ceil for reservation to pay fees. | +| `order_price` | [string](#string) | | limit order price for the order, the price is the exchange ratio of X/Y where X is the amount of the first coin and Y is the amount of the second coin when their denoms are sorted alphabetically. | + + + + + + + + +### MsgSwapWithinBatchResponse +MsgSwapWithinBatchResponse defines the Msg/Swap response type. + + + + + + + + +### MsgWithdrawWithinBatch +`MsgWithdrawWithinBatch` defines an `sdk.Msg` type that supports submitting +a withdraw request to the batch of the liquidity pool. +Withdraw is submitted to the batch from the Liquidity pool with the +specified `pool_id`, `pool_coin` of the pool. +This request is stacked in the batch of the liquidity pool, is not processed +immediately, and is processed in the `endblock` at the same time as other +requests. + +See: +https://github.com/gravity-devs/liquidity/blob/develop/x/liquidity/spec/04_messages.md + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `withdrawer_address` | [string](#string) | | | +| `pool_id` | [uint64](#uint64) | | id of the target pool | +| `pool_coin` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | | | + + + + + + + + +### MsgWithdrawWithinBatchResponse +MsgWithdrawWithinBatchResponse defines the Msg/WithdrawWithinBatch response +type. + + + + + + + + + + + + + + +### Msg +Msg defines the liquidity Msg service. + +| Method Name | Request Type | Response Type | Description | HTTP Verb | Endpoint | +| ----------- | ------------ | ------------- | ------------| ------- | -------- | +| `CreatePool` | [MsgCreatePool](#cyber.liquidity.v1beta1.MsgCreatePool) | [MsgCreatePoolResponse](#cyber.liquidity.v1beta1.MsgCreatePoolResponse) | Submit a create liquidity pool message. | | +| `DepositWithinBatch` | [MsgDepositWithinBatch](#cyber.liquidity.v1beta1.MsgDepositWithinBatch) | [MsgDepositWithinBatchResponse](#cyber.liquidity.v1beta1.MsgDepositWithinBatchResponse) | Submit a deposit to the liquidity pool batch. | | +| `WithdrawWithinBatch` | [MsgWithdrawWithinBatch](#cyber.liquidity.v1beta1.MsgWithdrawWithinBatch) | [MsgWithdrawWithinBatchResponse](#cyber.liquidity.v1beta1.MsgWithdrawWithinBatchResponse) | Submit a withdraw from the liquidity pool batch. | | +| `Swap` | [MsgSwapWithinBatch](#cyber.liquidity.v1beta1.MsgSwapWithinBatch) | [MsgSwapWithinBatchResponse](#cyber.liquidity.v1beta1.MsgSwapWithinBatchResponse) | Submit a swap to the liquidity pool batch. | | + + + + + + +

Top

+ +## cyber/liquidity/v1beta1/liquidity.proto + + + + + +### DepositMsgState +DepositMsgState defines the state of deposit message that contains state +information as it is processed in the next batch or batches. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `msg_height` | [int64](#int64) | | height where this message is appended to the batch | +| `msg_index` | [uint64](#uint64) | | index of this deposit message in this liquidity pool | +| `executed` | [bool](#bool) | | true if executed on this batch, false if not executed | +| `succeeded` | [bool](#bool) | | true if executed successfully on this batch, false if failed | +| `to_be_deleted` | [bool](#bool) | | true if ready to be deleted on kvstore, false if not ready to be deleted | +| `msg` | [MsgDepositWithinBatch](#cyber.liquidity.v1beta1.MsgDepositWithinBatch) | | MsgDepositWithinBatch | + + + + + + + + +### Params +Params defines the parameters for the liquidity module. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `pool_types` | [PoolType](#cyber.liquidity.v1beta1.PoolType) | repeated | list of available pool types | +| `min_init_deposit_amount` | [string](#string) | | Minimum number of coins to be deposited to the liquidity pool on pool creation. | +| `init_pool_coin_mint_amount` | [string](#string) | | Initial mint amount of pool coins upon pool creation. | +| `max_reserve_coin_amount` | [string](#string) | | Limit the size of each liquidity pool to minimize risk. In development, set to 0 for no limit. In production, set a limit. | +| `pool_creation_fee` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | repeated | Fee paid to create a Liquidity Pool. Set a fee to prevent spamming. | +| `swap_fee_rate` | [string](#string) | | Swap fee rate for every executed swap. | +| `withdraw_fee_rate` | [string](#string) | | Reserve coin withdrawal with less proportion by withdrawFeeRate. | +| `max_order_amount_ratio` | [string](#string) | | Maximum ratio of reserve coins that can be ordered at a swap order. | +| `unit_batch_height` | [uint32](#uint32) | | The smallest unit batch height for every liquidity pool. | +| `circuit_breaker_enabled` | [bool](#bool) | | Circuit breaker enables or disables transaction messages in liquidity module. | + + + + + + + + +### Pool +Pool defines the liquidity pool that contains pool information. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `id` | [uint64](#uint64) | | id of the pool | +| `type_id` | [uint32](#uint32) | | id of the pool_type | +| `reserve_coin_denoms` | [string](#string) | repeated | denoms of reserve coin pair of the pool | +| `reserve_account_address` | [string](#string) | | reserve account address of the pool | +| `pool_coin_denom` | [string](#string) | | denom of pool coin of the pool | + + + + + + + + +### PoolBatch +PoolBatch defines the batch or batches of a given liquidity pool that +contains indexes of deposit, withdraw, and swap messages. Index param +increments by 1 if the pool id is same. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `pool_id` | [uint64](#uint64) | | id of the pool | +| `index` | [uint64](#uint64) | | index of this batch | +| `begin_height` | [int64](#int64) | | height where this batch is started | +| `deposit_msg_index` | [uint64](#uint64) | | last index of DepositMsgStates | +| `withdraw_msg_index` | [uint64](#uint64) | | last index of WithdrawMsgStates | +| `swap_msg_index` | [uint64](#uint64) | | last index of SwapMsgStates | +| `executed` | [bool](#bool) | | true if executed, false if not executed | + + + + + + + + +### PoolMetadata +Metadata for the state of each pool for invariant checking after genesis +export or import. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `pool_id` | [uint64](#uint64) | | id of the pool | +| `pool_coin_total_supply` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | | pool coin issued at the pool | +| `reserve_coins` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | repeated | reserve coins deposited in the pool | + + + + + + + + +### PoolType +Structure for the pool type to distinguish the characteristics of the reserve +pools. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `id` | [uint32](#uint32) | | This is the id of the pool_type that is used as pool_type_id for pool creation. In this version, only pool-type-id 1 is supported. {"id":1,"name":"ConstantProductLiquidityPool","min_reserve_coin_num":2,"max_reserve_coin_num":2,"description":""} | +| `name` | [string](#string) | | name of the pool type. | +| `min_reserve_coin_num` | [uint32](#uint32) | | minimum number of reserveCoins for LiquidityPoolType, only 2 reserve coins are supported. | +| `max_reserve_coin_num` | [uint32](#uint32) | | maximum number of reserveCoins for LiquidityPoolType, only 2 reserve coins are supported. | +| `description` | [string](#string) | | description of the pool type. | + + + + + + + + +### SwapMsgState +SwapMsgState defines the state of the swap message that contains state +information as the message is processed in the next batch or batches. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `msg_height` | [int64](#int64) | | height where this message is appended to the batch | +| `msg_index` | [uint64](#uint64) | | index of this swap message in this liquidity pool | +| `executed` | [bool](#bool) | | true if executed on this batch, false if not executed | +| `succeeded` | [bool](#bool) | | true if executed successfully on this batch, false if failed | +| `to_be_deleted` | [bool](#bool) | | true if ready to be deleted on kvstore, false if not ready to be deleted | +| `order_expiry_height` | [int64](#int64) | | swap orders are cancelled when current height is equal to or higher than ExpiryHeight | +| `exchanged_offer_coin` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | | offer coin exchanged until now | +| `remaining_offer_coin` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | | offer coin currently remaining to be exchanged | +| `reserved_offer_coin_fee` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | | reserve fee for pays fee in half offer coin | +| `msg` | [MsgSwapWithinBatch](#cyber.liquidity.v1beta1.MsgSwapWithinBatch) | | MsgSwapWithinBatch | + + + + + + + + +### WithdrawMsgState +WithdrawMsgState defines the state of the withdraw message that contains +state information as the message is processed in the next batch or batches. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `msg_height` | [int64](#int64) | | height where this message is appended to the batch | +| `msg_index` | [uint64](#uint64) | | index of this withdraw message in this liquidity pool | +| `executed` | [bool](#bool) | | true if executed on this batch, false if not executed | +| `succeeded` | [bool](#bool) | | true if executed successfully on this batch, false if failed | +| `to_be_deleted` | [bool](#bool) | | true if ready to be deleted on kvstore, false if not ready to be deleted | +| `msg` | [MsgWithdrawWithinBatch](#cyber.liquidity.v1beta1.MsgWithdrawWithinBatch) | | MsgWithdrawWithinBatch | + + + + + + + + + + + + + + + + +

Top

+ +## cyber/liquidity/v1beta1/genesis.proto + + + + + +### GenesisState +GenesisState defines the liquidity module's genesis state. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `params` | [Params](#cyber.liquidity.v1beta1.Params) | | params defines all the parameters for the liquidity module. | +| `pool_records` | [PoolRecord](#cyber.liquidity.v1beta1.PoolRecord) | repeated | | + + + + + + + + +### PoolRecord +records the state of each pool after genesis export or import, used to check +variables + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `pool` | [Pool](#cyber.liquidity.v1beta1.Pool) | | | +| `pool_metadata` | [PoolMetadata](#cyber.liquidity.v1beta1.PoolMetadata) | | | +| `pool_batch` | [PoolBatch](#cyber.liquidity.v1beta1.PoolBatch) | | | +| `deposit_msg_states` | [DepositMsgState](#cyber.liquidity.v1beta1.DepositMsgState) | repeated | | +| `withdraw_msg_states` | [WithdrawMsgState](#cyber.liquidity.v1beta1.WithdrawMsgState) | repeated | | +| `swap_msg_states` | [SwapMsgState](#cyber.liquidity.v1beta1.SwapMsgState) | repeated | | + + + + + + + + + + + + + + + + +

Top

+ +## cyber/liquidity/v1beta1/query.proto + + + + + +### QueryLiquidityPoolBatchRequest +the request type for the QueryLiquidityPoolBatch RPC method. requestable +including specified pool_id. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `pool_id` | [uint64](#uint64) | | id of the target pool for query | + + + + + + + + +### QueryLiquidityPoolBatchResponse +the response type for the QueryLiquidityPoolBatchResponse RPC method. Returns +the liquidity pool batch that corresponds to the requested pool_id. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `batch` | [PoolBatch](#cyber.liquidity.v1beta1.PoolBatch) | | | + + + + + + + + +### QueryLiquidityPoolByPoolCoinDenomRequest +the request type for the QueryLiquidityByPoolCoinDenomPool RPC method. +Requestable specified pool_coin_denom. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `pool_coin_denom` | [string](#string) | | | + + + + + + + + +### QueryLiquidityPoolByReserveAccRequest +the request type for the QueryLiquidityByReserveAcc RPC method. Requestable +specified reserve_acc. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `reserve_acc` | [string](#string) | | | + + + + + + + + +### QueryLiquidityPoolRequest +the request type for the QueryLiquidityPool RPC method. requestable specified +pool_id. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `pool_id` | [uint64](#uint64) | | | + + + + + + + + +### QueryLiquidityPoolResponse +the response type for the QueryLiquidityPoolResponse RPC method. Returns the +liquidity pool that corresponds to the requested pool_id. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `pool` | [Pool](#cyber.liquidity.v1beta1.Pool) | | | + + + + + + + + +### QueryLiquidityPoolsRequest +the request type for the QueryLiquidityPools RPC method. Requestable +including pagination offset, limit, key. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `pagination` | [cosmos.base.query.v1beta1.PageRequest](#cosmos.base.query.v1beta1.PageRequest) | | pagination defines an optional pagination for the request. | + + + + + + + + +### QueryLiquidityPoolsResponse +the response type for the QueryLiquidityPoolsResponse RPC method. This +includes a list of all existing liquidity pools and paging results that +contain next_key and total count. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `pools` | [Pool](#cyber.liquidity.v1beta1.Pool) | repeated | | +| `pagination` | [cosmos.base.query.v1beta1.PageResponse](#cosmos.base.query.v1beta1.PageResponse) | | pagination defines the pagination in the response. not working on this version. | + + + + + + + + +### QueryParamsRequest +QueryParamsRequest is request type for the QueryParams RPC method. + + + + + + + + +### QueryParamsResponse +the response type for the QueryParamsResponse RPC method. This includes +current parameter of the liquidity module. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `params` | [Params](#cyber.liquidity.v1beta1.Params) | | params holds all the parameters of this module. | + + + + + + + + +### QueryPoolBatchDepositMsgRequest +the request type for the QueryPoolBatchDeposit RPC method. requestable +including specified pool_id and msg_index. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `pool_id` | [uint64](#uint64) | | id of the target pool for query | +| `msg_index` | [uint64](#uint64) | | target msg_index of the pool | + + + + + + + + +### QueryPoolBatchDepositMsgResponse +the response type for the QueryPoolBatchDepositMsg RPC method. This includes +a batch swap message of the batch. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `deposit` | [DepositMsgState](#cyber.liquidity.v1beta1.DepositMsgState) | | | + + + + + + + + +### QueryPoolBatchDepositMsgsRequest +the request type for the QueryPoolBatchDeposit RPC method. Requestable +including specified pool_id and pagination offset, limit, key. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `pool_id` | [uint64](#uint64) | | id of the target pool for query | +| `pagination` | [cosmos.base.query.v1beta1.PageRequest](#cosmos.base.query.v1beta1.PageRequest) | | pagination defines an optional pagination for the request. | + + + + + + + + +### QueryPoolBatchDepositMsgsResponse +the response type for the QueryPoolBatchDeposit RPC method. This includes a +list of all currently existing deposit messages of the batch and paging +results that contain next_key and total count. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `deposits` | [DepositMsgState](#cyber.liquidity.v1beta1.DepositMsgState) | repeated | | +| `pagination` | [cosmos.base.query.v1beta1.PageResponse](#cosmos.base.query.v1beta1.PageResponse) | | pagination defines the pagination in the response. not working on this version. | + + + + + + + + +### QueryPoolBatchSwapMsgRequest +the request type for the QueryPoolBatchSwap RPC method. Requestable including +specified pool_id and msg_index. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `pool_id` | [uint64](#uint64) | | id of the target pool for query | +| `msg_index` | [uint64](#uint64) | | target msg_index of the pool | + + + + + + + + +### QueryPoolBatchSwapMsgResponse +the response type for the QueryPoolBatchSwapMsg RPC method. This includes a +batch swap message of the batch. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `swap` | [SwapMsgState](#cyber.liquidity.v1beta1.SwapMsgState) | | | + + + + + + + + +### QueryPoolBatchSwapMsgsRequest +the request type for the QueryPoolBatchSwapMsgs RPC method. Requestable +including specified pool_id and pagination offset, limit, key. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `pool_id` | [uint64](#uint64) | | id of the target pool for query | +| `pagination` | [cosmos.base.query.v1beta1.PageRequest](#cosmos.base.query.v1beta1.PageRequest) | | pagination defines an optional pagination for the request. | + + + + + + + + +### QueryPoolBatchSwapMsgsResponse +the response type for the QueryPoolBatchSwapMsgs RPC method. This includes +list of all currently existing swap messages of the batch and paging results +that contain next_key and total count. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `swaps` | [SwapMsgState](#cyber.liquidity.v1beta1.SwapMsgState) | repeated | | +| `pagination` | [cosmos.base.query.v1beta1.PageResponse](#cosmos.base.query.v1beta1.PageResponse) | | pagination defines the pagination in the response. not working on this version. | + + + + + + + + +### QueryPoolBatchWithdrawMsgRequest +the request type for the QueryPoolBatchWithdraw RPC method. requestable +including specified pool_id and msg_index. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `pool_id` | [uint64](#uint64) | | id of the target pool for query | +| `msg_index` | [uint64](#uint64) | | target msg_index of the pool | + + + + + + + + +### QueryPoolBatchWithdrawMsgResponse +the response type for the QueryPoolBatchWithdrawMsg RPC method. This includes +a batch swap message of the batch. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `withdraw` | [WithdrawMsgState](#cyber.liquidity.v1beta1.WithdrawMsgState) | | | + + + + + + + + +### QueryPoolBatchWithdrawMsgsRequest +the request type for the QueryPoolBatchWithdraw RPC method. Requestable +including specified pool_id and pagination offset, limit, key. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `pool_id` | [uint64](#uint64) | | id of the target pool for query | +| `pagination` | [cosmos.base.query.v1beta1.PageRequest](#cosmos.base.query.v1beta1.PageRequest) | | pagination defines an optional pagination for the request. | + + + + + + + + +### QueryPoolBatchWithdrawMsgsResponse +the response type for the QueryPoolBatchWithdraw RPC method. This includes a +list of all currently existing withdraw messages of the batch and paging +results that contain next_key and total count. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| `withdraws` | [WithdrawMsgState](#cyber.liquidity.v1beta1.WithdrawMsgState) | repeated | | +| `pagination` | [cosmos.base.query.v1beta1.PageResponse](#cosmos.base.query.v1beta1.PageResponse) | | pagination defines the pagination in the response. Not supported on this version. | + + + + + + + + + + + + + + +### Query +Query defines the gRPC query service for the liquidity module. + +| Method Name | Request Type | Response Type | Description | HTTP Verb | Endpoint | +| ----------- | ------------ | ------------- | ------------| ------- | -------- | +| `LiquidityPools` | [QueryLiquidityPoolsRequest](#cyber.liquidity.v1beta1.QueryLiquidityPoolsRequest) | [QueryLiquidityPoolsResponse](#cyber.liquidity.v1beta1.QueryLiquidityPoolsResponse) | Get existing liquidity pools. | GET|/cosmos/liquidity/v1beta1/pools| +| `LiquidityPool` | [QueryLiquidityPoolRequest](#cyber.liquidity.v1beta1.QueryLiquidityPoolRequest) | [QueryLiquidityPoolResponse](#cyber.liquidity.v1beta1.QueryLiquidityPoolResponse) | Get specific liquidity pool. | GET|/cosmos/liquidity/v1beta1/pools/{pool_id}| +| `LiquidityPoolByPoolCoinDenom` | [QueryLiquidityPoolByPoolCoinDenomRequest](#cyber.liquidity.v1beta1.QueryLiquidityPoolByPoolCoinDenomRequest) | [QueryLiquidityPoolResponse](#cyber.liquidity.v1beta1.QueryLiquidityPoolResponse) | Get specific liquidity pool corresponding to the pool_coin_denom. | GET|/cosmos/liquidity/v1beta1/pools/pool_coin_denom/{pool_coin_denom}| +| `LiquidityPoolByReserveAcc` | [QueryLiquidityPoolByReserveAccRequest](#cyber.liquidity.v1beta1.QueryLiquidityPoolByReserveAccRequest) | [QueryLiquidityPoolResponse](#cyber.liquidity.v1beta1.QueryLiquidityPoolResponse) | Get specific liquidity pool corresponding to the reserve account. | GET|/cosmos/liquidity/v1beta1/pools/reserve_acc/{reserve_acc}| +| `LiquidityPoolBatch` | [QueryLiquidityPoolBatchRequest](#cyber.liquidity.v1beta1.QueryLiquidityPoolBatchRequest) | [QueryLiquidityPoolBatchResponse](#cyber.liquidity.v1beta1.QueryLiquidityPoolBatchResponse) | Get the pool's current batch. | GET|/cosmos/liquidity/v1beta1/pools/{pool_id}/batch| +| `PoolBatchSwapMsgs` | [QueryPoolBatchSwapMsgsRequest](#cyber.liquidity.v1beta1.QueryPoolBatchSwapMsgsRequest) | [QueryPoolBatchSwapMsgsResponse](#cyber.liquidity.v1beta1.QueryPoolBatchSwapMsgsResponse) | Get all swap messages in the pool's current batch. | GET|/cosmos/liquidity/v1beta1/pools/{pool_id}/batch/swaps| +| `PoolBatchSwapMsg` | [QueryPoolBatchSwapMsgRequest](#cyber.liquidity.v1beta1.QueryPoolBatchSwapMsgRequest) | [QueryPoolBatchSwapMsgResponse](#cyber.liquidity.v1beta1.QueryPoolBatchSwapMsgResponse) | Get a specific swap message in the pool's current batch. | GET|/cosmos/liquidity/v1beta1/pools/{pool_id}/batch/swaps/{msg_index}| +| `PoolBatchDepositMsgs` | [QueryPoolBatchDepositMsgsRequest](#cyber.liquidity.v1beta1.QueryPoolBatchDepositMsgsRequest) | [QueryPoolBatchDepositMsgsResponse](#cyber.liquidity.v1beta1.QueryPoolBatchDepositMsgsResponse) | Get all deposit messages in the pool's current batch. | GET|/cosmos/liquidity/v1beta1/pools/{pool_id}/batch/deposits| +| `PoolBatchDepositMsg` | [QueryPoolBatchDepositMsgRequest](#cyber.liquidity.v1beta1.QueryPoolBatchDepositMsgRequest) | [QueryPoolBatchDepositMsgResponse](#cyber.liquidity.v1beta1.QueryPoolBatchDepositMsgResponse) | Get a specific deposit message in the pool's current batch. | GET|/cosmos/liquidity/v1beta1/pools/{pool_id}/batch/deposits/{msg_index}| +| `PoolBatchWithdrawMsgs` | [QueryPoolBatchWithdrawMsgsRequest](#cyber.liquidity.v1beta1.QueryPoolBatchWithdrawMsgsRequest) | [QueryPoolBatchWithdrawMsgsResponse](#cyber.liquidity.v1beta1.QueryPoolBatchWithdrawMsgsResponse) | Get all withdraw messages in the pool's current batch. | GET|/cosmos/liquidity/v1beta1/pools/{pool_id}/batch/withdraws| +| `PoolBatchWithdrawMsg` | [QueryPoolBatchWithdrawMsgRequest](#cyber.liquidity.v1beta1.QueryPoolBatchWithdrawMsgRequest) | [QueryPoolBatchWithdrawMsgResponse](#cyber.liquidity.v1beta1.QueryPoolBatchWithdrawMsgResponse) | Get a specific withdraw message in the pool's current batch. | GET|/cosmos/liquidity/v1beta1/pools/{pool_id}/batch/withdraws/{msg_index}| +| `Params` | [QueryParamsRequest](#cyber.liquidity.v1beta1.QueryParamsRequest) | [QueryParamsResponse](#cyber.liquidity.v1beta1.QueryParamsResponse) | Get all parameters of the liquidity module. | GET|/cosmos/liquidity/v1beta1/params| + + + + +

Top

diff --git a/go.mod b/go.mod index 89f00329..15358911 100644 --- a/go.mod +++ b/go.mod @@ -26,12 +26,13 @@ require ( github.com/rakyll/statik v0.1.7 // indirect github.com/spf13/cast v1.6.0 github.com/spf13/cobra v1.8.0 + github.com/spf13/pflag v1.0.5 github.com/spf13/viper v1.18.2 github.com/stretchr/testify v1.9.0 github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d - //github.com/gravity-devs/liquidity v1.5.3 google.golang.org/genproto/googleapis/api v0.0.0-20240123012728-ef4313101c80 google.golang.org/grpc v1.62.1 + gopkg.in/yaml.v2 v2.4.0 ) require ( @@ -165,7 +166,6 @@ require ( github.com/sourcegraph/conc v0.3.0 // indirect github.com/spaolacci/murmur3 v1.1.0 // indirect github.com/spf13/afero v1.11.0 // indirect - github.com/spf13/pflag v1.0.5 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/tendermint/go-amino v0.16.0 // indirect github.com/tidwall/btree v1.6.0 // indirect @@ -196,7 +196,6 @@ require ( google.golang.org/genproto/googleapis/rpc v0.0.0-20240123012728-ef4313101c80 // indirect google.golang.org/protobuf v1.33.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect nhooyr.io/websocket v1.8.6 // indirect pgregory.net/rapid v1.1.0 // indirect diff --git a/plugins/liquidity.go b/plugins/liquidity.go index 560e6c48..fad66d24 100644 --- a/plugins/liquidity.go +++ b/plugins/liquidity.go @@ -1,195 +1,195 @@ package plugins -// -//import ( -// "encoding/json" -// -// wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" -// wasmvmtypes "github.com/CosmWasm/wasmvm/types" -// liquiditytypes "github.com/gravity-devs/liquidity/x/liquidity/types" -// -// "github.com/CosmWasm/wasmd/x/wasm" -// sdk "github.com/cosmos/cosmos-sdk/types" -// sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -// -// "github.com/gravity-devs/liquidity/x/liquidity/keeper" -//) -// -//var ( -// _ WasmQuerierInterface = WasmQuerier{} -// _ WasmMsgParserInterface = WasmMsgParser{} -//) -// -////-------------------------------------------------- -// -//type WasmMsgParser struct{} -// -//func NewLiquidityWasmMsgParser() WasmMsgParser { -// return WasmMsgParser{} -//} -// -//func (WasmMsgParser) Parse(_ sdk.AccAddress, _ wasmvmtypes.CosmosMsg) ([]sdk.Msg, error) { -// return nil, nil -//} -// -//type CosmosMsg struct { -// CreatePool *liquiditytypes.MsgCreatePool `json:"create_pool,omitempty"` -// DepositWithinBatch *liquiditytypes.MsgDepositWithinBatch `json:"deposit_within_batch,omitempty"` -// WithdrawWithinBatch *liquiditytypes.MsgWithdrawWithinBatch `json:"withdraw_within_batch,omitempty"` -// SwapWithinBatch *liquiditytypes.MsgSwapWithinBatch `json:"swap_within_batch,omitempty"` -//} -// -//func (WasmMsgParser) ParseCustom(contractAddr sdk.AccAddress, data json.RawMessage) ([]sdk.Msg, error) { -// var sdkMsg CosmosMsg -// err := json.Unmarshal(data, &sdkMsg) -// if err != nil { -// return nil, sdkerrors.Wrap(err, "failed to parse link custom msg") -// } -// -// switch { -// case sdkMsg.SwapWithinBatch != nil: -// return []sdk.Msg{sdkMsg.SwapWithinBatch}, sdkMsg.SwapWithinBatch.ValidateBasic() -// case sdkMsg.DepositWithinBatch != nil: -// return []sdk.Msg{sdkMsg.DepositWithinBatch}, sdkMsg.DepositWithinBatch.ValidateBasic() -// case sdkMsg.WithdrawWithinBatch != nil: -// return []sdk.Msg{sdkMsg.WithdrawWithinBatch}, sdkMsg.WithdrawWithinBatch.ValidateBasic() -// case sdkMsg.CreatePool != nil: -// return []sdk.Msg{sdkMsg.CreatePool}, sdkMsg.CreatePool.ValidateBasic() -// default: -// return nil, sdkerrors.Wrap(wasm.ErrInvalidMsg, "Unknown variant of Liquidity") -// } -//} -// -////-------------------------------------------------- -// -//type WasmQuerier struct { -// keeper.Keeper -//} -// -//func NewLiquidityWasmQuerier(keeper keeper.Keeper) WasmQuerier { -// return WasmQuerier{keeper} -//} -// -//func (WasmQuerier) Query(_ sdk.Context, _ wasmvmtypes.QueryRequest) ([]byte, error) { return nil, nil } -// -//type CosmosQuery struct { -// PoolParams *QueryPoolParams `json:"pool_params,omitempty"` -// PoolLiquidity *QueryPoolParams `json:"pool_liquidity,omitempty"` -// PoolSupply *QueryPoolParams `json:"pool_supply,omitempty"` -// PoolPrice *QueryPoolParams `json:"pool_price,omitempty"` -// PoolAddress *QueryPoolParams `json:"pool_address,omitempty"` -//} -// -//type QueryPoolParams struct { -// PoolID uint64 `json:"pool_id"` -//} -// -//type PoolParamsResponse struct { -// TypeID uint32 `json:"type_id"` -// ReserveCoinDenoms []string `json:"reserve_coin_denoms"` -// ReserveAccountAddress string `json:"reserve_account_address"` -// PoolCoinDenom string `json:"pool_coin_denom"` -//} -// -//type PoolLiquidityResponse struct { -// Liquidity wasmvmtypes.Coins `json:"liquidity"` -//} -// -//type PoolSupplyResponse struct { -// Supply wasmvmtypes.Coin `json:"supply"` -//} -// -//type PoolPriceResponse struct { -// Price string `json:"price"` -//} -// -//type PoolAddressResponse struct { -// Address string `json:"address"` -//} -// -//func (querier WasmQuerier) QueryCustom(ctx sdk.Context, data json.RawMessage) ([]byte, error) { -// var query CosmosQuery -// err := json.Unmarshal(data, &query) -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) -// } -// -// var bz []byte -// -// switch { -// case query.PoolParams != nil: -// pool, found := querier.Keeper.GetPool(ctx, query.PoolParams.PoolID) -// if !found { -// return nil, sdkerrors.ErrInvalidRequest -// } -// -// bz, err = json.Marshal( -// PoolParamsResponse{ -// TypeID: pool.TypeId, -// ReserveCoinDenoms: pool.ReserveCoinDenoms, -// ReserveAccountAddress: pool.ReserveAccountAddress, -// PoolCoinDenom: pool.PoolCoinDenom, -// }, -// ) -// case query.PoolLiquidity != nil: -// pool, found := querier.Keeper.GetPool(ctx, query.PoolLiquidity.PoolID) -// if !found { -// return nil, sdkerrors.ErrInvalidRequest -// } -// -// reserveCoins := querier.Keeper.GetReserveCoins(ctx, pool) -// -// bz, err = json.Marshal( -// PoolLiquidityResponse{ -// Liquidity: wasmkeeper.ConvertSdkCoinsToWasmCoins(reserveCoins), -// }, -// ) -// case query.PoolSupply != nil: -// pool, found := querier.Keeper.GetPool(ctx, query.PoolSupply.PoolID) -// if !found { -// return nil, sdkerrors.ErrInvalidRequest -// } -// -// poolSupply := querier.Keeper.GetPoolCoinTotal(ctx, pool) -// -// bz, err = json.Marshal( -// PoolSupplyResponse{ -// Supply: wasmkeeper.ConvertSdkCoinToWasmCoin(poolSupply), -// }, -// ) -// case query.PoolPrice != nil: -// pool, found := querier.Keeper.GetPool(ctx, query.PoolPrice.PoolID) -// if !found { -// return nil, sdkerrors.ErrInvalidRequest -// } -// -// reserveCoins := querier.Keeper.GetReserveCoins(ctx, pool) -// X := reserveCoins[0].Amount.ToDec() -// Y := reserveCoins[1].Amount.ToDec() -// -// bz, err = json.Marshal( -// PoolPriceResponse{ -// Price: X.Quo(Y).String(), -// }, -// ) -// case query.PoolAddress != nil: -// pool, found := querier.Keeper.GetPool(ctx, query.PoolAddress.PoolID) -// if !found { -// return nil, sdkerrors.ErrInvalidRequest -// } -// -// bz, err = json.Marshal( -// PoolAddressResponse{ -// Address: pool.ReserveAccountAddress, -// }, -// ) -// default: -// return nil, wasmvmtypes.UnsupportedRequest{Kind: "unknown Liquidity variant"} -// } -// -// if err != nil { -// return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) -// } -// -// return bz, nil -//} +import ( + "encoding/json" + + wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" + wasmvmtypes "github.com/CosmWasm/wasmvm/types" + + liquiditytypes "github.com/cybercongress/go-cyber/v4/x/liquidity/types" + + "github.com/CosmWasm/wasmd/x/wasm" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/cybercongress/go-cyber/v4/x/liquidity/keeper" +) + +var ( + _ WasmQuerierInterface = WasmQuerier{} + _ WasmMsgParserInterface = WasmMsgParser{} +) + +//-------------------------------------------------- + +type WasmMsgParser struct{} + +func NewLiquidityWasmMsgParser() WasmMsgParser { + return WasmMsgParser{} +} + +func (WasmMsgParser) Parse(_ sdk.AccAddress, _ wasmvmtypes.CosmosMsg) ([]sdk.Msg, error) { + return nil, nil +} + +type CosmosMsg struct { + CreatePool *liquiditytypes.MsgCreatePool `json:"create_pool,omitempty"` + DepositWithinBatch *liquiditytypes.MsgDepositWithinBatch `json:"deposit_within_batch,omitempty"` + WithdrawWithinBatch *liquiditytypes.MsgWithdrawWithinBatch `json:"withdraw_within_batch,omitempty"` + SwapWithinBatch *liquiditytypes.MsgSwapWithinBatch `json:"swap_within_batch,omitempty"` +} + +func (WasmMsgParser) ParseCustom(contractAddr sdk.AccAddress, data json.RawMessage) ([]sdk.Msg, error) { + var sdkMsg CosmosMsg + err := json.Unmarshal(data, &sdkMsg) + if err != nil { + return nil, sdkerrors.Wrap(err, "failed to parse link custom msg") + } + + switch { + case sdkMsg.SwapWithinBatch != nil: + return []sdk.Msg{sdkMsg.SwapWithinBatch}, sdkMsg.SwapWithinBatch.ValidateBasic() + case sdkMsg.DepositWithinBatch != nil: + return []sdk.Msg{sdkMsg.DepositWithinBatch}, sdkMsg.DepositWithinBatch.ValidateBasic() + case sdkMsg.WithdrawWithinBatch != nil: + return []sdk.Msg{sdkMsg.WithdrawWithinBatch}, sdkMsg.WithdrawWithinBatch.ValidateBasic() + case sdkMsg.CreatePool != nil: + return []sdk.Msg{sdkMsg.CreatePool}, sdkMsg.CreatePool.ValidateBasic() + default: + return nil, sdkerrors.Wrap(wasm.ErrInvalidMsg, "Unknown variant of Liquidity") + } +} + +//-------------------------------------------------- + +type WasmQuerier struct { + keeper.Keeper +} + +func NewLiquidityWasmQuerier(keeper keeper.Keeper) WasmQuerier { + return WasmQuerier{keeper} +} + +func (WasmQuerier) Query(_ sdk.Context, _ wasmvmtypes.QueryRequest) ([]byte, error) { return nil, nil } + +type CosmosQuery struct { + PoolParams *QueryPoolParams `json:"pool_params,omitempty"` + PoolLiquidity *QueryPoolParams `json:"pool_liquidity,omitempty"` + PoolSupply *QueryPoolParams `json:"pool_supply,omitempty"` + PoolPrice *QueryPoolParams `json:"pool_price,omitempty"` + PoolAddress *QueryPoolParams `json:"pool_address,omitempty"` +} + +type QueryPoolParams struct { + PoolID uint64 `json:"pool_id"` +} + +type PoolParamsResponse struct { + TypeID uint32 `json:"type_id"` + ReserveCoinDenoms []string `json:"reserve_coin_denoms"` + ReserveAccountAddress string `json:"reserve_account_address"` + PoolCoinDenom string `json:"pool_coin_denom"` +} + +type PoolLiquidityResponse struct { + Liquidity wasmvmtypes.Coins `json:"liquidity"` +} + +type PoolSupplyResponse struct { + Supply wasmvmtypes.Coin `json:"supply"` +} + +type PoolPriceResponse struct { + Price string `json:"price"` +} + +type PoolAddressResponse struct { + Address string `json:"address"` +} + +func (querier WasmQuerier) QueryCustom(ctx sdk.Context, data json.RawMessage) ([]byte, error) { + var query CosmosQuery + err := json.Unmarshal(data, &query) + if err != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) + } + + var bz []byte + + switch { + case query.PoolParams != nil: + pool, found := querier.Keeper.GetPool(ctx, query.PoolParams.PoolID) + if !found { + return nil, sdkerrors.ErrInvalidRequest + } + + bz, err = json.Marshal( + PoolParamsResponse{ + TypeID: pool.TypeId, + ReserveCoinDenoms: pool.ReserveCoinDenoms, + ReserveAccountAddress: pool.ReserveAccountAddress, + PoolCoinDenom: pool.PoolCoinDenom, + }, + ) + case query.PoolLiquidity != nil: + pool, found := querier.Keeper.GetPool(ctx, query.PoolLiquidity.PoolID) + if !found { + return nil, sdkerrors.ErrInvalidRequest + } + + reserveCoins := querier.Keeper.GetReserveCoins(ctx, pool) + + bz, err = json.Marshal( + PoolLiquidityResponse{ + Liquidity: wasmkeeper.ConvertSdkCoinsToWasmCoins(reserveCoins), + }, + ) + case query.PoolSupply != nil: + pool, found := querier.Keeper.GetPool(ctx, query.PoolSupply.PoolID) + if !found { + return nil, sdkerrors.ErrInvalidRequest + } + + poolSupply := querier.Keeper.GetPoolCoinTotal(ctx, pool) + + bz, err = json.Marshal( + PoolSupplyResponse{ + Supply: wasmkeeper.ConvertSdkCoinToWasmCoin(poolSupply), + }, + ) + case query.PoolPrice != nil: + pool, found := querier.Keeper.GetPool(ctx, query.PoolPrice.PoolID) + if !found { + return nil, sdkerrors.ErrInvalidRequest + } + + reserveCoins := querier.Keeper.GetReserveCoins(ctx, pool) + X := reserveCoins[0].Amount.ToLegacyDec() + Y := reserveCoins[1].Amount.ToLegacyDec() + + bz, err = json.Marshal( + PoolPriceResponse{ + Price: X.Quo(Y).String(), + }, + ) + case query.PoolAddress != nil: + pool, found := querier.Keeper.GetPool(ctx, query.PoolAddress.PoolID) + if !found { + return nil, sdkerrors.ErrInvalidRequest + } + + bz, err = json.Marshal( + PoolAddressResponse{ + Address: pool.ReserveAccountAddress, + }, + ) + default: + return nil, wasmvmtypes.UnsupportedRequest{Kind: "unknown Liquidity variant"} + } + + if err != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) + } + + return bz, nil +} diff --git a/plugins/msg_binding.go b/plugins/msg_binding.go index 79384ba5..c8b998bc 100644 --- a/plugins/msg_binding.go +++ b/plugins/msg_binding.go @@ -3,7 +3,7 @@ package plugins import ( "encoding/json" - // liquiditytypes "github.com/gravity-devs/liquidity/x/liquidity/types" + liquiditytypes "github.com/cybercongress/go-cyber/v4/x/liquidity/types" "github.com/CosmWasm/wasmd/x/wasm" wasmvmtypes "github.com/CosmWasm/wasmvm/types" @@ -42,7 +42,7 @@ const ( WasmMsgParserRouteDmn = dmntypes.ModuleName WasmMsgParserRouteGrid = gridtypes.ModuleName WasmMsgParserRouteResources = resourcestypes.ModuleName - // WasmMsgParserLiquidity = liquiditytypes.ModuleName + WasmMsgParserLiquidity = liquiditytypes.ModuleName ) func (p MsgParser) ParseCustom(contractAddr sdk.AccAddress, data json.RawMessage) ([]sdk.Msg, error) { diff --git a/plugins/query_binding.go b/plugins/query_binding.go index 3082b9f0..9e17dee1 100644 --- a/plugins/query_binding.go +++ b/plugins/query_binding.go @@ -5,7 +5,7 @@ import ( "github.com/CosmWasm/wasmd/x/wasm" - // liquiditytypes "github.com/gravity-devs/liquidity/x/liquidity/types" + liquiditytypes "github.com/cybercongress/go-cyber/v4/x/liquidity/types" wasmvmtypes "github.com/CosmWasm/wasmvm/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -44,7 +44,7 @@ const ( WasmQueryRouteDmn = dmntypes.ModuleName WasmQueryRouteGrid = gridtypes.ModuleName WasmQueryRouteBandwidth = bandwidthtypes.ModuleName - // WasmQueryRouteLiquidity = liquiditytypes.ModuleName + WasmQueryRouteLiquidity = liquiditytypes.ModuleName ) func (q Querier) QueryCustom(ctx sdk.Context, data json.RawMessage) ([]byte, error) { diff --git a/plugins/wasm.go b/plugins/wasm.go index da243efb..1127df76 100644 --- a/plugins/wasm.go +++ b/plugins/wasm.go @@ -4,7 +4,7 @@ import ( "github.com/CosmWasm/wasmd/x/wasm" wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" - // liquiditykeeper "github.com/gravity-devs/liquidity/x/liquidity/keeper" + liquiditykeeper "github.com/cybercongress/go-cyber/v4/x/liquidity/keeper" bandwidthkeeper "github.com/cybercongress/go-cyber/v4/x/bandwidth/keeper" bandwidthwasm "github.com/cybercongress/go-cyber/v4/x/bandwidth/wasm" @@ -25,7 +25,7 @@ func RegisterCustomPlugins( dmn *dmnkeeper.Keeper, grid gridkeeper.Keeper, bandwidth *bandwidthkeeper.BandwidthMeter, - // liquidity liquiditykeeper.Keeper, + liquidity liquiditykeeper.Keeper, ) []wasmkeeper.Option { // Initialize Cyber's query integrations querier := NewQuerier() @@ -35,7 +35,7 @@ func RegisterCustomPlugins( WasmQueryRouteDmn: dmnwasm.NewWasmQuerier(*dmn), WasmQueryRouteGrid: gridwasm.NewWasmQuerier(grid), WasmQueryRouteBandwidth: bandwidthwasm.NewWasmQuerier(bandwidth), - // WasmQueryRouteLiquidity: NewLiquidityWasmQuerier(liquidity), + WasmQueryRouteLiquidity: NewLiquidityWasmQuerier(liquidity), } querier.Queriers = queries @@ -50,7 +50,7 @@ func RegisterCustomPlugins( WasmMsgParserRouteDmn: dmnwasm.NewWasmMsgParser(), WasmMsgParserRouteGrid: gridwasm.NewWasmMsgParser(), WasmMsgParserRouteResources: resourceswasm.NewWasmMsgParser(), - // WasmMsgParserLiquidity: NewLiquidityWasmMsgParser(), + WasmMsgParserLiquidity: NewLiquidityWasmMsgParser(), } parser.Parsers = parsers diff --git a/proto/buf.yaml b/proto/buf.yaml index 73e08766..376591de 100644 --- a/proto/buf.yaml +++ b/proto/buf.yaml @@ -23,6 +23,9 @@ lint: - COMMENT_FIELD - SERVICE_SUFFIX - PACKAGE_VERSION_SUFFIX + - COMMENTS + - RPC_RESPONSE_STANDARD_NAME + - RPC_REQUEST_RESPONSE_UNIQUE - RPC_REQUEST_STANDARD_NAME - PACKAGE_DIRECTORY_MATCH - RPC_REQUEST_RESPONSE_UNIQUE diff --git a/proto/cyber/liquidity/v1beta1/genesis.proto b/proto/cyber/liquidity/v1beta1/genesis.proto new file mode 100644 index 00000000..e29deb72 --- /dev/null +++ b/proto/cyber/liquidity/v1beta1/genesis.proto @@ -0,0 +1,45 @@ +syntax = "proto3"; +package cyber.liquidity.v1beta1; + +import "cyber/liquidity/v1beta1/liquidity.proto"; +import "gogoproto/gogo.proto"; + +option go_package = "github.com/cybercongress/go-cyber/x/liquidity/types"; + +// records the state of each pool after genesis export or import, used to check +// variables +message PoolRecord { + Pool pool = 1 + [ (gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"pool\"" ]; + PoolMetadata pool_metadata = 2 [ + (gogoproto.nullable) = false, + (gogoproto.moretags) = "yaml:\"pool_metadata\"" + ]; + PoolBatch pool_batch = 3 [ + (gogoproto.nullable) = false, + (gogoproto.moretags) = "yaml:\"pool_batch\"" + ]; + repeated DepositMsgState deposit_msg_states = 4 [ + (gogoproto.nullable) = false, + (gogoproto.moretags) = "yaml:\"deposit_msg_states\"" + ]; + repeated WithdrawMsgState withdraw_msg_states = 5 [ + (gogoproto.nullable) = false, + (gogoproto.moretags) = "yaml:\"withdraw_msg_states\"" + ]; + repeated SwapMsgState swap_msg_states = 6 [ + (gogoproto.nullable) = false, + (gogoproto.moretags) = "yaml:\"swap_msg_states\"" + ]; +} + +// GenesisState defines the liquidity module's genesis state. +message GenesisState { + option (gogoproto.equal) = false; + option (gogoproto.goproto_getters) = false; + + // params defines all the parameters for the liquidity module. + Params params = 1 [ (gogoproto.nullable) = false ]; + repeated PoolRecord pool_records = 2 + [ (gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"pools\"" ]; +} diff --git a/proto/cyber/liquidity/v1beta1/liquidity.proto b/proto/cyber/liquidity/v1beta1/liquidity.proto new file mode 100644 index 00000000..02bb6b76 --- /dev/null +++ b/proto/cyber/liquidity/v1beta1/liquidity.proto @@ -0,0 +1,300 @@ +syntax = "proto3"; +package cyber.liquidity.v1beta1; + +import "cyber/liquidity/v1beta1/tx.proto"; +import "gogoproto/gogo.proto"; +import "cosmos/base/v1beta1/coin.proto"; +// import "google/api/annotations.proto"; +import "cosmos_proto/cosmos.proto"; + +option go_package = "github.com/cybercongress/go-cyber/x/liquidity/types"; +option (gogoproto.goproto_getters_all) = false; + +// Structure for the pool type to distinguish the characteristics of the reserve +// pools. +message PoolType { + option (gogoproto.equal) = true; + + // This is the id of the pool_type that is used as pool_type_id for pool + // creation. In this version, only pool-type-id 1 is supported. + // {"id":1,"name":"ConstantProductLiquidityPool","min_reserve_coin_num":2,"max_reserve_coin_num":2,"description":""} + uint32 id = 1 [ (gogoproto.moretags) = "yaml:\"id\"" ]; + + // name of the pool type. + string name = 2 [ (gogoproto.moretags) = "yaml:\"name\"" ]; + + // minimum number of reserveCoins for LiquidityPoolType, only 2 reserve coins + // are supported. + uint32 min_reserve_coin_num = 3 + [ (gogoproto.moretags) = "yaml:\"min_reserve_coin_num\"" ]; + + // maximum number of reserveCoins for LiquidityPoolType, only 2 reserve coins + // are supported. + uint32 max_reserve_coin_num = 4 + [ (gogoproto.moretags) = "yaml:\"max_reserve_coin_num\"" ]; + + // description of the pool type. + string description = 5 [ (gogoproto.moretags) = "yaml:\"description\"" ]; +} + +// Params defines the parameters for the liquidity module. +message Params { + option (gogoproto.equal) = true; + option (gogoproto.goproto_stringer) = false; + + // list of available pool types + repeated PoolType pool_types = 1 [ + (gogoproto.moretags) = "yaml:\"pool_types\"", + (gogoproto.nullable) = false + ]; + + // Minimum number of coins to be deposited to the liquidity pool on pool + // creation. + string min_init_deposit_amount = 2 [ + (gogoproto.moretags) = "yaml:\"min_init_deposit_amount\"", + (cosmos_proto.scalar) = "cosmos.Int", + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", + (gogoproto.nullable) = false + ]; + + // Initial mint amount of pool coins upon pool creation. + string init_pool_coin_mint_amount = 3 [ + (gogoproto.moretags) = "yaml:\"init_pool_coin_mint_amount\"", + (cosmos_proto.scalar) = "cosmos.Int", + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", + (gogoproto.nullable) = false + ]; + + // Limit the size of each liquidity pool to minimize risk. In development, set + // to 0 for no limit. In production, set a limit. + string max_reserve_coin_amount = 4 [ + (gogoproto.moretags) = "yaml:\"max_reserve_coin_amount\"", + (cosmos_proto.scalar) = "cosmos.Int", + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", + (gogoproto.nullable) = false + ]; + + // Fee paid to create a Liquidity Pool. Set a fee to prevent spamming. + repeated cosmos.base.v1beta1.Coin pool_creation_fee = 5 [ + (gogoproto.moretags) = "yaml:\"pool_creation_fee\"", + (gogoproto.nullable) = false, + (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" + ]; + + // Swap fee rate for every executed swap. + string swap_fee_rate = 6 [ + (gogoproto.moretags) = "yaml:\"swap_fee_rate\"", + (cosmos_proto.scalar) = "cosmos.Dec", + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", + (gogoproto.nullable) = false + ]; + + // Reserve coin withdrawal with less proportion by withdrawFeeRate. + string withdraw_fee_rate = 7 [ + (gogoproto.moretags) = "yaml:\"withdraw_fee_rate\"", + (cosmos_proto.scalar) = "cosmos.Dec", + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", + (gogoproto.nullable) = false + ]; + + // Maximum ratio of reserve coins that can be ordered at a swap order. + string max_order_amount_ratio = 8 [ + (gogoproto.moretags) = "yaml:\"max_order_amount_ratio\"", + (cosmos_proto.scalar) = "cosmos.Dec", + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", + (gogoproto.nullable) = false + ]; + + // The smallest unit batch height for every liquidity pool. + uint32 unit_batch_height = 9 + [ (gogoproto.moretags) = "yaml:\"unit_batch_height\"" ]; + + // Circuit breaker enables or disables transaction messages in liquidity + // module. + bool circuit_breaker_enabled = 10 + [ (gogoproto.moretags) = "yaml:\"circuit_breaker_enabled\"" ]; +} + +// Pool defines the liquidity pool that contains pool information. +message Pool { + option (gogoproto.equal) = true; + option (gogoproto.goproto_stringer) = true; + + // id of the pool + uint64 id = 1 + [ (gogoproto.moretags) = "yaml:\"id\"", (gogoproto.jsontag) = "id" ]; + + // id of the pool_type + uint32 type_id = 2 [ (gogoproto.moretags) = "yaml:\"type_id\"" ]; + + // denoms of reserve coin pair of the pool + repeated string reserve_coin_denoms = 3 + [ (gogoproto.moretags) = "yaml:\"reserve_coin_denoms\"" ]; + + // reserve account address of the pool + string reserve_account_address = 4 [ + (gogoproto.moretags) = "yaml:\"reserve_account_address\"", + (cosmos_proto.scalar) = "cosmos.AddressString" + ]; + + // denom of pool coin of the pool + string pool_coin_denom = 5 + [ (gogoproto.moretags) = "yaml:\"pool_coin_denom\"" ]; +} + +// Metadata for the state of each pool for invariant checking after genesis +// export or import. +message PoolMetadata { + option (gogoproto.equal) = true; + option (gogoproto.goproto_stringer) = true; + + // id of the pool + uint64 pool_id = 1 [ + (gogoproto.moretags) = "yaml:\"pool_id\"", + (gogoproto.jsontag) = "pool_id" + ]; + + // pool coin issued at the pool + cosmos.base.v1beta1.Coin pool_coin_total_supply = 2 [ + (gogoproto.moretags) = "yaml:\"pool_coin\"", + (gogoproto.nullable) = false, + (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coin" + ]; + + // reserve coins deposited in the pool + repeated cosmos.base.v1beta1.Coin reserve_coins = 3 [ + (gogoproto.moretags) = "yaml:\"deposit_coins\"", + (gogoproto.nullable) = false, + (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" + ]; +} + +// PoolBatch defines the batch or batches of a given liquidity pool that +// contains indexes of deposit, withdraw, and swap messages. Index param +// increments by 1 if the pool id is same. +message PoolBatch { + option (gogoproto.equal) = true; + option (gogoproto.goproto_stringer) = true; + + // id of the pool + uint64 pool_id = 1 [ + (gogoproto.moretags) = "yaml:\"pool_id\"", + (gogoproto.jsontag) = "pool_id" + ]; + + // index of this batch + uint64 index = 2 [ (gogoproto.moretags) = "yaml:\"index\"" ]; + + // height where this batch is started + int64 begin_height = 3 [ (gogoproto.moretags) = "yaml:\"begin_height\"" ]; + + // last index of DepositMsgStates + uint64 deposit_msg_index = 4 + [ (gogoproto.moretags) = "yaml:\"deposit_msg_index\"" ]; + + // last index of WithdrawMsgStates + uint64 withdraw_msg_index = 5 + [ (gogoproto.moretags) = "yaml:\"withdraw_msg_index\"" ]; + + // last index of SwapMsgStates + uint64 swap_msg_index = 6 + [ (gogoproto.moretags) = "yaml:\"swap_msg_index\"" ]; + + // true if executed, false if not executed + bool executed = 7 [ (gogoproto.moretags) = "yaml:\"executed\"" ]; +} + +// DepositMsgState defines the state of deposit message that contains state +// information as it is processed in the next batch or batches. +message DepositMsgState { + + // height where this message is appended to the batch + int64 msg_height = 1 [ (gogoproto.moretags) = "yaml:\"msg_height\"" ]; + + // index of this deposit message in this liquidity pool + uint64 msg_index = 2 [ (gogoproto.moretags) = "yaml:\"msg_index\"" ]; + + // true if executed on this batch, false if not executed + bool executed = 3 [ (gogoproto.moretags) = "yaml:\"executed\"" ]; + + // true if executed successfully on this batch, false if failed + bool succeeded = 4 [ (gogoproto.moretags) = "yaml:\"succeeded\"" ]; + + // true if ready to be deleted on kvstore, false if not ready to be deleted + bool to_be_deleted = 5 [ (gogoproto.moretags) = "yaml:\"to_be_deleted\"" ]; + + // MsgDepositWithinBatch + MsgDepositWithinBatch msg = 6 [ (gogoproto.moretags) = "yaml:\"msg\"" ]; +} + +// WithdrawMsgState defines the state of the withdraw message that contains +// state information as the message is processed in the next batch or batches. +message WithdrawMsgState { + + // height where this message is appended to the batch + int64 msg_height = 1 [ (gogoproto.moretags) = "yaml:\"msg_height\"" ]; + + // index of this withdraw message in this liquidity pool + uint64 msg_index = 2 [ (gogoproto.moretags) = "yaml:\"msg_index\"" ]; + + // true if executed on this batch, false if not executed + bool executed = 3 [ (gogoproto.moretags) = "yaml:\"executed\"" ]; + + // true if executed successfully on this batch, false if failed + bool succeeded = 4 [ (gogoproto.moretags) = "yaml:\"succeeded\"" ]; + + // true if ready to be deleted on kvstore, false if not ready to be deleted + bool to_be_deleted = 5 [ (gogoproto.moretags) = "yaml:\"to_be_deleted\"" ]; + + // MsgWithdrawWithinBatch + MsgWithdrawWithinBatch msg = 6 [ (gogoproto.moretags) = "yaml:\"msg\"" ]; +} + +// SwapMsgState defines the state of the swap message that contains state +// information as the message is processed in the next batch or batches. +message SwapMsgState { + + // height where this message is appended to the batch + int64 msg_height = 1 [ (gogoproto.moretags) = "yaml:\"msg_height\"" ]; + + // index of this swap message in this liquidity pool + uint64 msg_index = 2 [ (gogoproto.moretags) = "yaml:\"msg_index\"" ]; + + // true if executed on this batch, false if not executed + bool executed = 3 [ (gogoproto.moretags) = "yaml:\"executed\"" ]; + + // true if executed successfully on this batch, false if failed + bool succeeded = 4 [ (gogoproto.moretags) = "yaml:\"succeeded\"" ]; + + // true if ready to be deleted on kvstore, false if not ready to be deleted + bool to_be_deleted = 5 [ (gogoproto.moretags) = "yaml:\"to_be_deleted\"" ]; + + // swap orders are cancelled when current height is equal to or higher than + // ExpiryHeight + int64 order_expiry_height = 6 + [ (gogoproto.moretags) = "yaml:\"order_expiry_height\"" ]; + + // offer coin exchanged until now + cosmos.base.v1beta1.Coin exchanged_offer_coin = 7 [ + (gogoproto.moretags) = "yaml:\"exchanged_offer_coin\"", + (gogoproto.nullable) = false, + (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coin" + ]; + + // offer coin currently remaining to be exchanged + cosmos.base.v1beta1.Coin remaining_offer_coin = 8 [ + (gogoproto.moretags) = "yaml:\"remaining_offer_coin\"", + (gogoproto.nullable) = false, + (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coin" + ]; + + // reserve fee for pays fee in half offer coin + cosmos.base.v1beta1.Coin reserved_offer_coin_fee = 9 [ + (gogoproto.moretags) = "yaml:\"reserved_offer_coin_fee\"", + (gogoproto.nullable) = false, + (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coin" + ]; + + // MsgSwapWithinBatch + MsgSwapWithinBatch msg = 10 [ (gogoproto.moretags) = "yaml:\"msg\"" ]; +} diff --git a/proto/cyber/liquidity/v1beta1/query.proto b/proto/cyber/liquidity/v1beta1/query.proto new file mode 100644 index 00000000..d13d5628 --- /dev/null +++ b/proto/cyber/liquidity/v1beta1/query.proto @@ -0,0 +1,252 @@ +syntax = "proto3"; +package cyber.liquidity.v1beta1; + +import "gogoproto/gogo.proto"; +import "cyber/liquidity/v1beta1/liquidity.proto"; +import "google/api/annotations.proto"; +import "cosmos/base/query/v1beta1/pagination.proto"; + +option go_package = "github.com/cybercongress/go-cyber/x/liquidity/types"; + +// Query defines the gRPC query service for the liquidity module. +service Query { + // Get existing liquidity pools. + rpc LiquidityPools(QueryLiquidityPoolsRequest) + returns (QueryLiquidityPoolsResponse) { + option (google.api.http).get = "/cosmos/liquidity/v1beta1/pools"; + } + + // Get specific liquidity pool. + rpc LiquidityPool(QueryLiquidityPoolRequest) + returns (QueryLiquidityPoolResponse) { + option (google.api.http).get = "/cosmos/liquidity/v1beta1/pools/{pool_id}"; + } + + // Get specific liquidity pool corresponding to the pool_coin_denom. + rpc LiquidityPoolByPoolCoinDenom(QueryLiquidityPoolByPoolCoinDenomRequest) + returns (QueryLiquidityPoolResponse) { + option (google.api.http).get = + "/cosmos/liquidity/v1beta1/pools/pool_coin_denom/{pool_coin_denom}"; + } + + // Get specific liquidity pool corresponding to the reserve account. + rpc LiquidityPoolByReserveAcc(QueryLiquidityPoolByReserveAccRequest) + returns (QueryLiquidityPoolResponse) { + option (google.api.http).get = + "/cosmos/liquidity/v1beta1/pools/reserve_acc/{reserve_acc}"; + } + + // Get the pool's current batch. + rpc LiquidityPoolBatch(QueryLiquidityPoolBatchRequest) + returns (QueryLiquidityPoolBatchResponse) { + option (google.api.http).get = + "/cosmos/liquidity/v1beta1/pools/{pool_id}/batch"; + } + + // Get all swap messages in the pool's current batch. + rpc PoolBatchSwapMsgs(QueryPoolBatchSwapMsgsRequest) + returns (QueryPoolBatchSwapMsgsResponse) { + option (google.api.http).get = + "/cosmos/liquidity/v1beta1/pools/{pool_id}/batch/swaps"; + } + + // Get a specific swap message in the pool's current batch. + rpc PoolBatchSwapMsg(QueryPoolBatchSwapMsgRequest) + returns (QueryPoolBatchSwapMsgResponse) { + option (google.api.http).get = + "/cosmos/liquidity/v1beta1/pools/{pool_id}/batch/swaps/{msg_index}"; + } + + // Get all deposit messages in the pool's current batch. + rpc PoolBatchDepositMsgs(QueryPoolBatchDepositMsgsRequest) + returns (QueryPoolBatchDepositMsgsResponse) { + option (google.api.http).get = + "/cosmos/liquidity/v1beta1/pools/{pool_id}/batch/deposits"; + } + + // Get a specific deposit message in the pool's current batch. + rpc PoolBatchDepositMsg(QueryPoolBatchDepositMsgRequest) + returns (QueryPoolBatchDepositMsgResponse) { + option (google.api.http).get = + "/cosmos/liquidity/v1beta1/pools/{pool_id}/batch/deposits/{msg_index}"; + } + + // Get all withdraw messages in the pool's current batch. + rpc PoolBatchWithdrawMsgs(QueryPoolBatchWithdrawMsgsRequest) + returns (QueryPoolBatchWithdrawMsgsResponse) { + option (google.api.http).get = + "/cosmos/liquidity/v1beta1/pools/{pool_id}/batch/withdraws"; + } + + // Get a specific withdraw message in the pool's current batch. + rpc PoolBatchWithdrawMsg(QueryPoolBatchWithdrawMsgRequest) + returns (QueryPoolBatchWithdrawMsgResponse) { + option (google.api.http).get = + "/cosmos/liquidity/v1beta1/pools/{pool_id}/batch/withdraws/{msg_index}"; + } + + // Get all parameters of the liquidity module. + rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { + option (google.api.http).get = "/cosmos/liquidity/v1beta1/params"; + } +} + +// the request type for the QueryLiquidityPool RPC method. requestable specified +// pool_id. +message QueryLiquidityPoolRequest { uint64 pool_id = 1; } + +// the response type for the QueryLiquidityPoolResponse RPC method. Returns the +// liquidity pool that corresponds to the requested pool_id. +message QueryLiquidityPoolResponse { + Pool pool = 1 [ (gogoproto.nullable) = false ]; +} + +// the request type for the QueryLiquidityByPoolCoinDenomPool RPC method. +// Requestable specified pool_coin_denom. +message QueryLiquidityPoolByPoolCoinDenomRequest { string pool_coin_denom = 1; } + +// the request type for the QueryLiquidityByReserveAcc RPC method. Requestable +// specified reserve_acc. +message QueryLiquidityPoolByReserveAccRequest { string reserve_acc = 1; } + +// the request type for the QueryLiquidityPoolBatch RPC method. requestable +// including specified pool_id. +message QueryLiquidityPoolBatchRequest { + // id of the target pool for query + uint64 pool_id = 1; +} + +// the response type for the QueryLiquidityPoolBatchResponse RPC method. Returns +// the liquidity pool batch that corresponds to the requested pool_id. +message QueryLiquidityPoolBatchResponse { + PoolBatch batch = 1 [ (gogoproto.nullable) = false ]; +} + +// the request type for the QueryLiquidityPools RPC method. Requestable +// including pagination offset, limit, key. +message QueryLiquidityPoolsRequest { + // pagination defines an optional pagination for the request. + cosmos.base.query.v1beta1.PageRequest pagination = 1; +} + +// the response type for the QueryLiquidityPoolsResponse RPC method. This +// includes a list of all existing liquidity pools and paging results that +// contain next_key and total count. +message QueryLiquidityPoolsResponse { + repeated Pool pools = 1 [ (gogoproto.nullable) = false ]; + // pagination defines the pagination in the response. not working on this + // version. + cosmos.base.query.v1beta1.PageResponse pagination = 2; +} + +// QueryParamsRequest is request type for the QueryParams RPC method. +message QueryParamsRequest {} + +// the response type for the QueryParamsResponse RPC method. This includes +// current parameter of the liquidity module. +message QueryParamsResponse { + // params holds all the parameters of this module. + Params params = 1 [ (gogoproto.nullable) = false ]; +} + +// the request type for the QueryPoolBatchSwapMsgs RPC method. Requestable +// including specified pool_id and pagination offset, limit, key. +message QueryPoolBatchSwapMsgsRequest { + // id of the target pool for query + uint64 pool_id = 1; + // pagination defines an optional pagination for the request. + cosmos.base.query.v1beta1.PageRequest pagination = 2; +} + +// the request type for the QueryPoolBatchSwap RPC method. Requestable including +// specified pool_id and msg_index. +message QueryPoolBatchSwapMsgRequest { + // id of the target pool for query + uint64 pool_id = 1; + // target msg_index of the pool + uint64 msg_index = 2; +} + +// the response type for the QueryPoolBatchSwapMsgs RPC method. This includes +// list of all currently existing swap messages of the batch and paging results +// that contain next_key and total count. +message QueryPoolBatchSwapMsgsResponse { + repeated SwapMsgState swaps = 1 [ (gogoproto.nullable) = false ]; + // pagination defines the pagination in the response. not working on this + // version. + cosmos.base.query.v1beta1.PageResponse pagination = 2; +} + +// the response type for the QueryPoolBatchSwapMsg RPC method. This includes a +// batch swap message of the batch. +message QueryPoolBatchSwapMsgResponse { + SwapMsgState swap = 1 [ (gogoproto.nullable) = false ]; +} + +// the request type for the QueryPoolBatchDeposit RPC method. Requestable +// including specified pool_id and pagination offset, limit, key. +message QueryPoolBatchDepositMsgsRequest { + // id of the target pool for query + uint64 pool_id = 1; + // pagination defines an optional pagination for the request. + cosmos.base.query.v1beta1.PageRequest pagination = 2; +} + +// the request type for the QueryPoolBatchDeposit RPC method. requestable +// including specified pool_id and msg_index. +message QueryPoolBatchDepositMsgRequest { + // id of the target pool for query + uint64 pool_id = 1; + // target msg_index of the pool + uint64 msg_index = 2; +} + +// the response type for the QueryPoolBatchDeposit RPC method. This includes a +// list of all currently existing deposit messages of the batch and paging +// results that contain next_key and total count. +message QueryPoolBatchDepositMsgsResponse { + repeated DepositMsgState deposits = 1 [ (gogoproto.nullable) = false ]; + // pagination defines the pagination in the response. not working on this + // version. + cosmos.base.query.v1beta1.PageResponse pagination = 2; +} + +// the response type for the QueryPoolBatchDepositMsg RPC method. This includes +// a batch swap message of the batch. +message QueryPoolBatchDepositMsgResponse { + DepositMsgState deposit = 1 [ (gogoproto.nullable) = false ]; +} + +// the request type for the QueryPoolBatchWithdraw RPC method. Requestable +// including specified pool_id and pagination offset, limit, key. +message QueryPoolBatchWithdrawMsgsRequest { + // id of the target pool for query + uint64 pool_id = 1; + // pagination defines an optional pagination for the request. + cosmos.base.query.v1beta1.PageRequest pagination = 2; +} + +// the request type for the QueryPoolBatchWithdraw RPC method. requestable +// including specified pool_id and msg_index. +message QueryPoolBatchWithdrawMsgRequest { + // id of the target pool for query + uint64 pool_id = 1; + // target msg_index of the pool + uint64 msg_index = 2; +} + +// the response type for the QueryPoolBatchWithdraw RPC method. This includes a +// list of all currently existing withdraw messages of the batch and paging +// results that contain next_key and total count. +message QueryPoolBatchWithdrawMsgsResponse { + repeated WithdrawMsgState withdraws = 1 [ (gogoproto.nullable) = false ]; + // pagination defines the pagination in the response. Not supported on this + // version. + cosmos.base.query.v1beta1.PageResponse pagination = 2; +} + +// the response type for the QueryPoolBatchWithdrawMsg RPC method. This includes +// a batch swap message of the batch. +message QueryPoolBatchWithdrawMsgResponse { + WithdrawMsgState withdraw = 1 [ (gogoproto.nullable) = false ]; +} diff --git a/proto/cyber/liquidity/v1beta1/tx.proto b/proto/cyber/liquidity/v1beta1/tx.proto new file mode 100644 index 00000000..dc6a6159 --- /dev/null +++ b/proto/cyber/liquidity/v1beta1/tx.proto @@ -0,0 +1,198 @@ +syntax = "proto3"; +package cyber.liquidity.v1beta1; + +import "gogoproto/gogo.proto"; +import "cosmos/base/v1beta1/coin.proto"; +// import "google/api/annotations.proto"; +// import "cosmos/msg/v1/msg.proto"; +import "cosmos_proto/cosmos.proto"; + +option go_package = "github.com/cybercongress/go-cyber/x/liquidity/types"; + +// Msg defines the liquidity Msg service. +service Msg { + + // Submit a create liquidity pool message. + rpc CreatePool(MsgCreatePool) returns (MsgCreatePoolResponse); + + // Submit a deposit to the liquidity pool batch. + rpc DepositWithinBatch(MsgDepositWithinBatch) + returns (MsgDepositWithinBatchResponse); + + // Submit a withdraw from the liquidity pool batch. + rpc WithdrawWithinBatch(MsgWithdrawWithinBatch) + returns (MsgWithdrawWithinBatchResponse); + + // Submit a swap to the liquidity pool batch. + rpc Swap(MsgSwapWithinBatch) returns (MsgSwapWithinBatchResponse); + + // rpc UpdateParams(MsgUpdateParams) returns (MsgUpdateParamsResponse); +} + +// MsgCreatePool defines an sdk.Msg type that supports submitting a create +// liquidity pool tx. +// +// See: +// https://github.com/gravity-devs/liquidity/blob/develop/x/liquidity/spec/04_messages.md +message MsgCreatePool { + option (gogoproto.equal) = false; + option (gogoproto.goproto_getters) = false; + + string pool_creator_address = 1 [ + (gogoproto.moretags) = "yaml:\"pool_creator_address\"", + (cosmos_proto.scalar) = "cosmos.AddressString" + ]; + + // id of the target pool type, must match the value in the pool. Only + // pool-type-id 1 is supported. + uint32 pool_type_id = 2 [ (gogoproto.moretags) = "yaml:\"pool_type_id\"" ]; + + // reserve coin pair of the pool to deposit. + repeated cosmos.base.v1beta1.Coin deposit_coins = 4 [ + (gogoproto.moretags) = "yaml:\"deposit_coins\"", + (gogoproto.nullable) = false, + (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" + ]; +} + +// MsgCreatePoolResponse defines the Msg/CreatePool response type. +message MsgCreatePoolResponse {} + +// `MsgDepositWithinBatch defines` an `sdk.Msg` type that supports submitting +// a deposit request to the batch of the liquidity pool. +// Deposit is submitted to the batch of the Liquidity pool with the specified +// `pool_id`, `deposit_coins` for reserve. +// This request is stacked in the batch of the liquidity pool, is not processed +// immediately, and is processed in the `endblock` at the same time as other +// requests. +// +// See: +// https://github.com/gravity-devs/liquidity/blob/develop/x/liquidity/spec/04_messages.md +message MsgDepositWithinBatch { + option (gogoproto.equal) = false; + option (gogoproto.goproto_getters) = false; + + string depositor_address = 1 [ + (cosmos_proto.scalar) = "cosmos.AddressString", + (gogoproto.moretags) = "yaml:\"depositor_address\"" + ]; + + // id of the target pool + uint64 pool_id = 2 [ (gogoproto.moretags) = "yaml:\"pool_id\"" ]; + + // reserve coin pair of the pool to deposit + repeated cosmos.base.v1beta1.Coin deposit_coins = 3 [ + (gogoproto.moretags) = "yaml:\"deposit_coins\"", + (gogoproto.nullable) = false, + (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" + ]; +} + +// MsgDepositWithinBatchResponse defines the Msg/DepositWithinBatch response +// type. +message MsgDepositWithinBatchResponse {} + +// `MsgWithdrawWithinBatch` defines an `sdk.Msg` type that supports submitting +// a withdraw request to the batch of the liquidity pool. +// Withdraw is submitted to the batch from the Liquidity pool with the +// specified `pool_id`, `pool_coin` of the pool. +// This request is stacked in the batch of the liquidity pool, is not processed +// immediately, and is processed in the `endblock` at the same time as other +// requests. +// +// See: +// https://github.com/gravity-devs/liquidity/blob/develop/x/liquidity/spec/04_messages.md +message MsgWithdrawWithinBatch { + option (gogoproto.equal) = false; + option (gogoproto.goproto_getters) = false; + + string withdrawer_address = 1 [ + (gogoproto.moretags) = "yaml:\"withdrawer_address\"", + (cosmos_proto.scalar) = "cosmos.AddressString" + ]; + // id of the target pool + uint64 pool_id = 2 [ (gogoproto.moretags) = "yaml:\"pool_id\"" ]; + + cosmos.base.v1beta1.Coin pool_coin = 3 [ + (gogoproto.moretags) = "yaml:\"pool_coin\"", + (gogoproto.nullable) = false, + (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coin" + ]; +} + +// MsgWithdrawWithinBatchResponse defines the Msg/WithdrawWithinBatch response +// type. +message MsgWithdrawWithinBatchResponse {} + +// `MsgSwapWithinBatch` defines an sdk.Msg type that supports submitting a swap +// offer request to the batch of the liquidity pool. Submit swap offer to the +// liquidity pool batch with the specified the `pool_id`, `swap_type_id`, +// `demand_coin_denom` with the coin and the price you're offering +// and `offer_coin_fee` must be half of offer coin amount * current +// `params.swap_fee_rate` and ceil for reservation to pay fees. This request is +// stacked in the batch of the liquidity pool, is not processed immediately, and +// is processed in the `endblock` at the same time as other requests. You must +// request the same fields as the pool. Only the default `swap_type_id` 1 is +// supported. +// +// See: https://github.com/gravity-devs/liquidity/tree/develop/doc +// https://github.com/gravity-devs/liquidity/blob/develop/x/liquidity/spec/04_messages.md +message MsgSwapWithinBatch { + option (gogoproto.equal) = false; + option (gogoproto.goproto_getters) = false; + // address of swap requester + string swap_requester_address = 1 [ + (gogoproto.moretags) = "yaml:\"swap_requester_address\"", + (cosmos_proto.scalar) = "cosmos.AddressString" + ]; + // id of swap type, must match the value in the pool. Only `swap_type_id` 1 is + // supported. + uint64 pool_id = 2 [ (gogoproto.moretags) = "yaml:\"pool_id\"" ]; + + // id of swap type. Must match the value in the pool. + uint32 swap_type_id = 3 [ (gogoproto.moretags) = "yaml:\"swap_type_id\"" ]; + + // offer sdk.coin for the swap request, must match the denom in the pool. + cosmos.base.v1beta1.Coin offer_coin = 4 [ + (gogoproto.moretags) = "yaml:\"offer_coin\"", + (gogoproto.nullable) = false, + (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coin" + ]; + + // denom of demand coin to be exchanged on the swap request, must match the + // denom in the pool. + string demand_coin_denom = 5 + [ (gogoproto.moretags) = "yaml:\"demand_coin_denom\"" ]; + + // half of offer coin amount * params.swap_fee_rate and ceil for reservation + // to pay fees. + cosmos.base.v1beta1.Coin offer_coin_fee = 6 [ + (gogoproto.moretags) = "yaml:\"offer_coin_fee\"", + (gogoproto.nullable) = false, + (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coin" + ]; + + // limit order price for the order, the price is the exchange ratio of X/Y + // where X is the amount of the first coin and Y is the amount + // of the second coin when their denoms are sorted alphabetically. + string order_price = 7 [ + (gogoproto.moretags) = "yaml:\"order_price\"", + (cosmos_proto.scalar) = "cosmos.Dec", + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", + (gogoproto.nullable) = false + ]; +} + +// MsgSwapWithinBatchResponse defines the Msg/Swap response type. +message MsgSwapWithinBatchResponse {} + +// TODO revisit this and apply, there is issue with cyclic dependency with +// Params import message MsgUpdateParams { +// option (cosmos.msg.v1.signer) = "authority"; +// +// string authority = 1 [ (cosmos_proto.scalar) = "cosmos.AddressString" ]; +// +// Params params = 2 [ (gogoproto.nullable) = false ]; +// } +// +// message MsgUpdateParamsResponse {} diff --git a/x/liquidity/abci.go b/x/liquidity/abci.go new file mode 100644 index 00000000..abff8712 --- /dev/null +++ b/x/liquidity/abci.go @@ -0,0 +1,25 @@ +package liquidity + +import ( + "time" + + "github.com/cosmos/cosmos-sdk/telemetry" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/cybercongress/go-cyber/v4/x/liquidity/keeper" + "github.com/cybercongress/go-cyber/v4/x/liquidity/types" +) + +// In the Begin blocker of the liquidity module, +// Reinitialize batch messages that were not executed in the previous batch and delete batch messages that were executed or ready to delete. +func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { + defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) + k.DeleteAndInitPoolBatches(ctx) +} + +// In case of deposit, withdraw, and swap msgs, unlike other normal tx msgs, +// collect them in the liquidity pool batch and perform an execution once at the endblock to calculate and use the universal price. +func EndBlocker(ctx sdk.Context, k keeper.Keeper) { + defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyEndBlocker) + k.ExecutePoolBatches(ctx) +} diff --git a/x/liquidity/client/cli/flags.go b/x/liquidity/client/cli/flags.go new file mode 100644 index 00000000..c1f49858 --- /dev/null +++ b/x/liquidity/client/cli/flags.go @@ -0,0 +1,21 @@ +package cli + +// DONTCOVER + +import ( + flag "github.com/spf13/pflag" +) + +const ( + FlagPoolCoinDenom = "pool-coin-denom" + FlagReserveAcc = "reserve-acc" +) + +func flagSetPool() *flag.FlagSet { + fs := flag.NewFlagSet("", flag.ContinueOnError) + + fs.String(FlagPoolCoinDenom, "", "The denomination of the pool coin") + fs.String(FlagReserveAcc, "", "The Bech32 address of the reserve account") + + return fs +} diff --git a/x/liquidity/client/cli/query.go b/x/liquidity/client/cli/query.go new file mode 100644 index 00000000..e33004ba --- /dev/null +++ b/x/liquidity/client/cli/query.go @@ -0,0 +1,577 @@ +package cli + +// DONTCOVER +// client is excluded from test coverage in the poc phase milestone 1 and will be included in milestone 2 with completeness + +import ( + "context" + "fmt" + "strconv" + "strings" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/version" + "github.com/spf13/cobra" + + "github.com/cybercongress/go-cyber/v4/x/liquidity/types" +) + +// GetQueryCmd returns the cli query commands for this module +func GetQueryCmd() *cobra.Command { + liquidityQueryCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Querying commands for the liquidity module", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + liquidityQueryCmd.AddCommand( + GetCmdQueryParams(), + GetCmdQueryLiquidityPool(), + GetCmdQueryLiquidityPools(), + GetCmdQueryLiquidityPoolBatch(), + GetCmdQueryPoolBatchDepositMsgs(), + GetCmdQueryPoolBatchDepositMsg(), + GetCmdQueryPoolBatchWithdrawMsgs(), + GetCmdQueryPoolBatchWithdrawMsg(), + GetCmdQueryPoolBatchSwapMsgs(), + GetCmdQueryPoolBatchSwapMsg(), + ) + + return liquidityQueryCmd +} + +// GetCmdQueryParams implements the params query command. +func GetCmdQueryParams() *cobra.Command { + cmd := &cobra.Command{ + Use: "params", + Args: cobra.NoArgs, + Short: "Query the values set as liquidity parameters", + Long: strings.TrimSpace( + fmt.Sprintf(`Query values set as liquidity parameters. + +Example: +$ %s query %s params +`, + version.AppName, types.ModuleName, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + + res, err := queryClient.Params( + context.Background(), + &types.QueryParamsRequest{}, + ) + if err != nil { + return err + } + + return clientCtx.PrintProto(&res.Params) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +func GetCmdQueryLiquidityPool() *cobra.Command { + cmd := &cobra.Command{ + Use: "pool [pool-id]", + Short: "Query details of a liquidity pool", + Long: strings.TrimSpace( + fmt.Sprintf(`Query details of a liquidity pool +Example: +$ %[1]s query %[2]s pool 1 + +Example (with pool coin denom): +$ %[1]s query %[2]s pool --pool-coin-denom=[denom] + +Example (with reserve acc): +$ %[1]s query %[2]s pool --reserve-acc=[address] +`, + version.AppName, types.ModuleName, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + var res *types.QueryLiquidityPoolResponse + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + foundArg := false + queryClient := types.NewQueryClient(clientCtx) + + poolCoinDenom, _ := cmd.Flags().GetString(FlagPoolCoinDenom) + if poolCoinDenom != "" { + foundArg = true + res, err = queryClient.LiquidityPoolByPoolCoinDenom( + context.Background(), + &types.QueryLiquidityPoolByPoolCoinDenomRequest{PoolCoinDenom: poolCoinDenom}, + ) + if err != nil { + return err + } + } + + reserveAcc, _ := cmd.Flags().GetString(FlagReserveAcc) + if !foundArg && reserveAcc != "" { + foundArg = true + res, err = queryClient.LiquidityPoolByReserveAcc( + context.Background(), + &types.QueryLiquidityPoolByReserveAccRequest{ReserveAcc: reserveAcc}, + ) + if err != nil { + return err + } + } + + if !foundArg && len(args) > 0 { + poolID, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return fmt.Errorf("pool-id %s not a valid uint, input a valid unsigned 32-bit integer for pool-id", args[0]) + } + + if poolID != 0 { + foundArg = true + res, err = queryClient.LiquidityPool( + context.Background(), + &types.QueryLiquidityPoolRequest{PoolId: poolID}, + ) + if err != nil { + return err + } + } + } + + if !foundArg { + return fmt.Errorf("provide the pool-id argument or --%s or --%s flag", FlagPoolCoinDenom, FlagReserveAcc) + } + + return clientCtx.PrintProto(res) + }, + } + cmd.Flags().AddFlagSet(flagSetPool()) + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +func GetCmdQueryLiquidityPools() *cobra.Command { + cmd := &cobra.Command{ + Use: "pools", + Args: cobra.NoArgs, + Short: "Query for all liquidity pools", + Long: strings.TrimSpace( + fmt.Sprintf(`Query details about all liquidity pools on a network. +Example: +$ %s query %s pools +`, + version.AppName, types.ModuleName, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + pageReq, err := client.ReadPageRequest(cmd.Flags()) + if err != nil { + return err + } + + res, err := queryClient.LiquidityPools( + context.Background(), + &types.QueryLiquidityPoolsRequest{Pagination: pageReq}, + ) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +func GetCmdQueryLiquidityPoolBatch() *cobra.Command { + cmd := &cobra.Command{ + Use: "batch [pool-id]", + Args: cobra.ExactArgs(1), + Short: "Query details of a liquidity pool batch", + Long: strings.TrimSpace( + fmt.Sprintf(`Query details of a liquidity pool batch +Example: +$ %s query %s batch 1 +`, + version.AppName, types.ModuleName, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + queryClient := types.NewQueryClient(clientCtx) + + poolID, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return fmt.Errorf("pool-id %s not a valid uint32, input a valid unsigned 32-bit integer pool-id", args[0]) + } + + res, err := queryClient.LiquidityPoolBatch( + context.Background(), + &types.QueryLiquidityPoolBatchRequest{PoolId: poolID}, + ) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + return cmd +} + +func GetCmdQueryPoolBatchDepositMsgs() *cobra.Command { + cmd := &cobra.Command{ + Use: "deposits [pool-id]", + Args: cobra.ExactArgs(1), + Short: "Query all deposit messages of the liquidity pool batch", + Long: strings.TrimSpace( + fmt.Sprintf(`Query all deposit messages of the liquidity pool batch on the specified pool + +If batch messages are normally processed from the endblock, the resulting state is applied and the messages are removed in the beginning of next block. +To query for past blocks, query the block height using the REST/gRPC API of a node that is not pruned. + +Example: +$ %s query %s deposits 1 +`, + version.AppName, types.ModuleName, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + pageReq, err := client.ReadPageRequest(cmd.Flags()) + if err != nil { + return err + } + + poolID, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return fmt.Errorf("pool-id %s not a valid uint, input a valid unsigned 32-bit integer pool-id", args[0]) + } + + res, err := queryClient.PoolBatchDepositMsgs( + context.Background(), + &types.QueryPoolBatchDepositMsgsRequest{ + PoolId: poolID, + Pagination: pageReq, + }, + ) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +func GetCmdQueryPoolBatchDepositMsg() *cobra.Command { + cmd := &cobra.Command{ + Use: "deposit [pool-id] [msg-index]", + Args: cobra.ExactArgs(2), + Short: "Query the deposit messages on the liquidity pool batch", + Long: strings.TrimSpace( + fmt.Sprintf(`Query the deposit messages on the liquidity pool batch for the specified pool-id and msg-index + +If batch messages are normally processed from the endblock, +the resulting state is applied and the messages are removed from the beginning of the next block. +To query for past blocks, query the block height using the REST/gRPC API of a node that is not pruned. + +Example: +$ %s query %s deposit 1 20 +`, + version.AppName, types.ModuleName, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + + poolID, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return fmt.Errorf("pool-id %s not a valid uint, input a valid unsigned 32-bit integer for pool-id", args[0]) + } + + msgIndex, err := strconv.ParseUint(args[1], 10, 64) + if err != nil { + return fmt.Errorf("msg-index %s not a valid uint, input a valid unsigned 32-bit integer for msg-index", args[1]) + } + + res, err := queryClient.PoolBatchDepositMsg( + context.Background(), + &types.QueryPoolBatchDepositMsgRequest{ + PoolId: poolID, + MsgIndex: msgIndex, + }, + ) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +func GetCmdQueryPoolBatchWithdrawMsgs() *cobra.Command { + cmd := &cobra.Command{ + Use: "withdraws [pool-id]", + Args: cobra.ExactArgs(1), + Short: "Query for all withdraw messages on the liquidity pool batch", + Long: strings.TrimSpace( + fmt.Sprintf(`Query all withdraw messages on the liquidity pool batch for the specified pool-id + +If batch messages are normally processed from the endblock, +the resulting state is applied and the messages are removed in the beginning of next block. +To query for past blocks, query the block height using the REST/gRPC API of a node that is not pruned. + +Example: +$ %s query %s withdraws 1 +`, + version.AppName, types.ModuleName, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + pageReq, err := client.ReadPageRequest(cmd.Flags()) + if err != nil { + return err + } + + poolID, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return fmt.Errorf("pool-id %s not a valid uint, input a valid unsigned 32-bit integer pool-id", args[0]) + } + + result, err := queryClient.PoolBatchWithdrawMsgs(context.Background(), &types.QueryPoolBatchWithdrawMsgsRequest{ + PoolId: poolID, Pagination: pageReq, + }) + if err != nil { + return err + } + return clientCtx.PrintProto(result) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +func GetCmdQueryPoolBatchWithdrawMsg() *cobra.Command { + cmd := &cobra.Command{ + Use: "withdraw [pool-id] [msg-index]", + Args: cobra.ExactArgs(2), + Short: "Query the withdraw messages in the liquidity pool batch", + Long: strings.TrimSpace( + fmt.Sprintf(`Query the withdraw messages in the liquidity pool batch for the specified pool-id and msg-index + +if the batch message are normally processed from the endblock, +the resulting state is applied and the messages are removed in the beginning of next block. +To query for past blocks, query the block height using the REST/gRPC API of a node that is not pruned. + +Example: +$ %s query %s withdraw 1 20 +`, + version.AppName, types.ModuleName, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + + poolID, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return fmt.Errorf("pool-id %s not a valid uint, input a valid unsigned 32-bit integer pool-id", args[0]) + } + + msgIndex, err := strconv.ParseUint(args[1], 10, 64) + if err != nil { + return fmt.Errorf("msg-index %s not a valid uint, input a valid unsigned 32-bit integer msg-index", args[1]) + } + + res, err := queryClient.PoolBatchWithdrawMsg( + context.Background(), + &types.QueryPoolBatchWithdrawMsgRequest{ + PoolId: poolID, + MsgIndex: msgIndex, + }, + ) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +func GetCmdQueryPoolBatchSwapMsgs() *cobra.Command { + cmd := &cobra.Command{ + Use: "swaps [pool-id]", + Args: cobra.ExactArgs(1), + Short: "Query all swap messages in the liquidity pool batch", + Long: strings.TrimSpace( + fmt.Sprintf(`Query all swap messages in the liquidity pool batch for the specified pool-id + +If batch messages are normally processed from the endblock, +the resulting state is applied and the messages are removed in the beginning of next block. +To query for past blocks, query the block height using the REST/gRPC API of a node that is not pruned. + +Example: +$ %s query %s swaps 1 +`, + version.AppName, types.ModuleName, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + pageReq, err := client.ReadPageRequest(cmd.Flags()) + if err != nil { + return err + } + + poolID, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return fmt.Errorf("pool-id %s not a valid uint, input a valid unsigned 32-bit integer pool-id", args[0]) + } + + res, err := queryClient.PoolBatchSwapMsgs( + context.Background(), + &types.QueryPoolBatchSwapMsgsRequest{ + PoolId: poolID, + Pagination: pageReq, + }, + ) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +func GetCmdQueryPoolBatchSwapMsg() *cobra.Command { + cmd := &cobra.Command{ + Use: "swap [pool-id] [msg-index]", + Args: cobra.ExactArgs(2), + Short: "Query for the swap message on the batch of the liquidity pool specified pool-id and msg-index", + Long: strings.TrimSpace( + fmt.Sprintf(`Query for the swap message on the batch of the liquidity pool specified pool-id and msg-index + +If the batch message are normally processed and from the endblock, +the resulting state is applied and the messages are removed in the beginning of next block. +To query for past blocks, query the block height using the REST/gRPC API of a node that is not pruned. + +Example: +$ %s query %s swap 1 20 +`, + version.AppName, types.ModuleName, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + + poolID, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return fmt.Errorf("pool-id %s not a valid uint, input a valid unsigned 32-bit integer for pool-id", args[0]) + } + + msgIndex, err := strconv.ParseUint(args[1], 10, 64) + if err != nil { + return fmt.Errorf("msg-index %s not a valid uint, input a valid unsigned 32-bit integer for msg-index", args[1]) + } + + res, err := queryClient.PoolBatchSwapMsg( + context.Background(), + &types.QueryPoolBatchSwapMsgRequest{ + PoolId: poolID, + MsgIndex: msgIndex, + }, + ) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} diff --git a/x/liquidity/client/cli/tx.go b/x/liquidity/client/cli/tx.go new file mode 100644 index 00000000..e81cbedb --- /dev/null +++ b/x/liquidity/client/cli/tx.go @@ -0,0 +1,336 @@ +package cli + +// DONTCOVER +// client is excluded from test coverage in the poc phase milestone 1 and will be included in milestone 2 with completeness + +import ( + "fmt" + "strconv" + "strings" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/tx" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/version" + "github.com/spf13/cobra" + + "github.com/cybercongress/go-cyber/v4/x/liquidity/types" +) + +// GetTxCmd returns a root CLI command handler for all x/liquidity transaction commands. +func GetTxCmd() *cobra.Command { + liquidityTxCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Liquidity transaction subcommands", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + liquidityTxCmd.AddCommand( + NewCreatePoolCmd(), + NewDepositWithinBatchCmd(), + NewWithdrawWithinBatchCmd(), + NewSwapWithinBatchCmd(), + ) + + return liquidityTxCmd +} + +// Create new liquidity pool with the specified pool type and deposit coins. +func NewCreatePoolCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "create-pool [pool-type] [deposit-coins]", + Args: cobra.ExactArgs(2), + Short: "Create liquidity pool and deposit coins", + Long: strings.TrimSpace( + fmt.Sprintf(`Create liquidity pool and deposit coins. + +Example: +$ %s tx %s create-pool 1 1000000000uatom,50000000000uusd --from mykey + +This example creates a liquidity pool of pool-type 1 (two coins) and deposits 1000000000uatom and 50000000000uusd. +New liquidity pools can be created only for coin combinations that do not already exist in the network. + +[pool-type]: The id of the liquidity pool-type. The only supported pool type is 1 +[deposit-coins]: The amount of coins to deposit to the liquidity pool. The number of deposit coins must be 2 in pool type 1. +`, + version.AppName, types.ModuleName, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + poolCreator := clientCtx.GetFromAddress() + + // Get pool type index + poolTypeID, err := strconv.ParseUint(args[0], 10, 32) + if err != nil { + return fmt.Errorf("pool-type %s not a valid uint, input a valid unsigned 32-bit integer for pool-type", args[0]) + } + + // Get deposit coins + depositCoins, err := sdk.ParseCoinsNormalized(args[1]) + if err != nil { + return err + } + + err = depositCoins.Validate() + if err != nil { + return err + } + + if poolTypeID != 1 { + return types.ErrPoolTypeNotExists + } + + if depositCoins.Len() != 2 { + return fmt.Errorf("the number of deposit coins must be two in pool-type 1") + } + + msg := types.NewMsgCreatePool(poolCreator, uint32(poolTypeID), depositCoins) + if err := msg.ValidateBasic(); err != nil { + return err + } + + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + return cmd +} + +// Deposit coins to the specified liquidity pool. +func NewDepositWithinBatchCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "deposit [pool-id] [deposit-coins]", + Args: cobra.ExactArgs(2), + Short: "Deposit coins to a liquidity pool", + Long: strings.TrimSpace( + fmt.Sprintf(`Deposit coins a liquidity pool. + +This deposit request is not processed immediately since it is accumulated in the liquidity pool batch. +All requests in a batch are treated equally and executed at the same swap price. + +Example: +$ %s tx %s deposit 1 100000000uatom,5000000000uusd --from mykey + +This example request deposits 100000000uatom and 5000000000uusd to pool-id 1. +Deposits must be the same coin denoms as the reserve coins. + +[pool-id]: The pool id of the liquidity pool +[deposit-coins]: The amount of coins to deposit to the liquidity pool +`, + version.AppName, types.ModuleName, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + depositor := clientCtx.GetFromAddress() + + // Get pool type index + poolID, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return fmt.Errorf("pool-id %s not a valid uint, input a valid unsigned 32-bit integer for pool-id", args[0]) + } + + // Get deposit coins + depositCoins, err := sdk.ParseCoinsNormalized(args[1]) + if err != nil { + return err + } + + err = depositCoins.Validate() + if err != nil { + return err + } + + if depositCoins.Len() != 2 { + return fmt.Errorf("the number of deposit coins must be two in the pool-type 1") + } + + msg := types.NewMsgDepositWithinBatch(depositor, poolID, depositCoins) + if err := msg.ValidateBasic(); err != nil { + return err + } + + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + return cmd +} + +// Withdraw pool coin from the specified liquidity pool. +func NewWithdrawWithinBatchCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "withdraw [pool-id] [pool-coin]", + Args: cobra.ExactArgs(2), + Short: "Withdraw pool coin from the specified liquidity pool", + Long: strings.TrimSpace( + fmt.Sprintf(`Withdraw pool coin from the specified liquidity pool. + +This swap request is not processed immediately since it is accumulated in the liquidity pool batch. +All requests in a batch are treated equally and executed at the same swap price. + +Example: +$ %s tx %s withdraw 1 10000pool96EF6EA6E5AC828ED87E8D07E7AE2A8180570ADD212117B2DA6F0B75D17A6295 --from mykey + +This example request withdraws 10000 pool coin from the specified liquidity pool. +The appropriate pool coin must be requested from the specified pool. + +[pool-id]: The pool id of the liquidity pool +[pool-coin]: The amount of pool coin to withdraw from the liquidity pool +`, + version.AppName, types.ModuleName, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + withdrawer := clientCtx.GetFromAddress() + + // Get pool type index + poolID, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return fmt.Errorf("pool-id %s not a valid uint, input a valid unsigned 32-bit integer for pool-id", args[0]) + } + + // Get pool coin of the target pool + poolCoin, err := sdk.ParseCoinNormalized(args[1]) + if err != nil { + return err + } + + err = poolCoin.Validate() + if err != nil { + return err + } + + msg := types.NewMsgWithdrawWithinBatch(withdrawer, poolID, poolCoin) + if err := msg.ValidateBasic(); err != nil { + return err + } + + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + return cmd +} + +// Swap offer coin with demand coin from the specified liquidity pool with the given order price. +func NewSwapWithinBatchCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "swap [pool-id] [swap-type] [offer-coin] [demand-coin-denom] [order-price] [swap-fee-rate]", + Args: cobra.ExactArgs(6), + Short: "Swap offer coin with demand coin from the liquidity pool with the given order price", + Long: strings.TrimSpace( + fmt.Sprintf(`Swap offer coin with demand coin from the liquidity pool with the given order price. + +This swap request is not processed immediately since it is accumulated in the liquidity pool batch. +All requests in a batch are treated equally and executed at the same swap price. +The order of swap requests is ignored since the universal swap price is calculated in every batch to prevent front running. + +The requested swap is executed with a swap price that is calculated from the given swap price function of the pool, the other swap requests, and the liquidity pool coin reserve status. +Swap orders are executed only when the execution swap price is equal to or greater than the submitted order price of the swap order. + +Example: +$ %s tx %s swap 1 1 50000000uusd uatom 0.019 0.003 --from mykey + +For this example, imagine that an existing liquidity pool has with 1000000000uatom and 50000000000uusd. +This example request swaps 50000000uusd for at least 950000uatom with the order price of 0.019 and swap fee rate of 0.003. +A sufficient balance of half of the swap-fee-rate of the offer coin is required to reserve the offer coin fee. + +The order price is the exchange ratio of X/Y, where X is the amount of the first coin and Y is the amount of the second coin when their denoms are sorted alphabetically. +Increasing order price reduces the possibility for your request to be processed and results in buying uatom at a lower price than the pool price. + +For explicit calculations, The swap fee rate must be the value that set as liquidity parameter in the current network. +The only supported swap-type is 1. For the detailed swap algorithm, see https://github.com/gravity-devs/liquidity/v3 + +[pool-id]: The pool id of the liquidity pool +[swap-type]: The swap type of the swap message. The only supported swap type is 1 (instant swap). +[offer-coin]: The amount of offer coin to swap +[demand-coin-denom]: The denomination of the coin to exchange with offer coin +[order-price]: The limit order price for the swap order. The price is the exchange ratio of X/Y where X is the amount of the first coin and Y is the amount of the second coin when their denoms are sorted alphabetically +[swap-fee-rate]: The swap fee rate to pay for swap that is proportional to swap amount. The swap fee rate must be the value that set as liquidity parameter in the current network. +`, + version.AppName, types.ModuleName, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + swapRequester := clientCtx.GetFromAddress() + + // Get pool id + poolID, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return fmt.Errorf("pool-id %s not a valid uint, input a valid unsigned 32-bit integer for pool-id", args[0]) + } + + // Get swap type + swapTypeID, err := strconv.ParseUint(args[1], 10, 32) + if err != nil { + return fmt.Errorf("swap-type %s not a valid uint, input a valid unsigned 32-bit integer for swap-type", args[2]) + } + + if swapTypeID != 1 { + return types.ErrSwapTypeNotExists + } + + // Get offer coin + offerCoin, err := sdk.ParseCoinNormalized(args[2]) + if err != nil { + return err + } + + err = offerCoin.Validate() + if err != nil { + return err + } + + err = sdk.ValidateDenom(args[3]) + if err != nil { + return err + } + + orderPrice, err := sdk.NewDecFromStr(args[4]) + if err != nil { + return err + } + + swapFeeRate, err := sdk.NewDecFromStr(args[5]) + if err != nil { + return err + } + + msg := types.NewMsgSwapWithinBatch(swapRequester, poolID, uint32(swapTypeID), offerCoin, args[3], orderPrice, swapFeeRate) + if err := msg.ValidateBasic(); err != nil { + return err + } + + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + return cmd +} diff --git a/x/liquidity/exported/exported.go b/x/liquidity/exported/exported.go new file mode 100644 index 00000000..27ae912d --- /dev/null +++ b/x/liquidity/exported/exported.go @@ -0,0 +1,22 @@ +package exported + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" +) + +type EnergyKeeper interface { + GetRoutedToEnergy(ctx sdk.Context, delegate sdk.AccAddress) sdk.Coins +} + +type ( + ParamSet = paramtypes.ParamSet + + // Subspace defines an interface that implements the legacy x/params Subspace + // type. + // + // NOTE: This is used solely for migration of x/params managed parameters. + Subspace interface { + GetParamSet(ctx sdk.Context, ps ParamSet) + } +) diff --git a/x/liquidity/genesis.go b/x/liquidity/genesis.go new file mode 100644 index 00000000..508a2558 --- /dev/null +++ b/x/liquidity/genesis.go @@ -0,0 +1,18 @@ +package liquidity + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/cybercongress/go-cyber/v4/x/liquidity/keeper" + "github.com/cybercongress/go-cyber/v4/x/liquidity/types" +) + +// InitGenesis new liquidity genesis +func InitGenesis(ctx sdk.Context, keeper keeper.Keeper, data types.GenesisState) { + keeper.InitGenesis(ctx, data) +} + +// ExportGenesis returns a GenesisState for a given context and keeper. +func ExportGenesis(ctx sdk.Context, keeper keeper.Keeper) *types.GenesisState { + return keeper.ExportGenesis(ctx) +} diff --git a/x/liquidity/handler.go b/x/liquidity/handler.go new file mode 100644 index 00000000..1e5836cd --- /dev/null +++ b/x/liquidity/handler.go @@ -0,0 +1,37 @@ +package liquidity + +import ( + errorsmod "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/cybercongress/go-cyber/v4/x/liquidity/keeper" + "github.com/cybercongress/go-cyber/v4/x/liquidity/types" +) + +// NewHandler returns a handler for all "liquidity" type messages. +func NewHandler(k keeper.Keeper) sdk.Handler { + msgServer := keeper.NewMsgServerImpl(k) + + return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { + ctx = ctx.WithEventManager(sdk.NewEventManager()) + + switch msg := msg.(type) { + case *types.MsgCreatePool: + res, err := msgServer.CreatePool(sdk.WrapSDKContext(ctx), msg) + return sdk.WrapServiceResult(ctx, res, err) + case *types.MsgDepositWithinBatch: + res, err := msgServer.DepositWithinBatch(sdk.WrapSDKContext(ctx), msg) + return sdk.WrapServiceResult(ctx, res, err) + case *types.MsgWithdrawWithinBatch: + res, err := msgServer.WithdrawWithinBatch(sdk.WrapSDKContext(ctx), msg) + return sdk.WrapServiceResult(ctx, res, err) + case *types.MsgSwapWithinBatch: + res, err := msgServer.Swap(sdk.WrapSDKContext(ctx), msg) + return sdk.WrapServiceResult(ctx, res, err) + + default: + return nil, errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized %s message type: %T", types.ModuleName, msg) + } + } +} diff --git a/x/liquidity/keeper/batch.go b/x/liquidity/keeper/batch.go new file mode 100644 index 00000000..0032be94 --- /dev/null +++ b/x/liquidity/keeper/batch.go @@ -0,0 +1,285 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + + "github.com/cybercongress/go-cyber/v4/x/liquidity/types" +) + +// DeleteAndInitPoolBatches resets batch msg states that were previously executed +// and deletes msg states that were marked to be deleted. +func (k Keeper) DeleteAndInitPoolBatches(ctx sdk.Context) { + k.IterateAllPoolBatches(ctx, func(poolBatch types.PoolBatch) bool { + // Re-initialize the executed batch. + if poolBatch.Executed { + // On the other hand, BatchDeposit, BatchWithdraw, is all handled by the endblock if there is no error. + // If there are BatchMsgs left, reset the Executed, Succeeded flag so that it can be executed in the next batch. + depositMsgs := k.GetAllRemainingPoolBatchDepositMsgStates(ctx, poolBatch) + if len(depositMsgs) > 0 { + for _, msg := range depositMsgs { + msg.Executed = false + msg.Succeeded = false + } + k.SetPoolBatchDepositMsgStatesByPointer(ctx, poolBatch.PoolId, depositMsgs) + } + + withdrawMsgs := k.GetAllRemainingPoolBatchWithdrawMsgStates(ctx, poolBatch) + if len(withdrawMsgs) > 0 { + for _, msg := range withdrawMsgs { + msg.Executed = false + msg.Succeeded = false + } + k.SetPoolBatchWithdrawMsgStatesByPointer(ctx, poolBatch.PoolId, withdrawMsgs) + } + + height := ctx.BlockHeight() + + // In the case of remaining swap msg states, those are either fractionally matched + // or has not yet been expired. + swapMsgs := k.GetAllRemainingPoolBatchSwapMsgStates(ctx, poolBatch) + if len(swapMsgs) > 0 { + for _, msg := range swapMsgs { + if height > msg.OrderExpiryHeight { + msg.ToBeDeleted = true + } else { + msg.Executed = false + msg.Succeeded = false + } + } + k.SetPoolBatchSwapMsgStatesByPointer(ctx, poolBatch.PoolId, swapMsgs) + } + + // Delete all batch msg states that are ready to be deleted. + k.DeleteAllReadyPoolBatchDepositMsgStates(ctx, poolBatch) + k.DeleteAllReadyPoolBatchWithdrawMsgStates(ctx, poolBatch) + k.DeleteAllReadyPoolBatchSwapMsgStates(ctx, poolBatch) + + if err := k.InitNextPoolBatch(ctx, poolBatch); err != nil { + panic(err) + } + } + return false + }) +} + +// InitNextPoolBatch re-initializes the batch and increases the batch index. +func (k Keeper) InitNextPoolBatch(ctx sdk.Context, poolBatch types.PoolBatch) error { + if !poolBatch.Executed { + return types.ErrBatchNotExecuted + } + + poolBatch.Index++ + poolBatch.BeginHeight = ctx.BlockHeight() + poolBatch.Executed = false + + k.SetPoolBatch(ctx, poolBatch) + return nil +} + +// ExecutePoolBatches executes the accumulated msgs in the batch. +// The order is (1)swap, (2)deposit, (3)withdraw. +func (k Keeper) ExecutePoolBatches(ctx sdk.Context) { + params := k.GetParams(ctx) + logger := k.Logger(ctx) + + k.IterateAllPoolBatches(ctx, func(poolBatch types.PoolBatch) bool { + if !poolBatch.Executed && ctx.BlockHeight()%int64(params.UnitBatchHeight) == 0 { + executedMsgCount, err := k.SwapExecution(ctx, poolBatch) + if err != nil { + panic(err) + } + + k.IterateAllPoolBatchDepositMsgStates(ctx, poolBatch, func(batchMsg types.DepositMsgState) bool { + if batchMsg.Executed || batchMsg.ToBeDeleted || batchMsg.Succeeded { + return false + } + executedMsgCount++ + if err := k.ExecuteDeposit(ctx, batchMsg, poolBatch); err != nil { + logger.Error("deposit failed", + "poolID", poolBatch.PoolId, + "batchIndex", poolBatch.Index, + "msgIndex", batchMsg.MsgIndex, + "depositor", batchMsg.Msg.GetDepositor(), + "error", err) + if err := k.RefundDeposit(ctx, batchMsg, poolBatch); err != nil { + panic(err) + } + } + return false + }) + + k.IterateAllPoolBatchWithdrawMsgStates(ctx, poolBatch, func(batchMsg types.WithdrawMsgState) bool { + if batchMsg.Executed || batchMsg.ToBeDeleted || batchMsg.Succeeded { + return false + } + executedMsgCount++ + if err := k.ExecuteWithdrawal(ctx, batchMsg, poolBatch); err != nil { + logger.Error("withdraw failed", + "poolID", poolBatch.PoolId, + "batchIndex", poolBatch.Index, + "msgIndex", batchMsg.MsgIndex, + "withdrawer", batchMsg.Msg.GetWithdrawer(), + "error", err) + if err := k.RefundWithdrawal(ctx, batchMsg, poolBatch); err != nil { + panic(err) + } + } + return false + }) + + // Mark the batch as executed when any msgs were executed. + if executedMsgCount > 0 { + poolBatch.Executed = true + k.SetPoolBatch(ctx, poolBatch) + } + } + return false + }) +} + +// HoldEscrow sends coins to the module account for an escrow. +func (k Keeper) HoldEscrow(ctx sdk.Context, depositor sdk.AccAddress, depositCoins sdk.Coins) error { + err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, depositor, types.ModuleName, depositCoins) + return err +} + +// If batch messages have expired or have not been processed, coins that were deposited with this function are refunded to the escrow. +func (k Keeper) ReleaseEscrow(ctx sdk.Context, withdrawer sdk.AccAddress, withdrawCoins sdk.Coins) error { + err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, withdrawer, withdrawCoins) + return err +} + +// Generate inputs and outputs to treat escrow refunds atomically. +func (k Keeper) ReleaseEscrowForMultiSend(withdrawer sdk.AccAddress, withdrawCoins sdk.Coins) ( + banktypes.Input, banktypes.Output, error, +) { + var input banktypes.Input + var output banktypes.Output + + input = banktypes.NewInput(k.accountKeeper.GetModuleAddress(types.ModuleName), withdrawCoins) + output = banktypes.NewOutput(withdrawer, withdrawCoins) + + if err := banktypes.ValidateInputsOutputs([]banktypes.Input{input}, []banktypes.Output{output}); err != nil { + return banktypes.Input{}, banktypes.Output{}, err + } + + return input, output, nil +} + +// In order to deal with the batch at the same time, the coins of msgs are deposited in escrow. +func (k Keeper) DepositWithinBatch(ctx sdk.Context, msg *types.MsgDepositWithinBatch) (types.DepositMsgState, error) { + if err := k.ValidateMsgDepositWithinBatch(ctx, *msg); err != nil { + return types.DepositMsgState{}, err + } + + poolBatch, found := k.GetPoolBatch(ctx, msg.PoolId) + if !found { + return types.DepositMsgState{}, types.ErrPoolBatchNotExists + } + + if poolBatch.BeginHeight == 0 { + poolBatch.BeginHeight = ctx.BlockHeight() + } + + msgState := types.DepositMsgState{ + MsgHeight: ctx.BlockHeight(), + MsgIndex: poolBatch.DepositMsgIndex, + Msg: msg, + } + + if err := k.HoldEscrow(ctx, msg.GetDepositor(), msg.DepositCoins); err != nil { + return types.DepositMsgState{}, err + } + + poolBatch.DepositMsgIndex++ + k.SetPoolBatch(ctx, poolBatch) + k.SetPoolBatchDepositMsgState(ctx, poolBatch.PoolId, msgState) + + return msgState, nil +} + +// In order to deal with the batch at the same time, the coins of msgs are deposited in escrow. +func (k Keeper) WithdrawWithinBatch(ctx sdk.Context, msg *types.MsgWithdrawWithinBatch) (types.WithdrawMsgState, error) { + if err := k.ValidateMsgWithdrawWithinBatch(ctx, *msg); err != nil { + return types.WithdrawMsgState{}, err + } + + poolBatch, found := k.GetPoolBatch(ctx, msg.PoolId) + if !found { + return types.WithdrawMsgState{}, types.ErrPoolBatchNotExists + } + + if poolBatch.BeginHeight == 0 { + poolBatch.BeginHeight = ctx.BlockHeight() + } + + batchPoolMsg := types.WithdrawMsgState{ + MsgHeight: ctx.BlockHeight(), + MsgIndex: poolBatch.WithdrawMsgIndex, + Msg: msg, + } + + if err := k.HoldEscrow(ctx, msg.GetWithdrawer(), sdk.NewCoins(msg.PoolCoin)); err != nil { + return types.WithdrawMsgState{}, err + } + + poolBatch.WithdrawMsgIndex++ + k.SetPoolBatch(ctx, poolBatch) + k.SetPoolBatchWithdrawMsgState(ctx, poolBatch.PoolId, batchPoolMsg) + + return batchPoolMsg, nil +} + +// In order to deal with the batch at the same time, the coins of msgs are deposited in escrow. +func (k Keeper) SwapWithinBatch(ctx sdk.Context, msg *types.MsgSwapWithinBatch, orderExpirySpanHeight int64) (*types.SwapMsgState, error) { + pool, found := k.GetPool(ctx, msg.PoolId) + if !found { + return nil, types.ErrPoolNotExists + } + if k.IsDepletedPool(ctx, pool) { + return nil, types.ErrDepletedPool + } + if err := k.ValidateMsgSwapWithinBatch(ctx, *msg, pool); err != nil { + return nil, err + } + poolBatch, found := k.GetPoolBatch(ctx, msg.PoolId) + if !found { + return nil, types.ErrPoolBatchNotExists + } + + if poolBatch.BeginHeight == 0 { + poolBatch.BeginHeight = ctx.BlockHeight() + } + + currentHeight := ctx.BlockHeight() + + if orderExpirySpanHeight == 0 { + params := k.GetParams(ctx) + u := int64(params.UnitBatchHeight) + orderExpirySpanHeight = (u - currentHeight%u) % u + } + + batchPoolMsg := types.SwapMsgState{ + MsgHeight: currentHeight, + MsgIndex: poolBatch.SwapMsgIndex, + Executed: false, + Succeeded: false, + ToBeDeleted: false, + OrderExpiryHeight: currentHeight + orderExpirySpanHeight, + ExchangedOfferCoin: sdk.NewCoin(msg.OfferCoin.Denom, sdk.ZeroInt()), + RemainingOfferCoin: msg.OfferCoin, + ReservedOfferCoinFee: msg.OfferCoinFee, + Msg: msg, + } + + if err := k.HoldEscrow(ctx, msg.GetSwapRequester(), sdk.NewCoins(msg.OfferCoin.Add(msg.OfferCoinFee))); err != nil { + return nil, err + } + + poolBatch.SwapMsgIndex++ + k.SetPoolBatch(ctx, poolBatch) + k.SetPoolBatchSwapMsgState(ctx, poolBatch.PoolId, batchPoolMsg) + + return &batchPoolMsg, nil +} diff --git a/x/liquidity/keeper/genesis.go b/x/liquidity/keeper/genesis.go new file mode 100644 index 00000000..d5186b29 --- /dev/null +++ b/x/liquidity/keeper/genesis.go @@ -0,0 +1,61 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/cybercongress/go-cyber/v4/x/liquidity/types" +) + +// InitGenesis initializes the liquidity module's state from a given genesis state. +func (k Keeper) InitGenesis(ctx sdk.Context, genState types.GenesisState) { + if err := k.ValidateGenesis(ctx, genState); err != nil { + panic(err) + } + + k.SetParams(ctx, genState.Params) + + for _, record := range genState.PoolRecords { + k.SetPoolRecord(ctx, record) + } +} + +// ExportGenesis returns the liquidity module's genesis state. +func (k Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { + params := k.GetParams(ctx) + + var poolRecords []types.PoolRecord + + pools := k.GetAllPools(ctx) + + for _, pool := range pools { + record, found := k.GetPoolRecord(ctx, pool) + if found { + poolRecords = append(poolRecords, record) + } + } + + if len(poolRecords) == 0 { + poolRecords = []types.PoolRecord{} + } + + return types.NewGenesisState(params, poolRecords) +} + +// ValidateGenesis validates the liquidity module's genesis state. +func (k Keeper) ValidateGenesis(ctx sdk.Context, genState types.GenesisState) error { + if err := genState.Params.Validate(); err != nil { + return err + } + + cc, _ := ctx.CacheContext() + k.SetParams(cc, genState.Params) + + for _, record := range genState.PoolRecords { + record = k.SetPoolRecord(cc, record) + if err := k.ValidatePoolRecord(cc, record); err != nil { + return err + } + } + + return nil +} diff --git a/x/liquidity/keeper/grpc_query.go b/x/liquidity/keeper/grpc_query.go new file mode 100644 index 00000000..f42a234d --- /dev/null +++ b/x/liquidity/keeper/grpc_query.go @@ -0,0 +1,327 @@ +package keeper + +// DONTCOVER +// client is excluded from test coverage in the poc phase milestone 1 and will be included in milestone 2 with completeness + +import ( + "context" + + "github.com/cosmos/cosmos-sdk/store/prefix" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/query" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/cybercongress/go-cyber/v4/x/liquidity/types" +) + +// Querier is used as Keeper will have duplicate methods if used directly, and gRPC names take precedence over keeper. +type Querier struct { + Keeper +} + +var _ types.QueryServer = Querier{} + +// LiquidityPool queries a liquidity pool with the given pool id. +func (k Querier) LiquidityPool(c context.Context, req *types.QueryLiquidityPoolRequest) (*types.QueryLiquidityPoolResponse, error) { + empty := &types.QueryLiquidityPoolRequest{} + if req == nil || *req == *empty { + return nil, status.Errorf(codes.InvalidArgument, "empty request") + } + + ctx := sdk.UnwrapSDKContext(c) + + pool, found := k.GetPool(ctx, req.PoolId) + if !found { + return nil, status.Errorf(codes.NotFound, "liquidity pool %d doesn't exist", req.PoolId) + } + + return k.MakeQueryLiquidityPoolResponse(pool) +} + +// LiquidityPool queries a liquidity pool with the given pool coin denom. +func (k Querier) LiquidityPoolByPoolCoinDenom(c context.Context, req *types.QueryLiquidityPoolByPoolCoinDenomRequest) (*types.QueryLiquidityPoolResponse, error) { + empty := &types.QueryLiquidityPoolByPoolCoinDenomRequest{} + if req == nil || *req == *empty { + return nil, status.Errorf(codes.InvalidArgument, "empty request") + } + ctx := sdk.UnwrapSDKContext(c) + reserveAcc, err := types.GetReserveAcc(req.PoolCoinDenom, false) + if err != nil { + return nil, status.Errorf(codes.NotFound, "liquidity pool with pool coin denom %s doesn't exist", req.PoolCoinDenom) + } + pool, found := k.GetPoolByReserveAccIndex(ctx, reserveAcc) + if !found { + return nil, status.Errorf(codes.NotFound, "liquidity pool with pool coin denom %s doesn't exist", req.PoolCoinDenom) + } + return k.MakeQueryLiquidityPoolResponse(pool) +} + +// LiquidityPool queries a liquidity pool with the given reserve account address. +func (k Querier) LiquidityPoolByReserveAcc(c context.Context, req *types.QueryLiquidityPoolByReserveAccRequest) (*types.QueryLiquidityPoolResponse, error) { + empty := &types.QueryLiquidityPoolByReserveAccRequest{} + if req == nil || *req == *empty { + return nil, status.Errorf(codes.InvalidArgument, "empty request") + } + ctx := sdk.UnwrapSDKContext(c) + reserveAcc, err := sdk.AccAddressFromBech32(req.ReserveAcc) + if err != nil { + return nil, status.Errorf(codes.NotFound, "the reserve account address %s is not valid", req.ReserveAcc) + } + pool, found := k.GetPoolByReserveAccIndex(ctx, reserveAcc) + if !found { + return nil, status.Errorf(codes.NotFound, "liquidity pool with pool reserve account %s doesn't exist", req.ReserveAcc) + } + return k.MakeQueryLiquidityPoolResponse(pool) +} + +// LiquidityPoolBatch queries a liquidity pool batch with the given pool id. +func (k Querier) LiquidityPoolBatch(c context.Context, req *types.QueryLiquidityPoolBatchRequest) (*types.QueryLiquidityPoolBatchResponse, error) { + empty := &types.QueryLiquidityPoolBatchRequest{} + if req == nil || *req == *empty { + return nil, status.Errorf(codes.InvalidArgument, "empty request") + } + + ctx := sdk.UnwrapSDKContext(c) + + batch, found := k.GetPoolBatch(ctx, req.PoolId) + if !found { + return nil, status.Errorf(codes.NotFound, "liquidity pool batch %d doesn't exist", req.PoolId) + } + + return &types.QueryLiquidityPoolBatchResponse{ + Batch: batch, + }, nil +} + +// Pools queries all liquidity pools currently existed with each liquidity pool with batch and metadata. +func (k Querier) LiquidityPools(c context.Context, req *types.QueryLiquidityPoolsRequest) (*types.QueryLiquidityPoolsResponse, error) { + ctx := sdk.UnwrapSDKContext(c) + + store := ctx.KVStore(k.storeKey) + poolStore := prefix.NewStore(store, types.PoolKeyPrefix) + + var pools types.Pools + + pageRes, err := query.Paginate(poolStore, req.Pagination, func(key []byte, value []byte) error { + pool, err := types.UnmarshalPool(k.cdc, value) + if err != nil { + return err + } + pools = append(pools, pool) + return nil + }) + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + + if len(pools) == 0 { + return nil, status.Error(codes.NotFound, "There are no pools present.") + } + + return &types.QueryLiquidityPoolsResponse{ + Pools: pools, + Pagination: pageRes, + }, nil +} + +// PoolBatchSwapMsg queries the pool batch swap message with the message index of the liquidity pool. +func (k Querier) PoolBatchSwapMsg(c context.Context, req *types.QueryPoolBatchSwapMsgRequest) (*types.QueryPoolBatchSwapMsgResponse, error) { + empty := &types.QueryPoolBatchSwapMsgRequest{} + if req == nil || *req == *empty { + return nil, status.Errorf(codes.InvalidArgument, "empty request") + } + + ctx := sdk.UnwrapSDKContext(c) + + msg, found := k.GetPoolBatchSwapMsgState(ctx, req.PoolId, req.MsgIndex) + if !found { + return nil, status.Errorf(codes.NotFound, "the msg given msg_index %d doesn't exist or deleted", req.MsgIndex) + } + + return &types.QueryPoolBatchSwapMsgResponse{ + Swap: msg, + }, nil +} + +// PoolBatchSwapMsgs queries all pool batch swap messages of the liquidity pool. +func (k Querier) PoolBatchSwapMsgs(c context.Context, req *types.QueryPoolBatchSwapMsgsRequest) (*types.QueryPoolBatchSwapMsgsResponse, error) { + empty := &types.QueryPoolBatchSwapMsgsRequest{} + if req == nil || *req == *empty { + return nil, status.Errorf(codes.InvalidArgument, "empty request") + } + + ctx := sdk.UnwrapSDKContext(c) + + _, found := k.GetPool(ctx, req.PoolId) + if !found { + return nil, status.Errorf(codes.NotFound, "liquidity pool %d doesn't exist", req.PoolId) + } + + store := ctx.KVStore(k.storeKey) + msgStore := prefix.NewStore(store, types.GetPoolBatchSwapMsgStatesPrefix(req.PoolId)) + + var msgs []types.SwapMsgState + + pageRes, err := query.Paginate(msgStore, req.Pagination, func(key []byte, value []byte) error { + msg, err := types.UnmarshalSwapMsgState(k.cdc, value) + if err != nil { + return err + } + + msgs = append(msgs, msg) + + return nil + }) + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + + return &types.QueryPoolBatchSwapMsgsResponse{ + Swaps: msgs, + Pagination: pageRes, + }, nil +} + +// PoolBatchDepositMsg queries the pool batch deposit message with the msg_index of the liquidity pool. +func (k Querier) PoolBatchDepositMsg(c context.Context, req *types.QueryPoolBatchDepositMsgRequest) (*types.QueryPoolBatchDepositMsgResponse, error) { + empty := &types.QueryPoolBatchDepositMsgRequest{} + if req == nil || *req == *empty { + return nil, status.Errorf(codes.InvalidArgument, "empty request") + } + + ctx := sdk.UnwrapSDKContext(c) + + msg, found := k.GetPoolBatchDepositMsgState(ctx, req.PoolId, req.MsgIndex) + if !found { + return nil, status.Errorf(codes.NotFound, "the msg given msg_index %d doesn't exist or deleted", req.MsgIndex) + } + + return &types.QueryPoolBatchDepositMsgResponse{ + Deposit: msg, + }, nil +} + +// PoolBatchDepositMsgs queries all pool batch deposit messages of the liquidity pool. +func (k Querier) PoolBatchDepositMsgs(c context.Context, req *types.QueryPoolBatchDepositMsgsRequest) (*types.QueryPoolBatchDepositMsgsResponse, error) { + empty := &types.QueryPoolBatchDepositMsgsRequest{} + if req == nil || *req == *empty { + return nil, status.Errorf(codes.InvalidArgument, "empty request") + } + + ctx := sdk.UnwrapSDKContext(c) + + _, found := k.GetPool(ctx, req.PoolId) + if !found { + return nil, status.Errorf(codes.NotFound, "liquidity pool %d doesn't exist", req.PoolId) + } + + store := ctx.KVStore(k.storeKey) + msgStore := prefix.NewStore(store, types.GetPoolBatchDepositMsgStatesPrefix(req.PoolId)) + var msgs []types.DepositMsgState + + pageRes, err := query.Paginate(msgStore, req.Pagination, func(key []byte, value []byte) error { + msg, err := types.UnmarshalDepositMsgState(k.cdc, value) + if err != nil { + return err + } + + msgs = append(msgs, msg) + + return nil + }) + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + + return &types.QueryPoolBatchDepositMsgsResponse{ + Deposits: msgs, + Pagination: pageRes, + }, nil +} + +// PoolBatchWithdrawMsg queries the pool batch withdraw message with the msg_index of the liquidity pool. +func (k Querier) PoolBatchWithdrawMsg(c context.Context, req *types.QueryPoolBatchWithdrawMsgRequest) (*types.QueryPoolBatchWithdrawMsgResponse, error) { + empty := &types.QueryPoolBatchWithdrawMsgRequest{} + if req == nil || *req == *empty { + return nil, status.Errorf(codes.InvalidArgument, "empty request") + } + + ctx := sdk.UnwrapSDKContext(c) + + msg, found := k.GetPoolBatchWithdrawMsgState(ctx, req.PoolId, req.MsgIndex) + if !found { + return nil, status.Errorf(codes.NotFound, "the msg given msg_index %d doesn't exist or deleted", req.MsgIndex) + } + + return &types.QueryPoolBatchWithdrawMsgResponse{ + Withdraw: msg, + }, nil +} + +// PoolBatchWithdrawMsgs queries all pool batch withdraw messages of the liquidity pool. +func (k Querier) PoolBatchWithdrawMsgs(c context.Context, req *types.QueryPoolBatchWithdrawMsgsRequest) (*types.QueryPoolBatchWithdrawMsgsResponse, error) { + empty := &types.QueryPoolBatchWithdrawMsgsRequest{} + if req == nil || *req == *empty { + return nil, status.Errorf(codes.InvalidArgument, "empty request") + } + + ctx := sdk.UnwrapSDKContext(c) + + _, found := k.GetPool(ctx, req.PoolId) + if !found { + return nil, status.Errorf(codes.NotFound, "liquidity pool %d doesn't exist", req.PoolId) + } + + store := ctx.KVStore(k.storeKey) + msgStore := prefix.NewStore(store, types.GetPoolBatchWithdrawMsgsPrefix(req.PoolId)) + var msgs []types.WithdrawMsgState + + pageRes, err := query.Paginate(msgStore, req.Pagination, func(key []byte, value []byte) error { + msg, err := types.UnmarshalWithdrawMsgState(k.cdc, value) + if err != nil { + return err + } + + msgs = append(msgs, msg) + + return nil + }) + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + + return &types.QueryPoolBatchWithdrawMsgsResponse{ + Withdraws: msgs, + Pagination: pageRes, + }, nil +} + +// Params queries params of liquidity module. +func (k Querier) Params(c context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { + ctx := sdk.UnwrapSDKContext(c) + params := k.GetParams(ctx) + + return &types.QueryParamsResponse{ + Params: params, + }, nil +} + +// MakeQueryLiquidityPoolResponse wraps MakeQueryLiquidityPoolResponse. +func (k Querier) MakeQueryLiquidityPoolResponse(pool types.Pool) (*types.QueryLiquidityPoolResponse, error) { + return &types.QueryLiquidityPoolResponse{ + Pool: pool, + }, nil +} + +// MakeQueryLiquidityPoolsResponse wraps a list of QueryLiquidityPoolResponses. +func (k Querier) MakeQueryLiquidityPoolsResponse(pools types.Pools) (*[]types.QueryLiquidityPoolResponse, error) { + resp := make([]types.QueryLiquidityPoolResponse, len(pools)) + for i, pool := range pools { + res := types.QueryLiquidityPoolResponse{ + Pool: pool, + } + resp[i] = res + } + return &resp, nil +} diff --git a/x/liquidity/keeper/invariants.go b/x/liquidity/keeper/invariants.go new file mode 100644 index 00000000..e8adda79 --- /dev/null +++ b/x/liquidity/keeper/invariants.go @@ -0,0 +1,389 @@ +package keeper + +import ( + "fmt" + + "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/cybercongress/go-cyber/v4/x/liquidity/types" +) + +// RegisterInvariants registers all liquidity invariants. +func RegisterInvariants(ir sdk.InvariantRegistry, k Keeper) { + ir.RegisterRoute(types.ModuleName, "escrow-amount", + LiquidityPoolsEscrowAmountInvariant(k)) +} + +// AllInvariants runs all invariants of the liquidity module. +func AllInvariants(k Keeper) sdk.Invariant { + return func(ctx sdk.Context) (string, bool) { + res, stop := LiquidityPoolsEscrowAmountInvariant(k)(ctx) + return res, stop + } +} + +// LiquidityPoolsEscrowAmountInvariant checks that outstanding unwithdrawn fees are never negative. +func LiquidityPoolsEscrowAmountInvariant(k Keeper) sdk.Invariant { + return func(ctx sdk.Context) (string, bool) { + remainingCoins := sdk.NewCoins() + batches := k.GetAllPoolBatches(ctx) + for _, batch := range batches { + swapMsgs := k.GetAllPoolBatchSwapMsgStatesNotToBeDeleted(ctx, batch) + for _, msg := range swapMsgs { + remainingCoins = remainingCoins.Add(msg.RemainingOfferCoin) + } + depositMsgs := k.GetAllPoolBatchDepositMsgStatesNotToBeDeleted(ctx, batch) + for _, msg := range depositMsgs { + remainingCoins = remainingCoins.Add(msg.Msg.DepositCoins...) + } + withdrawMsgs := k.GetAllPoolBatchWithdrawMsgStatesNotToBeDeleted(ctx, batch) + for _, msg := range withdrawMsgs { + remainingCoins = remainingCoins.Add(msg.Msg.PoolCoin) + } + } + + batchEscrowAcc := k.accountKeeper.GetModuleAddress(types.ModuleName) + escrowAmt := k.bankKeeper.GetAllBalances(ctx, batchEscrowAcc) + + broken := !escrowAmt.IsAllGTE(remainingCoins) + + return sdk.FormatInvariant(types.ModuleName, "batch escrow amount invariant broken", + "batch escrow amount LT batch remaining amount"), broken + } +} + +// These invariants cannot be registered via RegisterInvariants since the module uses per-block batch execution. +// We should approach adding these invariant checks inside actual logics of deposit / withdraw / swap. + +var ( + BatchLogicInvariantCheckFlag = false // It is only used at the development stage, and is disabled at the product level. + // For coin amounts less than coinAmountThreshold, a high errorRate does not mean + // that the calculation logic has errors. + // For example, if there were two X coins and three Y coins in the pool, and someone deposits + // one X coin and one Y coin, it's an acceptable input. + // But pool price would change from 2/3 to 3/4 so errorRate will report 1/8(=0.125), + // meaning that the price has changed by 12.5%. + // This happens with small coin amounts, so there should be a threshold for coin amounts + // before we calculate the errorRate. + errorRateThreshold = sdk.NewDecWithPrec(5, 2) // 5% + coinAmountThreshold = sdk.NewInt(20) // If a decimal error occurs at a value less than 20, the error rate is over 5%. +) + +func errorRate(expected, actual sdk.Dec) sdk.Dec { + // To prevent divide-by-zero panics, return 1.0(=100%) as the error rate + // when the expected value is 0. + if expected.IsZero() { + return sdk.OneDec() + } + return actual.Sub(expected).Quo(expected).Abs() +} + +// MintingPoolCoinsInvariant checks the correct ratio of minting amount of pool coins. +func MintingPoolCoinsInvariant(poolCoinTotalSupply, mintPoolCoin, depositCoinA, depositCoinB, lastReserveCoinA, lastReserveCoinB, refundedCoinA, refundedCoinB math.Int) { + if !refundedCoinA.IsZero() { + depositCoinA = depositCoinA.Sub(refundedCoinA) + } + + if !refundedCoinB.IsZero() { + depositCoinB = depositCoinB.Sub(refundedCoinB) + } + + poolCoinRatio := sdk.NewDecFromInt(mintPoolCoin).QuoInt(poolCoinTotalSupply) + depositCoinARatio := sdk.NewDecFromInt(depositCoinA).QuoInt(lastReserveCoinA) + depositCoinBRatio := sdk.NewDecFromInt(depositCoinB).QuoInt(lastReserveCoinB) + expectedMintPoolCoinAmtBasedA := depositCoinARatio.MulInt(poolCoinTotalSupply).TruncateInt() + expectedMintPoolCoinAmtBasedB := depositCoinBRatio.MulInt(poolCoinTotalSupply).TruncateInt() + + // NewPoolCoinAmount / LastPoolCoinSupply == AfterRefundedDepositCoinA / LastReserveCoinA + // NewPoolCoinAmount / LastPoolCoinSupply == AfterRefundedDepositCoinA / LastReserveCoinB + if depositCoinA.GTE(coinAmountThreshold) && depositCoinB.GTE(coinAmountThreshold) && + lastReserveCoinA.GTE(coinAmountThreshold) && lastReserveCoinB.GTE(coinAmountThreshold) && + mintPoolCoin.GTE(coinAmountThreshold) && poolCoinTotalSupply.GTE(coinAmountThreshold) { + if errorRate(depositCoinARatio, poolCoinRatio).GT(errorRateThreshold) || + errorRate(depositCoinBRatio, poolCoinRatio).GT(errorRateThreshold) { + panic("invariant check fails due to incorrect ratio of pool coins") + } + } + + if mintPoolCoin.GTE(coinAmountThreshold) && + (sdk.NewDecFromInt(sdk.MaxInt(mintPoolCoin, expectedMintPoolCoinAmtBasedA).Sub(sdk.MinInt(mintPoolCoin, expectedMintPoolCoinAmtBasedA))).QuoInt(mintPoolCoin).GT(errorRateThreshold) || + sdk.NewDecFromInt(sdk.MaxInt(mintPoolCoin, expectedMintPoolCoinAmtBasedB).Sub(sdk.MinInt(mintPoolCoin, expectedMintPoolCoinAmtBasedA))).QuoInt(mintPoolCoin).GT(errorRateThreshold)) { + panic("invariant check fails due to incorrect amount of pool coins") + } +} + +// DepositInvariant checks after deposit amounts. +// +//nolint:staticcheck +func DepositInvariant(lastReserveCoinA, lastReserveCoinB, depositCoinA, depositCoinB, afterReserveCoinA, afterReserveCoinB, refundedCoinA, refundedCoinB math.Int) { + depositCoinA = depositCoinA.Sub(refundedCoinA) + depositCoinB = depositCoinB.Sub(refundedCoinB) + + depositCoinRatio := sdk.NewDecFromInt(depositCoinA).Quo(sdk.NewDecFromInt(depositCoinB)) + lastReserveRatio := sdk.NewDecFromInt(lastReserveCoinA).Quo(sdk.NewDecFromInt(lastReserveCoinB)) + afterReserveRatio := sdk.NewDecFromInt(afterReserveCoinA).Quo(sdk.NewDecFromInt(afterReserveCoinB)) + + // AfterDepositReserveCoinA = LastReserveCoinA + AfterRefundedDepositCoinA + // AfterDepositReserveCoinB = LastReserveCoinB + AfterRefundedDepositCoinA + if !afterReserveCoinA.Equal(lastReserveCoinA.Add(depositCoinA)) || + !afterReserveCoinB.Equal(lastReserveCoinB.Add(depositCoinB)) { + panic("invariant check fails due to incorrect deposit amounts") + } + + if depositCoinA.GTE(coinAmountThreshold) && depositCoinB.GTE(coinAmountThreshold) && + lastReserveCoinA.GTE(coinAmountThreshold) && lastReserveCoinB.GTE(coinAmountThreshold) { + // AfterRefundedDepositCoinA / AfterRefundedDepositCoinA = LastReserveCoinA / LastReserveCoinB + if errorRate(lastReserveRatio, depositCoinRatio).GT(errorRateThreshold) { + panic("invariant check fails due to incorrect deposit ratio") + } + // LastReserveCoinA / LastReserveCoinB = AfterDepositReserveCoinA / AfterDepositReserveCoinB + if errorRate(lastReserveRatio, afterReserveRatio).GT(errorRateThreshold) { + panic("invariant check fails due to incorrect pool price ratio") + } + } +} + +// BurningPoolCoinsInvariant checks the correct burning amount of pool coins. +// +//nolint:staticcheck +func BurningPoolCoinsInvariant(burnedPoolCoin, withdrawCoinA, withdrawCoinB, reserveCoinA, reserveCoinB, lastPoolCoinSupply math.Int, withdrawFeeCoins sdk.Coins) { + burningPoolCoinRatio := sdk.NewDecFromInt(burnedPoolCoin).Quo(sdk.NewDecFromInt(lastPoolCoinSupply)) + if burningPoolCoinRatio.Equal(sdk.OneDec()) { + return + } + + withdrawCoinARatio := sdk.NewDecFromInt(withdrawCoinA.Add(withdrawFeeCoins[0].Amount)).Quo(sdk.NewDecFromInt(reserveCoinA)) + withdrawCoinBRatio := sdk.NewDecFromInt(withdrawCoinB.Add(withdrawFeeCoins[1].Amount)).Quo(sdk.NewDecFromInt(reserveCoinB)) + + // BurnedPoolCoinAmount / LastPoolCoinSupply >= (WithdrawCoinA+WithdrawFeeCoinA) / LastReserveCoinA + // BurnedPoolCoinAmount / LastPoolCoinSupply >= (WithdrawCoinB+WithdrawFeeCoinB) / LastReserveCoinB + if withdrawCoinARatio.GT(burningPoolCoinRatio) || withdrawCoinBRatio.GT(burningPoolCoinRatio) { + panic("invariant check fails due to incorrect ratio of burning pool coins") + } + + expectedBurningPoolCoinBasedA := sdk.NewDecFromInt(lastPoolCoinSupply).MulTruncate(withdrawCoinARatio).TruncateInt() + expectedBurningPoolCoinBasedB := sdk.NewDecFromInt(lastPoolCoinSupply).MulTruncate(withdrawCoinBRatio).TruncateInt() + + if burnedPoolCoin.GTE(coinAmountThreshold) && + (sdk.NewDecFromInt(sdk.MaxInt(burnedPoolCoin, expectedBurningPoolCoinBasedA).Sub(sdk.MinInt(burnedPoolCoin, expectedBurningPoolCoinBasedA))).QuoInt(burnedPoolCoin).GT(errorRateThreshold) || + sdk.NewDecFromInt(sdk.MaxInt(burnedPoolCoin, expectedBurningPoolCoinBasedB).Sub(sdk.MinInt(burnedPoolCoin, expectedBurningPoolCoinBasedB))).QuoInt(burnedPoolCoin).GT(errorRateThreshold)) { + panic("invariant check fails due to incorrect amount of burning pool coins") + } +} + +// WithdrawReserveCoinsInvariant checks the after withdraw amounts. +// +//nolint:staticcheck +func WithdrawReserveCoinsInvariant(withdrawCoinA, withdrawCoinB, reserveCoinA, reserveCoinB, + afterReserveCoinA, afterReserveCoinB, afterPoolCoinTotalSupply, lastPoolCoinSupply, burnedPoolCoin math.Int, +) { + // AfterWithdrawReserveCoinA = LastReserveCoinA - WithdrawCoinA + if !afterReserveCoinA.Equal(reserveCoinA.Sub(withdrawCoinA)) { + panic("invariant check fails due to incorrect withdraw coin A amount") + } + + // AfterWithdrawReserveCoinB = LastReserveCoinB - WithdrawCoinB + if !afterReserveCoinB.Equal(reserveCoinB.Sub(withdrawCoinB)) { + panic("invariant check fails due to incorrect withdraw coin B amount") + } + + // AfterWithdrawPoolCoinSupply = LastPoolCoinSupply - BurnedPoolCoinAmount + if !afterPoolCoinTotalSupply.Equal(lastPoolCoinSupply.Sub(burnedPoolCoin)) { + panic("invariant check fails due to incorrect total supply") + } +} + +// WithdrawAmountInvariant checks the correct ratio of withdraw coin amounts. +// +//nolint:staticcheck +func WithdrawAmountInvariant(withdrawCoinA, withdrawCoinB, reserveCoinA, reserveCoinB, burnedPoolCoin, poolCoinSupply math.Int, withdrawFeeRate sdk.Dec) { + ratio := sdk.NewDecFromInt(burnedPoolCoin).Quo(sdk.NewDecFromInt(poolCoinSupply)).Mul(sdk.OneDec().Sub(withdrawFeeRate)) + idealWithdrawCoinA := sdk.NewDecFromInt(reserveCoinA).Mul(ratio) + idealWithdrawCoinB := sdk.NewDecFromInt(reserveCoinB).Mul(ratio) + diffA := idealWithdrawCoinA.Sub(sdk.NewDecFromInt(withdrawCoinA)).Abs() + diffB := idealWithdrawCoinB.Sub(sdk.NewDecFromInt(withdrawCoinB)).Abs() + if !burnedPoolCoin.Equal(poolCoinSupply) { + if diffA.GTE(sdk.OneDec()) { + panic(fmt.Sprintf("withdraw coin amount %v differs too much from %v", withdrawCoinA, idealWithdrawCoinA)) + } + if diffB.GTE(sdk.OneDec()) { + panic(fmt.Sprintf("withdraw coin amount %v differs too much from %v", withdrawCoinB, idealWithdrawCoinB)) + } + } +} + +// ImmutablePoolPriceAfterWithdrawInvariant checks the immutable pool price after withdrawing coins. +// +//nolint:staticcheck +func ImmutablePoolPriceAfterWithdrawInvariant(reserveCoinA, reserveCoinB, withdrawCoinA, withdrawCoinB, afterReserveCoinA, afterReserveCoinB math.Int) { + // TestReinitializePool tests a scenario where after reserve coins are zero + if !afterReserveCoinA.IsZero() && !afterReserveCoinB.IsZero() { + reserveCoinA = reserveCoinA.Sub(withdrawCoinA) + reserveCoinB = reserveCoinB.Sub(withdrawCoinB) + + reserveCoinRatio := sdk.NewDecFromInt(reserveCoinA).Quo(sdk.NewDecFromInt(reserveCoinB)) + afterReserveCoinRatio := sdk.NewDecFromInt(afterReserveCoinA).Quo(sdk.NewDecFromInt(afterReserveCoinB)) + + // LastReserveCoinA / LastReserveCoinB = AfterWithdrawReserveCoinA / AfterWithdrawReserveCoinB + if reserveCoinA.GTE(coinAmountThreshold) && reserveCoinB.GTE(coinAmountThreshold) && + withdrawCoinA.GTE(coinAmountThreshold) && withdrawCoinB.GTE(coinAmountThreshold) && + errorRate(reserveCoinRatio, afterReserveCoinRatio).GT(errorRateThreshold) { + panic("invariant check fails due to incorrect pool price ratio") + } + } +} + +// SwapMatchingInvariants checks swap matching results of both X to Y and Y to X cases. +func SwapMatchingInvariants(xToY, yToX []*types.SwapMsgState, matchResultXtoY, matchResultYtoX []types.MatchResult) { + beforeMatchingXtoYLen := len(xToY) + beforeMatchingYtoXLen := len(yToX) + afterMatchingXtoYLen := len(matchResultXtoY) + afterMatchingYtoXLen := len(matchResultYtoX) + + notMatchedXtoYLen := beforeMatchingXtoYLen - afterMatchingXtoYLen + notMatchedYtoXLen := beforeMatchingYtoXLen - afterMatchingYtoXLen + + if notMatchedXtoYLen != types.CountNotMatchedMsgs(xToY) { + panic("invariant check fails due to invalid xToY match length") + } + + if notMatchedYtoXLen != types.CountNotMatchedMsgs(yToX) { + panic("invariant check fails due to invalid yToX match length") + } +} + +// SwapPriceInvariants checks swap price invariants. +func SwapPriceInvariants(matchResultXtoY, matchResultYtoX []types.MatchResult, poolXDelta, poolYDelta, poolXDelta2, poolYDelta2 sdk.Dec, result types.BatchResult) { + invariantCheckX := sdk.ZeroDec() + invariantCheckY := sdk.ZeroDec() + + for _, m := range matchResultXtoY { + invariantCheckX = invariantCheckX.Sub(m.TransactedCoinAmt) + invariantCheckY = invariantCheckY.Add(m.ExchangedDemandCoinAmt) + } + + for _, m := range matchResultYtoX { + invariantCheckY = invariantCheckY.Sub(m.TransactedCoinAmt) + invariantCheckX = invariantCheckX.Add(m.ExchangedDemandCoinAmt) + } + + invariantCheckX = invariantCheckX.Add(poolXDelta2) + invariantCheckY = invariantCheckY.Add(poolYDelta2) + + if !invariantCheckX.IsZero() && !invariantCheckY.IsZero() { + panic(fmt.Errorf("invariant check fails due to invalid swap price: %s", invariantCheckX.String())) + } + + validitySwapPrice := types.CheckSwapPrice(matchResultXtoY, matchResultYtoX, result.SwapPrice) + if !validitySwapPrice { + panic("invariant check fails due to invalid swap price") + } +} + +// SwapPriceDirectionInvariants checks whether the calculated swap price is increased, decreased, or stayed from the last pool price. +func SwapPriceDirectionInvariants(currentPoolPrice sdk.Dec, batchResult types.BatchResult) { + switch batchResult.PriceDirection { + case types.Increasing: + if !batchResult.SwapPrice.GT(currentPoolPrice) { + panic("invariant check fails due to incorrect price direction") + } + case types.Decreasing: + if !batchResult.SwapPrice.LT(currentPoolPrice) { + panic("invariant check fails due to incorrect price direction") + } + case types.Staying: + if !batchResult.SwapPrice.Equal(currentPoolPrice) { + panic("invariant check fails due to incorrect price direction") + } + } +} + +// SwapMsgStatesInvariants checks swap match result states invariants. +func SwapMsgStatesInvariants(matchResultXtoY, matchResultYtoX []types.MatchResult, matchResultMap map[uint64]types.MatchResult, + swapMsgStates []*types.SwapMsgState, xToY, yToX []*types.SwapMsgState, +) { + if len(matchResultXtoY)+len(matchResultYtoX) != len(matchResultMap) { + panic("invalid length of match result") + } + + for k, v := range matchResultMap { + if k != v.SwapMsgState.MsgIndex { + panic("broken map consistency") + } + } + + for _, sms := range swapMsgStates { + for _, smsXtoY := range xToY { + if sms.MsgIndex == smsXtoY.MsgIndex { + if *(sms) != *(smsXtoY) || sms != smsXtoY { + panic("swap message state not matched") + } else { + break + } + } + } + + for _, smsYtoX := range yToX { + if sms.MsgIndex == smsYtoX.MsgIndex { + if *(sms) != *(smsYtoX) || sms != smsYtoX { + panic("swap message state not matched") + } else { + break + } + } + } + + if msgAfter, ok := matchResultMap[sms.MsgIndex]; ok { + if sms.MsgIndex == msgAfter.SwapMsgState.MsgIndex { + if *(sms) != *(msgAfter.SwapMsgState) || sms != msgAfter.SwapMsgState { + panic("batch message not matched") + } + } else { + panic("fail msg pointer consistency") + } + } + } +} + +// SwapOrdersExecutionStateInvariants checks all executed orders have order price which is not "executable" or not "unexecutable". +func SwapOrdersExecutionStateInvariants(matchResultMap map[uint64]types.MatchResult, swapMsgStates []*types.SwapMsgState, + batchResult types.BatchResult, denomX string, +) { + for _, sms := range swapMsgStates { + if _, ok := matchResultMap[sms.MsgIndex]; ok { + if !sms.Executed || !sms.Succeeded { + panic("swap msg state consistency error, matched but not succeeded") + } + + if sms.Msg.OfferCoin.Denom == denomX { + // buy orders having equal or higher order price than found swapPrice + if !sms.Msg.OrderPrice.GTE(batchResult.SwapPrice) { + panic("execution validity failed, executed but unexecutable") + } + } else { + // sell orders having equal or lower order price than found swapPrice + if !sms.Msg.OrderPrice.LTE(batchResult.SwapPrice) { + panic("execution validity failed, executed but unexecutable") + } + } + } else { + // check whether every unexecuted orders have order price which is not "executable" + if sms.Executed && sms.Succeeded { + panic("sms consistency error, not matched but succeeded") + } + + if sms.Msg.OfferCoin.Denom == denomX { + // buy orders having equal or lower order price than found swapPrice + if !sms.Msg.OrderPrice.LTE(batchResult.SwapPrice) { + panic("execution validity failed, unexecuted but executable") + } + } else { + // sell orders having equal or higher order price than found swapPrice + if !sms.Msg.OrderPrice.GTE(batchResult.SwapPrice) { + panic("execution validity failed, unexecuted but executable") + } + } + } + } +} diff --git a/x/liquidity/keeper/keeper.go b/x/liquidity/keeper/keeper.go new file mode 100644 index 00000000..602cf156 --- /dev/null +++ b/x/liquidity/keeper/keeper.go @@ -0,0 +1,85 @@ +package keeper + +import ( + "fmt" + + "github.com/cometbft/cometbft/libs/log" + "github.com/cosmos/cosmos-sdk/codec" + storetypes "github.com/cosmos/cosmos-sdk/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/cybercongress/go-cyber/v4/x/liquidity/types" +) + +// Keeper of the liquidity store +type Keeper struct { + cdc codec.BinaryCodec + storeKey storetypes.StoreKey + bankKeeper types.BankKeeper + accountKeeper types.AccountKeeper + distrKeeper types.DistributionKeeper + + authority string +} + +// NewKeeper returns a liquidity keeper. It handles: +// - creating new ModuleAccounts for each pool ReserveAccount +// - sending to and from ModuleAccounts +// - minting, burning PoolCoins +func NewKeeper( + cdc codec.BinaryCodec, + key storetypes.StoreKey, + bankKeeper types.BankKeeper, + accountKeeper types.AccountKeeper, + distrKeeper types.DistributionKeeper, + authority string, +) Keeper { + // ensure liquidity module account is set + if addr := accountKeeper.GetModuleAddress(types.ModuleName); addr == nil { + panic(fmt.Sprintf("%s module account has not been set", types.ModuleName)) + } + + return Keeper{ + storeKey: key, + bankKeeper: bankKeeper, + accountKeeper: accountKeeper, + distrKeeper: distrKeeper, + cdc: cdc, + authority: authority, + } +} + +// GetAuthority returns the x/mint module's authority. +func (k Keeper) GetAuthority() string { return k.authority } + +func (k Keeper) Logger(ctx sdk.Context) log.Logger { + return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) +} + +func (k Keeper) SetParams(ctx sdk.Context, p types.Params) error { + if err := p.Validate(); err != nil { + return err + } + + store := ctx.KVStore(k.storeKey) + bz := k.cdc.MustMarshal(&p) + store.Set(types.ParamsKey, bz) + + return nil +} + +func (k Keeper) GetParams(ctx sdk.Context) (p types.Params) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.ParamsKey) + if bz == nil { + return p + } + + k.cdc.MustUnmarshal(bz, &p) + return p +} + +// GetCircuitBreakerEnabled returns circuit breaker enabled param from the paramspace. +func (k Keeper) GetCircuitBreakerEnabled(ctx sdk.Context) bool { + return k.GetParams(ctx).CircuitBreakerEnabled +} diff --git a/x/liquidity/keeper/liquidity_pool.go b/x/liquidity/keeper/liquidity_pool.go new file mode 100644 index 00000000..faddafcb --- /dev/null +++ b/x/liquidity/keeper/liquidity_pool.go @@ -0,0 +1,918 @@ +package keeper + +import ( + "fmt" + "strconv" + + errorsmod "cosmossdk.io/errors" + "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + + "github.com/cybercongress/go-cyber/v4/x/liquidity/types" +) + +func (k Keeper) ValidateMsgCreatePool(ctx sdk.Context, msg *types.MsgCreatePool) error { + params := k.GetParams(ctx) + var poolType types.PoolType + + // check poolType exist, get poolType from param + if len(params.PoolTypes) >= int(msg.PoolTypeId) { + poolType = params.PoolTypes[msg.PoolTypeId-1] + if poolType.Id != msg.PoolTypeId { + return types.ErrPoolTypeNotExists + } + } else { + return types.ErrPoolTypeNotExists + } + + reserveCoinNum := uint32(msg.DepositCoins.Len()) + if reserveCoinNum > poolType.MaxReserveCoinNum || poolType.MinReserveCoinNum > reserveCoinNum { + return types.ErrNumOfReserveCoin + } + + reserveCoinDenoms := make([]string, reserveCoinNum) + for i := 0; i < int(reserveCoinNum); i++ { + reserveCoinDenoms[i] = msg.DepositCoins.GetDenomByIndex(i) + } + + denomA, denomB := types.AlphabeticalDenomPair(reserveCoinDenoms[0], reserveCoinDenoms[1]) + if denomA != msg.DepositCoins[0].Denom || denomB != msg.DepositCoins[1].Denom { + return types.ErrBadOrderingReserveCoin + } + + if denomA == denomB { + return types.ErrEqualDenom + } + + if err := types.ValidateReserveCoinLimit(params.MaxReserveCoinAmount, msg.DepositCoins); err != nil { + return err + } + + poolName := types.PoolName(reserveCoinDenoms, msg.PoolTypeId) + reserveAcc := types.GetPoolReserveAcc(poolName, false) + _, found := k.GetPoolByReserveAccIndex(ctx, reserveAcc) + if found { + return types.ErrPoolAlreadyExists + } + return nil +} + +func (k Keeper) MintAndSendPoolCoin(ctx sdk.Context, pool types.Pool, srcAddr, creatorAddr sdk.AccAddress, depositCoins sdk.Coins) (sdk.Coin, error) { + cacheCtx, writeCache := ctx.CacheContext() + + params := k.GetParams(cacheCtx) + + mintingCoin := sdk.NewCoin(pool.PoolCoinDenom, params.InitPoolCoinMintAmount) + mintingCoins := sdk.NewCoins(mintingCoin) + if err := k.bankKeeper.MintCoins(cacheCtx, types.ModuleName, mintingCoins); err != nil { + return sdk.Coin{}, err + } + + reserveAcc := pool.GetReserveAccount() + + var inputs []banktypes.Input + var outputs []banktypes.Output + + inputs = append(inputs, banktypes.NewInput(srcAddr, depositCoins)) + outputs = append(outputs, banktypes.NewOutput(reserveAcc, depositCoins)) + + inputs = append(inputs, banktypes.NewInput(k.accountKeeper.GetModuleAddress(types.ModuleName), mintingCoins)) + outputs = append(outputs, banktypes.NewOutput(creatorAddr, mintingCoins)) + + if err := k.bankKeeper.InputOutputCoins(cacheCtx, inputs, outputs); err != nil { + return sdk.Coin{}, err + } + + writeCache() + + return mintingCoin, nil +} + +func (k Keeper) CreatePool(ctx sdk.Context, msg *types.MsgCreatePool) (types.Pool, error) { + if err := k.ValidateMsgCreatePool(ctx, msg); err != nil { + return types.Pool{}, err + } + + params := k.GetParams(ctx) + + denom1, denom2 := types.AlphabeticalDenomPair(msg.DepositCoins[0].Denom, msg.DepositCoins[1].Denom) + reserveCoinDenoms := []string{denom1, denom2} + + poolName := types.PoolName(reserveCoinDenoms, msg.PoolTypeId) + + pool := types.Pool{ + // Id: will set on SetPoolAtomic + TypeId: msg.PoolTypeId, + ReserveCoinDenoms: reserveCoinDenoms, + ReserveAccountAddress: types.GetPoolReserveAcc(poolName, false).String(), + PoolCoinDenom: types.GetPoolCoinDenom(poolName), + } + + poolCreator := msg.GetPoolCreator() + + for _, coin := range msg.DepositCoins { + if coin.Amount.LT(params.MinInitDepositAmount) { + return types.Pool{}, errorsmod.Wrapf( + types.ErrLessThanMinInitDeposit, "deposit coin %s is smaller than %s", coin, params.MinInitDepositAmount) + } + } + + for _, coin := range msg.DepositCoins { + balance := k.bankKeeper.GetBalance(ctx, poolCreator, coin.Denom) + if balance.IsLT(coin) { + return types.Pool{}, errorsmod.Wrapf( + types.ErrInsufficientBalance, "%s is smaller than %s", balance, coin) + } + } + + for _, coin := range params.PoolCreationFee { + balance := k.bankKeeper.GetBalance(ctx, poolCreator, coin.Denom) + neededAmt := coin.Amount.Add(msg.DepositCoins.AmountOf(coin.Denom)) + neededCoin := sdk.NewCoin(coin.Denom, neededAmt) + if balance.IsLT(neededCoin) { + return types.Pool{}, errorsmod.Wrapf( + types.ErrInsufficientPoolCreationFee, "%s is smaller than %s", balance, neededCoin) + } + } + + if _, err := k.MintAndSendPoolCoin(ctx, pool, poolCreator, poolCreator, msg.DepositCoins); err != nil { + return types.Pool{}, err + } + + // pool creation fees are collected in community pool + if err := k.distrKeeper.FundCommunityPool(ctx, params.PoolCreationFee, poolCreator); err != nil { + return types.Pool{}, err + } + + pool = k.SetPoolAtomic(ctx, pool) + batch := types.NewPoolBatch(pool.Id, 1) + batch.BeginHeight = ctx.BlockHeight() + + k.SetPoolBatch(ctx, batch) + + reserveCoins := k.GetReserveCoins(ctx, pool) + lastReserveRatio := sdk.NewDecFromInt(reserveCoins[0].Amount).Quo(sdk.NewDecFromInt(reserveCoins[1].Amount)) + logger := k.Logger(ctx) + logger.Debug( + "create liquidity pool", + "msg", msg, + "pool", pool, + "reserveCoins", reserveCoins, + "lastReserveRatio", lastReserveRatio, + ) + + return pool, nil +} + +func (k Keeper) ExecuteDeposit(ctx sdk.Context, msg types.DepositMsgState, batch types.PoolBatch) error { + if msg.Executed || msg.ToBeDeleted || msg.Succeeded { + return fmt.Errorf("cannot process already executed batch msg") + } + msg.Executed = true + k.SetPoolBatchDepositMsgState(ctx, msg.Msg.PoolId, msg) + + if err := k.ValidateMsgDepositWithinBatch(ctx, *msg.Msg); err != nil { + return err + } + + pool, found := k.GetPool(ctx, msg.Msg.PoolId) + if !found { + return types.ErrPoolNotExists + } + + depositCoins := msg.Msg.DepositCoins.Sort() + + batchEscrowAcc := k.accountKeeper.GetModuleAddress(types.ModuleName) + reserveAcc := pool.GetReserveAccount() + depositor := msg.Msg.GetDepositor() + + params := k.GetParams(ctx) + + reserveCoins := k.GetReserveCoins(ctx, pool) + + // reinitialize pool if the pool is depleted + if k.IsDepletedPool(ctx, pool) { + for _, depositCoin := range msg.Msg.DepositCoins { + if depositCoin.Amount.Add(reserveCoins.AmountOf(depositCoin.Denom)).LT(params.MinInitDepositAmount) { + return types.ErrLessThanMinInitDeposit + } + } + poolCoin, err := k.MintAndSendPoolCoin(ctx, pool, batchEscrowAcc, depositor, msg.Msg.DepositCoins) + if err != nil { + return err + } + + // set deposit msg state of the pool batch complete + msg.Succeeded = true + msg.ToBeDeleted = true + k.SetPoolBatchDepositMsgState(ctx, msg.Msg.PoolId, msg) + + reserveCoins = k.GetReserveCoins(ctx, pool) + lastReserveCoinA := sdk.NewDecFromInt(reserveCoins[0].Amount) + lastReserveCoinB := sdk.NewDecFromInt(reserveCoins[1].Amount) + lastReserveRatio := lastReserveCoinA.Quo(lastReserveCoinB) + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeDepositToPool, + sdk.NewAttribute(types.AttributeValuePoolId, strconv.FormatUint(pool.Id, 10)), + sdk.NewAttribute(types.AttributeValueBatchIndex, strconv.FormatUint(batch.Index, 10)), + sdk.NewAttribute(types.AttributeValueMsgIndex, strconv.FormatUint(msg.MsgIndex, 10)), + sdk.NewAttribute(types.AttributeValueDepositor, depositor.String()), + sdk.NewAttribute(types.AttributeValueAcceptedCoins, msg.Msg.DepositCoins.String()), + sdk.NewAttribute(types.AttributeValueRefundedCoins, ""), + sdk.NewAttribute(types.AttributeValuePoolCoinDenom, poolCoin.Denom), + sdk.NewAttribute(types.AttributeValuePoolCoinAmount, poolCoin.Amount.String()), + sdk.NewAttribute(types.AttributeValueSuccess, types.Success), + ), + ) + logger := k.Logger(ctx) + logger.Debug( + "reinitialize pool", + "msg", msg, + "pool", pool, + "reserveCoins", reserveCoins, + "lastReserveRatio", lastReserveRatio, + ) + + return nil + } + + reserveCoins.Sort() + + lastReserveCoinA := reserveCoins[0] + lastReserveCoinB := reserveCoins[1] + + depositCoinA := depositCoins[0] + depositCoinB := depositCoins[1] + + poolCoinTotalSupply := sdk.NewDecFromInt(k.GetPoolCoinTotalSupply(ctx, pool)) + if err := types.CheckOverflowWithDec(poolCoinTotalSupply, sdk.NewDecFromInt(depositCoinA.Amount)); err != nil { + return err + } + if err := types.CheckOverflowWithDec(poolCoinTotalSupply, sdk.NewDecFromInt(depositCoinB.Amount)); err != nil { + return err + } + poolCoinMintAmt := sdk.MinDec( + poolCoinTotalSupply.MulTruncate(sdk.NewDecFromInt(depositCoinA.Amount)).QuoTruncate(sdk.NewDecFromInt(lastReserveCoinA.Amount)), + poolCoinTotalSupply.MulTruncate(sdk.NewDecFromInt(depositCoinB.Amount)).QuoTruncate(sdk.NewDecFromInt(lastReserveCoinB.Amount)), + ) + mintRate := poolCoinMintAmt.TruncateDec().QuoTruncate(poolCoinTotalSupply) + acceptedCoins := sdk.NewCoins( + sdk.NewCoin(depositCoins[0].Denom, sdk.NewDecFromInt(lastReserveCoinA.Amount).Mul(mintRate).TruncateInt()), + sdk.NewCoin(depositCoins[1].Denom, sdk.NewDecFromInt(lastReserveCoinB.Amount).Mul(mintRate).TruncateInt()), + ) + refundedCoins := depositCoins.Sub(acceptedCoins...) + refundedCoinA := sdk.NewCoin(depositCoinA.Denom, refundedCoins.AmountOf(depositCoinA.Denom)) + refundedCoinB := sdk.NewCoin(depositCoinB.Denom, refundedCoins.AmountOf(depositCoinB.Denom)) + + mintPoolCoin := sdk.NewCoin(pool.PoolCoinDenom, poolCoinMintAmt.TruncateInt()) + mintPoolCoins := sdk.NewCoins(mintPoolCoin) + + if mintPoolCoins.IsZero() || acceptedCoins.IsZero() { + return fmt.Errorf("pool coin truncated, no accepted coin, refund") + } + + if err := k.bankKeeper.MintCoins(ctx, types.ModuleName, mintPoolCoins); err != nil { + return err + } + + var inputs []banktypes.Input + var outputs []banktypes.Output + + if !refundedCoins.IsZero() { + // refund truncated deposit coins + inputs = append(inputs, banktypes.NewInput(batchEscrowAcc, refundedCoins)) + outputs = append(outputs, banktypes.NewOutput(depositor, refundedCoins)) + } + + // send accepted deposit coins + inputs = append(inputs, banktypes.NewInput(batchEscrowAcc, acceptedCoins)) + outputs = append(outputs, banktypes.NewOutput(reserveAcc, acceptedCoins)) + + // send minted pool coins + inputs = append(inputs, banktypes.NewInput(batchEscrowAcc, mintPoolCoins)) + outputs = append(outputs, banktypes.NewOutput(depositor, mintPoolCoins)) + + // execute multi-send + if err := k.bankKeeper.InputOutputCoins(ctx, inputs, outputs); err != nil { + return err + } + + msg.Succeeded = true + msg.ToBeDeleted = true + k.SetPoolBatchDepositMsgState(ctx, msg.Msg.PoolId, msg) + + if BatchLogicInvariantCheckFlag { + afterReserveCoins := k.GetReserveCoins(ctx, pool) + afterReserveCoinA := afterReserveCoins[0].Amount + afterReserveCoinB := afterReserveCoins[1].Amount + + MintingPoolCoinsInvariant(poolCoinTotalSupply.TruncateInt(), mintPoolCoin.Amount, depositCoinA.Amount, depositCoinB.Amount, + lastReserveCoinA.Amount, lastReserveCoinB.Amount, refundedCoinA.Amount, refundedCoinB.Amount) + DepositInvariant(lastReserveCoinA.Amount, lastReserveCoinB.Amount, depositCoinA.Amount, depositCoinB.Amount, + afterReserveCoinA, afterReserveCoinB, refundedCoinA.Amount, refundedCoinB.Amount) + } + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeDepositToPool, + sdk.NewAttribute(types.AttributeValuePoolId, strconv.FormatUint(pool.Id, 10)), + sdk.NewAttribute(types.AttributeValueBatchIndex, strconv.FormatUint(batch.Index, 10)), + sdk.NewAttribute(types.AttributeValueMsgIndex, strconv.FormatUint(msg.MsgIndex, 10)), + sdk.NewAttribute(types.AttributeValueDepositor, depositor.String()), + sdk.NewAttribute(types.AttributeValueAcceptedCoins, acceptedCoins.String()), + sdk.NewAttribute(types.AttributeValueRefundedCoins, refundedCoins.String()), + sdk.NewAttribute(types.AttributeValuePoolCoinDenom, mintPoolCoin.Denom), + sdk.NewAttribute(types.AttributeValuePoolCoinAmount, mintPoolCoin.Amount.String()), + sdk.NewAttribute(types.AttributeValueSuccess, types.Success), + ), + ) + + reserveCoins = k.GetReserveCoins(ctx, pool) + lastReserveRatio := sdk.NewDecFromInt(reserveCoins[0].Amount).Quo(sdk.NewDecFromInt(reserveCoins[1].Amount)) + + logger := k.Logger(ctx) + logger.Debug( + "deposit coins to the pool", + "msg", msg, + "pool", pool, + "inputs", inputs, + "outputs", outputs, + "reserveCoins", reserveCoins, + "lastReserveRatio", lastReserveRatio, + ) + + return nil +} + +// ExecuteWithdrawal withdraws pool coin from the liquidity pool +func (k Keeper) ExecuteWithdrawal(ctx sdk.Context, msg types.WithdrawMsgState, batch types.PoolBatch) error { + if msg.Executed || msg.ToBeDeleted || msg.Succeeded { + return fmt.Errorf("cannot process already executed batch msg") + } + msg.Executed = true + k.SetPoolBatchWithdrawMsgState(ctx, msg.Msg.PoolId, msg) + + if err := k.ValidateMsgWithdrawWithinBatch(ctx, *msg.Msg); err != nil { + return err + } + poolCoins := sdk.NewCoins(msg.Msg.PoolCoin) + + pool, found := k.GetPool(ctx, msg.Msg.PoolId) + if !found { + return types.ErrPoolNotExists + } + + poolCoinTotalSupply := k.GetPoolCoinTotalSupply(ctx, pool) + reserveCoins := k.GetReserveCoins(ctx, pool) + reserveCoins.Sort() + + var inputs []banktypes.Input + var outputs []banktypes.Output + + reserveAcc := pool.GetReserveAccount() + withdrawer := msg.Msg.GetWithdrawer() + + params := k.GetParams(ctx) + withdrawProportion := sdk.OneDec().Sub(params.WithdrawFeeRate) + withdrawCoins := sdk.NewCoins() + withdrawFeeCoins := sdk.NewCoins() + + // Case for withdrawing all reserve coins + if msg.Msg.PoolCoin.Amount.Equal(poolCoinTotalSupply) { + withdrawCoins = reserveCoins + } else { + // Calculate withdraw amount of respective reserve coin considering fees and pool coin's totally supply + for _, reserveCoin := range reserveCoins { + if err := types.CheckOverflow(reserveCoin.Amount, msg.Msg.PoolCoin.Amount); err != nil { + return err + } + if err := types.CheckOverflow(sdk.NewDecFromInt(reserveCoin.Amount.Mul(msg.Msg.PoolCoin.Amount)).TruncateInt(), poolCoinTotalSupply); err != nil { + return err + } + // WithdrawAmount = ReserveAmount * PoolCoinAmount * WithdrawFeeProportion / TotalSupply + withdrawAmtWithFee := sdk.NewDecFromInt(reserveCoin.Amount.Mul(msg.Msg.PoolCoin.Amount)).TruncateInt().Quo(poolCoinTotalSupply) + withdrawAmt := sdk.NewDecFromInt(reserveCoin.Amount.Mul(msg.Msg.PoolCoin.Amount)).MulTruncate(withdrawProportion).TruncateInt().Quo(poolCoinTotalSupply) + withdrawCoins = append(withdrawCoins, sdk.NewCoin(reserveCoin.Denom, withdrawAmt)) + withdrawFeeCoins = append(withdrawFeeCoins, sdk.NewCoin(reserveCoin.Denom, withdrawAmtWithFee.Sub(withdrawAmt))) + } + } + + if withdrawCoins.IsValid() { + inputs = append(inputs, banktypes.NewInput(reserveAcc, withdrawCoins)) + outputs = append(outputs, banktypes.NewOutput(withdrawer, withdrawCoins)) + } else { + return types.ErrBadPoolCoinAmount + } + + // send withdrawing coins to the withdrawer + if err := k.bankKeeper.InputOutputCoins(ctx, inputs, outputs); err != nil { + return err + } + + // burn the escrowed pool coins + if err := k.bankKeeper.BurnCoins(ctx, types.ModuleName, poolCoins); err != nil { + return err + } + + msg.Succeeded = true + msg.ToBeDeleted = true + k.SetPoolBatchWithdrawMsgState(ctx, msg.Msg.PoolId, msg) + + if BatchLogicInvariantCheckFlag { + afterPoolCoinTotalSupply := k.GetPoolCoinTotalSupply(ctx, pool) + afterReserveCoins := k.GetReserveCoins(ctx, pool) + afterReserveCoinA := sdk.ZeroInt() + afterReserveCoinB := sdk.ZeroInt() + if !afterReserveCoins.IsZero() { + afterReserveCoinA = afterReserveCoins[0].Amount + afterReserveCoinB = afterReserveCoins[1].Amount + } + burnedPoolCoin := poolCoins[0].Amount + withdrawCoinA := withdrawCoins[0].Amount + withdrawCoinB := withdrawCoins[1].Amount + reserveCoinA := reserveCoins[0].Amount + reserveCoinB := reserveCoins[1].Amount + lastPoolCoinTotalSupply := poolCoinTotalSupply + afterPoolTotalSupply := afterPoolCoinTotalSupply + + BurningPoolCoinsInvariant(burnedPoolCoin, withdrawCoinA, withdrawCoinB, reserveCoinA, reserveCoinB, lastPoolCoinTotalSupply, withdrawFeeCoins) + WithdrawReserveCoinsInvariant(withdrawCoinA, withdrawCoinB, reserveCoinA, reserveCoinB, + afterReserveCoinA, afterReserveCoinB, afterPoolTotalSupply, lastPoolCoinTotalSupply, burnedPoolCoin) + WithdrawAmountInvariant(withdrawCoinA, withdrawCoinB, reserveCoinA, reserveCoinB, burnedPoolCoin, lastPoolCoinTotalSupply, params.WithdrawFeeRate) + ImmutablePoolPriceAfterWithdrawInvariant(reserveCoinA, reserveCoinB, withdrawCoinA, withdrawCoinB, afterReserveCoinA, afterReserveCoinB) + } + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeWithdrawFromPool, + sdk.NewAttribute(types.AttributeValuePoolId, strconv.FormatUint(pool.Id, 10)), + sdk.NewAttribute(types.AttributeValueBatchIndex, strconv.FormatUint(batch.Index, 10)), + sdk.NewAttribute(types.AttributeValueMsgIndex, strconv.FormatUint(msg.MsgIndex, 10)), + sdk.NewAttribute(types.AttributeValueWithdrawer, withdrawer.String()), + sdk.NewAttribute(types.AttributeValuePoolCoinDenom, msg.Msg.PoolCoin.Denom), + sdk.NewAttribute(types.AttributeValuePoolCoinAmount, msg.Msg.PoolCoin.Amount.String()), + sdk.NewAttribute(types.AttributeValueWithdrawCoins, withdrawCoins.String()), + sdk.NewAttribute(types.AttributeValueWithdrawFeeCoins, withdrawFeeCoins.String()), + sdk.NewAttribute(types.AttributeValueSuccess, types.Success), + ), + ) + + reserveCoins = k.GetReserveCoins(ctx, pool) + + var lastReserveRatio sdk.Dec + if reserveCoins.IsZero() { + lastReserveRatio = sdk.ZeroDec() + } else { + lastReserveRatio = sdk.NewDecFromInt(reserveCoins[0].Amount).Quo(sdk.NewDecFromInt(reserveCoins[1].Amount)) + } + + logger := k.Logger(ctx) + logger.Debug( + "withdraw pool coin from the pool", + "msg", msg, + "pool", pool, + "inputs", inputs, + "outputs", outputs, + "reserveCoins", reserveCoins, + "lastReserveRatio", lastReserveRatio, + ) + + return nil +} + +// GetPoolCoinTotalSupply returns total supply of pool coin of the pool in form of math.Int +// +//nolint:staticcheck +func (k Keeper) GetPoolCoinTotalSupply(ctx sdk.Context, pool types.Pool) math.Int { + return k.bankKeeper.GetSupply(ctx, pool.PoolCoinDenom).Amount +} + +// IsDepletedPool returns true if the pool is depleted. +func (k Keeper) IsDepletedPool(ctx sdk.Context, pool types.Pool) bool { + reserveCoins := k.GetReserveCoins(ctx, pool) + return !k.GetPoolCoinTotalSupply(ctx, pool).IsPositive() || + reserveCoins.AmountOf(pool.ReserveCoinDenoms[0]).IsZero() || + reserveCoins.AmountOf(pool.ReserveCoinDenoms[1]).IsZero() +} + +// GetPoolCoinTotal returns total supply of pool coin of the pool in form of sdk.Coin +func (k Keeper) GetPoolCoinTotal(ctx sdk.Context, pool types.Pool) sdk.Coin { + return sdk.NewCoin(pool.PoolCoinDenom, k.GetPoolCoinTotalSupply(ctx, pool)) +} + +// GetReserveCoins returns reserve coins from the liquidity pool +func (k Keeper) GetReserveCoins(ctx sdk.Context, pool types.Pool) (reserveCoins sdk.Coins) { + reserveAcc := pool.GetReserveAccount() + reserveCoins = sdk.NewCoins() + for _, denom := range pool.ReserveCoinDenoms { + reserveCoins = append(reserveCoins, k.bankKeeper.GetBalance(ctx, reserveAcc, denom)) + } + return +} + +// GetPoolMetaData returns metadata of the pool +func (k Keeper) GetPoolMetaData(ctx sdk.Context, pool types.Pool) types.PoolMetadata { + return types.PoolMetadata{ + PoolId: pool.Id, + PoolCoinTotalSupply: k.GetPoolCoinTotal(ctx, pool), + ReserveCoins: k.GetReserveCoins(ctx, pool), + } +} + +// GetPoolRecord returns the liquidity pool record with the given pool information +func (k Keeper) GetPoolRecord(ctx sdk.Context, pool types.Pool) (types.PoolRecord, bool) { + batch, found := k.GetPoolBatch(ctx, pool.Id) + if !found { + return types.PoolRecord{}, false + } + return types.PoolRecord{ + Pool: pool, + PoolMetadata: k.GetPoolMetaData(ctx, pool), + PoolBatch: batch, + DepositMsgStates: k.GetAllPoolBatchDepositMsgs(ctx, batch), + WithdrawMsgStates: k.GetAllPoolBatchWithdrawMsgStates(ctx, batch), + SwapMsgStates: k.GetAllPoolBatchSwapMsgStates(ctx, batch), + }, true +} + +// SetPoolRecord stores liquidity pool states +func (k Keeper) SetPoolRecord(ctx sdk.Context, record types.PoolRecord) types.PoolRecord { + k.SetPoolAtomic(ctx, record.Pool) + if record.PoolBatch.BeginHeight > ctx.BlockHeight() { + record.PoolBatch.BeginHeight = 0 + } + k.SetPoolBatch(ctx, record.PoolBatch) + k.SetPoolBatchDepositMsgStates(ctx, record.Pool.Id, record.DepositMsgStates) + k.SetPoolBatchWithdrawMsgStates(ctx, record.Pool.Id, record.WithdrawMsgStates) + k.SetPoolBatchSwapMsgStates(ctx, record.Pool.Id, record.SwapMsgStates) + return record +} + +// RefundDeposit refunds deposit amounts to the depositor +func (k Keeper) RefundDeposit(ctx sdk.Context, batchMsg types.DepositMsgState, batch types.PoolBatch) error { + batchMsg, _ = k.GetPoolBatchDepositMsgState(ctx, batchMsg.Msg.PoolId, batchMsg.MsgIndex) + if !batchMsg.Executed || batchMsg.Succeeded { + return fmt.Errorf("cannot refund not executed or already succeeded msg") + } + pool, _ := k.GetPool(ctx, batchMsg.Msg.PoolId) + if err := k.ReleaseEscrow(ctx, batchMsg.Msg.GetDepositor(), batchMsg.Msg.DepositCoins); err != nil { + return err + } + // not delete now, set ToBeDeleted true for delete on next block beginblock + batchMsg.ToBeDeleted = true + k.SetPoolBatchDepositMsgState(ctx, batchMsg.Msg.PoolId, batchMsg) + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeDepositToPool, + sdk.NewAttribute(types.AttributeValuePoolId, strconv.FormatUint(pool.Id, 10)), + sdk.NewAttribute(types.AttributeValueBatchIndex, strconv.FormatUint(batch.Index, 10)), + sdk.NewAttribute(types.AttributeValueMsgIndex, strconv.FormatUint(batchMsg.MsgIndex, 10)), + sdk.NewAttribute(types.AttributeValueDepositor, batchMsg.Msg.GetDepositor().String()), + sdk.NewAttribute(types.AttributeValueAcceptedCoins, sdk.NewCoins().String()), + sdk.NewAttribute(types.AttributeValueRefundedCoins, batchMsg.Msg.DepositCoins.String()), + sdk.NewAttribute(types.AttributeValueSuccess, types.Failure), + )) + return nil +} + +// RefundWithdrawal refunds pool coin of the liquidity pool to the withdrawer +func (k Keeper) RefundWithdrawal(ctx sdk.Context, batchMsg types.WithdrawMsgState, batch types.PoolBatch) error { + batchMsg, _ = k.GetPoolBatchWithdrawMsgState(ctx, batchMsg.Msg.PoolId, batchMsg.MsgIndex) + if !batchMsg.Executed || batchMsg.Succeeded { + return fmt.Errorf("cannot refund not executed or already succeeded msg") + } + pool, _ := k.GetPool(ctx, batchMsg.Msg.PoolId) + if err := k.ReleaseEscrow(ctx, batchMsg.Msg.GetWithdrawer(), sdk.NewCoins(batchMsg.Msg.PoolCoin)); err != nil { + return err + } + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeWithdrawFromPool, + sdk.NewAttribute(types.AttributeValuePoolId, strconv.FormatUint(pool.Id, 10)), + sdk.NewAttribute(types.AttributeValueBatchIndex, strconv.FormatUint(batch.Index, 10)), + sdk.NewAttribute(types.AttributeValueMsgIndex, strconv.FormatUint(batchMsg.MsgIndex, 10)), + sdk.NewAttribute(types.AttributeValueWithdrawer, batchMsg.Msg.GetWithdrawer().String()), + sdk.NewAttribute(types.AttributeValuePoolCoinDenom, batchMsg.Msg.PoolCoin.Denom), + sdk.NewAttribute(types.AttributeValuePoolCoinAmount, batchMsg.Msg.PoolCoin.Amount.String()), + sdk.NewAttribute(types.AttributeValueSuccess, types.Failure), + )) + + // not delete now, set ToBeDeleted true for delete on next block beginblock + batchMsg.ToBeDeleted = true + k.SetPoolBatchWithdrawMsgState(ctx, batchMsg.Msg.PoolId, batchMsg) + return nil +} + +// TransactAndRefundSwapLiquidityPool transacts, refunds, expires, sends coins with escrow, update state by TransactAndRefundSwapLiquidityPool +func (k Keeper) TransactAndRefundSwapLiquidityPool(ctx sdk.Context, swapMsgStates []*types.SwapMsgState, + matchResultMap map[uint64]types.MatchResult, pool types.Pool, batchResult types.BatchResult, +) error { + var inputs []banktypes.Input + var outputs []banktypes.Output + batchEscrowAcc := k.accountKeeper.GetModuleAddress(types.ModuleName) + poolReserveAcc := pool.GetReserveAccount() + batch, found := k.GetPoolBatch(ctx, pool.Id) + if !found { + return types.ErrPoolBatchNotExists + } + sendCoin := func(from, to sdk.AccAddress, coin sdk.Coin) { + coins := sdk.NewCoins(coin) + if !coins.Empty() && coins.IsValid() { + inputs = append(inputs, banktypes.NewInput(from, coins)) + outputs = append(outputs, banktypes.NewOutput(to, coins)) + } + } + for _, sms := range swapMsgStates { + if pool.Id != sms.Msg.PoolId { + return fmt.Errorf("broken msg pool consistency") + } + if !sms.Executed && sms.Succeeded { + return fmt.Errorf("can't refund not executed with succeed msg") + } + if sms.RemainingOfferCoin.IsNegative() { + return fmt.Errorf("negative RemainingOfferCoin") + } else if sms.RemainingOfferCoin.IsPositive() && + ((!sms.ToBeDeleted && sms.OrderExpiryHeight <= ctx.BlockHeight()) || + (sms.ToBeDeleted && sms.OrderExpiryHeight != ctx.BlockHeight())) { + return fmt.Errorf("consistency of OrderExpiryHeight and ToBeDeleted flag is broken") + } + + if match, ok := matchResultMap[sms.MsgIndex]; ok { + transactedAmt := match.TransactedCoinAmt.TruncateInt() + receiveAmt := match.ExchangedDemandCoinAmt.Sub(match.ExchangedCoinFeeAmt).TruncateInt() + offerCoinFeeAmt := match.OfferCoinFeeAmt.TruncateInt() + + sendCoin(batchEscrowAcc, poolReserveAcc, sdk.NewCoin(sms.Msg.OfferCoin.Denom, transactedAmt)) + sendCoin(poolReserveAcc, sms.Msg.GetSwapRequester(), sdk.NewCoin(sms.Msg.DemandCoinDenom, receiveAmt)) + sendCoin(batchEscrowAcc, poolReserveAcc, sdk.NewCoin(sms.Msg.OfferCoin.Denom, offerCoinFeeAmt)) + + if sms.RemainingOfferCoin.Add(sms.ReservedOfferCoinFee).IsPositive() && sms.OrderExpiryHeight == ctx.BlockHeight() { + sendCoin(batchEscrowAcc, sms.Msg.GetSwapRequester(), sms.RemainingOfferCoin.Add(sms.ReservedOfferCoinFee)) + } + + sms.Succeeded = true + if sms.RemainingOfferCoin.IsZero() { + sms.ToBeDeleted = true + } + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeSwapTransacted, + sdk.NewAttribute(types.AttributeValuePoolId, strconv.FormatUint(pool.Id, 10)), + sdk.NewAttribute(types.AttributeValueBatchIndex, strconv.FormatUint(batch.Index, 10)), + sdk.NewAttribute(types.AttributeValueMsgIndex, strconv.FormatUint(sms.MsgIndex, 10)), + sdk.NewAttribute(types.AttributeValueSwapRequester, sms.Msg.GetSwapRequester().String()), + sdk.NewAttribute(types.AttributeValueSwapTypeId, strconv.FormatUint(uint64(sms.Msg.SwapTypeId), 10)), + sdk.NewAttribute(types.AttributeValueOfferCoinDenom, sms.Msg.OfferCoin.Denom), + sdk.NewAttribute(types.AttributeValueOfferCoinAmount, sms.Msg.OfferCoin.Amount.String()), + sdk.NewAttribute(types.AttributeValueDemandCoinDenom, sms.Msg.DemandCoinDenom), + sdk.NewAttribute(types.AttributeValueOrderPrice, sms.Msg.OrderPrice.String()), + sdk.NewAttribute(types.AttributeValueSwapPrice, batchResult.SwapPrice.String()), + sdk.NewAttribute(types.AttributeValueTransactedCoinAmount, transactedAmt.String()), + sdk.NewAttribute(types.AttributeValueRemainingOfferCoinAmount, sms.RemainingOfferCoin.Amount.String()), + sdk.NewAttribute(types.AttributeValueExchangedOfferCoinAmount, sms.ExchangedOfferCoin.Amount.String()), + sdk.NewAttribute(types.AttributeValueExchangedDemandCoinAmount, receiveAmt.String()), + sdk.NewAttribute(types.AttributeValueOfferCoinFeeAmount, offerCoinFeeAmt.String()), + sdk.NewAttribute(types.AttributeValueExchangedCoinFeeAmount, match.ExchangedCoinFeeAmt.String()), + sdk.NewAttribute(types.AttributeValueReservedOfferCoinFeeAmount, sms.ReservedOfferCoinFee.Amount.String()), + sdk.NewAttribute(types.AttributeValueOrderExpiryHeight, strconv.FormatInt(sms.OrderExpiryHeight, 10)), + sdk.NewAttribute(types.AttributeValueSuccess, types.Success), + )) + } else { + // Not matched, remaining + sendCoin(batchEscrowAcc, sms.Msg.GetSwapRequester(), sms.RemainingOfferCoin.Add(sms.ReservedOfferCoinFee)) + sms.Succeeded = false + sms.ToBeDeleted = true + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeSwapTransacted, + sdk.NewAttribute(types.AttributeValuePoolId, strconv.FormatUint(pool.Id, 10)), + sdk.NewAttribute(types.AttributeValueBatchIndex, strconv.FormatUint(batch.Index, 10)), + sdk.NewAttribute(types.AttributeValueMsgIndex, strconv.FormatUint(sms.MsgIndex, 10)), + sdk.NewAttribute(types.AttributeValueSwapRequester, sms.Msg.GetSwapRequester().String()), + sdk.NewAttribute(types.AttributeValueSwapTypeId, strconv.FormatUint(uint64(sms.Msg.SwapTypeId), 10)), + sdk.NewAttribute(types.AttributeValueOfferCoinDenom, sms.Msg.OfferCoin.Denom), + sdk.NewAttribute(types.AttributeValueOfferCoinAmount, sms.Msg.OfferCoin.Amount.String()), + sdk.NewAttribute(types.AttributeValueDemandCoinDenom, sms.Msg.DemandCoinDenom), + sdk.NewAttribute(types.AttributeValueOrderPrice, sms.Msg.OrderPrice.String()), + sdk.NewAttribute(types.AttributeValueSwapPrice, batchResult.SwapPrice.String()), + sdk.NewAttribute(types.AttributeValueRemainingOfferCoinAmount, sms.RemainingOfferCoin.Amount.String()), + sdk.NewAttribute(types.AttributeValueExchangedOfferCoinAmount, sms.ExchangedOfferCoin.Amount.String()), + sdk.NewAttribute(types.AttributeValueReservedOfferCoinFeeAmount, sms.ReservedOfferCoinFee.Amount.String()), + sdk.NewAttribute(types.AttributeValueOrderExpiryHeight, strconv.FormatInt(sms.OrderExpiryHeight, 10)), + sdk.NewAttribute(types.AttributeValueSuccess, types.Failure), + )) + + } + } + if err := k.bankKeeper.InputOutputCoins(ctx, inputs, outputs); err != nil { + return err + } + k.SetPoolBatchSwapMsgStatesByPointer(ctx, pool.Id, swapMsgStates) + return nil +} + +func (k Keeper) RefundSwaps(ctx sdk.Context, pool types.Pool, swapMsgStates []*types.SwapMsgState) error { + var inputs []banktypes.Input + var outputs []banktypes.Output + sendCoin := func(from, to sdk.AccAddress, coin sdk.Coin) { + coins := sdk.NewCoins(coin) + if !coins.Empty() && coins.IsValid() { + inputs = append(inputs, banktypes.NewInput(from, coins)) + outputs = append(outputs, banktypes.NewOutput(to, coins)) + } + } + for _, sms := range swapMsgStates { + if sms.OrderExpiryHeight == ctx.BlockHeight() { + sendCoin(k.accountKeeper.GetModuleAddress(types.ModuleName), sms.Msg.GetSwapRequester(), sms.RemainingOfferCoin.Add(sms.ReservedOfferCoinFee)) + sms.Succeeded = false + sms.ToBeDeleted = true + } + } + if err := k.bankKeeper.InputOutputCoins(ctx, inputs, outputs); err != nil { + return err + } + k.SetPoolBatchSwapMsgStatesByPointer(ctx, pool.Id, swapMsgStates) + return nil +} + +// ValidateMsgDepositWithinBatch validates MsgDepositWithinBatch +func (k Keeper) ValidateMsgDepositWithinBatch(ctx sdk.Context, msg types.MsgDepositWithinBatch) error { + pool, found := k.GetPool(ctx, msg.PoolId) + if !found { + return types.ErrPoolNotExists + } + + if msg.DepositCoins.Len() != len(pool.ReserveCoinDenoms) { + return types.ErrNumOfReserveCoin + } + + params := k.GetParams(ctx) + reserveCoins := k.GetReserveCoins(ctx, pool) + if err := types.ValidateReserveCoinLimit(params.MaxReserveCoinAmount, reserveCoins.Add(msg.DepositCoins...)); err != nil { + return err + } + + denomA, denomB := types.AlphabeticalDenomPair(msg.DepositCoins[0].Denom, msg.DepositCoins[1].Denom) + if denomA != pool.ReserveCoinDenoms[0] || denomB != pool.ReserveCoinDenoms[1] { + return types.ErrNotMatchedReserveCoin + } + return nil +} + +// ValidateMsgWithdrawWithinBatch validates MsgWithdrawWithinBatch +func (k Keeper) ValidateMsgWithdrawWithinBatch(ctx sdk.Context, msg types.MsgWithdrawWithinBatch) error { + pool, found := k.GetPool(ctx, msg.PoolId) + if !found { + return types.ErrPoolNotExists + } + + if msg.PoolCoin.Denom != pool.PoolCoinDenom { + return types.ErrBadPoolCoinDenom + } + + poolCoinTotalSupply := k.GetPoolCoinTotalSupply(ctx, pool) + if k.IsDepletedPool(ctx, pool) { + return types.ErrDepletedPool + } + + if msg.PoolCoin.Amount.GT(poolCoinTotalSupply) { + return types.ErrBadPoolCoinAmount + } + return nil +} + +// ValidateMsgSwapWithinBatch validates MsgSwapWithinBatch. +func (k Keeper) ValidateMsgSwapWithinBatch(ctx sdk.Context, msg types.MsgSwapWithinBatch, pool types.Pool) error { + denomA, denomB := types.AlphabeticalDenomPair(msg.OfferCoin.Denom, msg.DemandCoinDenom) + if denomA != pool.ReserveCoinDenoms[0] || denomB != pool.ReserveCoinDenoms[1] { + return types.ErrNotMatchedReserveCoin + } + + params := k.GetParams(ctx) + + // can not exceed max order ratio of reserve coins that can be ordered at a order + reserveCoinAmt := k.GetReserveCoins(ctx, pool).AmountOf(msg.OfferCoin.Denom) + + // Decimal Error, Multiply the Int coin amount by the Decimal Rate and erase the decimal point to order a lower value + maximumOrderableAmt := reserveCoinAmt.ToLegacyDec().MulTruncate(params.MaxOrderAmountRatio).TruncateInt() + if msg.OfferCoin.Amount.GT(maximumOrderableAmt) { + return types.ErrExceededMaxOrderable + } + + if msg.OfferCoinFee.Denom != msg.OfferCoin.Denom { + return types.ErrBadOfferCoinFee + } + + if err := types.CheckOverflowWithDec(msg.OfferCoin.Amount.ToLegacyDec(), msg.OrderPrice); err != nil { + return err + } + + if !msg.OfferCoinFee.Equal(types.GetOfferCoinFee(msg.OfferCoin, params.SwapFeeRate)) { + return types.ErrBadOfferCoinFee + } + + return nil +} + +// ValidatePool validates logic for liquidity pool after set or before export +func (k Keeper) ValidatePool(ctx sdk.Context, pool *types.Pool) error { + params := k.GetParams(ctx) + var poolType types.PoolType + + // check poolType exist, get poolType from param + if len(params.PoolTypes) >= int(pool.TypeId) { + poolType = params.PoolTypes[pool.TypeId-1] + if poolType.Id != pool.TypeId { + return types.ErrPoolTypeNotExists + } + } else { + return types.ErrPoolTypeNotExists + } + + if poolType.MaxReserveCoinNum > types.MaxReserveCoinNum || types.MinReserveCoinNum > poolType.MinReserveCoinNum { + return types.ErrNumOfReserveCoin + } + + reserveCoins := k.GetReserveCoins(ctx, *pool) + if uint32(reserveCoins.Len()) > poolType.MaxReserveCoinNum || poolType.MinReserveCoinNum > uint32(reserveCoins.Len()) { + return types.ErrNumOfReserveCoin + } + + if len(pool.ReserveCoinDenoms) != reserveCoins.Len() { + return types.ErrNumOfReserveCoin + } + for i, denom := range pool.ReserveCoinDenoms { + if denom != reserveCoins[i].Denom { + return types.ErrInvalidDenom + } + } + + denomA, denomB := types.AlphabeticalDenomPair(pool.ReserveCoinDenoms[0], pool.ReserveCoinDenoms[1]) + if denomA != pool.ReserveCoinDenoms[0] || denomB != pool.ReserveCoinDenoms[1] { + return types.ErrBadOrderingReserveCoin + } + + poolName := types.PoolName(pool.ReserveCoinDenoms, pool.TypeId) + poolCoin := k.GetPoolCoinTotal(ctx, *pool) + if poolCoin.Denom != types.GetPoolCoinDenom(poolName) { + return types.ErrBadPoolCoinDenom + } + + _, found := k.GetPoolBatch(ctx, pool.Id) + if !found { + return types.ErrPoolBatchNotExists + } + + return nil +} + +// ValidatePoolMetadata validates logic for liquidity pool metadata +func (k Keeper) ValidatePoolMetadata(ctx sdk.Context, pool *types.Pool, metaData *types.PoolMetadata) error { + if err := metaData.ReserveCoins.Validate(); err != nil { + return err + } + if !metaData.ReserveCoins.IsEqual(k.GetReserveCoins(ctx, *pool)) { + return types.ErrNumOfReserveCoin + } + if !metaData.PoolCoinTotalSupply.IsEqual(sdk.NewCoin(pool.PoolCoinDenom, k.GetPoolCoinTotalSupply(ctx, *pool))) { + return types.ErrBadPoolCoinAmount + } + return nil +} + +// ValidatePoolRecord validates liquidity pool record after init or after export +func (k Keeper) ValidatePoolRecord(ctx sdk.Context, record types.PoolRecord) error { + if err := k.ValidatePool(ctx, &record.Pool); err != nil { + return err + } + + if err := k.ValidatePoolMetadata(ctx, &record.Pool, &record.PoolMetadata); err != nil { + return err + } + + if len(record.DepositMsgStates) != 0 && record.PoolBatch.DepositMsgIndex != record.DepositMsgStates[len(record.DepositMsgStates)-1].MsgIndex+1 { + return types.ErrBadBatchMsgIndex + } + if len(record.WithdrawMsgStates) != 0 && record.PoolBatch.WithdrawMsgIndex != record.WithdrawMsgStates[len(record.WithdrawMsgStates)-1].MsgIndex+1 { + return types.ErrBadBatchMsgIndex + } + if len(record.SwapMsgStates) != 0 && record.PoolBatch.SwapMsgIndex != record.SwapMsgStates[len(record.SwapMsgStates)-1].MsgIndex+1 { + return types.ErrBadBatchMsgIndex + } + + return nil +} + +// IsPoolCoinDenom returns true if the denom is a valid pool coin denom. +func (k Keeper) IsPoolCoinDenom(ctx sdk.Context, denom string) bool { + reserveAcc, err := types.GetReserveAcc(denom, false) + if err != nil { + return false + } + _, found := k.GetPoolByReserveAccIndex(ctx, reserveAcc) + return found +} diff --git a/x/liquidity/keeper/migrator.go b/x/liquidity/keeper/migrator.go new file mode 100644 index 00000000..3e808c6b --- /dev/null +++ b/x/liquidity/keeper/migrator.go @@ -0,0 +1,27 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/cybercongress/go-cyber/v4/x/liquidity/exported" + v2 "github.com/cybercongress/go-cyber/v4/x/liquidity/migrations/v2" +) + +// Migrator is a struct for handling in-place store migrations. +type Migrator struct { + keeper Keeper + legacySubspace exported.Subspace +} + +// NewMigrator returns a new Migrator. +func NewMigrator(keeper Keeper, ss exported.Subspace) Migrator { + return Migrator{ + keeper: keeper, + legacySubspace: ss, + } +} + +// Migrate1to2 migrates from version 1 to 2. +func (m Migrator) Migrate1to2(ctx sdk.Context) error { + return v2.Migrate(ctx, ctx.KVStore(m.keeper.storeKey), m.legacySubspace, m.keeper.cdc) +} diff --git a/x/liquidity/keeper/msg_server.go b/x/liquidity/keeper/msg_server.go new file mode 100644 index 00000000..1df4202a --- /dev/null +++ b/x/liquidity/keeper/msg_server.go @@ -0,0 +1,167 @@ +package keeper + +// DONTCOVER + +// Although written in msg_server_test.go, it is approached at the keeper level rather than at the msgServer level +// so is not included in the coverage. + +import ( + "context" + "fmt" + "strconv" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/cybercongress/go-cyber/v4/x/liquidity/types" +) + +type msgServer struct { + Keeper +} + +// NewMsgServerImpl returns an implementation of the distribution MsgServer interface +// for the provided Keeper. +func NewMsgServerImpl(keeper Keeper) types.MsgServer { + return &msgServer{Keeper: keeper} +} + +var _ types.MsgServer = msgServer{} + +// Message server, handler for CreatePool msg +func (k msgServer) CreatePool(goCtx context.Context, msg *types.MsgCreatePool) (*types.MsgCreatePoolResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + if k.GetCircuitBreakerEnabled(ctx) { + return nil, types.ErrCircuitBreakerEnabled + } + + pool, err := k.Keeper.CreatePool(ctx, msg) + if err != nil { + return nil, err + } + + ctx.EventManager().EmitEvents(sdk.Events{ + sdk.NewEvent( + sdk.EventTypeMessage, + sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), + ), + sdk.NewEvent( + types.EventTypeCreatePool, + sdk.NewAttribute(types.AttributeValuePoolId, strconv.FormatUint(pool.Id, 10)), + sdk.NewAttribute(types.AttributeValuePoolTypeId, fmt.Sprintf("%d", msg.PoolTypeId)), + sdk.NewAttribute(types.AttributeValuePoolName, pool.Name()), + sdk.NewAttribute(types.AttributeValueReserveAccount, pool.ReserveAccountAddress), + sdk.NewAttribute(types.AttributeValueDepositCoins, msg.DepositCoins.String()), + sdk.NewAttribute(types.AttributeValuePoolCoinDenom, pool.PoolCoinDenom), + ), + }) + + return &types.MsgCreatePoolResponse{}, nil +} + +// Message server, handler for MsgDepositWithinBatch +func (k msgServer) DepositWithinBatch(goCtx context.Context, msg *types.MsgDepositWithinBatch) (*types.MsgDepositWithinBatchResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + if k.GetCircuitBreakerEnabled(ctx) { + return nil, types.ErrCircuitBreakerEnabled + } + + poolBatch, found := k.GetPoolBatch(ctx, msg.PoolId) + if !found { + return nil, types.ErrPoolBatchNotExists + } + + batchMsg, err := k.Keeper.DepositWithinBatch(ctx, msg) + if err != nil { + return nil, err + } + + ctx.EventManager().EmitEvents(sdk.Events{ + sdk.NewEvent( + sdk.EventTypeMessage, + sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), + ), + sdk.NewEvent( + types.EventTypeDepositWithinBatch, + sdk.NewAttribute(types.AttributeValuePoolId, strconv.FormatUint(batchMsg.Msg.PoolId, 10)), + sdk.NewAttribute(types.AttributeValueBatchIndex, strconv.FormatUint(poolBatch.Index, 10)), + sdk.NewAttribute(types.AttributeValueMsgIndex, strconv.FormatUint(batchMsg.MsgIndex, 10)), + sdk.NewAttribute(types.AttributeValueDepositCoins, batchMsg.Msg.DepositCoins.String()), + ), + }) + + return &types.MsgDepositWithinBatchResponse{}, nil +} + +// Message server, handler for MsgWithdrawWithinBatch +func (k msgServer) WithdrawWithinBatch(goCtx context.Context, msg *types.MsgWithdrawWithinBatch) (*types.MsgWithdrawWithinBatchResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + poolBatch, found := k.GetPoolBatch(ctx, msg.PoolId) + if !found { + return nil, types.ErrPoolBatchNotExists + } + + batchMsg, err := k.Keeper.WithdrawWithinBatch(ctx, msg) + if err != nil { + return nil, err + } + + ctx.EventManager().EmitEvents(sdk.Events{ + sdk.NewEvent( + sdk.EventTypeMessage, + sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), + ), + sdk.NewEvent( + types.EventTypeWithdrawWithinBatch, + sdk.NewAttribute(types.AttributeValuePoolId, strconv.FormatUint(batchMsg.Msg.PoolId, 10)), + sdk.NewAttribute(types.AttributeValueBatchIndex, strconv.FormatUint(poolBatch.Index, 10)), + sdk.NewAttribute(types.AttributeValueMsgIndex, strconv.FormatUint(batchMsg.MsgIndex, 10)), + sdk.NewAttribute(types.AttributeValuePoolCoinDenom, batchMsg.Msg.PoolCoin.Denom), + sdk.NewAttribute(types.AttributeValuePoolCoinAmount, batchMsg.Msg.PoolCoin.Amount.String()), + ), + }) + + return &types.MsgWithdrawWithinBatchResponse{}, nil +} + +// Message server, handler for MsgSwapWithinBatch +func (k msgServer) Swap(goCtx context.Context, msg *types.MsgSwapWithinBatch) (*types.MsgSwapWithinBatchResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + if k.GetCircuitBreakerEnabled(ctx) { + return nil, types.ErrCircuitBreakerEnabled + } + + poolBatch, found := k.GetPoolBatch(ctx, msg.PoolId) + if !found { + return nil, types.ErrPoolBatchNotExists + } + + batchMsg, err := k.Keeper.SwapWithinBatch(ctx, msg, types.CancelOrderLifeSpan) + if err != nil { + return nil, err + } + + ctx.EventManager().EmitEvents(sdk.Events{ + sdk.NewEvent( + sdk.EventTypeMessage, + sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), + ), + sdk.NewEvent( + types.EventTypeSwapWithinBatch, + sdk.NewAttribute(types.AttributeValuePoolId, strconv.FormatUint(batchMsg.Msg.PoolId, 10)), + sdk.NewAttribute(types.AttributeValueBatchIndex, strconv.FormatUint(poolBatch.Index, 10)), + sdk.NewAttribute(types.AttributeValueMsgIndex, strconv.FormatUint(batchMsg.MsgIndex, 10)), + sdk.NewAttribute(types.AttributeValueSwapTypeId, strconv.FormatUint(uint64(batchMsg.Msg.SwapTypeId), 10)), + sdk.NewAttribute(types.AttributeValueOfferCoinDenom, batchMsg.Msg.OfferCoin.Denom), + sdk.NewAttribute(types.AttributeValueOfferCoinAmount, batchMsg.Msg.OfferCoin.Amount.String()), + sdk.NewAttribute(types.AttributeValueOfferCoinFeeAmount, batchMsg.Msg.OfferCoinFee.Amount.String()), + sdk.NewAttribute(types.AttributeValueDemandCoinDenom, batchMsg.Msg.DemandCoinDenom), + sdk.NewAttribute(types.AttributeValueOrderPrice, batchMsg.Msg.OrderPrice.String()), + ), + }) + + return &types.MsgSwapWithinBatchResponse{}, nil +} diff --git a/x/liquidity/keeper/store.go b/x/liquidity/keeper/store.go new file mode 100644 index 00000000..4213283f --- /dev/null +++ b/x/liquidity/keeper/store.go @@ -0,0 +1,600 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + gogotypes "github.com/cosmos/gogoproto/types" + + "github.com/cybercongress/go-cyber/v4/x/liquidity/types" +) + +// GetPool reads from kvstore and returns a specific pool +func (k Keeper) GetPool(ctx sdk.Context, poolID uint64) (pool types.Pool, found bool) { + store := ctx.KVStore(k.storeKey) + key := types.GetPoolKey(poolID) + + value := store.Get(key) + if value == nil { + return pool, false + } + + pool = types.MustUnmarshalPool(k.cdc, value) + + return pool, true +} + +// SetPool sets to kvstore a specific pool +func (k Keeper) SetPool(ctx sdk.Context, pool types.Pool) { + store := ctx.KVStore(k.storeKey) + b := types.MustMarshalPool(k.cdc, pool) + store.Set(types.GetPoolKey(pool.Id), b) +} + +// delete from kvstore a specific liquidityPool +func (k Keeper) DeletePool(ctx sdk.Context, pool types.Pool) { + store := ctx.KVStore(k.storeKey) + Key := types.GetPoolKey(pool.Id) + store.Delete(Key) +} + +// IterateAllPools iterate through all of the liquidityPools +func (k Keeper) IterateAllPools(ctx sdk.Context, cb func(pool types.Pool) (stop bool)) { + store := ctx.KVStore(k.storeKey) + + iterator := sdk.KVStorePrefixIterator(store, types.PoolKeyPrefix) + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + pool := types.MustUnmarshalPool(k.cdc, iterator.Value()) + if cb(pool) { + break + } + } +} + +// GetAllPools returns all liquidityPools used during genesis dump +func (k Keeper) GetAllPools(ctx sdk.Context) (pools []types.Pool) { + k.IterateAllPools(ctx, func(liquidityPool types.Pool) bool { + pools = append(pools, liquidityPool) + return false + }) + + return pools +} + +// GetNextPoolIDWithUpdate returns and increments the global Pool ID counter. +// If the global account number is not set, it initializes it with value 0. +func (k Keeper) GetNextPoolIDWithUpdate(ctx sdk.Context) uint64 { + store := ctx.KVStore(k.storeKey) + poolID := k.GetNextPoolID(ctx) + bz := k.cdc.MustMarshal(&gogotypes.UInt64Value{Value: poolID + 1}) + store.Set(types.GlobalLiquidityPoolIDKey, bz) + return poolID +} + +// GetNextPoolID returns next pool id for new pool, using index of latest pool id +func (k Keeper) GetNextPoolID(ctx sdk.Context) uint64 { + var poolID uint64 + store := ctx.KVStore(k.storeKey) + + bz := store.Get(types.GlobalLiquidityPoolIDKey) + if bz == nil { + // initialize the LiquidityPoolID + poolID = 1 + } else { + val := gogotypes.UInt64Value{} + + err := k.cdc.Unmarshal(bz, &val) + if err != nil { + panic(err) + } + + poolID = val.GetValue() + } + return poolID +} + +// GetPoolByReserveAccIndex reads from kvstore and return a specific liquidityPool indexed by given reserve account +func (k Keeper) GetPoolByReserveAccIndex(ctx sdk.Context, reserveAcc sdk.AccAddress) (pool types.Pool, found bool) { + store := ctx.KVStore(k.storeKey) + key := types.GetPoolByReserveAccIndexKey(reserveAcc) + + value := store.Get(key) + if value == nil { + return pool, false + } + + val := gogotypes.UInt64Value{} + err := k.cdc.Unmarshal(value, &val) + if err != nil { + return pool, false + } + poolID := val.GetValue() + return k.GetPool(ctx, poolID) +} + +// SetPoolByReserveAccIndex sets Index by ReserveAcc for pool duplication check +func (k Keeper) SetPoolByReserveAccIndex(ctx sdk.Context, pool types.Pool) { + store := ctx.KVStore(k.storeKey) + b := k.cdc.MustMarshal(&gogotypes.UInt64Value{Value: pool.Id}) + store.Set(types.GetPoolByReserveAccIndexKey(pool.GetReserveAccount()), b) +} + +// SetPoolAtomic sets pool with set global pool id index +1 and index by reserveAcc +func (k Keeper) SetPoolAtomic(ctx sdk.Context, pool types.Pool) types.Pool { + pool.Id = k.GetNextPoolIDWithUpdate(ctx) + k.SetPool(ctx, pool) + k.SetPoolByReserveAccIndex(ctx, pool) + return pool +} + +// GetPoolBatch returns a specific pool batch +func (k Keeper) GetPoolBatch(ctx sdk.Context, poolID uint64) (poolBatch types.PoolBatch, found bool) { + store := ctx.KVStore(k.storeKey) + key := types.GetPoolBatchKey(poolID) + + value := store.Get(key) + if value == nil { + return poolBatch, false + } + + poolBatch = types.MustUnmarshalPoolBatch(k.cdc, value) + + return poolBatch, true +} + +// GetAllPoolBatches returns all batches of the all existed liquidity pools +func (k Keeper) GetAllPoolBatches(ctx sdk.Context) (poolBatches []types.PoolBatch) { + k.IterateAllPoolBatches(ctx, func(poolBatch types.PoolBatch) bool { + poolBatches = append(poolBatches, poolBatch) + return false + }) + + return poolBatches +} + +// IterateAllPoolBatches iterate through all of the pool batches +func (k Keeper) IterateAllPoolBatches(ctx sdk.Context, cb func(poolBatch types.PoolBatch) (stop bool)) { + store := ctx.KVStore(k.storeKey) + + iterator := sdk.KVStorePrefixIterator(store, types.PoolBatchKeyPrefix) + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + poolBatch := types.MustUnmarshalPoolBatch(k.cdc, iterator.Value()) + if cb(poolBatch) { + break + } + } +} + +// DeletePoolBatch deletes batch of the pool, it used for test case +func (k Keeper) DeletePoolBatch(ctx sdk.Context, poolBatch types.PoolBatch) { + store := ctx.KVStore(k.storeKey) + batchKey := types.GetPoolBatchKey(poolBatch.PoolId) + store.Delete(batchKey) +} + +// SetPoolBatch sets batch of the pool, with current state +func (k Keeper) SetPoolBatch(ctx sdk.Context, poolBatch types.PoolBatch) { + store := ctx.KVStore(k.storeKey) + b := types.MustMarshalPoolBatch(k.cdc, poolBatch) + store.Set(types.GetPoolBatchKey(poolBatch.PoolId), b) +} + +// GetPoolBatchDepositMsgState returns a specific DepositMsgState +func (k Keeper) GetPoolBatchDepositMsgState(ctx sdk.Context, poolID, msgIndex uint64) (state types.DepositMsgState, found bool) { + store := ctx.KVStore(k.storeKey) + key := types.GetPoolBatchDepositMsgStateIndexKey(poolID, msgIndex) + + value := store.Get(key) + if value == nil { + return state, false + } + + state = types.MustUnmarshalDepositMsgState(k.cdc, value) + return state, true +} + +// SetPoolBatchDepositMsgState sets deposit msg state of the pool batch, with current state +func (k Keeper) SetPoolBatchDepositMsgState(ctx sdk.Context, poolID uint64, state types.DepositMsgState) { + store := ctx.KVStore(k.storeKey) + b := types.MustMarshalDepositMsgState(k.cdc, state) + store.Set(types.GetPoolBatchDepositMsgStateIndexKey(poolID, state.MsgIndex), b) +} + +// SetPoolBatchDepositMsgStatesByPointer sets deposit batch msgs of the pool batch, with current state using pointers +func (k Keeper) SetPoolBatchDepositMsgStatesByPointer(ctx sdk.Context, poolID uint64, states []*types.DepositMsgState) { + store := ctx.KVStore(k.storeKey) + for _, state := range states { + if poolID != state.Msg.PoolId { + continue + } + b := types.MustMarshalDepositMsgState(k.cdc, *state) + store.Set(types.GetPoolBatchDepositMsgStateIndexKey(poolID, state.MsgIndex), b) + } +} + +// SetPoolBatchDepositMsgStates sets deposit batch msgs of the pool batch, with current state +func (k Keeper) SetPoolBatchDepositMsgStates(ctx sdk.Context, poolID uint64, states []types.DepositMsgState) { + store := ctx.KVStore(k.storeKey) + for _, state := range states { + if poolID != state.Msg.PoolId { + continue + } + b := types.MustMarshalDepositMsgState(k.cdc, state) + store.Set(types.GetPoolBatchDepositMsgStateIndexKey(poolID, state.MsgIndex), b) + } +} + +// IterateAllPoolBatchDepositMsgStates iterate through all of the DepositMsgStates in the batch +func (k Keeper) IterateAllPoolBatchDepositMsgStates(ctx sdk.Context, poolBatch types.PoolBatch, cb func(state types.DepositMsgState) (stop bool)) { + store := ctx.KVStore(k.storeKey) + + prefix := types.GetPoolBatchDepositMsgStatesPrefix(poolBatch.PoolId) + iterator := sdk.KVStorePrefixIterator(store, prefix) + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + state := types.MustUnmarshalDepositMsgState(k.cdc, iterator.Value()) + if cb(state) { + break + } + } +} + +// IterateAllDepositMsgStates iterate through all of the DepositMsgState of all batches +func (k Keeper) IterateAllDepositMsgStates(ctx sdk.Context, cb func(state types.DepositMsgState) (stop bool)) { + store := ctx.KVStore(k.storeKey) + + prefix := types.PoolBatchDepositMsgStateIndexKeyPrefix + iterator := sdk.KVStorePrefixIterator(store, prefix) + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + state := types.MustUnmarshalDepositMsgState(k.cdc, iterator.Value()) + if cb(state) { + break + } + } +} + +// GetAllDepositMsgStates returns all BatchDepositMsgs for all batches. +func (k Keeper) GetAllDepositMsgStates(ctx sdk.Context) (states []types.DepositMsgState) { + k.IterateAllDepositMsgStates(ctx, func(state types.DepositMsgState) bool { + states = append(states, state) + return false + }) + return states +} + +// GetAllPoolBatchDepositMsgs returns all BatchDepositMsgs indexed by the pool batch +func (k Keeper) GetAllPoolBatchDepositMsgs(ctx sdk.Context, poolBatch types.PoolBatch) (states []types.DepositMsgState) { + k.IterateAllPoolBatchDepositMsgStates(ctx, poolBatch, func(state types.DepositMsgState) bool { + states = append(states, state) + return false + }) + return states +} + +// GetAllPoolBatchDepositMsgStatesNotToBeDeleted returns all Not toDelete BatchDepositMsgs indexed by the liquidityPoolBatch +func (k Keeper) GetAllPoolBatchDepositMsgStatesNotToBeDeleted(ctx sdk.Context, poolBatch types.PoolBatch) (states []types.DepositMsgState) { + k.IterateAllPoolBatchDepositMsgStates(ctx, poolBatch, func(state types.DepositMsgState) bool { + if !state.ToBeDeleted { + states = append(states, state) + } + return false + }) + return states +} + +// GetAllRemainingPoolBatchDepositMsgStates returns all remaining DepositMsgStates after endblock, +// which are executed but not to be deleted +func (k Keeper) GetAllRemainingPoolBatchDepositMsgStates(ctx sdk.Context, poolBatch types.PoolBatch) (states []*types.DepositMsgState) { + k.IterateAllPoolBatchDepositMsgStates(ctx, poolBatch, func(state types.DepositMsgState) bool { + if state.Executed && !state.ToBeDeleted { + states = append(states, &state) + } + return false + }) + return states +} + +// delete deposit batch msgs of the liquidity pool batch which has state ToBeDeleted +func (k Keeper) DeleteAllReadyPoolBatchDepositMsgStates(ctx sdk.Context, poolBatch types.PoolBatch) { + store := ctx.KVStore(k.storeKey) + iterator := sdk.KVStorePrefixIterator(store, types.GetPoolBatchDepositMsgStatesPrefix(poolBatch.PoolId)) + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + state := types.MustUnmarshalDepositMsgState(k.cdc, iterator.Value()) + if state.ToBeDeleted { + store.Delete(iterator.Key()) + } + } +} + +// return a specific liquidityPoolBatchWithdrawMsg +func (k Keeper) GetPoolBatchWithdrawMsgState(ctx sdk.Context, poolID, msgIndex uint64) (state types.WithdrawMsgState, found bool) { + store := ctx.KVStore(k.storeKey) + key := types.GetPoolBatchWithdrawMsgStateIndexKey(poolID, msgIndex) + + value := store.Get(key) + if value == nil { + return state, false + } + + state = types.MustUnmarshalWithdrawMsgState(k.cdc, value) + return state, true +} + +// set withdraw batch msg of the liquidity pool batch, with current state +func (k Keeper) SetPoolBatchWithdrawMsgState(ctx sdk.Context, poolID uint64, state types.WithdrawMsgState) { + store := ctx.KVStore(k.storeKey) + b := types.MustMarshalWithdrawMsgState(k.cdc, state) + store.Set(types.GetPoolBatchWithdrawMsgStateIndexKey(poolID, state.MsgIndex), b) +} + +// set withdraw batch msgs of the liquidity pool batch, with current state using pointers +func (k Keeper) SetPoolBatchWithdrawMsgStatesByPointer(ctx sdk.Context, poolID uint64, states []*types.WithdrawMsgState) { + store := ctx.KVStore(k.storeKey) + for _, state := range states { + if poolID != state.Msg.PoolId { + continue + } + b := types.MustMarshalWithdrawMsgState(k.cdc, *state) + store.Set(types.GetPoolBatchWithdrawMsgStateIndexKey(poolID, state.MsgIndex), b) + } +} + +// set withdraw batch msgs of the pool batch, with current state +func (k Keeper) SetPoolBatchWithdrawMsgStates(ctx sdk.Context, poolID uint64, states []types.WithdrawMsgState) { + store := ctx.KVStore(k.storeKey) + for _, state := range states { + if poolID != state.Msg.PoolId { + continue + } + b := types.MustMarshalWithdrawMsgState(k.cdc, state) + store.Set(types.GetPoolBatchWithdrawMsgStateIndexKey(poolID, state.MsgIndex), b) + } +} + +// IterateAllPoolBatchWithdrawMsgStates iterate through all of the LiquidityPoolBatchWithdrawMsgs +func (k Keeper) IterateAllPoolBatchWithdrawMsgStates(ctx sdk.Context, poolBatch types.PoolBatch, cb func(state types.WithdrawMsgState) (stop bool)) { + store := ctx.KVStore(k.storeKey) + + prefix := types.GetPoolBatchWithdrawMsgsPrefix(poolBatch.PoolId) + iterator := sdk.KVStorePrefixIterator(store, prefix) + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + state := types.MustUnmarshalWithdrawMsgState(k.cdc, iterator.Value()) + if cb(state) { + break + } + } +} + +// IterateAllWithdrawMsgStates iterate through all of the WithdrawMsgState of all batches +func (k Keeper) IterateAllWithdrawMsgStates(ctx sdk.Context, cb func(state types.WithdrawMsgState) (stop bool)) { + store := ctx.KVStore(k.storeKey) + + prefix := types.PoolBatchWithdrawMsgStateIndexKeyPrefix + iterator := sdk.KVStorePrefixIterator(store, prefix) + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + state := types.MustUnmarshalWithdrawMsgState(k.cdc, iterator.Value()) + if cb(state) { + break + } + } +} + +// GetAllWithdrawMsgStates returns all BatchWithdrawMsgs for all batches +func (k Keeper) GetAllWithdrawMsgStates(ctx sdk.Context) (states []types.WithdrawMsgState) { + k.IterateAllWithdrawMsgStates(ctx, func(state types.WithdrawMsgState) bool { + states = append(states, state) + return false + }) + return states +} + +// GetAllPoolBatchWithdrawMsgStates returns all BatchWithdrawMsgs indexed by the liquidityPoolBatch +func (k Keeper) GetAllPoolBatchWithdrawMsgStates(ctx sdk.Context, poolBatch types.PoolBatch) (states []types.WithdrawMsgState) { + k.IterateAllPoolBatchWithdrawMsgStates(ctx, poolBatch, func(state types.WithdrawMsgState) bool { + states = append(states, state) + return false + }) + return states +} + +// GetAllPoolBatchWithdrawMsgStatesNotToBeDeleted returns all Not to delete BatchWithdrawMsgs indexed by the liquidityPoolBatch +func (k Keeper) GetAllPoolBatchWithdrawMsgStatesNotToBeDeleted(ctx sdk.Context, poolBatch types.PoolBatch) (states []types.WithdrawMsgState) { + k.IterateAllPoolBatchWithdrawMsgStates(ctx, poolBatch, func(state types.WithdrawMsgState) bool { + if !state.ToBeDeleted { + states = append(states, state) + } + return false + }) + return states +} + +// GetAllRemainingPoolBatchWithdrawMsgStates returns All only remaining BatchWithdrawMsgs after endblock, executed but not toDelete +func (k Keeper) GetAllRemainingPoolBatchWithdrawMsgStates(ctx sdk.Context, poolBatch types.PoolBatch) (states []*types.WithdrawMsgState) { + k.IterateAllPoolBatchWithdrawMsgStates(ctx, poolBatch, func(state types.WithdrawMsgState) bool { + if state.Executed && !state.ToBeDeleted { + states = append(states, &state) + } + return false + }) + return states +} + +// delete withdraw batch msgs of the liquidity pool batch which has state ToBeDeleted +func (k Keeper) DeleteAllReadyPoolBatchWithdrawMsgStates(ctx sdk.Context, poolBatch types.PoolBatch) { + store := ctx.KVStore(k.storeKey) + iterator := sdk.KVStorePrefixIterator(store, types.GetPoolBatchWithdrawMsgsPrefix(poolBatch.PoolId)) + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + state := types.MustUnmarshalWithdrawMsgState(k.cdc, iterator.Value()) + if state.ToBeDeleted { + store.Delete(iterator.Key()) + } + } +} + +// return a specific SwapMsgState given the pool_id with the msg_index +func (k Keeper) GetPoolBatchSwapMsgState(ctx sdk.Context, poolID, msgIndex uint64) (state types.SwapMsgState, found bool) { + store := ctx.KVStore(k.storeKey) + key := types.GetPoolBatchSwapMsgStateIndexKey(poolID, msgIndex) + + value := store.Get(key) + if value == nil { + return state, false + } + + state = types.MustUnmarshalSwapMsgState(k.cdc, value) + return state, true +} + +// set swap batch msg of the liquidity pool batch, with current state +func (k Keeper) SetPoolBatchSwapMsgState(ctx sdk.Context, poolID uint64, state types.SwapMsgState) { + store := ctx.KVStore(k.storeKey) + b := types.MustMarshalSwapMsgState(k.cdc, state) + store.Set(types.GetPoolBatchSwapMsgStateIndexKey(poolID, state.MsgIndex), b) +} + +// Delete swap batch msg of the liquidity pool batch, it used for test case +func (k Keeper) DeletePoolBatchSwapMsgState(ctx sdk.Context, poolID uint64, msgIndex uint64) { + store := ctx.KVStore(k.storeKey) + batchKey := types.GetPoolBatchSwapMsgStateIndexKey(poolID, msgIndex) + store.Delete(batchKey) +} + +// IterateAllPoolBatchSwapMsgStates iterate through all of the LiquidityPoolBatchSwapMsgs +func (k Keeper) IterateAllPoolBatchSwapMsgStates(ctx sdk.Context, poolBatch types.PoolBatch, cb func(state types.SwapMsgState) (stop bool)) { + store := ctx.KVStore(k.storeKey) + + prefix := types.GetPoolBatchSwapMsgStatesPrefix(poolBatch.PoolId) + iterator := sdk.KVStorePrefixIterator(store, prefix) + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + state := types.MustUnmarshalSwapMsgState(k.cdc, iterator.Value()) + if cb(state) { + break + } + } +} + +// IterateAllSwapMsgStates iterate through all of the SwapMsgState of all batches +func (k Keeper) IterateAllSwapMsgStates(ctx sdk.Context, cb func(state types.SwapMsgState) (stop bool)) { + store := ctx.KVStore(k.storeKey) + + prefix := types.PoolBatchSwapMsgStateIndexKeyPrefix + iterator := sdk.KVStorePrefixIterator(store, prefix) + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + state := types.MustUnmarshalSwapMsgState(k.cdc, iterator.Value()) + if cb(state) { + break + } + } +} + +// GetAllSwapMsgStates returns all BatchSwapMsgs of all batches +func (k Keeper) GetAllSwapMsgStates(ctx sdk.Context) (states []types.SwapMsgState) { + k.IterateAllSwapMsgStates(ctx, func(state types.SwapMsgState) bool { + states = append(states, state) + return false + }) + return states +} + +// delete swap batch msgs of the liquidity pool batch which has state ToBeDeleted +func (k Keeper) DeleteAllReadyPoolBatchSwapMsgStates(ctx sdk.Context, poolBatch types.PoolBatch) { + store := ctx.KVStore(k.storeKey) + iterator := sdk.KVStorePrefixIterator(store, types.GetPoolBatchSwapMsgStatesPrefix(poolBatch.PoolId)) + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + state := types.MustUnmarshalSwapMsgState(k.cdc, iterator.Value()) + if state.ToBeDeleted { + store.Delete(iterator.Key()) + } + } +} + +// GetAllPoolBatchSwapMsgStatesAsPointer returns all BatchSwapMsgs pointer indexed by the liquidityPoolBatch +func (k Keeper) GetAllPoolBatchSwapMsgStatesAsPointer(ctx sdk.Context, poolBatch types.PoolBatch) (states []*types.SwapMsgState) { + k.IterateAllPoolBatchSwapMsgStates(ctx, poolBatch, func(state types.SwapMsgState) bool { + states = append(states, &state) + return false + }) + return states +} + +// GetAllPoolBatchSwapMsgStates returns all BatchSwapMsgs indexed by the liquidityPoolBatch +func (k Keeper) GetAllPoolBatchSwapMsgStates(ctx sdk.Context, poolBatch types.PoolBatch) (states []types.SwapMsgState) { + k.IterateAllPoolBatchSwapMsgStates(ctx, poolBatch, func(state types.SwapMsgState) bool { + states = append(states, state) + return false + }) + return states +} + +// GetAllNotProcessedPoolBatchSwapMsgStates returns All only not processed swap msgs, not executed with not succeed and not toDelete BatchSwapMsgs indexed by the liquidityPoolBatch +func (k Keeper) GetAllNotProcessedPoolBatchSwapMsgStates(ctx sdk.Context, poolBatch types.PoolBatch) (states []*types.SwapMsgState) { + k.IterateAllPoolBatchSwapMsgStates(ctx, poolBatch, func(state types.SwapMsgState) bool { + if !state.Executed && !state.Succeeded && !state.ToBeDeleted { + states = append(states, &state) + } + return false + }) + return states +} + +// GetAllRemainingPoolBatchSwapMsgStates returns All only remaining after endblock swap msgs, executed but not toDelete +func (k Keeper) GetAllRemainingPoolBatchSwapMsgStates(ctx sdk.Context, poolBatch types.PoolBatch) (states []*types.SwapMsgState) { + k.IterateAllPoolBatchSwapMsgStates(ctx, poolBatch, func(state types.SwapMsgState) bool { + if state.Executed && !state.ToBeDeleted { + states = append(states, &state) + } + return false + }) + return states +} + +// GetAllPoolBatchSwapMsgStatesNotToBeDeleted returns All only not to delete swap msgs +func (k Keeper) GetAllPoolBatchSwapMsgStatesNotToBeDeleted(ctx sdk.Context, poolBatch types.PoolBatch) (states []*types.SwapMsgState) { + k.IterateAllPoolBatchSwapMsgStates(ctx, poolBatch, func(state types.SwapMsgState) bool { + if !state.ToBeDeleted { + states = append(states, &state) + } + return false + }) + return states +} + +// set swap batch msgs of the liquidity pool batch, with current state using pointers +func (k Keeper) SetPoolBatchSwapMsgStatesByPointer(ctx sdk.Context, poolID uint64, states []*types.SwapMsgState) { + store := ctx.KVStore(k.storeKey) + for _, state := range states { + if poolID != state.Msg.PoolId { + continue + } + b := types.MustMarshalSwapMsgState(k.cdc, *state) + store.Set(types.GetPoolBatchSwapMsgStateIndexKey(poolID, state.MsgIndex), b) + } +} + +// set swap batch msgs of the liquidity pool batch, with current state +func (k Keeper) SetPoolBatchSwapMsgStates(ctx sdk.Context, poolID uint64, states []types.SwapMsgState) { + store := ctx.KVStore(k.storeKey) + for _, state := range states { + if poolID != state.Msg.PoolId { + continue + } + b := types.MustMarshalSwapMsgState(k.cdc, state) + store.Set(types.GetPoolBatchSwapMsgStateIndexKey(poolID, state.MsgIndex), b) + } +} diff --git a/x/liquidity/keeper/swap.go b/x/liquidity/keeper/swap.go new file mode 100644 index 00000000..ca6f74fe --- /dev/null +++ b/x/liquidity/keeper/swap.go @@ -0,0 +1,147 @@ +package keeper + +import ( + "fmt" + "strconv" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/cybercongress/go-cyber/v4/x/liquidity/types" +) + +// Execute Swap of the pool batch, Collect swap messages in batch for transact the same price for each batch and run them on endblock. +func (k Keeper) SwapExecution(ctx sdk.Context, poolBatch types.PoolBatch) (uint64, error) { + // get all swap message batch states that are not executed, not succeeded, and not to be deleted. + swapMsgStates := k.GetAllNotProcessedPoolBatchSwapMsgStates(ctx, poolBatch) + if len(swapMsgStates) == 0 { + return 0, nil + } + + pool, found := k.GetPool(ctx, poolBatch.PoolId) + if !found { + return 0, types.ErrPoolNotExists + } + + if k.IsDepletedPool(ctx, pool) { + return 0, types.ErrDepletedPool + } + + currentHeight := ctx.BlockHeight() + // set executed states of all messages to true + executedMsgCount := uint64(0) + var swapMsgStatesNotToBeDeleted []*types.SwapMsgState + for _, sms := range swapMsgStates { + sms.Executed = true + executedMsgCount++ + if currentHeight > sms.OrderExpiryHeight { + sms.ToBeDeleted = true + } + if err := k.ValidateMsgSwapWithinBatch(ctx, *sms.Msg, pool); err != nil { + sms.ToBeDeleted = true + } + if !sms.ToBeDeleted { + swapMsgStatesNotToBeDeleted = append(swapMsgStatesNotToBeDeleted, sms) + } else { + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeSwapTransacted, + sdk.NewAttribute(types.AttributeValuePoolId, strconv.FormatUint(pool.Id, 10)), + sdk.NewAttribute(types.AttributeValueBatchIndex, strconv.FormatUint(poolBatch.Index, 10)), + sdk.NewAttribute(types.AttributeValueMsgIndex, strconv.FormatUint(sms.MsgIndex, 10)), + sdk.NewAttribute(types.AttributeValueSwapRequester, sms.Msg.GetSwapRequester().String()), + sdk.NewAttribute(types.AttributeValueSwapTypeId, strconv.FormatUint(uint64(sms.Msg.SwapTypeId), 10)), + sdk.NewAttribute(types.AttributeValueOfferCoinDenom, sms.Msg.OfferCoin.Denom), + sdk.NewAttribute(types.AttributeValueOfferCoinAmount, sms.Msg.OfferCoin.Amount.String()), + sdk.NewAttribute(types.AttributeValueDemandCoinDenom, sms.Msg.DemandCoinDenom), + sdk.NewAttribute(types.AttributeValueOrderPrice, sms.Msg.OrderPrice.String()), + sdk.NewAttribute(types.AttributeValueRemainingOfferCoinAmount, sms.RemainingOfferCoin.Amount.String()), + sdk.NewAttribute(types.AttributeValueExchangedOfferCoinAmount, sms.ExchangedOfferCoin.Amount.String()), + sdk.NewAttribute(types.AttributeValueReservedOfferCoinFeeAmount, sms.ReservedOfferCoinFee.Amount.String()), + sdk.NewAttribute(types.AttributeValueOrderExpiryHeight, strconv.FormatInt(sms.OrderExpiryHeight, 10)), + sdk.NewAttribute(types.AttributeValueSuccess, types.Failure), + )) + } + } + k.SetPoolBatchSwapMsgStatesByPointer(ctx, pool.Id, swapMsgStates) + swapMsgStates = swapMsgStatesNotToBeDeleted + + types.ValidateStateAndExpireOrders(swapMsgStates, currentHeight, false) + + // get reserve coins from the liquidity pool and calculate the current pool price (p = x / y) + reserveCoins := k.GetReserveCoins(ctx, pool) + + X := reserveCoins[0].Amount.ToLegacyDec() + Y := reserveCoins[1].Amount.ToLegacyDec() + currentPoolPrice := X.Quo(Y) + denomX := reserveCoins[0].Denom + denomY := reserveCoins[1].Denom + + // make orderMap, orderbook by sort orderMap + orderMap, xToY, yToX := types.MakeOrderMap(swapMsgStates, denomX, denomY, false) + orderBook := orderMap.SortOrderBook() + + // check orderbook validity and compute batchResult(direction, swapPrice, ..) + result, found := orderBook.Match(X, Y) + + if !found || X.Quo(Y).IsZero() { + err := k.RefundSwaps(ctx, pool, swapMsgStates) + return executedMsgCount, err + } + + // find order match, calculate pool delta with the total x, y amounts for the invariant check + var matchResultXtoY, matchResultYtoX []types.MatchResult + + poolXDelta := sdk.ZeroDec() + poolYDelta := sdk.ZeroDec() + + if result.MatchType != types.NoMatch { + var poolXDeltaXtoY, poolXDeltaYtoX, poolYDeltaYtoX, poolYDeltaXtoY sdk.Dec + matchResultXtoY, poolXDeltaXtoY, poolYDeltaXtoY = types.FindOrderMatch(types.DirectionXtoY, xToY, result.EX, result.SwapPrice, currentHeight) + matchResultYtoX, poolXDeltaYtoX, poolYDeltaYtoX = types.FindOrderMatch(types.DirectionYtoX, yToX, result.EY, result.SwapPrice, currentHeight) + poolXDelta = poolXDeltaXtoY.Add(poolXDeltaYtoX) + poolYDelta = poolYDeltaXtoY.Add(poolYDeltaYtoX) + } + + xToY, yToX, X, Y, poolXDelta2, poolYDelta2 := types.UpdateSwapMsgStates(X, Y, xToY, yToX, matchResultXtoY, matchResultYtoX) + + lastPrice := X.Quo(Y) + + if BatchLogicInvariantCheckFlag { + SwapMatchingInvariants(xToY, yToX, matchResultXtoY, matchResultYtoX) + SwapPriceInvariants(matchResultXtoY, matchResultYtoX, poolXDelta, poolYDelta, poolXDelta2, poolYDelta2, result) + } + + types.ValidateStateAndExpireOrders(xToY, currentHeight, false) + types.ValidateStateAndExpireOrders(yToX, currentHeight, false) + + orderMapExecuted, _, _ := types.MakeOrderMap(append(xToY, yToX...), denomX, denomY, true) + orderBookExecuted := orderMapExecuted.SortOrderBook() + if !orderBookExecuted.Validate(lastPrice) { + return executedMsgCount, types.ErrOrderBookInvalidity + } + + types.ValidateStateAndExpireOrders(xToY, currentHeight, true) + types.ValidateStateAndExpireOrders(yToX, currentHeight, true) + + // make index map for match result + matchResultMap := make(map[uint64]types.MatchResult) + for _, match := range append(matchResultXtoY, matchResultYtoX...) { + if _, ok := matchResultMap[match.SwapMsgState.MsgIndex]; ok { + return executedMsgCount, fmt.Errorf("duplicate match order") + } + matchResultMap[match.SwapMsgState.MsgIndex] = match + } + + if BatchLogicInvariantCheckFlag { + SwapPriceDirectionInvariants(currentPoolPrice, result) + SwapMsgStatesInvariants(matchResultXtoY, matchResultYtoX, matchResultMap, swapMsgStates, xToY, yToX) + SwapOrdersExecutionStateInvariants(matchResultMap, swapMsgStates, result, denomX) + } + + // execute transact, refund, expire, send coins with escrow, update state by TransactAndRefundSwapLiquidityPool + if err := k.TransactAndRefundSwapLiquidityPool(ctx, swapMsgStates, matchResultMap, pool, result); err != nil { + return executedMsgCount, err + } + + return executedMsgCount, nil +} diff --git a/x/liquidity/migrations/v2/migrate.go b/x/liquidity/migrations/v2/migrate.go new file mode 100644 index 00000000..99060138 --- /dev/null +++ b/x/liquidity/migrations/v2/migrate.go @@ -0,0 +1,28 @@ +package v2 + +import ( + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/cybercongress/go-cyber/v4/x/liquidity/exported" + "github.com/cybercongress/go-cyber/v4/x/liquidity/types" +) + +func Migrate( + ctx sdk.Context, + store sdk.KVStore, + legacySubspace exported.Subspace, + cdc codec.BinaryCodec, +) error { + var currParams types.Params + legacySubspace.GetParamSet(ctx, &currParams) + + if err := currParams.Validate(); err != nil { + return err + } + + bz := cdc.MustMarshal(&currParams) + store.Set(types.ParamsKey, bz) + + return nil +} diff --git a/x/liquidity/module.go b/x/liquidity/module.go new file mode 100644 index 00000000..546e7d23 --- /dev/null +++ b/x/liquidity/module.go @@ -0,0 +1,168 @@ +package liquidity + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/cybercongress/go-cyber/v4/x/liquidity/exported" + + abci "github.com/cometbft/cometbft/abci/types" + sdkclient "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + + "github.com/cybercongress/go-cyber/v4/x/liquidity/client/cli" + "github.com/cybercongress/go-cyber/v4/x/liquidity/keeper" + "github.com/cybercongress/go-cyber/v4/x/liquidity/types" +) + +var ( + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} +) + +// AppModuleBasic defines the basic application module used by the liquidity module. +type AppModuleBasic struct { + cdc codec.Codec +} + +// Name returns the liquidity module's name. +func (AppModuleBasic) Name() string { + return types.ModuleName +} + +// RegisterLegacyAminoCodec registers the gov module's types for the given codec. +func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + types.RegisterLegacyAminoCodec(cdc) +} + +// DefaultGenesis returns default genesis state as raw bytes for the liquidity module. +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { + return cdc.MustMarshalJSON(types.DefaultGenesisState()) +} + +// ValidateGenesis performs genesis state validation for the liquidity module. +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, _ sdkclient.TxEncodingConfig, bz json.RawMessage) error { + var data types.GenesisState + if err := cdc.UnmarshalJSON(bz, &data); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + + return types.ValidateGenesis(data) +} + +// GetTxCmd returns the root tx command for the liquidity module. +func (AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd() +} + +// GetQueryCmd returns no root query command for the liquidity module. +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd() +} + +// RegisterInterfaces implements InterfaceModule.RegisterInterfaces +func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { + types.RegisterInterfaces(registry) +} + +// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the liquidity module. +func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx sdkclient.Context, mux *runtime.ServeMux) { + if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { + panic(err) + } +} + +// RegisterServices registers module services. +func (am AppModule) RegisterServices(cfg module.Configurator) { + types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) + querier := keeper.Querier{Keeper: am.keeper} + types.RegisterQueryServer(cfg.QueryServer(), querier) + m := keeper.NewMigrator(am.keeper, am.legacySubspace) + if err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2); err != nil { + panic(fmt.Sprintf("failed to migrate x/%s from version 1 to 2: %v", types.ModuleName, err)) + } +} + +// AppModule implements an application module for the liquidity module. +type AppModule struct { + AppModuleBasic + + keeper keeper.Keeper + accountKeeper types.AccountKeeper + bankKeeper types.BankKeeper + distrKeeper types.DistributionKeeper + legacySubspace exported.Subspace +} + +// NewAppModule creates a new AppModule object +func NewAppModule(cdc codec.Codec, + keeper keeper.Keeper, + ak types.AccountKeeper, + bk types.BankKeeper, + dk types.DistributionKeeper, + ss exported.Subspace, +) AppModule { + return AppModule{ + AppModuleBasic: AppModuleBasic{cdc: cdc}, + keeper: keeper, + accountKeeper: ak, + bankKeeper: bk, + distrKeeper: dk, + legacySubspace: ss, + } +} + +// Name returns the liquidity module's name. +func (AppModule) Name() string { + return types.ModuleName +} + +// RegisterLegacyAminoCodec registers the gov module's types for the given codec. +func (AppModule) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + types.RegisterLegacyAminoCodec(cdc) +} + +// RegisterInvariants registers the liquidity module invariants. +func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { + keeper.RegisterInvariants(ir, am.keeper) +} + +// QuerierRoute returns the liquidity module's querier route name. +func (AppModule) QuerierRoute() string { + return types.QuerierRoute +} + +// InitGenesis performs genesis initialization for the liquidity module. It returns +// no validator updates. +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { + var genesisState types.GenesisState + cdc.MustUnmarshalJSON(data, &genesisState) + InitGenesis(ctx, am.keeper, genesisState) + return []abci.ValidatorUpdate{} +} + +// ExportGenesis returns the exported genesis state as raw bytes for the liquidity module. +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { + gs := ExportGenesis(ctx, am.keeper) + return cdc.MustMarshalJSON(gs) +} + +// ConsensusVersion implements AppModule/ConsensusVersion. +func (AppModule) ConsensusVersion() uint64 { return 2 } + +// BeginBlock performs a no-op. +func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { + BeginBlocker(ctx, am.keeper) +} + +// EndBlock returns the end blocker for the liquidity module. It returns no validator updates. +func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { + EndBlocker(ctx, am.keeper) + return []abci.ValidatorUpdate{} +} diff --git a/x/liquidity/spec/01_concepts.md b/x/liquidity/spec/01_concepts.md new file mode 100644 index 00000000..0b4a3d7d --- /dev/null +++ b/x/liquidity/spec/01_concepts.md @@ -0,0 +1,67 @@ + + + # Concepts + +## Liquidity Module + +The liquidity module is a module that can be used on any Cosmos SDK-based application. The liquidity module implements a decentralized exchange (DEX) that serves liquidity providing and coin swap functions. Anyone can create a liquidity pool with a pair of coins, provide liquidity by depositing reserve coins into the liquidity pool, and trade coins using the liquidity pool. All of the logic is designed to always protect the pool investors. + +## Liquidity Pool + +A liquidity pool is a coin reserve that contains two different types of coins in a trading pair. The trading pair has to be unique. A liquidity provider can be anyone (permissionless) who provides liquidity by depositing reserve coins into the pool. The liquidity provider earns the accumulated swap fees with respect to their pool share. The pool share is represented as possession of pool coins. All matchable swap requests are expected to be executed and unmatched swap requests are removed. +## Equivalent Swap Price Model (ESPM) + +The liquidity module is a Cosmos SDK implementation of an AMM system with a novel economic model called the Equivalent Swap Price Model (ESPM). + +The key distinguishing feature of the ESPM model from the Constant Product Market Maker (CPMM) model is the implementation of a hybrid system that combines an orderbook model exchange with a simple liquidity pool model that governs the order book with a set of order rules and performs execution in batches. In the ESPM, the pool price is always equal to the last swap price which reduces opportunities for arbitrage. + +The ESPM model is intended to provide protection against price volatility, transaction ordering vulnerabilities, and losses due to arbitrage. AMMs such as Uniswap do not provide this level of protection. + +## Batch Execution + +The liquidity module uses a batch execution methodology. Deposits, withdrawals, and swap orders are accumulated in a liquidity pool for a pre-defined period that is one or more blocks in length. Orders are then added to the pool and executed at the end of the batch. The size of each batch is configured by using the `UnitBatchSize` governance parameter. + +## Price Discovery + +Swap prices in liquidity pools are determined by the current pool coin reserves and the requested swap amount. Arbitrageurs buy or sell coins in liquidity pools to gain instant profit that results in real-time price discovery of liquidity pools. + +## Escrow Process + +The liquidity module uses a module account that acts as an escrow account. The module account holds and releases the coin amount during batch execution. + +## Refund + +The liquidity module has refund functions when deposit, withdraw, or swap batch states are not successfully executed. +Read [the batch transaction logic](https://github.com/tendermint/liquidity/blob/e8ab2f4d75079157d008eba9f310b199573eed28/x/liquidity/keeper/batch.go#L83-L127) in the code for more context. +## Fees + +You set liquidity module fees for pool creation, withdrawal, and swap in genesis state. These fees can be updated by the governance proposal. +### PoolCreationFee + +The liquidity module pool creation fee set by the `PoolCreationFee` parameter is paid on pool creation. The purpose of this fee is to prevent users from creating useless pools and making limitless transactions. The funds from this fee go to the community fund. +### WithdrawalFeeRate + +The liquidity module has `WithdrawFeeRate` parameter that is paid upon withdrawal. The purpose of this fee is to prevent from making limitless withdrawals. + +### SwapFeeRate + +Swap fees are paid upon swap orders. They are accumulated in the pools and are shared among the liquidity providers. The liquidity module implements half-half-fee mechanism that minimizes the impact of fee payment process. Read [the issue about fees in half offer coins, half exchanged coins](https://github.com/tendermint/liquidity/issues/41) to have more context. +## Pool Identification + +The pools in the liquidity module are identified with: +### PoolName + +- Concatenate two different reserve coin denoms and pool type id and forward slash `/` separator. + - Example: `uatom/stake/1` +### PoolReserveAccount + +- `sdk.AccAddress(crypto.AddressHash([]byte(PoolName)))` + - Example: `cosmos16ddqestwukv0jzcyfn3fdfq9h2wrs83cr4rfm3` (`D35A0CC16EE598F90B044CE296A405BA9C381E38`) +### PoolCoinDenom + +- `fmt.Sprintf("%s%X", PoolCoinDenomPrefix, sha256.Sum256([]byte(PoolName)))` +- Use `PoolCoinDenomPrefix` for `pool` + - Example: `poolD35A0CC16EE598F90B044CE296A405BA9C381E38837599D96F2F70C2F02A23A4` + + + diff --git a/x/liquidity/spec/02_state.md b/x/liquidity/spec/02_state.md new file mode 100644 index 00000000..831d917f --- /dev/null +++ b/x/liquidity/spec/02_state.md @@ -0,0 +1,123 @@ + + + # State + +The liquidity module `x/liquidity` keeps track of the Pool and PoolBatch states. The state represents your app at a given moment. +## Pool + +Pool stores information about the liquidity pool. + +Pool type has the following structure. + +```go +type Pool struct { + Id uint64 // index of this liquidity pool + TypeId uint32 // pool type of this liquidity pool + ReserveCoinDenoms []string // list of reserve coin denoms for this liquidity pool + ReserveAccountAddress string // reserve account address for this liquidity pool to store reserve coins + PoolCoinDenom string // denom of pool coin for this liquidity pool +} +``` + +The parameters of the Pool state are: + +- Pool: `0x11 | Id -> ProtocolBuffer(Pool)` + +- PoolByReserveAccIndex: `0x12 | ReserveAccLen (1 byte) | ReserveAcc -> ProtocolBuffer(uint64)` + +- GlobalLiquidityPoolIdKey: `[]byte("globalLiquidityPoolId")` + +- ModuleName, RouterKey, StoreKey, QuerierRoute: `liquidity` + +- PoolCoinDenomPrefix: `pool` +## PoolBatch + +PoolBatch stores information about the liquidity pool batch states. + +PoolBatch type has the following structure. + +```go +type PoolBatch struct { + PoolId uint64 // id of target liquidity pool + Index uint64 // index of this batch + BeginHeight uint64 // block height when batch is created + DepositMsgIndex uint64 // last index of DepositMsgStates + WithdrawMsgIndex uint64 // last index of WithdrawMsgStates + SwapMsgIndex uint64 // last index of SwapMsgStates + Executed bool // true if executed, false if not executed +} +``` + +## Batch Messages + +Deposit, withdrawal, or swap orders are accumulated in a liquidity pool for a pre-defined period, which can be one or more blocks in length. Orders are then added to the pool and executed at the end of the batch. The following messages are executed in batch-style. + +### DepositMsgState + +`DepositMsgState` defines the state of deposit message as it is processed in the next batch or batches. + +When a user sends `MsgDepositWithinBatch` transaction to the network, it is accumulated in a batch. `DepositMsgState` contains the state information about the message; if the transaction is executed, successfully matched, and if it is to be deleted in the next block. + +```go +type DepositMsgState struct { + MsgHeight int64 // block height where this message is appended to the batch + MsgIndex uint64 // index of this deposit message in this liquidity pool + Executed bool // true if executed on this batch, false if not executed + Succeeded bool // true if executed successfully on this batch, false if failed + ToBeDelete bool // true if ready to be deleted on kvstore, false if not ready to be deleted + Msg MsgDepositWithinBatch +} +``` +### WithdrawMsgState + +`WithdrawMsgState` defines the state of the withdraw message as it is processed in the next batch or batches. + +When a user sends a `MsgWithdrawWithinBatch` transaction to the network, it is accumulated in a batch. `WithdrawMsgState` contains the state information about the message: + +- If the transaction is executed +- If the transaction is successfully matched +- If the transaction will be deleted in the next block + +```go +type WithdrawMsgState struct { + MsgHeight int64 // block height where this message is appended to the batch + MsgIndex uint64 // index of this withdraw message in this liquidity pool + Executed bool // true if executed on this batch, false if not executed + Succeeded bool // true if executed successfully on this batch, false if failed + ToBeDelete bool // true if ready to be deleted on kvstore, false if not ready to be deleted + Msg MsgWithdrawWithinBatch +} +``` +### SwapMsgState + +`SwapMsgState` defines the state of swap message as it is processed in the next batch or batches. + +When a user sends a `MsgSwapWithinBatch` transaction to the network, it is accumulated in a batch. `SwapMsgState` contains the state information about the message: + +- If the transaction is executed +- If the transaction is successfully matched +- If the transaction will be deleted in the next block + +```go +type SwapMsgState struct { + MsgHeight int64 // block height where this message is appended to the batch + MsgIndex uint64 // index of this swap message in this liquidity pool + Executed bool // true if executed on this batch, false if not executed + Succeeded bool // true if executed successfully on this batch, false if failed + ToBeDelete bool // true if ready to be deleted on kvstore, false if not ready to be deleted + OrderExpiryHeight int64 // swap orders are cancelled when current height is equal to or greater than ExpiryHeight + ExchangedOfferCoin sdk.Coin // offer coin exchanged so far + RemainingOfferCoin sdk.Coin // offer coin remaining to be exchanged + Msg MsgSwapWithinBatch +} +``` + +The parameters of the PoolBatch, DepositMsgState, WithdrawMsgState, and SwapMsgState states are: + +- PoolBatch: `0x22 | PoolId -> ProtocolBuffer(PoolBatch)` + +- PoolBatchDepositMsgStates: `0x31 | PoolId | MsgIndex -> ProtocolBuffer(DepositMsgState)` + +- PoolBatchWithdrawMsgStates: `0x32 | PoolId | MsgIndex -> ProtocolBuffer(WithdrawMsgState)` + +- PoolBatchSwapMsgStates: `0x33 | PoolId | MsgIndex -> ProtocolBuffer(SwapMsgState)` diff --git a/x/liquidity/spec/03_state_transitions.md b/x/liquidity/spec/03_state_transitions.md new file mode 100644 index 00000000..6b7c7f08 --- /dev/null +++ b/x/liquidity/spec/03_state_transitions.md @@ -0,0 +1,250 @@ + + + # State Transitions + +These messages (Msg) in the liquidity module trigger state transitions. + +## Coin Escrow for Liquidity Module Messages + +Transaction confirmation causes state transition on the [Bank](https://docs.cosmos.network/master/modules/bank/) module. Some messages on the liquidity module require coin escrow before confirmation. + +The coin escrow processes for each message type are: + +### MsgDepositWithinBatch + +To deposit coins into an existing `Pool`, the depositor must escrow `DepositCoins` into `LiquidityModuleEscrowAccount`. + +### MsgWithdrawWithinBatch + +To withdraw coins from a `Pool`, the withdrawer must escrow `PoolCoin` into `LiquidityModuleEscrowAccount`. + +### MsgSwapWithinBatch + +To request a coin swap, the swap requestor must escrow `OfferCoin` into `LiquidityModuleEscrowAccount`. + +## LiquidityPoolBatch Execution + +Batch execution causes state transitions on the `Bank` module. The following categories describe state transition executed by each process in the `PoolBatch` execution. + +### Coin Swap + +After a successful coin swap, coins accumulated in `LiquidityModuleEscrowAccount` for coin swaps are sent to other swap requestors(self-swap) or to the `Pool`(pool-swap). Fees are also sent to the liquidity `Pool`. + +### LiquidityPool Deposit + +After a successful deposit transaction, escrowed coins are sent to the `ReserveAccount` of the targeted `Pool` and new pool coins are minted and sent to the depositor. + +### LiquidityPool Withdrawal + +After a successful withdraw transaction, escrowed pool coins are burned and a corresponding amount of reserve coins are sent to the withdrawer from the liquidity `Pool`. + +## Pseudo Algorithm for LiquidityPoolBatch Execution + +If you are curious, you can see a Python simulation script on the B-Harvest [GitHub repo](https://github.com/b-harvest/Liquidity-Module-For-the-Hub/blob/master/pseudo-batch-execution-logic/batch.py). + +## Swap Price Calculation + +Swap execution applies a universal swap ratio for all swap requests. + +Swap price calculations are used for these cases. + +**Find price direction** + +Variables: + +- `X`: Reserve of X coin +- `Y`: Reserve of Y coin before this batch execution +- `PoolPrice` = `X`/`Y` +- `XOverLastPrice`: amount of orders that swap X for Y with order price higher than the last `PoolPrice` +- `XAtLastPrice`: amount of orders that swap X for Y with order price equal to the last `PoolPrice` +- `YUnderLastPrice`: amount of orders that swap Y for X with order price lower than last `PoolPrice` +- `YAtLastPrice`: amount of orders that swap Y for X with order price equal to the last `PoolPrice` + +- **Increase**: swap price is increased from the last `PoolPrice` + + - `XOverLastPrice` > (`YUnderLastPrice`+`YAtLastPrice`)*`PoolPrice` + +- **Decrease**: swap price is decreased from the last `PoolPrice` + + - `YUnderLastPrice` > (`XOverLastPrice`+`XAtLastPrice`)/`PoolPrice` + +- **Stay**: swap price is not changed from the last `PoolPrice` when the increase and decrease inequalities do not hold + +### Stay case + +Variables: + +- `swapPrice` = last `PoolPrice` +- `EX`: All executable orders that swap X for Y with order price equal to or greater than last `PoolPrice` +- `EY`: All executable orders that swap Y for X with order price equal or lower than last `PoolPrice` + +- **ExactMatch**: If `EX` == `EY`*`swapPrice` + + - Amount of X coins matched from swap orders = `EX` + - Amount of Y coins matched from swap orders = `EY` + +- **FractionalMatch** + + - If `EX` > `EY`*`swapPrice`: Residual X order amount remains + + - Amount of X coins matched from swap orders = `EY`*`swapPrice` + - Amount of Y coins matched from swap orders = `EY` + + - If `EY` > `EX`/`swapPrice`: Residual Y order amount remains + + - Amount of X coins matched from swap orders = `EX` + - Amount of Y coins matched from swap orders = `EX`/`swapPrice` + +### Increase case + +Iteration: iterate `orderPrice(i)` of all swap orders from low to high. + +Variables: + +- `EX(i)`: Sum of all order amount of swap orders that swap X for Y with order price equal or higher than this `orderPrice(i)` +- `EY(i)`: Sum of all order amounts of swap orders that swap Y for X with order price equal or lower than this `orderPrice(i)` + +- ExactMatch: SwapPrice is found between two orderPrices + + - `swapPrice(i)` = (`X` + 2_`EX(i)`)/(`Y` + 2_`EY(i-1)`) + + - condition1) `orderPrice(i-1)` < `swapPrice(i)` < `orderPrice(i)` + + - `PoolY(i)` = (`swapPrice(i)`_`Y` - `X`) / (2_`swapPrice(i)`) + + - condition2) `PoolY(i)` >= 0 + + - If both above conditions are met, `swapPrice` is the swap price for this iteration + + - Amount of X coins matched = `EX(i)` + + - If one of these conditions doesn't hold, go to FractionalMatch + +- FractionalMatch: SwapPrice is found at an orderPrice + + - `swapPrice(i)` = `orderPrice(i)` + - `PoolY(i)` = (`swapPrice(i)`_`Y` - `X`) / (2_`swapPrice(i)`) + - Amount of X coins matched: + + - `EX(i)` ← min[ `EX(i)`, (`EY(i)`+`PoolY(i)`)*`swapPrice(i)` ] + +- Find optimized swapPrice: + + - Find `swapPrice(k)` that has the largest amount of X coins matched + + - this is our optimized swap price + - corresponding swap result variables + + - `swapPrice(k)`, `EX(k)`, `EY(k)`, `PoolY(k)` + +### Decrease case + +Iteration: iterate `orderPrice(i)` of all swap orders from high to low. + +Variables: + +- `EX(i)`: Sum of all order amount of swap orders that swap X for Y with order price equal or higher than this `orderPrice(i)` +- `EY(i)`: Sum of all order amount of swap orders that swap Y for X with order price equal or lower than this `orderPrice(i)` + +- ExactMatch: SwapPrice is found between two orderPrices + +- `swapPrice(i)` = (`X` + 2_`EX(i)`)/(`Y` + 2_`EY(i-1)`) + + - condition1) `orderPrice(i)` < `swapPrice(i)` < `orderPrice(i-1)` + +- `PoolX(i)` = (`X` - `swapPrice(i)`*`Y`)/2 + + - condition2) `PoolX(i)` >= 0 + +- If both above conditions are met, `swapPrice` is the swap price for this iteration + + - Amount of Y coins matched = `EY(i)` + +- If one of these conditions doesn't hold, go to FractionalMatch + +- FractionalMatch: SwapPrice is found at an orderPrice + +- `swapPrice(i)` = `orderPrice(i)` + +- `PoolX(i)` = (`X` - `swapPrice(i)`*`Y`)/2 + +- Amount of Y coins matched: + + - `EY(i)` ← min[ `EY(i)`, (`EX(i)`+`PoolX(i)`)/`swapPrice(i)` ] + +- Find optimized swapPrice + + - Find `swapPrice(k)` that has the largest amount of Y coins matched + + - this is our optimized swap price + - corresponding swap result variables + + - `swapPrice(k)`, `EX(k)`, `EY(k)`, `PoolX(k)` + +### Calculate matching result + +- for swap orders from X to Y + + - Iteration: iterate `orderPrice(i)` of swap orders from X to Y (high to low) + + - sort by order price (high to low), sum all order amount with each `orderPrice(i)` + - if `EX(i)` ≤ `EX(k)` + + - `fractionalRatio` = 1 + + - if `EX(i)` > `EX(k)` + + - `fractionalRatio(i)` = (`EX(k)` - `EX(i-1)`) / (`EX(i)` - `EX(i-1)`) + - break the iteration + + - matching amount for swap orders with this `orderPrice(i)`: + + - `matchingAmt` = `offerAmt` * `fractionalRatio(i)` + +- for swap orders from Y to X + + - Iteration: iterate `orderPrice(i)` of swap orders from Y to X (low to high) + + - sort by order price (low to high), sum all order amount with each `orderPrice(i)` + - if `EY(i)` ≤ `EY(k)` + + - `fractionalRatio` = 1 + + - if `EY(i)` > `EY(k)` + + - `fractionalRatio(i)` = (`EY(k)` - `EY(i-1)`) / (`EY(i)` - `EY(i-1)`) + - break the iteration + + - matching amount for swap orders with this `orderPrice(i)`: + + - `matchingAmt` = `offerAmt` * `fractionalRatio(i)` + +### Swap Fee Payment + +Rather than taking fee solely from `OfferCoin`, liquidity module is designed to take fees half from `OfferCoin`, and the other half from `ExchangedCoin`. This smooths out an impact of the fee payment process. +- **OfferCoin Fee Reservation ( fee before batch process, in OfferCoin )** + - when user orders 100 Xcoin, the swap message demands + - `OfferCoin`(in Xcoin) : 100 + - `ReservedOfferCoinFeeAmount`(in Xcoin) = `OfferCoin`*(`SwapFeeRate`/2) + - user needs to have at least 100+100*(`SwapFeeRate`/2) amount of Xcoin to successfully commit this swap message + - the message fails when user's balance is below this amount +- **Actual Fee Payment** + - if 10 Xcoin is executed + - **OfferCoin Fee Payment from Reserved OfferCoin Fee** + - `OfferCoinFeeAmount`(in Xcoin) = (10/100)*`ReservedOfferCoinFeeAmount` + - `ReservedOfferCoinFeeAmount` is reduced from this fee payment + - **ExchangedCoin Fee Payment ( fee after batch process, in ExchangedCoin )** + - `ExchangedCoinFeeAmount`(in Ycoin) = `OfferCoinFeeAmount` / `SwapPrice` + - this is exactly equal value compared to advance fee payment assuming the current SwapPrice, to minimize the pool price impact from fee payment process + +- Swap fees are proportional to the coins received from matched swap orders. +- Swap fees are sent to the liquidity pool. +- The decimal points of the swap fees are rounded up. + +## Cancel unexecuted swap orders with expired CancelHeight + +After execution of `PoolBatch`, all remaining swap orders with `CancelHeight` equal to or higher than current height are cancelled. + +## Refund escrowed coins + +Refunds are issued for escrowed coins for cancelled swap order and failed create pool, deposit, and withdraw messages. diff --git a/x/liquidity/spec/04_messages.md b/x/liquidity/spec/04_messages.md new file mode 100644 index 00000000..1cf2a383 --- /dev/null +++ b/x/liquidity/spec/04_messages.md @@ -0,0 +1,104 @@ + + + # Messages + +Messages (Msg) are objects that trigger state transitions. Msgs are wrapped in transactions (Txs) that clients submit to the network. The Cosmos SDK wraps and unwraps liquidity module messages from transactions. + +## MsgCreatePool + +A liquidity pool is created and initial coins are deposited with the `MsgCreatePool` message. + +```go +type MsgCreatePool struct { + PoolCreatorAddress string // account address of the origin of this message + PoolTypeId uint32 // id of the new liquidity pool + DepositCoins sdk.Coins // deposit initial coins for new liquidity pool +} +``` + +### Validity Checks + +Validity checks are performed for MsgCreatePool messages. The transaction that is triggered with `MsgCreatePool` fails if: + +- if `params.CircuitBreakerEnabled` is true +- `PoolCreator` address does not exist +- `PoolTypeId` does not exist in parameters +- A duplicate `LiquidityPool` with same `PoolTypeId` and `ReserveCoinDenoms` exists +- One or more coins in `ReserveCoinDenoms` do not exist in `bank` module +- The balance of `PoolCreator` does not have enough amount of coins for `DepositCoins` +- The balance of `PoolCreator` does not have enough coins for `PoolCreationFee` + +## MsgDepositWithinBatch + +Coins are deposited in a batch to a liquidity pool with the `MsgDepositWithinBatch` message. + +```go +type MsgDepositWithinBatch struct { + DepositorAddress string // account address of depositor that originated this message + PoolId uint64 // id of the liquidity pool to receive deposit + DepositCoins sdk.Coins // deposit coins +} +``` + +## Validity Checks + +The MsgDepositWithinBatch message performs validity checks. The transaction that is triggered with the `MsgDepositWithinBatch` message fails if: + +- if `params.CircuitBreakerEnabled` is true +- `Depositor` address does not exist +- `PoolId` does not exist +- The denoms of `DepositCoins` are not composed of existing `ReserveCoinDenoms` of the specified `LiquidityPool` +- The balance of `Depositor` does not have enough coins for `DepositCoins` + +## MsgWithdrawWithinBatch + +Withdraw coins in batch from liquidity pool with the `MsgWithdrawWithinBatch` message. + +```go +type MsgWithdrawWithinBatch struct { + WithdrawerAddress string // account address of the origin of this message + PoolId uint64 // id of the liquidity pool to withdraw the coins from + PoolCoin sdk.Coin // pool coin sent for reserve coin withdrawal +} +``` + +## Validity Checks + +The MsgWithdrawWithinBatch message performs validity checks. The transaction that is triggered with the `MsgWithdrawWithinBatch` message fails if: + +- `Withdrawer` address does not exist +- `PoolId` does not exist +- The denom of `PoolCoin` are not equal to the `PoolCoinDenom` of the `LiquidityPool` +- The balance of `Depositor` does not have enough coins for `PoolCoin` + +## MsgSwapWithinBatch + +Swap coins between liquidity pools in batch with the `MsgSwapWithinBatch` message. + +Offer coins are swapped with demand coins for the given order price. + +```go +type MsgSwapWithinBatch struct { + SwapRequesterAddress string // account address of the origin of this message + PoolId uint64 // id of the liquidity pool + SwapTypeId uint32 // swap type id of this swap message, default 1: InstantSwap, requesting instant swap + OfferCoin sdk.Coin // offer coin of this swap + DemandCoinDenom string // denom of demand coin of this swap + OfferCoinFee sdk.Coin // offer coin fee for pay fees in half offer coin + OrderPrice sdk.Dec // limit order price where the price is the exchange ratio of X/Y where X is the amount of the first coin and Y is the amount of the second coin when their denoms are sorted alphabetically +} +``` + +## Validity checks + +The MsgSwapWithinBatch message performs validity checks. The transaction that is triggered with the `MsgSwapWithinBatch` message fails if: + +- if `params.CircuitBreakerEnabled` is true +- `SwapRequester` address does not exist +- `PoolId` does not exist +- `SwapTypeId` does not exist +- Denoms of `OfferCoin` or `DemandCoin` do not exist in `bank` module +- The balance of `SwapRequester` does not have enough coins for `OfferCoin` +- `OrderPrice` <= zero +- `OfferCoinFee` equals `OfferCoin` * `params.SwapFeeRate` * `0.5` with ceiling +- Has sufficient balance `OfferCoinFee` to reserve offer coin fee diff --git a/x/liquidity/spec/05_begin_block.md b/x/liquidity/spec/05_begin_block.md new file mode 100644 index 00000000..bfe2d735 --- /dev/null +++ b/x/liquidity/spec/05_begin_block.md @@ -0,0 +1,18 @@ + + + # Begin-Block + +Begin block operations for the liquidity module reinitialize batch messages that were not executed in the previous batch and delete batch messages that were executed or ready to be deleted. + +## Delete pool batch messages and reset states for pool batch messages + +- Delete `{*action}MsgState` messages that have `ToBeDeleted` state +- Reset states for the remaining `{*action}MsgState` messages to execute on `end-block` of the next batch index + +## Reinitialize executed pool batch to next liquidity pool batch + +Reinitialize the executed `PoolBatch` for the next batch. The reinitialization process includes the following actions: + +- Increase state `BatchIndex` of the batch +- Reset state `BeginHeight` as current block height +- Reset state `Executed` as `false` diff --git a/x/liquidity/spec/06_end_block.md b/x/liquidity/spec/06_end_block.md new file mode 100644 index 00000000..e0d0d2b7 --- /dev/null +++ b/x/liquidity/spec/06_end_block.md @@ -0,0 +1,32 @@ + + + # Before-End-Block + +These operations occur before the end-block operations for the liquidity module. + +## Append messages to LiquidityPoolBatch + +After successful message verification and coin `escrow` process, the incoming `MsgDepositWithinBatch`, `MsgWithdrawWithinBatch`, and `MsgSwapWithinBatch` messages are appended to the current `PoolBatch` of the corresponding `Pool`. + +# End-Block + +End-block operations for the Liquidity Module. + +## Execute LiquidityPoolBatch upon execution heights + +If there are `{*action}MsgState` messages that have not yet executed in the `PoolBatch` for each `Pool`, the `PoolBatch` is executed. This batch contains one or more `DepositLiquidityPool`, `WithdrawLiquidityPool`, and `SwapExecution` processes. + +### Transact and refund for each message + +A liquidity module escrow account holds coins temporarily and releases them when state changes. Refunds from the escrow account are made for cancellations, partial cancellations, expiration, and failed messages. + +### Set states for each message according to the results + +After transact and refund transactions occur for each message, update the state of each `{*action}MsgState` message according to the results. + +Even if the message is completed or expired: + +1. Set the `ToBeDeleted` state value as true instead of deleting the message directly from the `end-block` +2. Delete the messages that have `ToBeDeleted` state from the begin-block in the next block so that each message with result state in the block can be stored to kvstore. + +This process allows searching for the past messages that have this result state. Searching is supported when the kvstore is not pruning. diff --git a/x/liquidity/spec/07_events.md b/x/liquidity/spec/07_events.md new file mode 100644 index 00000000..74e6b160 --- /dev/null +++ b/x/liquidity/spec/07_events.md @@ -0,0 +1,118 @@ + + + # Events + +The liquidity module emits the following events. + +## Handlers + +### MsgCreatePool + +Type | Attribute Key | Attribute Value +----------- | --------------- | ------------------------ +create_pool | pool_id | {poolId} +create_pool | pool_type_id | {poolTypeId} +create_pool | pool_name | {AttributeValuePoolName} +create_pool | reserve_account | {reserveAccountAddress} +create_pool | deposit_coins | {depositCoins} +create_pool | pool_coin_denom | {poolCoinDenom} +message | module | liquidity +message | action | create_pool +message | sender | {senderAddress} + +### MsgDepositWithinBatch + +Type | Attribute Key | Attribute Value +-------------------- | ------------- | -------------------- +deposit_within_batch | pool_id | {poolId} +deposit_within_batch | batch_index | {batchIndex} +deposit_within_batch | msg_index | {depositMsgIndex} +deposit_within_batch | deposit_coins | {depositCoins} +message | module | liquidity +message | action | deposit_within_batch +message | sender | {senderAddress} + +### MsgWithdrawWithinBatch + +Type | Attribute Key | Attribute Value +--------------------- | ---------------- | --------------------- +withdraw_within_batch | pool_id | {poolId} +withdraw_within_batch | batch_index | {batchIndex} +withdraw_within_batch | msg_index | {withdrawMsgIndex} +withdraw_within_batch | pool_coin_denom | {poolCoinDenom} +withdraw_within_batch | pool_coin_amount | {poolCoinAmount} +message | module | liquidity +message | action | withdraw_within_batch +message | sender | {senderAddress} + +### MsgSwapWithinBatch + +Type | Attribute Key | Attribute Value +----------------- | ----------------- | ----------------- +swap_within_batch | pool_id | {poolId} +swap_within_batch | batch_index | {batchIndex} +swap_within_batch | msg_index | {swapMsgIndex} +swap_within_batch | swap_type_id | {swapTypeId} +swap_within_batch | offer_coin_denom | {offerCoinDenom} +swap_within_batch | offer_coin_amount | {offerCoinAmount} +swap_within_batch | demand_coin_denom | {demandCoinDenom} +swap_within_batch | order_price | {orderPrice} +message | module | liquidity +message | action | swap_within_batch +message | sender | {senderAddress} + +## EndBlocker + +### Batch Result for MsgDepositWithinBatch + +Type | Attribute Key | Attribute Value +--------------- | ---------------- | ------------------ +deposit_to_pool | pool_id | {poolId} +deposit_to_pool | batch_index | {batchIndex} +deposit_to_pool | msg_index | {depositMsgIndex} +deposit_to_pool | depositor | {depositorAddress} +deposit_to_pool | accepted_coins | {acceptedCoins} +deposit_to_pool | refunded_coins | {refundedCoins} +deposit_to_pool | pool_coin_denom | {poolCoinDenom} +deposit_to_pool | pool_coin_amount | {poolCoinAmount} +deposit_to_pool | success | {success} + +### Batch Result for MsgWithdrawWithinBatch + +| Type | Attribute Key | Attribute Value | +| ------------------ | ------------------ | ------------------- | +| withdraw_from_pool | pool_id | {poolId} | +| withdraw_from_pool | batch_index | {batchIndex} | +| withdraw_from_pool | msg_index | {withdrawMsgIndex} | +| withdraw_from_pool | withdrawer | {withdrawerAddress} | +| withdraw_from_pool | pool_coin_denom | {poolCoinDenom} | +| withdraw_from_pool | pool_coin_amount | {poolCoinAmount} | +| withdraw_from_pool | withdraw_coins | {withdrawCoins} | +| withdraw_from_pool | withdraw_fee_coins | {withdrawFeeCoins} | +| withdraw_from_pool | success | {success} | + +### Batch Result for MsgSwapWithinBatch + +Type | Attribute Key | Attribute Value +--------------- | ------------------------------ | ---------------------------- +swap_transacted | pool_id | {poolId} +swap_transacted | batch_index | {batchIndex} +swap_transacted | msg_index | {swapMsgIndex} +swap_transacted | swap_requester | {swapRequesterAddress} +swap_transacted | swap_type_id | {swapTypeId} +swap_transacted | offer_coin_denom | {offerCoinDenom} +swap_transacted | offer_coin_amount | {offerCoinAmount} +swap_transacted | exchanged_coin_denom | {exchangedCoinDenom} +swap_transacted | order_price | {orderPrice} +swap_transacted | swap_price | {swapPrice} +swap_transacted | transacted_coin_amount | {transactedCoinAmount} +swap_transacted | remaining_offer_coin_amount | {remainingOfferCoinAmount} +swap_transacted | exchanged_offer_coin_amount | {exchangedOfferCoinAmount} +swap_transacted | exchanged_demand_coin_amount | {exchangedDemandCoinAmount} +swap_transacted | offer_coin_fee_amount | {offerCoinFeeAmount} +swap_transacted | exchanged_coin_fee_amount | {exchangedCoinFeeAmount} +swap_transacted | reserved_offer_coin_fee_amount | {reservedOfferCoinFeeAmount} +swap_transacted | order_expiry_height | {orderExpiryHeight} +swap_transacted | success | {success} + + diff --git a/x/liquidity/spec/08_params.md b/x/liquidity/spec/08_params.md new file mode 100644 index 00000000..255731fd --- /dev/null +++ b/x/liquidity/spec/08_params.md @@ -0,0 +1,92 @@ + + + # Parameters + +The liquidity module contains the following parameters: + +Key | Type | Example +---------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------- +PoolTypes | []PoolType | [{"id":1,"name":"StandardLiquidityPool","min_reserve_coin_num":2,"max_reserve_coin_num":2,"description":"Standard liquidity pool with pool price function X/Y, ESPM constraint, and two kinds of reserve coins"}] +MinInitDepositAmount | string (math.Int) | "1000000" +InitPoolCoinMintAmount | string (math.Int) | "1000000" +MaxReserveCoinAmount | string (math.Int) | "0" +PoolCreationFee | sdk.Coins | [{"denom":"stake","amount":"40000000"}] +SwapFeeRate | string (sdk.Dec) | "0.003000000000000000" +WithdrawFeeRate | string (sdk.Dec) | "0.000000000000000000" +MaxOrderAmountRatio | string (sdk.Dec) | "0.100000000000000000" +UnitBatchHeight | uint32 | 1 +CircuitBreakerEnabled | bool | false + +## PoolTypes + +List of available PoolType + +```go +type PoolType struct { + Id uint32 + Name string + MinReserveCoinNum uint32 + MaxReserveCoinNum uint32 + Description string +} +``` + +## MinInitDepositAmount + +Minimum number of coins to be deposited to the liquidity pool upon pool creation. + +## InitPoolCoinMintAmount + +Initial mint amount of pool coin on pool creation. + +## MaxReserveCoinAmount + +Limit the size of each liquidity pool. The deposit transaction fails if the total reserve coin amount after the deposit is larger than the reserve coin amount. + +The default value of zero means no limit. + +**Note:** Especially in the early phases of liquidity module adoption, set `MaxReserveCoinAmount` to a non-zero value to minimize risk on error or exploitation. + +## PoolCreationFee + +Fee paid for to create a LiquidityPool creation. This fee prevents spamming and is collected in in the community pool of the distribution module. + +## SwapFeeRate + +Swap fee rate for every executed swap. When a swap is requested, the swap fee is reserved: + +- Half reserved as `OfferCoinFee` +- Half reserved as `ExchangedCoinFee` + +The swap fee is collected when a batch is executed. + +## WithdrawFeeRate + +Reserve coin withdrawal with less proportion by `WithdrawFeeRate`. This fee prevents attack vectors from repeated deposit/withdraw transactions. + +## MaxOrderAmountRatio + +Maximum ratio of reserve coins that can be ordered at a swap order. + +## UnitBatchHeight + +The smallest unit batch size for every liquidity pool. + +## CircuitBreakerEnabled + +The intention of circuit breaker is to have a contingency plan for a running network which maintains network liveness. This parameter enables or disables `MsgCreatePool`, `MsgDepositWithinBatch` and `MsgSwapWithinBatch` message types in liquidity module. +# Constant Variables + +Key | Type | Constant Value +------------------- | ------ | -------------- +CancelOrderLifeSpan | int64 | 0 +MinReserveCoinNum | uint32 | 2 +MaxReserveCoinNum | uint32 | 2 + +## CancelOrderLifeSpan + +The life span of swap orders in block heights. + +## MinReserveCoinNum, MaxReserveCoinNum + +The mininum and maximum number of reserveCoins for `PoolType`. diff --git a/x/liquidity/spec/README.md b/x/liquidity/spec/README.md new file mode 100644 index 00000000..9faf82fd --- /dev/null +++ b/x/liquidity/spec/README.md @@ -0,0 +1,27 @@ + + + # `liquidity` + +## Abstract + +This document specifies the liquidity module of the Cosmos SDK that serves AMM (Automated Market Makers) style decentralized liquidity providing and coin swap functions. + +The module enables you to create a liquidity pool with a pair of coins, deposit reserve coins into the pool to provide liquidity, request withdrawal from the pool, and trade coins using the liquidity pool. + +This module is available in the Cosmos Hub and can be used by other blockchains that are based on the Cosmos SDK. + +## Contents + +1. **[Concepts](01_concepts.md)** +2. **[State](02_state.md)** +3. **[State Transitions](03_state_transitions.md)** +4. **[Messages](04_messages.md)** +5. **[Begin-Block](05_begin_block.md)** +6. **[End-Block](06_end_block.md)** +7. **[Events](07_events.md)** +8. **[Parameters](08_params.md)** + +## References + +- [Liquidity module proposal and milestone](https://github.com/b-harvest/Liquidity-Module-For-the-Hub) +- [Cosmos SDK modules](https://github.com/cosmos/cosmos-sdk/tree/master/x) diff --git a/x/liquidity/types/codec.go b/x/liquidity/types/codec.go new file mode 100644 index 00000000..df9096fb --- /dev/null +++ b/x/liquidity/types/codec.go @@ -0,0 +1,54 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/msgservice" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" +) + +// RegisterLegacyAminoCodec registers concrete types on the codec. +func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + cdc.RegisterConcrete(&MsgCreatePool{}, "liquidity/MsgCreatePool", nil) + cdc.RegisterConcrete(&MsgDepositWithinBatch{}, "liquidity/MsgDepositWithinBatch", nil) + cdc.RegisterConcrete(&MsgWithdrawWithinBatch{}, "liquidity/MsgWithdrawWithinBatch", nil) + cdc.RegisterConcrete(&MsgSwapWithinBatch{}, "liquidity/MsgSwapWithinBatch", nil) +} + +// RegisterInterfaces registers the x/liquidity interface types with the +// interface registry +func RegisterInterfaces(registry types.InterfaceRegistry) { + registry.RegisterImplementations((*sdk.Msg)(nil), + &MsgCreatePool{}, + &MsgDepositWithinBatch{}, + &MsgWithdrawWithinBatch{}, + &MsgSwapWithinBatch{}, + ) + msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +} + +// legacy amino codecs +var ( + amino = codec.NewLegacyAmino() + + // ModuleCdc references the global x/liquidity module codec. Note, the + // codec should ONLY be used in certain instances of tests and for JSON + // encoding as Amino is still used for that purpose. + // + // The actual codec used for serialization should be provided to x/liquidity + // and defined at the application level. + ModuleCdc = codec.NewAminoCodec(amino) +) + +func init() { + RegisterLegacyAminoCodec(amino) + cryptocodec.RegisterCrypto(amino) + // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be + // used to properly serialize MsgGrant and MsgExec instances + sdk.RegisterLegacyAminoCodec(amino) + RegisterLegacyAminoCodec(authzcodec.Amino) + + amino.Seal() +} diff --git a/x/liquidity/types/errors.go b/x/liquidity/types/errors.go new file mode 100644 index 00000000..0b7b2235 --- /dev/null +++ b/x/liquidity/types/errors.go @@ -0,0 +1,50 @@ +package types + +import ( + sdkerrors "cosmossdk.io/errors" +) + +// liquidity module sentinel errors +var ( + ErrPoolNotExists = sdkerrors.Register(ModuleName, 1, "pool not exists") + ErrPoolTypeNotExists = sdkerrors.Register(ModuleName, 2, "pool type not exists") + ErrEqualDenom = sdkerrors.Register(ModuleName, 3, "reserve coin denomination are equal") + ErrInvalidDenom = sdkerrors.Register(ModuleName, 4, "invalid denom") + ErrNumOfReserveCoin = sdkerrors.Register(ModuleName, 5, "invalid number of reserve coin") + ErrNumOfPoolCoin = sdkerrors.Register(ModuleName, 6, "invalid number of pool coin") + ErrInsufficientPool = sdkerrors.Register(ModuleName, 7, "insufficient pool") + ErrInsufficientBalance = sdkerrors.Register(ModuleName, 8, "insufficient coin balance") + ErrLessThanMinInitDeposit = sdkerrors.Register(ModuleName, 9, "deposit coin less than MinInitDepositAmount") + ErrNotImplementedYet = sdkerrors.Register(ModuleName, 10, "not implemented yet") + ErrPoolAlreadyExists = sdkerrors.Register(ModuleName, 11, "the pool already exists") + ErrPoolBatchNotExists = sdkerrors.Register(ModuleName, 12, "pool batch not exists") + ErrOrderBookInvalidity = sdkerrors.Register(ModuleName, 13, "orderbook is not validity") + ErrBatchNotExecuted = sdkerrors.Register(ModuleName, 14, "the liquidity pool batch is not executed") + ErrInvalidPoolCreatorAddr = sdkerrors.Register(ModuleName, 15, "invalid pool creator address") + ErrInvalidDepositorAddr = sdkerrors.Register(ModuleName, 16, "invalid pool depositor address") + ErrInvalidWithdrawerAddr = sdkerrors.Register(ModuleName, 17, "invalid pool withdrawer address") + ErrInvalidSwapRequesterAddr = sdkerrors.Register(ModuleName, 18, "invalid pool swap requester address") + ErrBadPoolCoinAmount = sdkerrors.Register(ModuleName, 19, "invalid pool coin amount") + ErrBadDepositCoinsAmount = sdkerrors.Register(ModuleName, 20, "invalid deposit coins amount") + ErrBadOfferCoinAmount = sdkerrors.Register(ModuleName, 21, "invalid offer coin amount") + ErrBadOrderingReserveCoin = sdkerrors.Register(ModuleName, 22, "reserve coin denoms not ordered alphabetical") + ErrBadOrderPrice = sdkerrors.Register(ModuleName, 23, "invalid order price") + ErrNumOfReserveCoinDenoms = sdkerrors.Register(ModuleName, 24, "invalid reserve coin denoms") + ErrEmptyReserveAccountAddress = sdkerrors.Register(ModuleName, 25, "empty reserve account address") + ErrEmptyPoolCoinDenom = sdkerrors.Register(ModuleName, 26, "empty pool coin denom") + ErrBadOrderingReserveCoinDenoms = sdkerrors.Register(ModuleName, 27, "bad ordering reserve coin denoms") + ErrBadReserveAccountAddress = sdkerrors.Register(ModuleName, 28, "bad reserve account address") + ErrBadPoolCoinDenom = sdkerrors.Register(ModuleName, 29, "bad pool coin denom") + ErrInsufficientPoolCreationFee = sdkerrors.Register(ModuleName, 30, "insufficient balances for pool creation fee") + ErrExceededMaxOrderable = sdkerrors.Register(ModuleName, 31, "can not exceed max order ratio of reserve coins that can be ordered at a order") + ErrBadBatchMsgIndex = sdkerrors.Register(ModuleName, 32, "bad msg index of the batch") + ErrSwapTypeNotExists = sdkerrors.Register(ModuleName, 33, "swap type not exists") + ErrLessThanMinOfferAmount = sdkerrors.Register(ModuleName, 34, "offer amount should be over 100 micro") + ErrBadOfferCoinFee = sdkerrors.Register(ModuleName, 35, "bad offer coin fee") + ErrNotMatchedReserveCoin = sdkerrors.Register(ModuleName, 36, "does not match the reserve coin of the pool") + ErrBadPoolTypeID = sdkerrors.Register(ModuleName, 37, "invalid index of the pool type") + ErrExceededReserveCoinLimit = sdkerrors.Register(ModuleName, 38, "can not exceed reserve coin limit amount") + ErrDepletedPool = sdkerrors.Register(ModuleName, 39, "the pool is depleted of reserve coin, reinitializing is required by deposit") + ErrCircuitBreakerEnabled = sdkerrors.Register(ModuleName, 40, "circuit breaker is triggered") + ErrOverflowAmount = sdkerrors.Register(ModuleName, 41, "invalid amount that can cause overflow") +) diff --git a/x/liquidity/types/events.go b/x/liquidity/types/events.go new file mode 100644 index 00000000..50475c0b --- /dev/null +++ b/x/liquidity/types/events.go @@ -0,0 +1,53 @@ +package types + +// Event types for the liquidity module. +const ( + EventTypeCreatePool = TypeMsgCreatePool + EventTypeDepositWithinBatch = TypeMsgDepositWithinBatch + EventTypeWithdrawWithinBatch = TypeMsgWithdrawWithinBatch + EventTypeSwapWithinBatch = TypeMsgSwapWithinBatch + EventTypeDepositToPool = "deposit_to_pool" + EventTypeWithdrawFromPool = "withdraw_from_pool" + EventTypeSwapTransacted = "swap_transacted" + + AttributeValuePoolId = "pool_id" //nolint:revive + AttributeValuePoolTypeId = "pool_type_id" //nolint:revive + AttributeValuePoolName = "pool_name" + AttributeValueReserveAccount = "reserve_account" + AttributeValuePoolCoinDenom = "pool_coin_denom" + AttributeValuePoolCoinAmount = "pool_coin_amount" + AttributeValueBatchIndex = "batch_index" + AttributeValueMsgIndex = "msg_index" + + AttributeValueDepositCoins = "deposit_coins" + + AttributeValueOfferCoinDenom = "offer_coin_denom" + AttributeValueOfferCoinAmount = "offer_coin_amount" + AttributeValueOfferCoinFeeAmount = "offer_coin_fee_amount" + AttributeValueExchangedCoinFeeAmount = "exchanged_coin_fee_amount" + AttributeValueDemandCoinDenom = "demand_coin_denom" + AttributeValueOrderPrice = "order_price" + + AttributeValueDepositor = "depositor" + AttributeValueRefundedCoins = "refunded_coins" + AttributeValueAcceptedCoins = "accepted_coins" + AttributeValueSuccess = "success" + AttributeValueWithdrawer = "withdrawer" + AttributeValueWithdrawCoins = "withdraw_coins" + AttributeValueWithdrawFeeCoins = "withdraw_fee_coins" + AttributeValueSwapRequester = "swap_requester" + AttributeValueSwapTypeId = "swap_type_id" //nolint:revive + AttributeValueSwapPrice = "swap_price" + + AttributeValueTransactedCoinAmount = "transacted_coin_amount" + AttributeValueRemainingOfferCoinAmount = "remaining_offer_coin_amount" + AttributeValueExchangedOfferCoinAmount = "exchanged_offer_coin_amount" + AttributeValueExchangedDemandCoinAmount = "exchanged_demand_coin_amount" + AttributeValueReservedOfferCoinFeeAmount = "reserved_offer_coin_fee_amount" + AttributeValueOrderExpiryHeight = "order_expiry_height" + + AttributeValueCategory = ModuleName + + Success = "success" + Failure = "failure" +) diff --git a/x/liquidity/types/expected_keepers.go b/x/liquidity/types/expected_keepers.go new file mode 100644 index 00000000..60478f98 --- /dev/null +++ b/x/liquidity/types/expected_keepers.go @@ -0,0 +1,33 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" +) + +// BankKeeper defines the expected bank send keeper +type BankKeeper interface { + InputOutputCoins(ctx sdk.Context, inputs []banktypes.Input, outputs []banktypes.Output) error + SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error + GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins + GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin + SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins + + GetSupply(ctx sdk.Context, denom string) sdk.Coin + SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error + SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error + BurnCoins(ctx sdk.Context, name string, amt sdk.Coins) error + MintCoins(ctx sdk.Context, name string, amt sdk.Coins) error +} + +// AccountKeeper defines the expected account keeper +type AccountKeeper interface { + GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI + GetModuleAddress(name string) sdk.AccAddress +} + +// DistributionKeeper defines the expected distribution keeper +type DistributionKeeper interface { + FundCommunityPool(ctx sdk.Context, amount sdk.Coins, sender sdk.AccAddress) error +} diff --git a/x/liquidity/types/genesis.go b/x/liquidity/types/genesis.go new file mode 100644 index 00000000..1f11496f --- /dev/null +++ b/x/liquidity/types/genesis.go @@ -0,0 +1,44 @@ +package types + +// NewGenesisState returns new GenesisState. +func NewGenesisState(params Params, liquidityPoolRecords []PoolRecord) *GenesisState { + return &GenesisState{ + Params: params, + PoolRecords: liquidityPoolRecords, + } +} + +// DefaultGenesisState returns the default genesis state. +func DefaultGenesisState() *GenesisState { + return NewGenesisState(DefaultParams(), []PoolRecord{}) +} + +// ValidateGenesis validates GenesisState. +func ValidateGenesis(data GenesisState) error { + if err := data.Params.Validate(); err != nil { + return err + } + for _, record := range data.PoolRecords { + if err := record.Validate(); err != nil { + return err + } + } + return nil +} + +// Validate validates PoolRecord. +func (record PoolRecord) Validate() error { + if record.PoolBatch.DepositMsgIndex == 0 || + (len(record.DepositMsgStates) > 0 && record.PoolBatch.DepositMsgIndex != record.DepositMsgStates[len(record.DepositMsgStates)-1].MsgIndex+1) { + return ErrBadBatchMsgIndex + } + if record.PoolBatch.WithdrawMsgIndex == 0 || + (len(record.WithdrawMsgStates) != 0 && record.PoolBatch.WithdrawMsgIndex != record.WithdrawMsgStates[len(record.WithdrawMsgStates)-1].MsgIndex+1) { + return ErrBadBatchMsgIndex + } + if record.PoolBatch.SwapMsgIndex == 0 || + (len(record.SwapMsgStates) != 0 && record.PoolBatch.SwapMsgIndex != record.SwapMsgStates[len(record.SwapMsgStates)-1].MsgIndex+1) { + return ErrBadBatchMsgIndex + } + return nil +} diff --git a/x/liquidity/types/genesis.pb.go b/x/liquidity/types/genesis.pb.go new file mode 100644 index 00000000..cc0a8300 --- /dev/null +++ b/x/liquidity/types/genesis.pb.go @@ -0,0 +1,875 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cyber/liquidity/v1beta1/genesis.proto + +package types + +import ( + fmt "fmt" + io "io" + math "math" + math_bits "math/bits" + + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = proto.Marshal + _ = fmt.Errorf + _ = 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 + +// records the state of each pool after genesis export or import, used to check +// variables +type PoolRecord struct { + Pool Pool `protobuf:"bytes,1,opt,name=pool,proto3" json:"pool" yaml:"pool"` + PoolMetadata PoolMetadata `protobuf:"bytes,2,opt,name=pool_metadata,json=poolMetadata,proto3" json:"pool_metadata" yaml:"pool_metadata"` + PoolBatch PoolBatch `protobuf:"bytes,3,opt,name=pool_batch,json=poolBatch,proto3" json:"pool_batch" yaml:"pool_batch"` + DepositMsgStates []DepositMsgState `protobuf:"bytes,4,rep,name=deposit_msg_states,json=depositMsgStates,proto3" json:"deposit_msg_states" yaml:"deposit_msg_states"` + WithdrawMsgStates []WithdrawMsgState `protobuf:"bytes,5,rep,name=withdraw_msg_states,json=withdrawMsgStates,proto3" json:"withdraw_msg_states" yaml:"withdraw_msg_states"` + SwapMsgStates []SwapMsgState `protobuf:"bytes,6,rep,name=swap_msg_states,json=swapMsgStates,proto3" json:"swap_msg_states" yaml:"swap_msg_states"` +} + +func (m *PoolRecord) Reset() { *m = PoolRecord{} } +func (m *PoolRecord) String() string { return proto.CompactTextString(m) } +func (*PoolRecord) ProtoMessage() {} +func (*PoolRecord) Descriptor() ([]byte, []int) { + return fileDescriptor_84edef6e81b0c617, []int{0} +} + +func (m *PoolRecord) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *PoolRecord) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PoolRecord.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 *PoolRecord) XXX_Merge(src proto.Message) { + xxx_messageInfo_PoolRecord.Merge(m, src) +} + +func (m *PoolRecord) XXX_Size() int { + return m.Size() +} + +func (m *PoolRecord) XXX_DiscardUnknown() { + xxx_messageInfo_PoolRecord.DiscardUnknown(m) +} + +var xxx_messageInfo_PoolRecord proto.InternalMessageInfo + +func (m *PoolRecord) GetPool() Pool { + if m != nil { + return m.Pool + } + return Pool{} +} + +func (m *PoolRecord) GetPoolMetadata() PoolMetadata { + if m != nil { + return m.PoolMetadata + } + return PoolMetadata{} +} + +func (m *PoolRecord) GetPoolBatch() PoolBatch { + if m != nil { + return m.PoolBatch + } + return PoolBatch{} +} + +func (m *PoolRecord) GetDepositMsgStates() []DepositMsgState { + if m != nil { + return m.DepositMsgStates + } + return nil +} + +func (m *PoolRecord) GetWithdrawMsgStates() []WithdrawMsgState { + if m != nil { + return m.WithdrawMsgStates + } + return nil +} + +func (m *PoolRecord) GetSwapMsgStates() []SwapMsgState { + if m != nil { + return m.SwapMsgStates + } + return nil +} + +// GenesisState defines the liquidity module's genesis state. +type GenesisState struct { + // params defines all the parameters for the liquidity module. + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` + PoolRecords []PoolRecord `protobuf:"bytes,2,rep,name=pool_records,json=poolRecords,proto3" json:"pool_records" yaml:"pools"` +} + +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_84edef6e81b0c617, []int{1} +} + +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 init() { + proto.RegisterType((*PoolRecord)(nil), "cyber.liquidity.v1beta1.PoolRecord") + proto.RegisterType((*GenesisState)(nil), "cyber.liquidity.v1beta1.GenesisState") +} + +func init() { + proto.RegisterFile("cyber/liquidity/v1beta1/genesis.proto", fileDescriptor_84edef6e81b0c617) +} + +var fileDescriptor_84edef6e81b0c617 = []byte{ + // 503 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x93, 0x41, 0x6b, 0xd4, 0x4e, + 0x18, 0xc6, 0x93, 0x76, 0xbb, 0xfc, 0xff, 0xb3, 0x5b, 0xb4, 0xd3, 0x45, 0xb7, 0x8b, 0x26, 0x75, + 0xa4, 0xb8, 0x1e, 0x4c, 0x68, 0x7b, 0x2b, 0x78, 0x09, 0xa2, 0xa7, 0x05, 0x49, 0x0f, 0x82, 0x14, + 0x96, 0x49, 0x32, 0x64, 0x03, 0x9b, 0xce, 0x98, 0x77, 0x6a, 0xcc, 0xc1, 0xa3, 0xe0, 0xd1, 0x8f, + 0xd0, 0x2f, 0xe1, 0x77, 0xe8, 0xb1, 0x47, 0x4f, 0x45, 0x76, 0x2f, 0x9e, 0xfd, 0x04, 0x92, 0xc9, + 0x98, 0x8d, 0xd5, 0xec, 0x29, 0xc3, 0xe4, 0x79, 0x9e, 0xdf, 0x0b, 0xf3, 0xbc, 0xe8, 0x20, 0x2c, + 0x02, 0x96, 0xb9, 0xf3, 0xe4, 0xdd, 0x45, 0x12, 0x25, 0xb2, 0x70, 0xdf, 0x1f, 0x06, 0x4c, 0xd2, + 0x43, 0x37, 0x66, 0xe7, 0x0c, 0x12, 0x70, 0x44, 0xc6, 0x25, 0xc7, 0xf7, 0x95, 0xcc, 0xa9, 0x65, + 0x8e, 0x96, 0x8d, 0x9e, 0xb4, 0xf9, 0x57, 0x52, 0x95, 0x30, 0x1a, 0xc4, 0x3c, 0xe6, 0xea, 0xe8, + 0x96, 0xa7, 0xea, 0x96, 0x7c, 0xda, 0x42, 0xe8, 0x35, 0xe7, 0x73, 0x9f, 0x85, 0x3c, 0x8b, 0xf0, + 0x4b, 0xd4, 0x11, 0x9c, 0xcf, 0x87, 0xe6, 0xbe, 0x39, 0xee, 0x1d, 0x3d, 0x74, 0x5a, 0xa8, 0x4e, + 0x69, 0xf1, 0x76, 0xaf, 0x6e, 0x6c, 0xe3, 0xe7, 0x8d, 0xdd, 0x2b, 0x68, 0x3a, 0x3f, 0x21, 0xa5, + 0x91, 0xf8, 0xca, 0x8f, 0x67, 0x68, 0xbb, 0xfc, 0x4e, 0x53, 0x26, 0x69, 0x44, 0x25, 0x1d, 0x6e, + 0xa8, 0xc0, 0x83, 0xb5, 0x81, 0x13, 0x2d, 0xf6, 0x1e, 0xe8, 0xe0, 0xc1, 0x2a, 0xb8, 0x4e, 0x22, + 0x7e, 0x5f, 0x34, 0xb4, 0xf8, 0x0c, 0x21, 0xf5, 0x3f, 0xa0, 0x32, 0x9c, 0x0d, 0x37, 0x15, 0x86, + 0xac, 0x9f, 0xbb, 0x54, 0x7a, 0x7b, 0x9a, 0xb1, 0xd3, 0x60, 0xa8, 0x0c, 0xe2, 0xff, 0x2f, 0x7e, + 0xab, 0x70, 0x81, 0x70, 0xc4, 0x04, 0x87, 0x44, 0x4e, 0x53, 0x88, 0xa7, 0x20, 0xa9, 0x64, 0x30, + 0xec, 0xec, 0x6f, 0x8e, 0x7b, 0x47, 0xe3, 0x56, 0xca, 0x8b, 0xca, 0x32, 0x81, 0xf8, 0xb4, 0x34, + 0x78, 0x8f, 0x34, 0x6b, 0xaf, 0x62, 0xfd, 0x9d, 0x48, 0xfc, 0xbb, 0xd1, 0x9f, 0x1e, 0xc0, 0x1f, + 0xd1, 0x6e, 0x9e, 0xc8, 0x59, 0x94, 0xd1, 0xbc, 0xc9, 0xde, 0x52, 0xec, 0xa7, 0xad, 0xec, 0x37, + 0xda, 0x53, 0xc3, 0x89, 0x86, 0x8f, 0x2a, 0xf8, 0x3f, 0x32, 0x89, 0xbf, 0x93, 0xdf, 0x72, 0x01, + 0x4e, 0xd1, 0x1d, 0xc8, 0xa9, 0x68, 0xa2, 0xbb, 0x0a, 0xdd, 0xfe, 0x86, 0xa7, 0x39, 0x15, 0x35, + 0xd6, 0xd2, 0xd8, 0x7b, 0x15, 0xf6, 0x56, 0x16, 0xf1, 0xb7, 0xa1, 0xa1, 0x06, 0xf2, 0xd5, 0x44, + 0xfd, 0x57, 0x55, 0xe3, 0xd5, 0x0d, 0x7e, 0x8e, 0xba, 0x82, 0x66, 0x34, 0x05, 0xdd, 0x45, 0xbb, + 0xfd, 0x4d, 0x95, 0xcc, 0xeb, 0x94, 0x40, 0x5f, 0x9b, 0xf0, 0x19, 0x52, 0x35, 0x99, 0x66, 0xaa, + 0xd7, 0x30, 0xdc, 0x50, 0xb3, 0x3f, 0x5e, 0x5b, 0x8c, 0x6a, 0x07, 0xbc, 0x81, 0x9e, 0xbc, 0xbf, + 0x6a, 0x06, 0x10, 0xbf, 0x27, 0x6a, 0x05, 0x9c, 0xfc, 0xf7, 0xf9, 0xd2, 0x36, 0x7e, 0x5c, 0xda, + 0x86, 0x37, 0xb9, 0x5a, 0x58, 0xe6, 0xf5, 0xc2, 0x32, 0xbf, 0x2f, 0x2c, 0xf3, 0xcb, 0xd2, 0x32, + 0xae, 0x97, 0x96, 0xf1, 0x6d, 0x69, 0x19, 0x6f, 0x8f, 0xe3, 0x44, 0xce, 0x2e, 0x02, 0x27, 0xe4, + 0xa9, 0xab, 0xa8, 0x21, 0x3f, 0x8f, 0x33, 0x06, 0xe0, 0xc6, 0xfc, 0x59, 0xb5, 0xb4, 0x1f, 0x1a, + 0x6b, 0x2b, 0x0b, 0xc1, 0x20, 0xe8, 0xaa, 0xad, 0x3c, 0xfe, 0x15, 0x00, 0x00, 0xff, 0xff, 0x5f, + 0x85, 0x58, 0xc8, 0x16, 0x04, 0x00, 0x00, +} + +func (m *PoolRecord) 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 *PoolRecord) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PoolRecord) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.SwapMsgStates) > 0 { + for iNdEx := len(m.SwapMsgStates) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.SwapMsgStates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + } + } + if len(m.WithdrawMsgStates) > 0 { + for iNdEx := len(m.WithdrawMsgStates) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.WithdrawMsgStates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + } + } + if len(m.DepositMsgStates) > 0 { + for iNdEx := len(m.DepositMsgStates) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.DepositMsgStates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + } + { + size, err := m.PoolBatch.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + { + size, err := m.PoolMetadata.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + { + size, err := m.Pool.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 (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 + if len(m.PoolRecords) > 0 { + for iNdEx := len(m.PoolRecords) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.PoolRecords[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + { + 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 *PoolRecord) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Pool.Size() + n += 1 + l + sovGenesis(uint64(l)) + l = m.PoolMetadata.Size() + n += 1 + l + sovGenesis(uint64(l)) + l = m.PoolBatch.Size() + n += 1 + l + sovGenesis(uint64(l)) + if len(m.DepositMsgStates) > 0 { + for _, e := range m.DepositMsgStates { + l = e.Size() + n += 1 + l + sovGenesis(uint64(l)) + } + } + if len(m.WithdrawMsgStates) > 0 { + for _, e := range m.WithdrawMsgStates { + l = e.Size() + n += 1 + l + sovGenesis(uint64(l)) + } + } + if len(m.SwapMsgStates) > 0 { + for _, e := range m.SwapMsgStates { + l = e.Size() + n += 1 + l + sovGenesis(uint64(l)) + } + } + return n +} + +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)) + if len(m.PoolRecords) > 0 { + for _, e := range m.PoolRecords { + l = e.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 *PoolRecord) 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: PoolRecord: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PoolRecord: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pool", 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.Pool.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolMetadata", 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.PoolMetadata.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolBatch", 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.PoolBatch.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DepositMsgStates", 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 + } + m.DepositMsgStates = append(m.DepositMsgStates, DepositMsgState{}) + if err := m.DepositMsgStates[len(m.DepositMsgStates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field WithdrawMsgStates", 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 + } + m.WithdrawMsgStates = append(m.WithdrawMsgStates, WithdrawMsgState{}) + if err := m.WithdrawMsgStates[len(m.WithdrawMsgStates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SwapMsgStates", 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 + } + m.SwapMsgStates = append(m.SwapMsgStates, SwapMsgState{}) + if err := m.SwapMsgStates[len(m.SwapMsgStates)-1].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 (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 + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolRecords", 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 + } + m.PoolRecords = append(m.PoolRecords, PoolRecord{}) + if err := m.PoolRecords[len(m.PoolRecords)-1].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/liquidity/types/keys.go b/x/liquidity/types/keys.go new file mode 100644 index 00000000..ae563c48 --- /dev/null +++ b/x/liquidity/types/keys.go @@ -0,0 +1,111 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/address" +) + +const ( + // ModuleName is the name of the liquidity module + ModuleName = "liquidity" + + // RouterKey is the message router key for the liquidity module + RouterKey = ModuleName + + // StoreKey is the default store key for the liquidity module + StoreKey = ModuleName + + // QuerierRoute is the querier route for the liquidity module + QuerierRoute = ModuleName + + // PoolCoinDenomPrefix is the prefix used for liquidity pool coin representation + PoolCoinDenomPrefix = "pool" +) + +var ( + // param key for global Liquidity Pool IDs + GlobalLiquidityPoolIDKey = []byte("globalLiquidityPoolId") + + ParamsKey = []byte{0x01} + + PoolKeyPrefix = []byte{0x11} + PoolByReserveAccIndexKeyPrefix = []byte{0x12} + + PoolBatchKeyPrefix = []byte{0x22} + + PoolBatchDepositMsgStateIndexKeyPrefix = []byte{0x31} + PoolBatchWithdrawMsgStateIndexKeyPrefix = []byte{0x32} + PoolBatchSwapMsgStateIndexKeyPrefix = []byte{0x33} +) + +// GetPoolKey returns kv indexing key of the pool +func GetPoolKey(poolID uint64) []byte { + key := make([]byte, 9) + key[0] = PoolKeyPrefix[0] + copy(key[1:], sdk.Uint64ToBigEndian(poolID)) + return key +} + +// GetPoolByReserveAccIndexKey returns kv indexing key of the pool indexed by reserve account +func GetPoolByReserveAccIndexKey(reserveAcc sdk.AccAddress) []byte { + return append(PoolByReserveAccIndexKeyPrefix, address.MustLengthPrefix(reserveAcc.Bytes())...) +} + +// GetPoolBatchKey returns kv indexing key of the pool batch indexed by pool id +func GetPoolBatchKey(poolID uint64) []byte { + key := make([]byte, 9) + key[0] = PoolBatchKeyPrefix[0] + copy(key[1:9], sdk.Uint64ToBigEndian(poolID)) + return key +} + +// GetPoolBatchDepositMsgStatesPrefix returns prefix of deposit message states in the pool's latest batch for iteration +func GetPoolBatchDepositMsgStatesPrefix(poolID uint64) []byte { + key := make([]byte, 9) + key[0] = PoolBatchDepositMsgStateIndexKeyPrefix[0] + copy(key[1:9], sdk.Uint64ToBigEndian(poolID)) + return key +} + +// GetPoolBatchWithdrawMsgsPrefix returns prefix of withdraw message states in the pool's latest batch for iteration +func GetPoolBatchWithdrawMsgsPrefix(poolID uint64) []byte { + key := make([]byte, 9) + key[0] = PoolBatchWithdrawMsgStateIndexKeyPrefix[0] + copy(key[1:9], sdk.Uint64ToBigEndian(poolID)) + return key +} + +// GetPoolBatchSwapMsgStatesPrefix returns prefix of swap message states in the pool's latest batch for iteration +func GetPoolBatchSwapMsgStatesPrefix(poolID uint64) []byte { + key := make([]byte, 9) + key[0] = PoolBatchSwapMsgStateIndexKeyPrefix[0] + copy(key[1:9], sdk.Uint64ToBigEndian(poolID)) + return key +} + +// GetPoolBatchDepositMsgStateIndexKey returns kv indexing key of the latest index value of the msg index +func GetPoolBatchDepositMsgStateIndexKey(poolID, msgIndex uint64) []byte { + key := make([]byte, 17) + key[0] = PoolBatchDepositMsgStateIndexKeyPrefix[0] + copy(key[1:9], sdk.Uint64ToBigEndian(poolID)) + copy(key[9:17], sdk.Uint64ToBigEndian(msgIndex)) + return key +} + +// GetPoolBatchWithdrawMsgStateIndexKey returns kv indexing key of the latest index value of the msg index +func GetPoolBatchWithdrawMsgStateIndexKey(poolID, msgIndex uint64) []byte { + key := make([]byte, 17) + key[0] = PoolBatchWithdrawMsgStateIndexKeyPrefix[0] + copy(key[1:9], sdk.Uint64ToBigEndian(poolID)) + copy(key[9:17], sdk.Uint64ToBigEndian(msgIndex)) + return key +} + +// GetPoolBatchSwapMsgStateIndexKey returns kv indexing key of the latest index value of the msg index +func GetPoolBatchSwapMsgStateIndexKey(poolID, msgIndex uint64) []byte { + key := make([]byte, 17) + key[0] = PoolBatchSwapMsgStateIndexKeyPrefix[0] + copy(key[1:9], sdk.Uint64ToBigEndian(poolID)) + copy(key[9:17], sdk.Uint64ToBigEndian(msgIndex)) + return key +} diff --git a/x/liquidity/types/liquidity.pb.go b/x/liquidity/types/liquidity.pb.go new file mode 100644 index 00000000..adb61e2d --- /dev/null +++ b/x/liquidity/types/liquidity.pb.go @@ -0,0 +1,3486 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cyber/liquidity/v1beta1/liquidity.proto + +package types + +import ( + fmt "fmt" + io "io" + math "math" + math_bits "math/bits" + + _ "github.com/cosmos/cosmos-proto" + github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" + types "github.com/cosmos/cosmos-sdk/types" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = proto.Marshal + _ = fmt.Errorf + _ = 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 + +// Structure for the pool type to distinguish the characteristics of the reserve +// pools. +type PoolType struct { + // This is the id of the pool_type that is used as pool_type_id for pool + // creation. In this version, only pool-type-id 1 is supported. + // {"id":1,"name":"ConstantProductLiquidityPool","min_reserve_coin_num":2,"max_reserve_coin_num":2,"description":""} + Id uint32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty" yaml:"id"` + // name of the pool type. + Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty" yaml:"name"` + // minimum number of reserveCoins for LiquidityPoolType, only 2 reserve coins + // are supported. + MinReserveCoinNum uint32 `protobuf:"varint,3,opt,name=min_reserve_coin_num,json=minReserveCoinNum,proto3" json:"min_reserve_coin_num,omitempty" yaml:"min_reserve_coin_num"` + // maximum number of reserveCoins for LiquidityPoolType, only 2 reserve coins + // are supported. + MaxReserveCoinNum uint32 `protobuf:"varint,4,opt,name=max_reserve_coin_num,json=maxReserveCoinNum,proto3" json:"max_reserve_coin_num,omitempty" yaml:"max_reserve_coin_num"` + // description of the pool type. + Description string `protobuf:"bytes,5,opt,name=description,proto3" json:"description,omitempty" yaml:"description"` +} + +func (m *PoolType) Reset() { *m = PoolType{} } +func (m *PoolType) String() string { return proto.CompactTextString(m) } +func (*PoolType) ProtoMessage() {} +func (*PoolType) Descriptor() ([]byte, []int) { + return fileDescriptor_67b6d59e96092d89, []int{0} +} + +func (m *PoolType) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *PoolType) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PoolType.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 *PoolType) XXX_Merge(src proto.Message) { + xxx_messageInfo_PoolType.Merge(m, src) +} + +func (m *PoolType) XXX_Size() int { + return m.Size() +} + +func (m *PoolType) XXX_DiscardUnknown() { + xxx_messageInfo_PoolType.DiscardUnknown(m) +} + +var xxx_messageInfo_PoolType proto.InternalMessageInfo + +// Params defines the parameters for the liquidity module. +type Params struct { + // list of available pool types + PoolTypes []PoolType `protobuf:"bytes,1,rep,name=pool_types,json=poolTypes,proto3" json:"pool_types" yaml:"pool_types"` + // Minimum number of coins to be deposited to the liquidity pool on pool + // creation. + MinInitDepositAmount github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,2,opt,name=min_init_deposit_amount,json=minInitDepositAmount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"min_init_deposit_amount" yaml:"min_init_deposit_amount"` + // Initial mint amount of pool coins upon pool creation. + InitPoolCoinMintAmount github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,3,opt,name=init_pool_coin_mint_amount,json=initPoolCoinMintAmount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"init_pool_coin_mint_amount" yaml:"init_pool_coin_mint_amount"` + // Limit the size of each liquidity pool to minimize risk. In development, set + // to 0 for no limit. In production, set a limit. + MaxReserveCoinAmount github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,4,opt,name=max_reserve_coin_amount,json=maxReserveCoinAmount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"max_reserve_coin_amount" yaml:"max_reserve_coin_amount"` + // Fee paid to create a Liquidity Pool. Set a fee to prevent spamming. + PoolCreationFee github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,5,rep,name=pool_creation_fee,json=poolCreationFee,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"pool_creation_fee" yaml:"pool_creation_fee"` + // Swap fee rate for every executed swap. + SwapFeeRate github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,6,opt,name=swap_fee_rate,json=swapFeeRate,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"swap_fee_rate" yaml:"swap_fee_rate"` + // Reserve coin withdrawal with less proportion by withdrawFeeRate. + WithdrawFeeRate github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,7,opt,name=withdraw_fee_rate,json=withdrawFeeRate,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"withdraw_fee_rate" yaml:"withdraw_fee_rate"` + // Maximum ratio of reserve coins that can be ordered at a swap order. + MaxOrderAmountRatio github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,8,opt,name=max_order_amount_ratio,json=maxOrderAmountRatio,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"max_order_amount_ratio" yaml:"max_order_amount_ratio"` + // The smallest unit batch height for every liquidity pool. + UnitBatchHeight uint32 `protobuf:"varint,9,opt,name=unit_batch_height,json=unitBatchHeight,proto3" json:"unit_batch_height,omitempty" yaml:"unit_batch_height"` + // Circuit breaker enables or disables transaction messages in liquidity + // module. + CircuitBreakerEnabled bool `protobuf:"varint,10,opt,name=circuit_breaker_enabled,json=circuitBreakerEnabled,proto3" json:"circuit_breaker_enabled,omitempty" yaml:"circuit_breaker_enabled"` +} + +func (m *Params) Reset() { *m = Params{} } +func (*Params) ProtoMessage() {} +func (*Params) Descriptor() ([]byte, []int) { + return fileDescriptor_67b6d59e96092d89, []int{1} +} + +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 + +// Pool defines the liquidity pool that contains pool information. +type Pool struct { + // id of the pool + Id uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id" yaml:"id"` + // id of the pool_type + TypeId uint32 `protobuf:"varint,2,opt,name=type_id,json=typeId,proto3" json:"type_id,omitempty" yaml:"type_id"` + // denoms of reserve coin pair of the pool + ReserveCoinDenoms []string `protobuf:"bytes,3,rep,name=reserve_coin_denoms,json=reserveCoinDenoms,proto3" json:"reserve_coin_denoms,omitempty" yaml:"reserve_coin_denoms"` + // reserve account address of the pool + ReserveAccountAddress string `protobuf:"bytes,4,opt,name=reserve_account_address,json=reserveAccountAddress,proto3" json:"reserve_account_address,omitempty" yaml:"reserve_account_address"` + // denom of pool coin of the pool + PoolCoinDenom string `protobuf:"bytes,5,opt,name=pool_coin_denom,json=poolCoinDenom,proto3" json:"pool_coin_denom,omitempty" yaml:"pool_coin_denom"` +} + +func (m *Pool) Reset() { *m = Pool{} } +func (m *Pool) String() string { return proto.CompactTextString(m) } +func (*Pool) ProtoMessage() {} +func (*Pool) Descriptor() ([]byte, []int) { + return fileDescriptor_67b6d59e96092d89, []int{2} +} + +func (m *Pool) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *Pool) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Pool.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 *Pool) XXX_Merge(src proto.Message) { + xxx_messageInfo_Pool.Merge(m, src) +} + +func (m *Pool) XXX_Size() int { + return m.Size() +} + +func (m *Pool) XXX_DiscardUnknown() { + xxx_messageInfo_Pool.DiscardUnknown(m) +} + +var xxx_messageInfo_Pool proto.InternalMessageInfo + +// Metadata for the state of each pool for invariant checking after genesis +// export or import. +type PoolMetadata struct { + // id of the pool + PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id" yaml:"pool_id"` + // pool coin issued at the pool + PoolCoinTotalSupply types.Coin `protobuf:"bytes,2,opt,name=pool_coin_total_supply,json=poolCoinTotalSupply,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coin" json:"pool_coin_total_supply" yaml:"pool_coin"` + // reserve coins deposited in the pool + ReserveCoins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,3,rep,name=reserve_coins,json=reserveCoins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"reserve_coins" yaml:"deposit_coins"` +} + +func (m *PoolMetadata) Reset() { *m = PoolMetadata{} } +func (m *PoolMetadata) String() string { return proto.CompactTextString(m) } +func (*PoolMetadata) ProtoMessage() {} +func (*PoolMetadata) Descriptor() ([]byte, []int) { + return fileDescriptor_67b6d59e96092d89, []int{3} +} + +func (m *PoolMetadata) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *PoolMetadata) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PoolMetadata.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 *PoolMetadata) XXX_Merge(src proto.Message) { + xxx_messageInfo_PoolMetadata.Merge(m, src) +} + +func (m *PoolMetadata) XXX_Size() int { + return m.Size() +} + +func (m *PoolMetadata) XXX_DiscardUnknown() { + xxx_messageInfo_PoolMetadata.DiscardUnknown(m) +} + +var xxx_messageInfo_PoolMetadata proto.InternalMessageInfo + +// PoolBatch defines the batch or batches of a given liquidity pool that +// contains indexes of deposit, withdraw, and swap messages. Index param +// increments by 1 if the pool id is same. +type PoolBatch struct { + // id of the pool + PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id" yaml:"pool_id"` + // index of this batch + Index uint64 `protobuf:"varint,2,opt,name=index,proto3" json:"index,omitempty" yaml:"index"` + // height where this batch is started + BeginHeight int64 `protobuf:"varint,3,opt,name=begin_height,json=beginHeight,proto3" json:"begin_height,omitempty" yaml:"begin_height"` + // last index of DepositMsgStates + DepositMsgIndex uint64 `protobuf:"varint,4,opt,name=deposit_msg_index,json=depositMsgIndex,proto3" json:"deposit_msg_index,omitempty" yaml:"deposit_msg_index"` + // last index of WithdrawMsgStates + WithdrawMsgIndex uint64 `protobuf:"varint,5,opt,name=withdraw_msg_index,json=withdrawMsgIndex,proto3" json:"withdraw_msg_index,omitempty" yaml:"withdraw_msg_index"` + // last index of SwapMsgStates + SwapMsgIndex uint64 `protobuf:"varint,6,opt,name=swap_msg_index,json=swapMsgIndex,proto3" json:"swap_msg_index,omitempty" yaml:"swap_msg_index"` + // true if executed, false if not executed + Executed bool `protobuf:"varint,7,opt,name=executed,proto3" json:"executed,omitempty" yaml:"executed"` +} + +func (m *PoolBatch) Reset() { *m = PoolBatch{} } +func (m *PoolBatch) String() string { return proto.CompactTextString(m) } +func (*PoolBatch) ProtoMessage() {} +func (*PoolBatch) Descriptor() ([]byte, []int) { + return fileDescriptor_67b6d59e96092d89, []int{4} +} + +func (m *PoolBatch) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *PoolBatch) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PoolBatch.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 *PoolBatch) XXX_Merge(src proto.Message) { + xxx_messageInfo_PoolBatch.Merge(m, src) +} + +func (m *PoolBatch) XXX_Size() int { + return m.Size() +} + +func (m *PoolBatch) XXX_DiscardUnknown() { + xxx_messageInfo_PoolBatch.DiscardUnknown(m) +} + +var xxx_messageInfo_PoolBatch proto.InternalMessageInfo + +// DepositMsgState defines the state of deposit message that contains state +// information as it is processed in the next batch or batches. +type DepositMsgState struct { + // height where this message is appended to the batch + MsgHeight int64 `protobuf:"varint,1,opt,name=msg_height,json=msgHeight,proto3" json:"msg_height,omitempty" yaml:"msg_height"` + // index of this deposit message in this liquidity pool + MsgIndex uint64 `protobuf:"varint,2,opt,name=msg_index,json=msgIndex,proto3" json:"msg_index,omitempty" yaml:"msg_index"` + // true if executed on this batch, false if not executed + Executed bool `protobuf:"varint,3,opt,name=executed,proto3" json:"executed,omitempty" yaml:"executed"` + // true if executed successfully on this batch, false if failed + Succeeded bool `protobuf:"varint,4,opt,name=succeeded,proto3" json:"succeeded,omitempty" yaml:"succeeded"` + // true if ready to be deleted on kvstore, false if not ready to be deleted + ToBeDeleted bool `protobuf:"varint,5,opt,name=to_be_deleted,json=toBeDeleted,proto3" json:"to_be_deleted,omitempty" yaml:"to_be_deleted"` + // MsgDepositWithinBatch + Msg *MsgDepositWithinBatch `protobuf:"bytes,6,opt,name=msg,proto3" json:"msg,omitempty" yaml:"msg"` +} + +func (m *DepositMsgState) Reset() { *m = DepositMsgState{} } +func (m *DepositMsgState) String() string { return proto.CompactTextString(m) } +func (*DepositMsgState) ProtoMessage() {} +func (*DepositMsgState) Descriptor() ([]byte, []int) { + return fileDescriptor_67b6d59e96092d89, []int{5} +} + +func (m *DepositMsgState) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *DepositMsgState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_DepositMsgState.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 *DepositMsgState) XXX_Merge(src proto.Message) { + xxx_messageInfo_DepositMsgState.Merge(m, src) +} + +func (m *DepositMsgState) XXX_Size() int { + return m.Size() +} + +func (m *DepositMsgState) XXX_DiscardUnknown() { + xxx_messageInfo_DepositMsgState.DiscardUnknown(m) +} + +var xxx_messageInfo_DepositMsgState proto.InternalMessageInfo + +// WithdrawMsgState defines the state of the withdraw message that contains +// state information as the message is processed in the next batch or batches. +type WithdrawMsgState struct { + // height where this message is appended to the batch + MsgHeight int64 `protobuf:"varint,1,opt,name=msg_height,json=msgHeight,proto3" json:"msg_height,omitempty" yaml:"msg_height"` + // index of this withdraw message in this liquidity pool + MsgIndex uint64 `protobuf:"varint,2,opt,name=msg_index,json=msgIndex,proto3" json:"msg_index,omitempty" yaml:"msg_index"` + // true if executed on this batch, false if not executed + Executed bool `protobuf:"varint,3,opt,name=executed,proto3" json:"executed,omitempty" yaml:"executed"` + // true if executed successfully on this batch, false if failed + Succeeded bool `protobuf:"varint,4,opt,name=succeeded,proto3" json:"succeeded,omitempty" yaml:"succeeded"` + // true if ready to be deleted on kvstore, false if not ready to be deleted + ToBeDeleted bool `protobuf:"varint,5,opt,name=to_be_deleted,json=toBeDeleted,proto3" json:"to_be_deleted,omitempty" yaml:"to_be_deleted"` + // MsgWithdrawWithinBatch + Msg *MsgWithdrawWithinBatch `protobuf:"bytes,6,opt,name=msg,proto3" json:"msg,omitempty" yaml:"msg"` +} + +func (m *WithdrawMsgState) Reset() { *m = WithdrawMsgState{} } +func (m *WithdrawMsgState) String() string { return proto.CompactTextString(m) } +func (*WithdrawMsgState) ProtoMessage() {} +func (*WithdrawMsgState) Descriptor() ([]byte, []int) { + return fileDescriptor_67b6d59e96092d89, []int{6} +} + +func (m *WithdrawMsgState) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *WithdrawMsgState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_WithdrawMsgState.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 *WithdrawMsgState) XXX_Merge(src proto.Message) { + xxx_messageInfo_WithdrawMsgState.Merge(m, src) +} + +func (m *WithdrawMsgState) XXX_Size() int { + return m.Size() +} + +func (m *WithdrawMsgState) XXX_DiscardUnknown() { + xxx_messageInfo_WithdrawMsgState.DiscardUnknown(m) +} + +var xxx_messageInfo_WithdrawMsgState proto.InternalMessageInfo + +// SwapMsgState defines the state of the swap message that contains state +// information as the message is processed in the next batch or batches. +type SwapMsgState struct { + // height where this message is appended to the batch + MsgHeight int64 `protobuf:"varint,1,opt,name=msg_height,json=msgHeight,proto3" json:"msg_height,omitempty" yaml:"msg_height"` + // index of this swap message in this liquidity pool + MsgIndex uint64 `protobuf:"varint,2,opt,name=msg_index,json=msgIndex,proto3" json:"msg_index,omitempty" yaml:"msg_index"` + // true if executed on this batch, false if not executed + Executed bool `protobuf:"varint,3,opt,name=executed,proto3" json:"executed,omitempty" yaml:"executed"` + // true if executed successfully on this batch, false if failed + Succeeded bool `protobuf:"varint,4,opt,name=succeeded,proto3" json:"succeeded,omitempty" yaml:"succeeded"` + // true if ready to be deleted on kvstore, false if not ready to be deleted + ToBeDeleted bool `protobuf:"varint,5,opt,name=to_be_deleted,json=toBeDeleted,proto3" json:"to_be_deleted,omitempty" yaml:"to_be_deleted"` + // swap orders are cancelled when current height is equal to or higher than + // ExpiryHeight + OrderExpiryHeight int64 `protobuf:"varint,6,opt,name=order_expiry_height,json=orderExpiryHeight,proto3" json:"order_expiry_height,omitempty" yaml:"order_expiry_height"` + // offer coin exchanged until now + ExchangedOfferCoin types.Coin `protobuf:"bytes,7,opt,name=exchanged_offer_coin,json=exchangedOfferCoin,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coin" json:"exchanged_offer_coin" yaml:"exchanged_offer_coin"` + // offer coin currently remaining to be exchanged + RemainingOfferCoin types.Coin `protobuf:"bytes,8,opt,name=remaining_offer_coin,json=remainingOfferCoin,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coin" json:"remaining_offer_coin" yaml:"remaining_offer_coin"` + // reserve fee for pays fee in half offer coin + ReservedOfferCoinFee types.Coin `protobuf:"bytes,9,opt,name=reserved_offer_coin_fee,json=reservedOfferCoinFee,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coin" json:"reserved_offer_coin_fee" yaml:"reserved_offer_coin_fee"` + // MsgSwapWithinBatch + Msg *MsgSwapWithinBatch `protobuf:"bytes,10,opt,name=msg,proto3" json:"msg,omitempty" yaml:"msg"` +} + +func (m *SwapMsgState) Reset() { *m = SwapMsgState{} } +func (m *SwapMsgState) String() string { return proto.CompactTextString(m) } +func (*SwapMsgState) ProtoMessage() {} +func (*SwapMsgState) Descriptor() ([]byte, []int) { + return fileDescriptor_67b6d59e96092d89, []int{7} +} + +func (m *SwapMsgState) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *SwapMsgState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_SwapMsgState.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 *SwapMsgState) XXX_Merge(src proto.Message) { + xxx_messageInfo_SwapMsgState.Merge(m, src) +} + +func (m *SwapMsgState) XXX_Size() int { + return m.Size() +} + +func (m *SwapMsgState) XXX_DiscardUnknown() { + xxx_messageInfo_SwapMsgState.DiscardUnknown(m) +} + +var xxx_messageInfo_SwapMsgState proto.InternalMessageInfo + +func init() { + proto.RegisterType((*PoolType)(nil), "cyber.liquidity.v1beta1.PoolType") + proto.RegisterType((*Params)(nil), "cyber.liquidity.v1beta1.Params") + proto.RegisterType((*Pool)(nil), "cyber.liquidity.v1beta1.Pool") + proto.RegisterType((*PoolMetadata)(nil), "cyber.liquidity.v1beta1.PoolMetadata") + proto.RegisterType((*PoolBatch)(nil), "cyber.liquidity.v1beta1.PoolBatch") + proto.RegisterType((*DepositMsgState)(nil), "cyber.liquidity.v1beta1.DepositMsgState") + proto.RegisterType((*WithdrawMsgState)(nil), "cyber.liquidity.v1beta1.WithdrawMsgState") + proto.RegisterType((*SwapMsgState)(nil), "cyber.liquidity.v1beta1.SwapMsgState") +} + +func init() { + proto.RegisterFile("cyber/liquidity/v1beta1/liquidity.proto", fileDescriptor_67b6d59e96092d89) +} + +var fileDescriptor_67b6d59e96092d89 = []byte{ + // 1553 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xec, 0x58, 0xcd, 0x6b, 0x1b, 0xc7, + 0x1b, 0xf6, 0x4a, 0xb2, 0x2d, 0x8d, 0xed, 0xc8, 0x5a, 0xcb, 0xb6, 0xec, 0xfc, 0xa2, 0x75, 0x36, + 0x90, 0x18, 0x42, 0x24, 0x92, 0xfc, 0x28, 0xc5, 0x14, 0x4a, 0x36, 0x4e, 0xb0, 0x69, 0xed, 0x38, + 0xe3, 0x40, 0x4a, 0x4a, 0xbb, 0xac, 0x76, 0x27, 0xab, 0x21, 0xda, 0x5d, 0x75, 0x77, 0x94, 0x48, + 0xf7, 0x1e, 0x7a, 0xec, 0x07, 0x85, 0x42, 0x28, 0x04, 0x7a, 0xeb, 0xb1, 0xf4, 0xd4, 0xbf, 0x20, + 0xc7, 0xd0, 0x53, 0xe9, 0x61, 0xdb, 0x26, 0x97, 0x92, 0x4b, 0xe9, 0xfe, 0x05, 0x65, 0x3e, 0xf6, + 0xc3, 0x92, 0xec, 0x44, 0xed, 0x35, 0x27, 0x4b, 0xef, 0xc7, 0x33, 0xcf, 0x3c, 0xef, 0xbc, 0xef, + 0x8c, 0x05, 0x2e, 0x98, 0x83, 0x16, 0xf2, 0x9b, 0x1d, 0xfc, 0x49, 0x0f, 0x5b, 0x98, 0x0c, 0x9a, + 0x0f, 0x2f, 0xb7, 0x10, 0x31, 0x2e, 0xa7, 0x96, 0x46, 0xd7, 0xf7, 0x88, 0x27, 0xaf, 0xb2, 0xc0, + 0x46, 0x6a, 0x16, 0x81, 0xeb, 0x1b, 0xc7, 0x21, 0x90, 0x3e, 0x4f, 0x5d, 0xaf, 0xda, 0x9e, 0xed, + 0xb1, 0x8f, 0x4d, 0xfa, 0x49, 0x58, 0xeb, 0xa6, 0x17, 0x38, 0x5e, 0xd0, 0x6c, 0x19, 0x01, 0x4a, + 0x72, 0x4c, 0x0f, 0xbb, 0xc2, 0xbf, 0xc6, 0xfd, 0x3a, 0x4f, 0xe4, 0x5f, 0xb8, 0x4b, 0xfd, 0x21, + 0x07, 0x8a, 0x07, 0x9e, 0xd7, 0xb9, 0x33, 0xe8, 0x22, 0xf9, 0x0c, 0xc8, 0x61, 0xab, 0x26, 0x6d, + 0x48, 0x9b, 0x0b, 0xda, 0x42, 0x14, 0x2a, 0xa5, 0x81, 0xe1, 0x74, 0xb6, 0x54, 0x6c, 0xa9, 0x30, + 0x87, 0x2d, 0xf9, 0x1c, 0x28, 0xb8, 0x86, 0x83, 0x6a, 0xb9, 0x0d, 0x69, 0xb3, 0xa4, 0x95, 0xa3, + 0x50, 0x99, 0xe3, 0x01, 0xd4, 0xaa, 0x42, 0xe6, 0x94, 0x0f, 0x40, 0xd5, 0xc1, 0xae, 0xee, 0xa3, + 0x00, 0xf9, 0x0f, 0x91, 0x4e, 0x59, 0xe8, 0x6e, 0xcf, 0xa9, 0xe5, 0x19, 0xaa, 0x12, 0x85, 0xca, + 0x69, 0x9e, 0x34, 0x2e, 0x4a, 0x85, 0x15, 0x07, 0xbb, 0x90, 0x5b, 0xaf, 0x7b, 0xd8, 0xdd, 0xef, + 0x39, 0x0c, 0xd1, 0xe8, 0x8f, 0x22, 0x16, 0x46, 0x10, 0xc7, 0x44, 0x51, 0x44, 0xa3, 0x3f, 0x84, + 0xf8, 0x36, 0x98, 0xb3, 0x50, 0x60, 0xfa, 0xb8, 0x4b, 0xb0, 0xe7, 0xd6, 0xa6, 0xd9, 0x7e, 0x56, + 0xa2, 0x50, 0x91, 0x39, 0x50, 0xc6, 0xa9, 0xc2, 0x6c, 0xe8, 0x56, 0xe1, 0xcf, 0x27, 0x8a, 0xa4, + 0x7e, 0x01, 0xc0, 0xcc, 0x81, 0xe1, 0x1b, 0x4e, 0x20, 0x7f, 0x08, 0x40, 0xd7, 0xf3, 0x3a, 0x3a, + 0x19, 0x74, 0x51, 0x50, 0x93, 0x36, 0xf2, 0x9b, 0x73, 0x57, 0xce, 0x36, 0x8e, 0x29, 0x70, 0x23, + 0x56, 0x5a, 0x5b, 0x7b, 0x1a, 0x2a, 0x53, 0x51, 0xa8, 0x54, 0xf8, 0x82, 0x29, 0x84, 0x0a, 0x4b, + 0x5d, 0x11, 0x14, 0xc8, 0x5f, 0x4b, 0x60, 0x95, 0xca, 0x84, 0x5d, 0x4c, 0x74, 0x0b, 0x75, 0xbd, + 0x00, 0x13, 0xdd, 0x70, 0xbc, 0x9e, 0x4b, 0x44, 0x11, 0x3e, 0xa6, 0x38, 0xbf, 0x86, 0xca, 0x79, + 0x1b, 0x93, 0x76, 0xaf, 0xd5, 0x30, 0x3d, 0x47, 0xd4, 0x57, 0xfc, 0xb9, 0x14, 0x58, 0x0f, 0x9a, + 0x0c, 0xb9, 0xb1, 0xeb, 0x92, 0x28, 0x54, 0xea, 0xa9, 0xfa, 0x63, 0x60, 0xd5, 0x9f, 0x7f, 0xbc, + 0x04, 0xc4, 0x01, 0xd9, 0x75, 0x09, 0xa4, 0xb5, 0xdc, 0x75, 0x31, 0xd9, 0xe6, 0x51, 0xd7, 0x58, + 0x90, 0xfc, 0xad, 0x04, 0xd6, 0x59, 0x32, 0xe3, 0xcd, 0xa4, 0x76, 0xb0, 0x9b, 0x50, 0xcb, 0x33, + 0x6a, 0xc6, 0xc4, 0xd4, 0xce, 0x8a, 0xe3, 0x76, 0x2c, 0xf2, 0x30, 0xbb, 0x15, 0x1a, 0x4a, 0x35, + 0xa5, 0x85, 0xdd, 0xc3, 0x6e, 0xcc, 0x8f, 0xe9, 0x36, 0x7c, 0x18, 0x04, 0xb9, 0xc2, 0x7f, 0xd4, + 0x6d, 0x3c, 0xec, 0xa8, 0x6e, 0x47, 0x0e, 0x9d, 0xe0, 0xf5, 0x95, 0x04, 0x2a, 0x7c, 0x63, 0x3e, + 0x32, 0xe8, 0x79, 0xd2, 0xef, 0x23, 0x54, 0x9b, 0x66, 0x87, 0x66, 0xad, 0x21, 0xd2, 0x69, 0x13, + 0x27, 0x07, 0x86, 0x26, 0x6b, 0xef, 0x8b, 0xc3, 0x52, 0xcb, 0x1c, 0x96, 0x2c, 0x82, 0xfa, 0xfd, + 0x6f, 0xca, 0xe6, 0x6b, 0x6c, 0x84, 0x82, 0x05, 0xb0, 0x4c, 0xf3, 0xaf, 0x8b, 0xf4, 0x9b, 0x08, + 0xc9, 0x7d, 0xb0, 0x10, 0x3c, 0x32, 0xba, 0x14, 0x49, 0xf7, 0x0d, 0x82, 0x6a, 0x33, 0x4c, 0xa2, + 0x3b, 0x13, 0x48, 0xb4, 0x8d, 0xcc, 0x28, 0x54, 0xaa, 0x9c, 0xdf, 0x11, 0xb0, 0xac, 0x30, 0xdb, + 0xc8, 0x84, 0x73, 0xd4, 0x7b, 0x13, 0x21, 0x68, 0x10, 0x24, 0x7f, 0x2a, 0x81, 0xca, 0x23, 0x4c, + 0xda, 0x96, 0x6f, 0x3c, 0x4a, 0x97, 0x9f, 0x65, 0xcb, 0x7f, 0x30, 0xf1, 0xf2, 0x42, 0x9e, 0x11, + 0xc0, 0x61, 0x0a, 0xe5, 0x38, 0x22, 0xa6, 0xf1, 0xa5, 0x04, 0x56, 0x68, 0x5d, 0x3d, 0xdf, 0x42, + 0xbe, 0x28, 0x28, 0xcd, 0xc4, 0x5e, 0xad, 0xc8, 0xb8, 0x7c, 0x34, 0x31, 0x97, 0x33, 0xe9, 0x69, + 0x19, 0x45, 0x1d, 0x26, 0xb4, 0xe4, 0x18, 0xfd, 0x5b, 0x34, 0x8a, 0x1f, 0x13, 0x48, 0x63, 0xe4, + 0x1d, 0x50, 0xe9, 0xd1, 0x46, 0x68, 0x19, 0xc4, 0x6c, 0xeb, 0x6d, 0x84, 0xed, 0x36, 0xa9, 0x95, + 0xd8, 0xc8, 0xfb, 0x5f, 0xba, 0xd9, 0x91, 0x10, 0x15, 0x96, 0xa9, 0x4d, 0xa3, 0xa6, 0x1d, 0x66, + 0x91, 0xef, 0x81, 0x55, 0x13, 0xfb, 0x66, 0x8f, 0x46, 0xfa, 0xc8, 0x78, 0x80, 0x7c, 0x1d, 0xb9, + 0x46, 0xab, 0x83, 0xac, 0x1a, 0xd8, 0x90, 0x36, 0x8b, 0x9a, 0x9a, 0x1e, 0xef, 0x63, 0x02, 0x55, + 0xb8, 0x2c, 0x3c, 0x1a, 0x77, 0xdc, 0xe0, 0xf6, 0xad, 0xe2, 0x37, 0x4f, 0x94, 0x29, 0x36, 0x13, + 0x5f, 0xe6, 0x40, 0x81, 0xb6, 0xa2, 0x7c, 0x2e, 0xb9, 0x44, 0x0a, 0xda, 0xd2, 0xcb, 0x50, 0xc9, + 0x61, 0x6b, 0xf4, 0x2a, 0xb9, 0x08, 0x66, 0xa9, 0x5c, 0x3a, 0xb6, 0xd8, 0x20, 0x5b, 0xd0, 0xe4, + 0x28, 0x54, 0x4e, 0xf1, 0x18, 0xe1, 0x50, 0xe1, 0x0c, 0xfd, 0xb4, 0x6b, 0xc9, 0xfb, 0x60, 0xe9, + 0x48, 0xcb, 0x59, 0xc8, 0xf5, 0x9c, 0xa0, 0x96, 0xdf, 0xc8, 0x6f, 0x96, 0xb4, 0x7a, 0x14, 0x2a, + 0xeb, 0x3c, 0x71, 0x4c, 0x90, 0x0a, 0x2b, 0x7e, 0xda, 0x86, 0xdb, 0xcc, 0x26, 0xfb, 0x60, 0x35, + 0x0e, 0x35, 0x4c, 0x93, 0xd5, 0xc5, 0xb0, 0x2c, 0x1f, 0x05, 0x81, 0x98, 0x0e, 0x5b, 0xa9, 0x20, + 0xc7, 0x04, 0xd2, 0x12, 0x56, 0x45, 0x09, 0xaf, 0x71, 0xd3, 0x21, 0xf1, 0xb1, 0x6b, 0xc3, 0x65, + 0x91, 0x71, 0x8d, 0x27, 0x08, 0xa7, 0xac, 0x81, 0x72, 0x3a, 0xd2, 0x18, 0x37, 0x71, 0xed, 0xac, + 0x47, 0xa1, 0xb2, 0x92, 0x6d, 0xec, 0x24, 0x40, 0x85, 0x0b, 0x5d, 0x31, 0xdb, 0x18, 0x71, 0x26, + 0xb6, 0xc4, 0xc4, 0xfe, 0x3b, 0x07, 0xe6, 0xa9, 0xd8, 0x7b, 0x88, 0x18, 0x96, 0x41, 0x0c, 0xf9, + 0x2d, 0x30, 0xcb, 0xb2, 0x13, 0xe5, 0xcf, 0xbc, 0x0c, 0x95, 0xd8, 0x94, 0x4a, 0x2b, 0x0c, 0x2a, + 0x9c, 0xa1, 0x9f, 0x76, 0x2d, 0x3a, 0x91, 0x56, 0xd2, 0x65, 0x89, 0x47, 0x8c, 0x8e, 0x1e, 0xf4, + 0xba, 0xdd, 0xce, 0x80, 0xd5, 0xe5, 0xc4, 0xb1, 0x74, 0x5d, 0x8c, 0xa5, 0xc5, 0x21, 0xf6, 0x74, + 0x1c, 0x5d, 0x78, 0xcd, 0x71, 0x04, 0x97, 0xe2, 0x2d, 0xde, 0xa1, 0x6b, 0x1f, 0xb2, 0xa5, 0xe5, + 0xcf, 0x24, 0xb0, 0x90, 0x2d, 0x26, 0xaf, 0xf5, 0x89, 0x64, 0x76, 0x04, 0x99, 0x6a, 0x7c, 0x83, + 0xf3, 0x5b, 0x8d, 0x65, 0x4f, 0x36, 0x1f, 0xe7, 0x33, 0x07, 0x26, 0xc8, 0x68, 0xfe, 0x53, 0x1e, + 0x94, 0xa8, 0xe6, 0xac, 0xb5, 0xfe, 0xb5, 0xe0, 0xe7, 0xc1, 0x34, 0x76, 0x2d, 0xd4, 0x67, 0xf2, + 0x16, 0xb4, 0xc5, 0x28, 0x54, 0xe6, 0xe3, 0x6b, 0xcf, 0x42, 0x7d, 0x15, 0x72, 0xb7, 0xbc, 0x05, + 0xe6, 0x5b, 0xc8, 0xc6, 0x6e, 0xdc, 0xf9, 0xf4, 0x4e, 0xcd, 0x6b, 0xab, 0x51, 0xa8, 0x2c, 0xf1, + 0xf0, 0xac, 0x57, 0x85, 0x73, 0xec, 0xab, 0x68, 0xf8, 0x1d, 0x50, 0x89, 0xf7, 0xef, 0x04, 0xb6, + 0xce, 0xd7, 0x2b, 0xb0, 0xf5, 0x32, 0xa3, 0x63, 0x24, 0x44, 0x85, 0x65, 0x61, 0xdb, 0x0b, 0xec, + 0x5d, 0xc6, 0xe2, 0x3d, 0x20, 0x27, 0xe3, 0x34, 0x85, 0x9a, 0xe6, 0x1b, 0x8e, 0x42, 0x65, 0x6d, + 0x68, 0xe4, 0x66, 0xb0, 0x16, 0x63, 0x63, 0x02, 0xf6, 0x2e, 0x38, 0xc5, 0xae, 0x86, 0x14, 0x68, + 0x86, 0x01, 0xad, 0x45, 0xa1, 0xb2, 0x9c, 0xb9, 0x3a, 0x32, 0x20, 0xf3, 0xd4, 0x90, 0x00, 0x34, + 0x41, 0x11, 0xf5, 0x91, 0xd9, 0x23, 0xc8, 0x62, 0x97, 0x44, 0x51, 0x5b, 0x8a, 0x42, 0xa5, 0xcc, + 0x53, 0x63, 0x8f, 0x0a, 0x93, 0xa0, 0x4c, 0xf1, 0xfe, 0xca, 0x81, 0xf2, 0x76, 0xb2, 0xb9, 0x43, + 0x42, 0xc7, 0xfe, 0xff, 0x01, 0xa0, 0x4b, 0x09, 0x81, 0x25, 0x26, 0xf0, 0x72, 0xfa, 0x26, 0x4b, + 0x7d, 0x2a, 0x2c, 0x39, 0x81, 0x2d, 0xc4, 0xbd, 0x0c, 0x4a, 0xe9, 0x06, 0x78, 0x11, 0xab, 0x69, + 0x13, 0x64, 0xb8, 0x17, 0x9d, 0x71, 0xbc, 0xf3, 0xaf, 0xc1, 0x5b, 0xbe, 0x02, 0x4a, 0x41, 0xcf, + 0x34, 0x11, 0xb2, 0x90, 0xc5, 0x0a, 0x57, 0xcc, 0xae, 0x91, 0xb8, 0x54, 0x98, 0x86, 0xc9, 0xef, + 0x80, 0x05, 0xe2, 0xe9, 0x2d, 0xa4, 0x5b, 0xa8, 0x83, 0xe8, 0x4a, 0xd3, 0x2c, 0xaf, 0x96, 0xf6, + 0xc4, 0x11, 0xb7, 0x0a, 0xe7, 0x88, 0xa7, 0xa1, 0x6d, 0xfe, 0x4d, 0x3e, 0x00, 0x79, 0x27, 0xb0, + 0x59, 0x41, 0xe6, 0xae, 0x34, 0x8e, 0x7d, 0xbf, 0xee, 0x05, 0xb6, 0x50, 0xf1, 0x2e, 0x26, 0x6d, + 0xec, 0xb2, 0x5e, 0xd0, 0x4e, 0x45, 0xa1, 0x02, 0x92, 0xfd, 0xab, 0x90, 0x42, 0xd1, 0x11, 0xb5, + 0x78, 0x37, 0x3d, 0x02, 0x6f, 0x24, 0x1f, 0x96, 0xfc, 0x76, 0x56, 0xf2, 0xe6, 0x49, 0x92, 0xc7, + 0x32, 0xbe, 0x52, 0xf3, 0xc7, 0xb3, 0x60, 0xfe, 0x90, 0x77, 0xcc, 0x1b, 0xbd, 0x87, 0xf5, 0xde, + 0x07, 0x4b, 0xfc, 0x29, 0x86, 0xfa, 0x5d, 0xec, 0x0f, 0x62, 0x51, 0x66, 0x98, 0x28, 0x99, 0x57, + 0xc4, 0x98, 0x20, 0x15, 0x56, 0x98, 0xf5, 0x06, 0x33, 0x0a, 0x95, 0x1e, 0x4b, 0xa0, 0x8a, 0xfa, + 0x66, 0xdb, 0x70, 0x6d, 0x64, 0xe9, 0xde, 0xfd, 0xfb, 0xc8, 0x67, 0xd7, 0x0d, 0x1b, 0x4d, 0x27, + 0xde, 0x55, 0xfb, 0xe2, 0xae, 0x3a, 0x1d, 0xcb, 0x33, 0x0a, 0x32, 0xd1, 0x1d, 0x2a, 0x27, 0x08, + 0xb7, 0x28, 0x00, 0xb5, 0x31, 0x76, 0x3e, 0x72, 0x0c, 0xec, 0x62, 0xd7, 0xce, 0xb2, 0x2b, 0x4e, + 0xc8, 0x6e, 0x1c, 0xc8, 0x64, 0xec, 0x12, 0x84, 0x94, 0xdd, 0x77, 0x52, 0xf2, 0x04, 0xcb, 0xee, + 0x9a, 0xfd, 0x3b, 0x54, 0x7a, 0x15, 0xc1, 0xdb, 0x82, 0xe0, 0xd1, 0x17, 0xda, 0x30, 0xce, 0x44, + 0x1c, 0xab, 0x31, 0x48, 0x42, 0x91, 0xfe, 0x63, 0xb4, 0xc7, 0x3b, 0x14, 0x30, 0x42, 0x17, 0x4f, + 0xea, 0x50, 0xda, 0x74, 0xaf, 0xea, 0x4e, 0xed, 0xf6, 0xd3, 0x3f, 0xea, 0x53, 0x4f, 0x9f, 0xd7, + 0xa5, 0x67, 0xcf, 0xeb, 0xd2, 0xef, 0xcf, 0xeb, 0xd2, 0xe7, 0x2f, 0xea, 0x53, 0xcf, 0x5e, 0xd4, + 0xa7, 0x7e, 0x79, 0x51, 0x9f, 0xba, 0x77, 0x35, 0xcb, 0x95, 0xae, 0x64, 0x7a, 0xae, 0x4d, 0x9f, + 0x8e, 0x4d, 0xdb, 0xbb, 0xc4, 0x7f, 0x17, 0xea, 0x67, 0x7e, 0x19, 0x62, 0xe4, 0x5b, 0x33, 0xec, + 0x47, 0x9c, 0xab, 0xff, 0x04, 0x00, 0x00, 0xff, 0xff, 0xe2, 0x7c, 0x06, 0x55, 0x7b, 0x12, 0x00, + 0x00, +} + +func (this *PoolType) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*PoolType) + if !ok { + that2, ok := that.(PoolType) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Id != that1.Id { + return false + } + if this.Name != that1.Name { + return false + } + if this.MinReserveCoinNum != that1.MinReserveCoinNum { + return false + } + if this.MaxReserveCoinNum != that1.MaxReserveCoinNum { + return false + } + if this.Description != that1.Description { + return false + } + return true +} + +func (this *Params) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*Params) + if !ok { + that2, ok := that.(Params) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if len(this.PoolTypes) != len(that1.PoolTypes) { + return false + } + for i := range this.PoolTypes { + if !this.PoolTypes[i].Equal(&that1.PoolTypes[i]) { + return false + } + } + if !this.MinInitDepositAmount.Equal(that1.MinInitDepositAmount) { + return false + } + if !this.InitPoolCoinMintAmount.Equal(that1.InitPoolCoinMintAmount) { + return false + } + if !this.MaxReserveCoinAmount.Equal(that1.MaxReserveCoinAmount) { + return false + } + if len(this.PoolCreationFee) != len(that1.PoolCreationFee) { + return false + } + for i := range this.PoolCreationFee { + if !this.PoolCreationFee[i].Equal(&that1.PoolCreationFee[i]) { + return false + } + } + if !this.SwapFeeRate.Equal(that1.SwapFeeRate) { + return false + } + if !this.WithdrawFeeRate.Equal(that1.WithdrawFeeRate) { + return false + } + if !this.MaxOrderAmountRatio.Equal(that1.MaxOrderAmountRatio) { + return false + } + if this.UnitBatchHeight != that1.UnitBatchHeight { + return false + } + if this.CircuitBreakerEnabled != that1.CircuitBreakerEnabled { + return false + } + return true +} + +func (this *Pool) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*Pool) + if !ok { + that2, ok := that.(Pool) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Id != that1.Id { + return false + } + if this.TypeId != that1.TypeId { + return false + } + if len(this.ReserveCoinDenoms) != len(that1.ReserveCoinDenoms) { + return false + } + for i := range this.ReserveCoinDenoms { + if this.ReserveCoinDenoms[i] != that1.ReserveCoinDenoms[i] { + return false + } + } + if this.ReserveAccountAddress != that1.ReserveAccountAddress { + return false + } + if this.PoolCoinDenom != that1.PoolCoinDenom { + return false + } + return true +} + +func (this *PoolMetadata) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*PoolMetadata) + if !ok { + that2, ok := that.(PoolMetadata) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.PoolId != that1.PoolId { + return false + } + if !this.PoolCoinTotalSupply.Equal(&that1.PoolCoinTotalSupply) { + return false + } + if len(this.ReserveCoins) != len(that1.ReserveCoins) { + return false + } + for i := range this.ReserveCoins { + if !this.ReserveCoins[i].Equal(&that1.ReserveCoins[i]) { + return false + } + } + return true +} + +func (this *PoolBatch) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*PoolBatch) + if !ok { + that2, ok := that.(PoolBatch) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.PoolId != that1.PoolId { + return false + } + if this.Index != that1.Index { + return false + } + if this.BeginHeight != that1.BeginHeight { + return false + } + if this.DepositMsgIndex != that1.DepositMsgIndex { + return false + } + if this.WithdrawMsgIndex != that1.WithdrawMsgIndex { + return false + } + if this.SwapMsgIndex != that1.SwapMsgIndex { + return false + } + if this.Executed != that1.Executed { + return false + } + return true +} + +func (m *PoolType) 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 *PoolType) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PoolType) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Description) > 0 { + i -= len(m.Description) + copy(dAtA[i:], m.Description) + i = encodeVarintLiquidity(dAtA, i, uint64(len(m.Description))) + i-- + dAtA[i] = 0x2a + } + if m.MaxReserveCoinNum != 0 { + i = encodeVarintLiquidity(dAtA, i, uint64(m.MaxReserveCoinNum)) + i-- + dAtA[i] = 0x20 + } + if m.MinReserveCoinNum != 0 { + i = encodeVarintLiquidity(dAtA, i, uint64(m.MinReserveCoinNum)) + i-- + dAtA[i] = 0x18 + } + if len(m.Name) > 0 { + i -= len(m.Name) + copy(dAtA[i:], m.Name) + i = encodeVarintLiquidity(dAtA, i, uint64(len(m.Name))) + i-- + dAtA[i] = 0x12 + } + if m.Id != 0 { + i = encodeVarintLiquidity(dAtA, i, uint64(m.Id)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +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 + if m.CircuitBreakerEnabled { + i-- + if m.CircuitBreakerEnabled { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x50 + } + if m.UnitBatchHeight != 0 { + i = encodeVarintLiquidity(dAtA, i, uint64(m.UnitBatchHeight)) + i-- + dAtA[i] = 0x48 + } + { + size := m.MaxOrderAmountRatio.Size() + i -= size + if _, err := m.MaxOrderAmountRatio.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintLiquidity(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x42 + { + size := m.WithdrawFeeRate.Size() + i -= size + if _, err := m.WithdrawFeeRate.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintLiquidity(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x3a + { + size := m.SwapFeeRate.Size() + i -= size + if _, err := m.SwapFeeRate.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintLiquidity(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + if len(m.PoolCreationFee) > 0 { + for iNdEx := len(m.PoolCreationFee) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.PoolCreationFee[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintLiquidity(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + } + } + { + size := m.MaxReserveCoinAmount.Size() + i -= size + if _, err := m.MaxReserveCoinAmount.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintLiquidity(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + { + size := m.InitPoolCoinMintAmount.Size() + i -= size + if _, err := m.InitPoolCoinMintAmount.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintLiquidity(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + { + size := m.MinInitDepositAmount.Size() + i -= size + if _, err := m.MinInitDepositAmount.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintLiquidity(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if len(m.PoolTypes) > 0 { + for iNdEx := len(m.PoolTypes) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.PoolTypes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintLiquidity(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *Pool) 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 *Pool) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Pool) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.PoolCoinDenom) > 0 { + i -= len(m.PoolCoinDenom) + copy(dAtA[i:], m.PoolCoinDenom) + i = encodeVarintLiquidity(dAtA, i, uint64(len(m.PoolCoinDenom))) + i-- + dAtA[i] = 0x2a + } + if len(m.ReserveAccountAddress) > 0 { + i -= len(m.ReserveAccountAddress) + copy(dAtA[i:], m.ReserveAccountAddress) + i = encodeVarintLiquidity(dAtA, i, uint64(len(m.ReserveAccountAddress))) + i-- + dAtA[i] = 0x22 + } + if len(m.ReserveCoinDenoms) > 0 { + for iNdEx := len(m.ReserveCoinDenoms) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.ReserveCoinDenoms[iNdEx]) + copy(dAtA[i:], m.ReserveCoinDenoms[iNdEx]) + i = encodeVarintLiquidity(dAtA, i, uint64(len(m.ReserveCoinDenoms[iNdEx]))) + i-- + dAtA[i] = 0x1a + } + } + if m.TypeId != 0 { + i = encodeVarintLiquidity(dAtA, i, uint64(m.TypeId)) + i-- + dAtA[i] = 0x10 + } + if m.Id != 0 { + i = encodeVarintLiquidity(dAtA, i, uint64(m.Id)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *PoolMetadata) 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 *PoolMetadata) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PoolMetadata) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ReserveCoins) > 0 { + for iNdEx := len(m.ReserveCoins) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.ReserveCoins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintLiquidity(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + { + size, err := m.PoolCoinTotalSupply.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintLiquidity(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if m.PoolId != 0 { + i = encodeVarintLiquidity(dAtA, i, uint64(m.PoolId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *PoolBatch) 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 *PoolBatch) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PoolBatch) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Executed { + i-- + if m.Executed { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x38 + } + if m.SwapMsgIndex != 0 { + i = encodeVarintLiquidity(dAtA, i, uint64(m.SwapMsgIndex)) + i-- + dAtA[i] = 0x30 + } + if m.WithdrawMsgIndex != 0 { + i = encodeVarintLiquidity(dAtA, i, uint64(m.WithdrawMsgIndex)) + i-- + dAtA[i] = 0x28 + } + if m.DepositMsgIndex != 0 { + i = encodeVarintLiquidity(dAtA, i, uint64(m.DepositMsgIndex)) + i-- + dAtA[i] = 0x20 + } + if m.BeginHeight != 0 { + i = encodeVarintLiquidity(dAtA, i, uint64(m.BeginHeight)) + i-- + dAtA[i] = 0x18 + } + if m.Index != 0 { + i = encodeVarintLiquidity(dAtA, i, uint64(m.Index)) + i-- + dAtA[i] = 0x10 + } + if m.PoolId != 0 { + i = encodeVarintLiquidity(dAtA, i, uint64(m.PoolId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *DepositMsgState) 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 *DepositMsgState) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *DepositMsgState) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Msg != nil { + { + size, err := m.Msg.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintLiquidity(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + } + if m.ToBeDeleted { + i-- + if m.ToBeDeleted { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x28 + } + if m.Succeeded { + i-- + if m.Succeeded { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x20 + } + if m.Executed { + i-- + if m.Executed { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x18 + } + if m.MsgIndex != 0 { + i = encodeVarintLiquidity(dAtA, i, uint64(m.MsgIndex)) + i-- + dAtA[i] = 0x10 + } + if m.MsgHeight != 0 { + i = encodeVarintLiquidity(dAtA, i, uint64(m.MsgHeight)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *WithdrawMsgState) 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 *WithdrawMsgState) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *WithdrawMsgState) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Msg != nil { + { + size, err := m.Msg.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintLiquidity(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + } + if m.ToBeDeleted { + i-- + if m.ToBeDeleted { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x28 + } + if m.Succeeded { + i-- + if m.Succeeded { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x20 + } + if m.Executed { + i-- + if m.Executed { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x18 + } + if m.MsgIndex != 0 { + i = encodeVarintLiquidity(dAtA, i, uint64(m.MsgIndex)) + i-- + dAtA[i] = 0x10 + } + if m.MsgHeight != 0 { + i = encodeVarintLiquidity(dAtA, i, uint64(m.MsgHeight)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *SwapMsgState) 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 *SwapMsgState) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *SwapMsgState) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Msg != nil { + { + size, err := m.Msg.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintLiquidity(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x52 + } + { + size, err := m.ReservedOfferCoinFee.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintLiquidity(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x4a + { + size, err := m.RemainingOfferCoin.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintLiquidity(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x42 + { + size, err := m.ExchangedOfferCoin.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintLiquidity(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x3a + if m.OrderExpiryHeight != 0 { + i = encodeVarintLiquidity(dAtA, i, uint64(m.OrderExpiryHeight)) + i-- + dAtA[i] = 0x30 + } + if m.ToBeDeleted { + i-- + if m.ToBeDeleted { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x28 + } + if m.Succeeded { + i-- + if m.Succeeded { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x20 + } + if m.Executed { + i-- + if m.Executed { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x18 + } + if m.MsgIndex != 0 { + i = encodeVarintLiquidity(dAtA, i, uint64(m.MsgIndex)) + i-- + dAtA[i] = 0x10 + } + if m.MsgHeight != 0 { + i = encodeVarintLiquidity(dAtA, i, uint64(m.MsgHeight)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func encodeVarintLiquidity(dAtA []byte, offset int, v uint64) int { + offset -= sovLiquidity(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} + +func (m *PoolType) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Id != 0 { + n += 1 + sovLiquidity(uint64(m.Id)) + } + l = len(m.Name) + if l > 0 { + n += 1 + l + sovLiquidity(uint64(l)) + } + if m.MinReserveCoinNum != 0 { + n += 1 + sovLiquidity(uint64(m.MinReserveCoinNum)) + } + if m.MaxReserveCoinNum != 0 { + n += 1 + sovLiquidity(uint64(m.MaxReserveCoinNum)) + } + l = len(m.Description) + if l > 0 { + n += 1 + l + sovLiquidity(uint64(l)) + } + return n +} + +func (m *Params) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.PoolTypes) > 0 { + for _, e := range m.PoolTypes { + l = e.Size() + n += 1 + l + sovLiquidity(uint64(l)) + } + } + l = m.MinInitDepositAmount.Size() + n += 1 + l + sovLiquidity(uint64(l)) + l = m.InitPoolCoinMintAmount.Size() + n += 1 + l + sovLiquidity(uint64(l)) + l = m.MaxReserveCoinAmount.Size() + n += 1 + l + sovLiquidity(uint64(l)) + if len(m.PoolCreationFee) > 0 { + for _, e := range m.PoolCreationFee { + l = e.Size() + n += 1 + l + sovLiquidity(uint64(l)) + } + } + l = m.SwapFeeRate.Size() + n += 1 + l + sovLiquidity(uint64(l)) + l = m.WithdrawFeeRate.Size() + n += 1 + l + sovLiquidity(uint64(l)) + l = m.MaxOrderAmountRatio.Size() + n += 1 + l + sovLiquidity(uint64(l)) + if m.UnitBatchHeight != 0 { + n += 1 + sovLiquidity(uint64(m.UnitBatchHeight)) + } + if m.CircuitBreakerEnabled { + n += 2 + } + return n +} + +func (m *Pool) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Id != 0 { + n += 1 + sovLiquidity(uint64(m.Id)) + } + if m.TypeId != 0 { + n += 1 + sovLiquidity(uint64(m.TypeId)) + } + if len(m.ReserveCoinDenoms) > 0 { + for _, s := range m.ReserveCoinDenoms { + l = len(s) + n += 1 + l + sovLiquidity(uint64(l)) + } + } + l = len(m.ReserveAccountAddress) + if l > 0 { + n += 1 + l + sovLiquidity(uint64(l)) + } + l = len(m.PoolCoinDenom) + if l > 0 { + n += 1 + l + sovLiquidity(uint64(l)) + } + return n +} + +func (m *PoolMetadata) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PoolId != 0 { + n += 1 + sovLiquidity(uint64(m.PoolId)) + } + l = m.PoolCoinTotalSupply.Size() + n += 1 + l + sovLiquidity(uint64(l)) + if len(m.ReserveCoins) > 0 { + for _, e := range m.ReserveCoins { + l = e.Size() + n += 1 + l + sovLiquidity(uint64(l)) + } + } + return n +} + +func (m *PoolBatch) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PoolId != 0 { + n += 1 + sovLiquidity(uint64(m.PoolId)) + } + if m.Index != 0 { + n += 1 + sovLiquidity(uint64(m.Index)) + } + if m.BeginHeight != 0 { + n += 1 + sovLiquidity(uint64(m.BeginHeight)) + } + if m.DepositMsgIndex != 0 { + n += 1 + sovLiquidity(uint64(m.DepositMsgIndex)) + } + if m.WithdrawMsgIndex != 0 { + n += 1 + sovLiquidity(uint64(m.WithdrawMsgIndex)) + } + if m.SwapMsgIndex != 0 { + n += 1 + sovLiquidity(uint64(m.SwapMsgIndex)) + } + if m.Executed { + n += 2 + } + return n +} + +func (m *DepositMsgState) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.MsgHeight != 0 { + n += 1 + sovLiquidity(uint64(m.MsgHeight)) + } + if m.MsgIndex != 0 { + n += 1 + sovLiquidity(uint64(m.MsgIndex)) + } + if m.Executed { + n += 2 + } + if m.Succeeded { + n += 2 + } + if m.ToBeDeleted { + n += 2 + } + if m.Msg != nil { + l = m.Msg.Size() + n += 1 + l + sovLiquidity(uint64(l)) + } + return n +} + +func (m *WithdrawMsgState) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.MsgHeight != 0 { + n += 1 + sovLiquidity(uint64(m.MsgHeight)) + } + if m.MsgIndex != 0 { + n += 1 + sovLiquidity(uint64(m.MsgIndex)) + } + if m.Executed { + n += 2 + } + if m.Succeeded { + n += 2 + } + if m.ToBeDeleted { + n += 2 + } + if m.Msg != nil { + l = m.Msg.Size() + n += 1 + l + sovLiquidity(uint64(l)) + } + return n +} + +func (m *SwapMsgState) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.MsgHeight != 0 { + n += 1 + sovLiquidity(uint64(m.MsgHeight)) + } + if m.MsgIndex != 0 { + n += 1 + sovLiquidity(uint64(m.MsgIndex)) + } + if m.Executed { + n += 2 + } + if m.Succeeded { + n += 2 + } + if m.ToBeDeleted { + n += 2 + } + if m.OrderExpiryHeight != 0 { + n += 1 + sovLiquidity(uint64(m.OrderExpiryHeight)) + } + l = m.ExchangedOfferCoin.Size() + n += 1 + l + sovLiquidity(uint64(l)) + l = m.RemainingOfferCoin.Size() + n += 1 + l + sovLiquidity(uint64(l)) + l = m.ReservedOfferCoinFee.Size() + n += 1 + l + sovLiquidity(uint64(l)) + if m.Msg != nil { + l = m.Msg.Size() + n += 1 + l + sovLiquidity(uint64(l)) + } + return n +} + +func sovLiquidity(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} + +func sozLiquidity(x uint64) (n int) { + return sovLiquidity(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} + +func (m *PoolType) 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 ErrIntOverflowLiquidity + } + 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: PoolType: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PoolType: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + m.Id = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Id |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + 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 ErrInvalidLengthLiquidity + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthLiquidity + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Name = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MinReserveCoinNum", wireType) + } + m.MinReserveCoinNum = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MinReserveCoinNum |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MaxReserveCoinNum", wireType) + } + m.MaxReserveCoinNum = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MaxReserveCoinNum |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + 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 ErrIntOverflowLiquidity + } + 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 ErrInvalidLengthLiquidity + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthLiquidity + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Description = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipLiquidity(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthLiquidity + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} + +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 ErrIntOverflowLiquidity + } + 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 PoolTypes", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthLiquidity + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthLiquidity + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PoolTypes = append(m.PoolTypes, PoolType{}) + if err := m.PoolTypes[len(m.PoolTypes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field MinInitDepositAmount", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + 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 ErrInvalidLengthLiquidity + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthLiquidity + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.MinInitDepositAmount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field InitPoolCoinMintAmount", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + 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 ErrInvalidLengthLiquidity + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthLiquidity + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.InitPoolCoinMintAmount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field MaxReserveCoinAmount", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + 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 ErrInvalidLengthLiquidity + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthLiquidity + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.MaxReserveCoinAmount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolCreationFee", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthLiquidity + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthLiquidity + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PoolCreationFee = append(m.PoolCreationFee, types.Coin{}) + if err := m.PoolCreationFee[len(m.PoolCreationFee)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SwapFeeRate", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + 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 ErrInvalidLengthLiquidity + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthLiquidity + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.SwapFeeRate.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field WithdrawFeeRate", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + 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 ErrInvalidLengthLiquidity + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthLiquidity + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.WithdrawFeeRate.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field MaxOrderAmountRatio", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + 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 ErrInvalidLengthLiquidity + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthLiquidity + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.MaxOrderAmountRatio.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 9: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field UnitBatchHeight", wireType) + } + m.UnitBatchHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.UnitBatchHeight |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 10: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CircuitBreakerEnabled", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.CircuitBreakerEnabled = bool(v != 0) + default: + iNdEx = preIndex + skippy, err := skipLiquidity(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthLiquidity + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} + +func (m *Pool) 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 ErrIntOverflowLiquidity + } + 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: Pool: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Pool: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + m.Id = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Id |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field TypeId", wireType) + } + m.TypeId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.TypeId |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ReserveCoinDenoms", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + 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 ErrInvalidLengthLiquidity + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthLiquidity + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ReserveCoinDenoms = append(m.ReserveCoinDenoms, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ReserveAccountAddress", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + 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 ErrInvalidLengthLiquidity + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthLiquidity + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ReserveAccountAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolCoinDenom", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + 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 ErrInvalidLengthLiquidity + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthLiquidity + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PoolCoinDenom = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipLiquidity(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthLiquidity + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} + +func (m *PoolMetadata) 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 ErrIntOverflowLiquidity + } + 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: PoolMetadata: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PoolMetadata: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) + } + m.PoolId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PoolId |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolCoinTotalSupply", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthLiquidity + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthLiquidity + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.PoolCoinTotalSupply.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ReserveCoins", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthLiquidity + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthLiquidity + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ReserveCoins = append(m.ReserveCoins, types.Coin{}) + if err := m.ReserveCoins[len(m.ReserveCoins)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipLiquidity(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthLiquidity + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} + +func (m *PoolBatch) 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 ErrIntOverflowLiquidity + } + 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: PoolBatch: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PoolBatch: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) + } + m.PoolId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PoolId |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) + } + m.Index = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Index |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field BeginHeight", wireType) + } + m.BeginHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.BeginHeight |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field DepositMsgIndex", wireType) + } + m.DepositMsgIndex = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.DepositMsgIndex |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field WithdrawMsgIndex", wireType) + } + m.WithdrawMsgIndex = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.WithdrawMsgIndex |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field SwapMsgIndex", wireType) + } + m.SwapMsgIndex = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.SwapMsgIndex |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 7: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Executed", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Executed = bool(v != 0) + default: + iNdEx = preIndex + skippy, err := skipLiquidity(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthLiquidity + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} + +func (m *DepositMsgState) 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 ErrIntOverflowLiquidity + } + 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: DepositMsgState: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DepositMsgState: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MsgHeight", wireType) + } + m.MsgHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MsgHeight |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MsgIndex", wireType) + } + m.MsgIndex = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MsgIndex |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Executed", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Executed = bool(v != 0) + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Succeeded", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Succeeded = bool(v != 0) + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ToBeDeleted", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.ToBeDeleted = bool(v != 0) + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthLiquidity + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthLiquidity + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Msg == nil { + m.Msg = &MsgDepositWithinBatch{} + } + if err := m.Msg.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipLiquidity(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthLiquidity + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} + +func (m *WithdrawMsgState) 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 ErrIntOverflowLiquidity + } + 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: WithdrawMsgState: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WithdrawMsgState: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MsgHeight", wireType) + } + m.MsgHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MsgHeight |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MsgIndex", wireType) + } + m.MsgIndex = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MsgIndex |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Executed", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Executed = bool(v != 0) + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Succeeded", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Succeeded = bool(v != 0) + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ToBeDeleted", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.ToBeDeleted = bool(v != 0) + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthLiquidity + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthLiquidity + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Msg == nil { + m.Msg = &MsgWithdrawWithinBatch{} + } + if err := m.Msg.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipLiquidity(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthLiquidity + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} + +func (m *SwapMsgState) 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 ErrIntOverflowLiquidity + } + 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: SwapMsgState: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SwapMsgState: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MsgHeight", wireType) + } + m.MsgHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MsgHeight |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MsgIndex", wireType) + } + m.MsgIndex = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MsgIndex |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Executed", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Executed = bool(v != 0) + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Succeeded", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Succeeded = bool(v != 0) + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ToBeDeleted", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.ToBeDeleted = bool(v != 0) + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field OrderExpiryHeight", wireType) + } + m.OrderExpiryHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.OrderExpiryHeight |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ExchangedOfferCoin", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthLiquidity + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthLiquidity + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ExchangedOfferCoin.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field RemainingOfferCoin", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthLiquidity + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthLiquidity + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.RemainingOfferCoin.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ReservedOfferCoinFee", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthLiquidity + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthLiquidity + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ReservedOfferCoinFee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 10: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLiquidity + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthLiquidity + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthLiquidity + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Msg == nil { + m.Msg = &MsgSwapWithinBatch{} + } + if err := m.Msg.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipLiquidity(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthLiquidity + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} + +func skipLiquidity(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, ErrIntOverflowLiquidity + } + 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, ErrIntOverflowLiquidity + } + 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, ErrIntOverflowLiquidity + } + 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, ErrInvalidLengthLiquidity + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupLiquidity + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthLiquidity + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthLiquidity = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowLiquidity = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupLiquidity = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/liquidity/types/liquidity_pool.go b/x/liquidity/types/liquidity_pool.go new file mode 100644 index 00000000..710a3b14 --- /dev/null +++ b/x/liquidity/types/liquidity_pool.go @@ -0,0 +1,190 @@ +package types + +import ( + "strconv" + "strings" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// PoolName returns unique name of the pool consists of given reserve coin denoms and type id. +func PoolName(reserveCoinDenoms []string, poolTypeID uint32) string { + return strings.Join(append(SortDenoms(reserveCoinDenoms), strconv.FormatUint(uint64(poolTypeID), 10)), "/") +} + +// Name returns the pool's name. +func (pool Pool) Name() string { + return PoolName(pool.ReserveCoinDenoms, pool.TypeId) +} + +// Validate validates Pool. +func (pool Pool) Validate() error { + if pool.Id == 0 { + return ErrPoolNotExists + } + if pool.TypeId == 0 { + return ErrPoolTypeNotExists + } + if pool.ReserveCoinDenoms == nil || len(pool.ReserveCoinDenoms) == 0 { + return ErrNumOfReserveCoinDenoms + } + if uint32(len(pool.ReserveCoinDenoms)) > MaxReserveCoinNum || uint32(len(pool.ReserveCoinDenoms)) < MinReserveCoinNum { + return ErrNumOfReserveCoinDenoms + } + sortedDenomA, sortedDenomB := AlphabeticalDenomPair(pool.ReserveCoinDenoms[0], pool.ReserveCoinDenoms[1]) + if sortedDenomA != pool.ReserveCoinDenoms[0] || sortedDenomB != pool.ReserveCoinDenoms[1] { + return ErrBadOrderingReserveCoinDenoms + } + if pool.ReserveAccountAddress == "" { + return ErrEmptyReserveAccountAddress + } + if pool.ReserveAccountAddress != GetPoolReserveAcc(pool.Name(), false).String() { + return ErrBadReserveAccountAddress + } + if pool.PoolCoinDenom == "" { + return ErrEmptyPoolCoinDenom + } + if pool.PoolCoinDenom != pool.Name() { + return ErrBadPoolCoinDenom + } + return nil +} + +// NewPoolBatch creates a new PoolBatch object. +func NewPoolBatch(poolID, batchIndex uint64) PoolBatch { + return PoolBatch{ + PoolId: poolID, + Index: batchIndex, + BeginHeight: 0, + DepositMsgIndex: 1, + WithdrawMsgIndex: 1, + SwapMsgIndex: 1, + Executed: false, + } +} + +// MustMarshalPool returns the Pool bytes. Panics if fails. +func MustMarshalPool(cdc codec.BinaryCodec, liquidityPool Pool) []byte { + return cdc.MustMarshal(&liquidityPool) +} + +// MustUnmarshalPool returns the Pool from bytes. Panics if fails. +func MustUnmarshalPool(cdc codec.BinaryCodec, value []byte) Pool { + liquidityPool, err := UnmarshalPool(cdc, value) + if err != nil { + panic(err) + } + return liquidityPool +} + +// UnmarshalPool returns the Pool from bytes. +func UnmarshalPool(cdc codec.BinaryCodec, value []byte) (liquidityPool Pool, err error) { + err = cdc.Unmarshal(value, &liquidityPool) + return liquidityPool, err +} + +// GetReserveAccount returns sdk.AccAddress of the pool's reserve account. +func (pool Pool) GetReserveAccount() sdk.AccAddress { + addr, err := sdk.AccAddressFromBech32(pool.ReserveAccountAddress) + if err != nil { + panic(err) + } + return addr +} + +// GetPoolCoinDenom returns the pool coin's denom. +func (pool Pool) GetPoolCoinDenom() string { return pool.PoolCoinDenom } + +// GetId returns id of the pool. +func (pool Pool) GetId() uint64 { return pool.Id } //nolint:revive + +// Pools is a collection of pools. +type Pools []Pool + +func (pools Pools) String() (out string) { + for _, del := range pools { + out += del.String() + "\n" + } + return strings.TrimSpace(out) +} + +// MustMarshalPoolBatch returns the PoolBatch bytes. Panics if fails. +func MustMarshalPoolBatch(cdc codec.BinaryCodec, poolBatch PoolBatch) []byte { + return cdc.MustMarshal(&poolBatch) +} + +// UnmarshalPoolBatch returns the PoolBatch from bytes. +func UnmarshalPoolBatch(cdc codec.BinaryCodec, value []byte) (poolBatch PoolBatch, err error) { + err = cdc.Unmarshal(value, &poolBatch) + return poolBatch, err +} + +// MustUnmarshalPoolBatch returns the PoolBatch from bytes. Panics if fails. +func MustUnmarshalPoolBatch(cdc codec.BinaryCodec, value []byte) PoolBatch { + poolBatch, err := UnmarshalPoolBatch(cdc, value) + if err != nil { + panic(err) + } + return poolBatch +} + +// MustMarshalDepositMsgState returns the DepositMsgState bytes. Panics if fails. +func MustMarshalDepositMsgState(cdc codec.BinaryCodec, msg DepositMsgState) []byte { + return cdc.MustMarshal(&msg) +} + +// UnmarshalDepositMsgState returns the DepositMsgState from bytes. +func UnmarshalDepositMsgState(cdc codec.BinaryCodec, value []byte) (msg DepositMsgState, err error) { + err = cdc.Unmarshal(value, &msg) + return msg, err +} + +// MustUnmarshalDepositMsgState returns the DepositMsgState from bytes. Panics if fails. +func MustUnmarshalDepositMsgState(cdc codec.BinaryCodec, value []byte) DepositMsgState { + msg, err := UnmarshalDepositMsgState(cdc, value) + if err != nil { + panic(err) + } + return msg +} + +// MustMarshalWithdrawMsgState returns the WithdrawMsgState bytes. Panics if fails. +func MustMarshalWithdrawMsgState(cdc codec.BinaryCodec, msg WithdrawMsgState) []byte { + return cdc.MustMarshal(&msg) +} + +// UnmarshalWithdrawMsgState returns the WithdrawMsgState from bytes. +func UnmarshalWithdrawMsgState(cdc codec.BinaryCodec, value []byte) (msg WithdrawMsgState, err error) { + err = cdc.Unmarshal(value, &msg) + return msg, err +} + +// MustUnmarshalWithdrawMsgState returns the WithdrawMsgState from bytes. Panics if fails. +func MustUnmarshalWithdrawMsgState(cdc codec.BinaryCodec, value []byte) WithdrawMsgState { + msg, err := UnmarshalWithdrawMsgState(cdc, value) + if err != nil { + panic(err) + } + return msg +} + +// MustMarshalSwapMsgState returns the SwapMsgState bytes. Panics if fails. +func MustMarshalSwapMsgState(cdc codec.BinaryCodec, msg SwapMsgState) []byte { + return cdc.MustMarshal(&msg) +} + +// UnmarshalSwapMsgState returns the UnmarshalSwapMsgState from bytes. +func UnmarshalSwapMsgState(cdc codec.BinaryCodec, value []byte) (msg SwapMsgState, err error) { + err = cdc.Unmarshal(value, &msg) + return msg, err +} + +// MustUnmarshalSwapMsgState returns the SwapMsgState from bytes. Panics if fails. +func MustUnmarshalSwapMsgState(cdc codec.BinaryCodec, value []byte) SwapMsgState { + msg, err := UnmarshalSwapMsgState(cdc, value) + if err != nil { + panic(err) + } + return msg +} diff --git a/x/liquidity/types/msgs.go b/x/liquidity/types/msgs.go new file mode 100644 index 00000000..a77b482d --- /dev/null +++ b/x/liquidity/types/msgs.go @@ -0,0 +1,230 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var ( + _ sdk.Msg = (*MsgCreatePool)(nil) + _ sdk.Msg = (*MsgDepositWithinBatch)(nil) + _ sdk.Msg = (*MsgWithdrawWithinBatch)(nil) + _ sdk.Msg = (*MsgSwapWithinBatch)(nil) +) + +// Message types for the liquidity module +// +//nolint:gosec +const ( + TypeMsgCreatePool = "create_pool" + TypeMsgDepositWithinBatch = "deposit_within_batch" + TypeMsgWithdrawWithinBatch = "withdraw_within_batch" + TypeMsgSwapWithinBatch = "swap_within_batch" +) + +// NewMsgCreatePool creates a new MsgCreatePool. +func NewMsgCreatePool(poolCreator sdk.AccAddress, poolTypeID uint32, depositCoins sdk.Coins) *MsgCreatePool { + return &MsgCreatePool{ + PoolCreatorAddress: poolCreator.String(), + PoolTypeId: poolTypeID, + DepositCoins: depositCoins, + } +} + +func (msg MsgCreatePool) Route() string { return RouterKey } + +func (msg MsgCreatePool) Type() string { return TypeMsgCreatePool } + +func (msg MsgCreatePool) ValidateBasic() error { + if 1 > msg.PoolTypeId { + return ErrBadPoolTypeID + } + if _, err := sdk.AccAddressFromBech32(msg.PoolCreatorAddress); err != nil { + return ErrInvalidPoolCreatorAddr + } + if err := msg.DepositCoins.Validate(); err != nil { + return err + } + if n := uint32(len(msg.DepositCoins)); n > MaxReserveCoinNum || n < MinReserveCoinNum { + return ErrNumOfReserveCoin + } + return nil +} + +func (msg MsgCreatePool) GetSignBytes() []byte { + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) +} + +func (msg MsgCreatePool) GetSigners() []sdk.AccAddress { + addr, err := sdk.AccAddressFromBech32(msg.PoolCreatorAddress) + if err != nil { + panic(err) + } + return []sdk.AccAddress{addr} +} + +func (msg MsgCreatePool) GetPoolCreator() sdk.AccAddress { + addr, err := sdk.AccAddressFromBech32(msg.PoolCreatorAddress) + if err != nil { + panic(err) + } + return addr +} + +// NewMsgDepositWithinBatch creates a new MsgDepositWithinBatch. +func NewMsgDepositWithinBatch(depositor sdk.AccAddress, poolID uint64, depositCoins sdk.Coins) *MsgDepositWithinBatch { + return &MsgDepositWithinBatch{ + DepositorAddress: depositor.String(), + PoolId: poolID, + DepositCoins: depositCoins, + } +} + +func (msg MsgDepositWithinBatch) Route() string { return RouterKey } + +func (msg MsgDepositWithinBatch) Type() string { return TypeMsgDepositWithinBatch } + +func (msg MsgDepositWithinBatch) ValidateBasic() error { + if _, err := sdk.AccAddressFromBech32(msg.DepositorAddress); err != nil { + return ErrInvalidDepositorAddr + } + if err := msg.DepositCoins.Validate(); err != nil { + return err + } + if !msg.DepositCoins.IsAllPositive() { + return ErrBadDepositCoinsAmount + } + if n := uint32(len(msg.DepositCoins)); n > MaxReserveCoinNum || n < MinReserveCoinNum { + return ErrNumOfReserveCoin + } + return nil +} + +func (msg MsgDepositWithinBatch) GetSignBytes() []byte { + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) +} + +func (msg MsgDepositWithinBatch) GetSigners() []sdk.AccAddress { + addr, err := sdk.AccAddressFromBech32(msg.DepositorAddress) + if err != nil { + panic(err) + } + return []sdk.AccAddress{addr} +} + +func (msg MsgDepositWithinBatch) GetDepositor() sdk.AccAddress { + addr, err := sdk.AccAddressFromBech32(msg.DepositorAddress) + if err != nil { + panic(err) + } + return addr +} + +// NewMsgWithdrawWithinBatch creates a new MsgWithdrawWithinBatch. +func NewMsgWithdrawWithinBatch(withdrawer sdk.AccAddress, poolID uint64, poolCoin sdk.Coin) *MsgWithdrawWithinBatch { + return &MsgWithdrawWithinBatch{ + WithdrawerAddress: withdrawer.String(), + PoolId: poolID, + PoolCoin: poolCoin, + } +} + +func (msg MsgWithdrawWithinBatch) Route() string { return RouterKey } + +func (msg MsgWithdrawWithinBatch) Type() string { return TypeMsgWithdrawWithinBatch } + +func (msg MsgWithdrawWithinBatch) ValidateBasic() error { + if _, err := sdk.AccAddressFromBech32(msg.WithdrawerAddress); err != nil { + return ErrInvalidWithdrawerAddr + } + if err := msg.PoolCoin.Validate(); err != nil { + return err + } + if !msg.PoolCoin.IsPositive() { + return ErrBadPoolCoinAmount + } + return nil +} + +func (msg MsgWithdrawWithinBatch) GetSignBytes() []byte { + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) +} + +func (msg MsgWithdrawWithinBatch) GetSigners() []sdk.AccAddress { + addr, err := sdk.AccAddressFromBech32(msg.WithdrawerAddress) + if err != nil { + panic(err) + } + return []sdk.AccAddress{addr} +} + +func (msg MsgWithdrawWithinBatch) GetWithdrawer() sdk.AccAddress { + addr, err := sdk.AccAddressFromBech32(msg.WithdrawerAddress) + if err != nil { + panic(err) + } + return addr +} + +// NewMsgSwapWithinBatch creates a new MsgSwapWithinBatch. +func NewMsgSwapWithinBatch( + swapRequester sdk.AccAddress, + poolID uint64, + swapTypeID uint32, + offerCoin sdk.Coin, + demandCoinDenom string, + orderPrice sdk.Dec, + swapFeeRate sdk.Dec, +) *MsgSwapWithinBatch { + return &MsgSwapWithinBatch{ + SwapRequesterAddress: swapRequester.String(), + PoolId: poolID, + SwapTypeId: swapTypeID, + OfferCoin: offerCoin, + OfferCoinFee: GetOfferCoinFee(offerCoin, swapFeeRate), + DemandCoinDenom: demandCoinDenom, + OrderPrice: orderPrice, + } +} + +func (msg MsgSwapWithinBatch) Route() string { return RouterKey } + +func (msg MsgSwapWithinBatch) Type() string { return TypeMsgSwapWithinBatch } + +func (msg MsgSwapWithinBatch) ValidateBasic() error { + if _, err := sdk.AccAddressFromBech32(msg.SwapRequesterAddress); err != nil { + return ErrInvalidSwapRequesterAddr + } + if err := msg.OfferCoin.Validate(); err != nil { + return err + } + if !msg.OfferCoin.IsPositive() { + return ErrBadOfferCoinAmount + } + if !msg.OrderPrice.IsPositive() { + return ErrBadOrderPrice + } + if !msg.OfferCoin.Amount.GTE(MinOfferCoinAmount) { + return ErrLessThanMinOfferAmount + } + return nil +} + +func (msg MsgSwapWithinBatch) GetSignBytes() []byte { + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) +} + +func (msg MsgSwapWithinBatch) GetSigners() []sdk.AccAddress { + addr, err := sdk.AccAddressFromBech32(msg.SwapRequesterAddress) + if err != nil { + panic(err) + } + return []sdk.AccAddress{addr} +} + +func (msg MsgSwapWithinBatch) GetSwapRequester() sdk.AccAddress { + addr, err := sdk.AccAddressFromBech32(msg.SwapRequesterAddress) + if err != nil { + panic(err) + } + return addr +} diff --git a/x/liquidity/types/params.go b/x/liquidity/types/params.go new file mode 100644 index 00000000..b46e3d50 --- /dev/null +++ b/x/liquidity/types/params.go @@ -0,0 +1,299 @@ +package types + +import ( + "fmt" + + "cosmossdk.io/math" + + sdk "github.com/cosmos/cosmos-sdk/types" + "gopkg.in/yaml.v2" +) + +const ( + // CancelOrderLifeSpan is the lifespan of order cancellation. + CancelOrderLifeSpan int64 = 0 + + // MinReserveCoinNum is the minimum number of reserve coins in each liquidity pool. + MinReserveCoinNum uint32 = 2 + + // MaxReserveCoinNum is the maximum number of reserve coins in each liquidity pool. + MaxReserveCoinNum uint32 = 2 + + // DefaultUnitBatchHeight is the default number of blocks in one batch. This param is used for scalability. + DefaultUnitBatchHeight uint32 = 1 + + // DefaultPoolTypeID is the default pool type id. The only supported pool type id is 1. + DefaultPoolTypeID uint32 = 1 + + // DefaultSwapTypeID is the default swap type id. The only supported swap type (instant swap) id is 1. + DefaultSwapTypeID uint32 = 1 + + // DefaultCircuitBreakerEnabled is the default circuit breaker status. This param is used for a contingency plan. + DefaultCircuitBreakerEnabled = false +) + +// Parameter store keys +var ( + KeyPoolTypes = []byte("PoolTypes") + KeyMinInitDepositAmount = []byte("MinInitDepositAmount") + KeyInitPoolCoinMintAmount = []byte("InitPoolCoinMintAmount") + KeyMaxReserveCoinAmount = []byte("MaxReserveCoinAmount") + KeySwapFeeRate = []byte("SwapFeeRate") + KeyPoolCreationFee = []byte("PoolCreationFee") + KeyUnitBatchHeight = []byte("UnitBatchHeight") + KeyWithdrawFeeRate = []byte("WithdrawFeeRate") + KeyMaxOrderAmountRatio = []byte("MaxOrderAmountRatio") + KeyCircuitBreakerEnabled = []byte("CircuitBreakerEnabled") +) + +var ( + DefaultMinInitDepositAmount = sdk.NewInt(1000000) + DefaultInitPoolCoinMintAmount = sdk.NewInt(1000000) + DefaultMaxReserveCoinAmount = sdk.ZeroInt() + DefaultSwapFeeRate = sdk.NewDecWithPrec(3, 3) // "0.003000000000000000" + DefaultWithdrawFeeRate = sdk.ZeroDec() + DefaultMaxOrderAmountRatio = sdk.NewDecWithPrec(1, 1) // "0.100000000000000000" + DefaultPoolCreationFee = sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(40000000))) + DefaultPoolType = PoolType{ + Id: 1, + Name: "StandardLiquidityPool", + MinReserveCoinNum: MinReserveCoinNum, + MaxReserveCoinNum: MaxReserveCoinNum, + Description: "Standard liquidity pool with pool price function X/Y, ESPM constraint, and two kinds of reserve coins", + } + DefaultPoolTypes = []PoolType{DefaultPoolType} + + MinOfferCoinAmount = sdk.NewInt(100) +) + +// DefaultParams returns the default liquidity module parameters. +func DefaultParams() Params { + return Params{ + PoolTypes: DefaultPoolTypes, + MinInitDepositAmount: DefaultMinInitDepositAmount, + InitPoolCoinMintAmount: DefaultInitPoolCoinMintAmount, + MaxReserveCoinAmount: DefaultMaxReserveCoinAmount, + PoolCreationFee: DefaultPoolCreationFee, + SwapFeeRate: DefaultSwapFeeRate, + WithdrawFeeRate: DefaultWithdrawFeeRate, + MaxOrderAmountRatio: DefaultMaxOrderAmountRatio, + UnitBatchHeight: DefaultUnitBatchHeight, + CircuitBreakerEnabled: DefaultCircuitBreakerEnabled, + } +} + +// String returns a human readable string representation of the parameters. +func (p Params) String() string { + out, _ := yaml.Marshal(p) + return string(out) +} + +// Validate validates parameters. +func (p Params) Validate() error { + for _, v := range []struct { + value interface{} + validator func(interface{}) error + }{ + {p.PoolTypes, validatePoolTypes}, + {p.MinInitDepositAmount, validateMinInitDepositAmount}, + {p.InitPoolCoinMintAmount, validateInitPoolCoinMintAmount}, + {p.MaxReserveCoinAmount, validateMaxReserveCoinAmount}, + {p.PoolCreationFee, validatePoolCreationFee}, + {p.SwapFeeRate, validateSwapFeeRate}, + {p.WithdrawFeeRate, validateWithdrawFeeRate}, + {p.MaxOrderAmountRatio, validateMaxOrderAmountRatio}, + {p.UnitBatchHeight, validateUnitBatchHeight}, + {p.CircuitBreakerEnabled, validateCircuitBreakerEnabled}, + } { + if err := v.validator(v.value); err != nil { + return err + } + } + return nil +} + +func validatePoolTypes(i interface{}) error { + v, ok := i.([]PoolType) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if len(v) == 0 { + return fmt.Errorf("pool types must not be empty") + } + + for i, p := range v { + if int(p.Id) != i+1 { + return fmt.Errorf("pool type ids must be sorted") + } + if p.MaxReserveCoinNum > MaxReserveCoinNum || MinReserveCoinNum > p.MinReserveCoinNum { + return fmt.Errorf("min, max reserve coin num value of pool types are out of bounds") + } + } + + if len(v) > 1 || !v[0].Equal(DefaultPoolType) { + return fmt.Errorf("the only supported pool type is 1") + } + + return nil +} + +//nolint:staticcheck,nolintlint +func validateMinInitDepositAmount(i interface{}) error { + v, ok := i.(math.Int) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if v.IsNil() { + return fmt.Errorf("minimum initial deposit amount must not be nil") + } + + if !v.IsPositive() { + return fmt.Errorf("minimum initial deposit amount must be positive: %s", v) + } + + return nil +} + +//nolint:staticcheck,nolintlint +func validateInitPoolCoinMintAmount(i interface{}) error { + v, ok := i.(math.Int) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if v.IsNil() { + return fmt.Errorf("initial pool coin mint amount must not be nil") + } + + if !v.IsPositive() { + return fmt.Errorf("initial pool coin mint amount must be positive: %s", v) + } + + if v.LT(DefaultInitPoolCoinMintAmount) { + return fmt.Errorf("initial pool coin mint amount must be greater than or equal to 1000000: %s", v) + } + + return nil +} + +//nolint:staticcheck,nolintlint +func validateMaxReserveCoinAmount(i interface{}) error { + v, ok := i.(math.Int) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if v.IsNil() { + return fmt.Errorf("max reserve coin amount must not be nil") + } + + if v.IsNegative() { + return fmt.Errorf("max reserve coin amount must not be negative: %s", v) + } + + return nil +} + +func validateSwapFeeRate(i interface{}) error { + v, ok := i.(sdk.Dec) //nolint:nolintlint + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if v.IsNil() { + return fmt.Errorf("swap fee rate must not be nil") + } + + if v.IsNegative() { + return fmt.Errorf("swap fee rate must not be negative: %s", v) + } + + if v.GT(sdk.OneDec()) { + return fmt.Errorf("swap fee rate too large: %s", v) + } + + return nil +} + +func validateWithdrawFeeRate(i interface{}) error { + v, ok := i.(sdk.Dec) //nolint:nolintlint + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if v.IsNil() { + return fmt.Errorf("withdraw fee rate must not be nil") + } + + if v.IsNegative() { + return fmt.Errorf("withdraw fee rate must not be negative: %s", v) + } + + if v.GT(sdk.OneDec()) { + return fmt.Errorf("withdraw fee rate too large: %s", v) + } + + return nil +} + +func validateMaxOrderAmountRatio(i interface{}) error { + v, ok := i.(sdk.Dec) //nolint:nolintlint + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if v.IsNil() { + return fmt.Errorf("max order amount ratio must not be nil") + } + + if v.IsNegative() { + return fmt.Errorf("max order amount ratio must not be negative: %s", v) + } + + if v.GT(sdk.OneDec()) { + return fmt.Errorf("max order amount ratio too large: %s", v) + } + + return nil +} + +func validatePoolCreationFee(i interface{}) error { + v, ok := i.(sdk.Coins) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if err := v.Validate(); err != nil { + return err + } + + if v.Empty() { + return fmt.Errorf("pool creation fee must not be empty") + } + + return nil +} + +func validateUnitBatchHeight(i interface{}) error { + v, ok := i.(uint32) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if v == 0 { + return fmt.Errorf("unit batch height must be positive: %d", v) + } + + return nil +} + +func validateCircuitBreakerEnabled(i interface{}) error { + _, ok := i.(bool) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + return nil +} diff --git a/x/liquidity/types/params_legacy.go b/x/liquidity/types/params_legacy.go new file mode 100644 index 00000000..07c1d281 --- /dev/null +++ b/x/liquidity/types/params_legacy.go @@ -0,0 +1,24 @@ +package types + +import paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" + +// Deprecated: Type declaration for parameters +func ParamKeyTable() paramstypes.KeyTable { + return paramstypes.NewKeyTable().RegisterParamSet(&Params{}) +} + +// ParamSetPairs implements paramstypes.ParamSet. +func (p *Params) ParamSetPairs() paramstypes.ParamSetPairs { + return paramstypes.ParamSetPairs{ + paramstypes.NewParamSetPair(KeyPoolTypes, &p.PoolTypes, validatePoolTypes), + paramstypes.NewParamSetPair(KeyMinInitDepositAmount, &p.MinInitDepositAmount, validateMinInitDepositAmount), + paramstypes.NewParamSetPair(KeyInitPoolCoinMintAmount, &p.InitPoolCoinMintAmount, validateInitPoolCoinMintAmount), + paramstypes.NewParamSetPair(KeyMaxReserveCoinAmount, &p.MaxReserveCoinAmount, validateMaxReserveCoinAmount), + paramstypes.NewParamSetPair(KeyPoolCreationFee, &p.PoolCreationFee, validatePoolCreationFee), + paramstypes.NewParamSetPair(KeySwapFeeRate, &p.SwapFeeRate, validateSwapFeeRate), + paramstypes.NewParamSetPair(KeyWithdrawFeeRate, &p.WithdrawFeeRate, validateWithdrawFeeRate), + paramstypes.NewParamSetPair(KeyMaxOrderAmountRatio, &p.MaxOrderAmountRatio, validateMaxOrderAmountRatio), + paramstypes.NewParamSetPair(KeyUnitBatchHeight, &p.UnitBatchHeight, validateUnitBatchHeight), + paramstypes.NewParamSetPair(KeyCircuitBreakerEnabled, &p.CircuitBreakerEnabled, validateCircuitBreakerEnabled), + } +} diff --git a/x/liquidity/types/querier.go b/x/liquidity/types/querier.go new file mode 100644 index 00000000..1e865588 --- /dev/null +++ b/x/liquidity/types/querier.go @@ -0,0 +1,33 @@ +package types + +// DONTCOVER +// client is excluded from test coverage in the poc phase milestone 1 and will be included in milestone 2 with completeness + +// QueryLiquidityPool liquidity query endpoint supported by the liquidity querier +const ( + QueryLiquidityPool = "liquidityPool" + QueryLiquidityPools = "liquidityPools" +) + +// QueryLiquidityPoolParams is the query parameters for 'custom/liquidity' +type QueryLiquidityPoolParams struct { + PoolId uint64 `json:"pool_id" yaml:"pool_id"` // nolint:revive,nolintlint +} + +// return params of Liquidity Pool Query +func NewQueryLiquidityPoolParams(poolID uint64) QueryLiquidityPoolParams { + return QueryLiquidityPoolParams{ + PoolId: poolID, + } +} + +// QueryValidatorsParams defines the params for the following queries: +// - 'custom/liquidity/liquidityPools' +type QueryLiquidityPoolsParams struct { + Page, Limit int +} + +// return params of Liquidity Pools Query +func NewQueryLiquidityPoolsParams(page, limit int) QueryLiquidityPoolsParams { + return QueryLiquidityPoolsParams{page, limit} +} diff --git a/x/liquidity/types/query.pb.go b/x/liquidity/types/query.pb.go new file mode 100644 index 00000000..e1a35a31 --- /dev/null +++ b/x/liquidity/types/query.pb.go @@ -0,0 +1,5087 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cyber/liquidity/v1beta1/query.proto + +package types + +import ( + context "context" + fmt "fmt" + io "io" + math "math" + math_bits "math/bits" + + query "github.com/cosmos/cosmos-sdk/types/query" + _ "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" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = proto.Marshal + _ = fmt.Errorf + _ = 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 + +// the request type for the QueryLiquidityPool RPC method. requestable specified +// pool_id. +type QueryLiquidityPoolRequest struct { + PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` +} + +func (m *QueryLiquidityPoolRequest) Reset() { *m = QueryLiquidityPoolRequest{} } +func (m *QueryLiquidityPoolRequest) String() string { return proto.CompactTextString(m) } +func (*QueryLiquidityPoolRequest) ProtoMessage() {} +func (*QueryLiquidityPoolRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_456c121a8965f63a, []int{0} +} + +func (m *QueryLiquidityPoolRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryLiquidityPoolRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryLiquidityPoolRequest.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 *QueryLiquidityPoolRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryLiquidityPoolRequest.Merge(m, src) +} + +func (m *QueryLiquidityPoolRequest) XXX_Size() int { + return m.Size() +} + +func (m *QueryLiquidityPoolRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryLiquidityPoolRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryLiquidityPoolRequest proto.InternalMessageInfo + +func (m *QueryLiquidityPoolRequest) GetPoolId() uint64 { + if m != nil { + return m.PoolId + } + return 0 +} + +// the response type for the QueryLiquidityPoolResponse RPC method. Returns the +// liquidity pool that corresponds to the requested pool_id. +type QueryLiquidityPoolResponse struct { + Pool Pool `protobuf:"bytes,1,opt,name=pool,proto3" json:"pool"` +} + +func (m *QueryLiquidityPoolResponse) Reset() { *m = QueryLiquidityPoolResponse{} } +func (m *QueryLiquidityPoolResponse) String() string { return proto.CompactTextString(m) } +func (*QueryLiquidityPoolResponse) ProtoMessage() {} +func (*QueryLiquidityPoolResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_456c121a8965f63a, []int{1} +} + +func (m *QueryLiquidityPoolResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryLiquidityPoolResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryLiquidityPoolResponse.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 *QueryLiquidityPoolResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryLiquidityPoolResponse.Merge(m, src) +} + +func (m *QueryLiquidityPoolResponse) XXX_Size() int { + return m.Size() +} + +func (m *QueryLiquidityPoolResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryLiquidityPoolResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryLiquidityPoolResponse proto.InternalMessageInfo + +func (m *QueryLiquidityPoolResponse) GetPool() Pool { + if m != nil { + return m.Pool + } + return Pool{} +} + +// the request type for the QueryLiquidityByPoolCoinDenomPool RPC method. +// Requestable specified pool_coin_denom. +type QueryLiquidityPoolByPoolCoinDenomRequest struct { + PoolCoinDenom string `protobuf:"bytes,1,opt,name=pool_coin_denom,json=poolCoinDenom,proto3" json:"pool_coin_denom,omitempty"` +} + +func (m *QueryLiquidityPoolByPoolCoinDenomRequest) Reset() { + *m = QueryLiquidityPoolByPoolCoinDenomRequest{} +} +func (m *QueryLiquidityPoolByPoolCoinDenomRequest) String() string { return proto.CompactTextString(m) } +func (*QueryLiquidityPoolByPoolCoinDenomRequest) ProtoMessage() {} +func (*QueryLiquidityPoolByPoolCoinDenomRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_456c121a8965f63a, []int{2} +} + +func (m *QueryLiquidityPoolByPoolCoinDenomRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryLiquidityPoolByPoolCoinDenomRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryLiquidityPoolByPoolCoinDenomRequest.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 *QueryLiquidityPoolByPoolCoinDenomRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryLiquidityPoolByPoolCoinDenomRequest.Merge(m, src) +} + +func (m *QueryLiquidityPoolByPoolCoinDenomRequest) XXX_Size() int { + return m.Size() +} + +func (m *QueryLiquidityPoolByPoolCoinDenomRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryLiquidityPoolByPoolCoinDenomRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryLiquidityPoolByPoolCoinDenomRequest proto.InternalMessageInfo + +func (m *QueryLiquidityPoolByPoolCoinDenomRequest) GetPoolCoinDenom() string { + if m != nil { + return m.PoolCoinDenom + } + return "" +} + +// the request type for the QueryLiquidityByReserveAcc RPC method. Requestable +// specified reserve_acc. +type QueryLiquidityPoolByReserveAccRequest struct { + ReserveAcc string `protobuf:"bytes,1,opt,name=reserve_acc,json=reserveAcc,proto3" json:"reserve_acc,omitempty"` +} + +func (m *QueryLiquidityPoolByReserveAccRequest) Reset() { *m = QueryLiquidityPoolByReserveAccRequest{} } +func (m *QueryLiquidityPoolByReserveAccRequest) String() string { return proto.CompactTextString(m) } +func (*QueryLiquidityPoolByReserveAccRequest) ProtoMessage() {} +func (*QueryLiquidityPoolByReserveAccRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_456c121a8965f63a, []int{3} +} + +func (m *QueryLiquidityPoolByReserveAccRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryLiquidityPoolByReserveAccRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryLiquidityPoolByReserveAccRequest.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 *QueryLiquidityPoolByReserveAccRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryLiquidityPoolByReserveAccRequest.Merge(m, src) +} + +func (m *QueryLiquidityPoolByReserveAccRequest) XXX_Size() int { + return m.Size() +} + +func (m *QueryLiquidityPoolByReserveAccRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryLiquidityPoolByReserveAccRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryLiquidityPoolByReserveAccRequest proto.InternalMessageInfo + +func (m *QueryLiquidityPoolByReserveAccRequest) GetReserveAcc() string { + if m != nil { + return m.ReserveAcc + } + return "" +} + +// the request type for the QueryLiquidityPoolBatch RPC method. requestable +// including specified pool_id. +type QueryLiquidityPoolBatchRequest struct { + // id of the target pool for query + PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` +} + +func (m *QueryLiquidityPoolBatchRequest) Reset() { *m = QueryLiquidityPoolBatchRequest{} } +func (m *QueryLiquidityPoolBatchRequest) String() string { return proto.CompactTextString(m) } +func (*QueryLiquidityPoolBatchRequest) ProtoMessage() {} +func (*QueryLiquidityPoolBatchRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_456c121a8965f63a, []int{4} +} + +func (m *QueryLiquidityPoolBatchRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryLiquidityPoolBatchRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryLiquidityPoolBatchRequest.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 *QueryLiquidityPoolBatchRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryLiquidityPoolBatchRequest.Merge(m, src) +} + +func (m *QueryLiquidityPoolBatchRequest) XXX_Size() int { + return m.Size() +} + +func (m *QueryLiquidityPoolBatchRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryLiquidityPoolBatchRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryLiquidityPoolBatchRequest proto.InternalMessageInfo + +func (m *QueryLiquidityPoolBatchRequest) GetPoolId() uint64 { + if m != nil { + return m.PoolId + } + return 0 +} + +// the response type for the QueryLiquidityPoolBatchResponse RPC method. Returns +// the liquidity pool batch that corresponds to the requested pool_id. +type QueryLiquidityPoolBatchResponse struct { + Batch PoolBatch `protobuf:"bytes,1,opt,name=batch,proto3" json:"batch"` +} + +func (m *QueryLiquidityPoolBatchResponse) Reset() { *m = QueryLiquidityPoolBatchResponse{} } +func (m *QueryLiquidityPoolBatchResponse) String() string { return proto.CompactTextString(m) } +func (*QueryLiquidityPoolBatchResponse) ProtoMessage() {} +func (*QueryLiquidityPoolBatchResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_456c121a8965f63a, []int{5} +} + +func (m *QueryLiquidityPoolBatchResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryLiquidityPoolBatchResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryLiquidityPoolBatchResponse.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 *QueryLiquidityPoolBatchResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryLiquidityPoolBatchResponse.Merge(m, src) +} + +func (m *QueryLiquidityPoolBatchResponse) XXX_Size() int { + return m.Size() +} + +func (m *QueryLiquidityPoolBatchResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryLiquidityPoolBatchResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryLiquidityPoolBatchResponse proto.InternalMessageInfo + +func (m *QueryLiquidityPoolBatchResponse) GetBatch() PoolBatch { + if m != nil { + return m.Batch + } + return PoolBatch{} +} + +// the request type for the QueryLiquidityPools RPC method. Requestable +// including pagination offset, limit, key. +type QueryLiquidityPoolsRequest struct { + // pagination defines an optional pagination for the request. + Pagination *query.PageRequest `protobuf:"bytes,1,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryLiquidityPoolsRequest) Reset() { *m = QueryLiquidityPoolsRequest{} } +func (m *QueryLiquidityPoolsRequest) String() string { return proto.CompactTextString(m) } +func (*QueryLiquidityPoolsRequest) ProtoMessage() {} +func (*QueryLiquidityPoolsRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_456c121a8965f63a, []int{6} +} + +func (m *QueryLiquidityPoolsRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryLiquidityPoolsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryLiquidityPoolsRequest.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 *QueryLiquidityPoolsRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryLiquidityPoolsRequest.Merge(m, src) +} + +func (m *QueryLiquidityPoolsRequest) XXX_Size() int { + return m.Size() +} + +func (m *QueryLiquidityPoolsRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryLiquidityPoolsRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryLiquidityPoolsRequest proto.InternalMessageInfo + +func (m *QueryLiquidityPoolsRequest) GetPagination() *query.PageRequest { + if m != nil { + return m.Pagination + } + return nil +} + +// the response type for the QueryLiquidityPoolsResponse RPC method. This +// includes a list of all existing liquidity pools and paging results that +// contain next_key and total count. +type QueryLiquidityPoolsResponse struct { + Pools []Pool `protobuf:"bytes,1,rep,name=pools,proto3" json:"pools"` + // pagination defines the pagination in the response. not working on this + // version. + Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryLiquidityPoolsResponse) Reset() { *m = QueryLiquidityPoolsResponse{} } +func (m *QueryLiquidityPoolsResponse) String() string { return proto.CompactTextString(m) } +func (*QueryLiquidityPoolsResponse) ProtoMessage() {} +func (*QueryLiquidityPoolsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_456c121a8965f63a, []int{7} +} + +func (m *QueryLiquidityPoolsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryLiquidityPoolsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryLiquidityPoolsResponse.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 *QueryLiquidityPoolsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryLiquidityPoolsResponse.Merge(m, src) +} + +func (m *QueryLiquidityPoolsResponse) XXX_Size() int { + return m.Size() +} + +func (m *QueryLiquidityPoolsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryLiquidityPoolsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryLiquidityPoolsResponse proto.InternalMessageInfo + +func (m *QueryLiquidityPoolsResponse) GetPools() []Pool { + if m != nil { + return m.Pools + } + return nil +} + +func (m *QueryLiquidityPoolsResponse) GetPagination() *query.PageResponse { + if m != nil { + return m.Pagination + } + return nil +} + +// QueryParamsRequest is request type for the QueryParams 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_456c121a8965f63a, []int{8} +} + +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 + +// the response type for the QueryParamsResponse RPC method. This includes +// current parameter of the liquidity module. +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_456c121a8965f63a, []int{9} +} + +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{} +} + +// the request type for the QueryPoolBatchSwapMsgs RPC method. Requestable +// including specified pool_id and pagination offset, limit, key. +type QueryPoolBatchSwapMsgsRequest struct { + // id of the target pool for query + PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` + // pagination defines an optional pagination for the request. + Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryPoolBatchSwapMsgsRequest) Reset() { *m = QueryPoolBatchSwapMsgsRequest{} } +func (m *QueryPoolBatchSwapMsgsRequest) String() string { return proto.CompactTextString(m) } +func (*QueryPoolBatchSwapMsgsRequest) ProtoMessage() {} +func (*QueryPoolBatchSwapMsgsRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_456c121a8965f63a, []int{10} +} + +func (m *QueryPoolBatchSwapMsgsRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryPoolBatchSwapMsgsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryPoolBatchSwapMsgsRequest.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 *QueryPoolBatchSwapMsgsRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryPoolBatchSwapMsgsRequest.Merge(m, src) +} + +func (m *QueryPoolBatchSwapMsgsRequest) XXX_Size() int { + return m.Size() +} + +func (m *QueryPoolBatchSwapMsgsRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryPoolBatchSwapMsgsRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryPoolBatchSwapMsgsRequest proto.InternalMessageInfo + +func (m *QueryPoolBatchSwapMsgsRequest) GetPoolId() uint64 { + if m != nil { + return m.PoolId + } + return 0 +} + +func (m *QueryPoolBatchSwapMsgsRequest) GetPagination() *query.PageRequest { + if m != nil { + return m.Pagination + } + return nil +} + +// the request type for the QueryPoolBatchSwap RPC method. Requestable including +// specified pool_id and msg_index. +type QueryPoolBatchSwapMsgRequest struct { + // id of the target pool for query + PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` + // target msg_index of the pool + MsgIndex uint64 `protobuf:"varint,2,opt,name=msg_index,json=msgIndex,proto3" json:"msg_index,omitempty"` +} + +func (m *QueryPoolBatchSwapMsgRequest) Reset() { *m = QueryPoolBatchSwapMsgRequest{} } +func (m *QueryPoolBatchSwapMsgRequest) String() string { return proto.CompactTextString(m) } +func (*QueryPoolBatchSwapMsgRequest) ProtoMessage() {} +func (*QueryPoolBatchSwapMsgRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_456c121a8965f63a, []int{11} +} + +func (m *QueryPoolBatchSwapMsgRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryPoolBatchSwapMsgRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryPoolBatchSwapMsgRequest.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 *QueryPoolBatchSwapMsgRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryPoolBatchSwapMsgRequest.Merge(m, src) +} + +func (m *QueryPoolBatchSwapMsgRequest) XXX_Size() int { + return m.Size() +} + +func (m *QueryPoolBatchSwapMsgRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryPoolBatchSwapMsgRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryPoolBatchSwapMsgRequest proto.InternalMessageInfo + +func (m *QueryPoolBatchSwapMsgRequest) GetPoolId() uint64 { + if m != nil { + return m.PoolId + } + return 0 +} + +func (m *QueryPoolBatchSwapMsgRequest) GetMsgIndex() uint64 { + if m != nil { + return m.MsgIndex + } + return 0 +} + +// the response type for the QueryPoolBatchSwapMsgs RPC method. This includes +// list of all currently existing swap messages of the batch and paging results +// that contain next_key and total count. +type QueryPoolBatchSwapMsgsResponse struct { + Swaps []SwapMsgState `protobuf:"bytes,1,rep,name=swaps,proto3" json:"swaps"` + // pagination defines the pagination in the response. not working on this + // version. + Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryPoolBatchSwapMsgsResponse) Reset() { *m = QueryPoolBatchSwapMsgsResponse{} } +func (m *QueryPoolBatchSwapMsgsResponse) String() string { return proto.CompactTextString(m) } +func (*QueryPoolBatchSwapMsgsResponse) ProtoMessage() {} +func (*QueryPoolBatchSwapMsgsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_456c121a8965f63a, []int{12} +} + +func (m *QueryPoolBatchSwapMsgsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryPoolBatchSwapMsgsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryPoolBatchSwapMsgsResponse.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 *QueryPoolBatchSwapMsgsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryPoolBatchSwapMsgsResponse.Merge(m, src) +} + +func (m *QueryPoolBatchSwapMsgsResponse) XXX_Size() int { + return m.Size() +} + +func (m *QueryPoolBatchSwapMsgsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryPoolBatchSwapMsgsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryPoolBatchSwapMsgsResponse proto.InternalMessageInfo + +func (m *QueryPoolBatchSwapMsgsResponse) GetSwaps() []SwapMsgState { + if m != nil { + return m.Swaps + } + return nil +} + +func (m *QueryPoolBatchSwapMsgsResponse) GetPagination() *query.PageResponse { + if m != nil { + return m.Pagination + } + return nil +} + +// the response type for the QueryPoolBatchSwapMsg RPC method. This includes a +// batch swap message of the batch. +type QueryPoolBatchSwapMsgResponse struct { + Swap SwapMsgState `protobuf:"bytes,1,opt,name=swap,proto3" json:"swap"` +} + +func (m *QueryPoolBatchSwapMsgResponse) Reset() { *m = QueryPoolBatchSwapMsgResponse{} } +func (m *QueryPoolBatchSwapMsgResponse) String() string { return proto.CompactTextString(m) } +func (*QueryPoolBatchSwapMsgResponse) ProtoMessage() {} +func (*QueryPoolBatchSwapMsgResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_456c121a8965f63a, []int{13} +} + +func (m *QueryPoolBatchSwapMsgResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryPoolBatchSwapMsgResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryPoolBatchSwapMsgResponse.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 *QueryPoolBatchSwapMsgResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryPoolBatchSwapMsgResponse.Merge(m, src) +} + +func (m *QueryPoolBatchSwapMsgResponse) XXX_Size() int { + return m.Size() +} + +func (m *QueryPoolBatchSwapMsgResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryPoolBatchSwapMsgResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryPoolBatchSwapMsgResponse proto.InternalMessageInfo + +func (m *QueryPoolBatchSwapMsgResponse) GetSwap() SwapMsgState { + if m != nil { + return m.Swap + } + return SwapMsgState{} +} + +// the request type for the QueryPoolBatchDeposit RPC method. Requestable +// including specified pool_id and pagination offset, limit, key. +type QueryPoolBatchDepositMsgsRequest struct { + // id of the target pool for query + PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` + // pagination defines an optional pagination for the request. + Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryPoolBatchDepositMsgsRequest) Reset() { *m = QueryPoolBatchDepositMsgsRequest{} } +func (m *QueryPoolBatchDepositMsgsRequest) String() string { return proto.CompactTextString(m) } +func (*QueryPoolBatchDepositMsgsRequest) ProtoMessage() {} +func (*QueryPoolBatchDepositMsgsRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_456c121a8965f63a, []int{14} +} + +func (m *QueryPoolBatchDepositMsgsRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryPoolBatchDepositMsgsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryPoolBatchDepositMsgsRequest.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 *QueryPoolBatchDepositMsgsRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryPoolBatchDepositMsgsRequest.Merge(m, src) +} + +func (m *QueryPoolBatchDepositMsgsRequest) XXX_Size() int { + return m.Size() +} + +func (m *QueryPoolBatchDepositMsgsRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryPoolBatchDepositMsgsRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryPoolBatchDepositMsgsRequest proto.InternalMessageInfo + +func (m *QueryPoolBatchDepositMsgsRequest) GetPoolId() uint64 { + if m != nil { + return m.PoolId + } + return 0 +} + +func (m *QueryPoolBatchDepositMsgsRequest) GetPagination() *query.PageRequest { + if m != nil { + return m.Pagination + } + return nil +} + +// the request type for the QueryPoolBatchDeposit RPC method. requestable +// including specified pool_id and msg_index. +type QueryPoolBatchDepositMsgRequest struct { + // id of the target pool for query + PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` + // target msg_index of the pool + MsgIndex uint64 `protobuf:"varint,2,opt,name=msg_index,json=msgIndex,proto3" json:"msg_index,omitempty"` +} + +func (m *QueryPoolBatchDepositMsgRequest) Reset() { *m = QueryPoolBatchDepositMsgRequest{} } +func (m *QueryPoolBatchDepositMsgRequest) String() string { return proto.CompactTextString(m) } +func (*QueryPoolBatchDepositMsgRequest) ProtoMessage() {} +func (*QueryPoolBatchDepositMsgRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_456c121a8965f63a, []int{15} +} + +func (m *QueryPoolBatchDepositMsgRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryPoolBatchDepositMsgRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryPoolBatchDepositMsgRequest.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 *QueryPoolBatchDepositMsgRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryPoolBatchDepositMsgRequest.Merge(m, src) +} + +func (m *QueryPoolBatchDepositMsgRequest) XXX_Size() int { + return m.Size() +} + +func (m *QueryPoolBatchDepositMsgRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryPoolBatchDepositMsgRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryPoolBatchDepositMsgRequest proto.InternalMessageInfo + +func (m *QueryPoolBatchDepositMsgRequest) GetPoolId() uint64 { + if m != nil { + return m.PoolId + } + return 0 +} + +func (m *QueryPoolBatchDepositMsgRequest) GetMsgIndex() uint64 { + if m != nil { + return m.MsgIndex + } + return 0 +} + +// the response type for the QueryPoolBatchDeposit RPC method. This includes a +// list of all currently existing deposit messages of the batch and paging +// results that contain next_key and total count. +type QueryPoolBatchDepositMsgsResponse struct { + Deposits []DepositMsgState `protobuf:"bytes,1,rep,name=deposits,proto3" json:"deposits"` + // pagination defines the pagination in the response. not working on this + // version. + Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryPoolBatchDepositMsgsResponse) Reset() { *m = QueryPoolBatchDepositMsgsResponse{} } +func (m *QueryPoolBatchDepositMsgsResponse) String() string { return proto.CompactTextString(m) } +func (*QueryPoolBatchDepositMsgsResponse) ProtoMessage() {} +func (*QueryPoolBatchDepositMsgsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_456c121a8965f63a, []int{16} +} + +func (m *QueryPoolBatchDepositMsgsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryPoolBatchDepositMsgsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryPoolBatchDepositMsgsResponse.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 *QueryPoolBatchDepositMsgsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryPoolBatchDepositMsgsResponse.Merge(m, src) +} + +func (m *QueryPoolBatchDepositMsgsResponse) XXX_Size() int { + return m.Size() +} + +func (m *QueryPoolBatchDepositMsgsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryPoolBatchDepositMsgsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryPoolBatchDepositMsgsResponse proto.InternalMessageInfo + +func (m *QueryPoolBatchDepositMsgsResponse) GetDeposits() []DepositMsgState { + if m != nil { + return m.Deposits + } + return nil +} + +func (m *QueryPoolBatchDepositMsgsResponse) GetPagination() *query.PageResponse { + if m != nil { + return m.Pagination + } + return nil +} + +// the response type for the QueryPoolBatchDepositMsg RPC method. This includes +// a batch swap message of the batch. +type QueryPoolBatchDepositMsgResponse struct { + Deposit DepositMsgState `protobuf:"bytes,1,opt,name=deposit,proto3" json:"deposit"` +} + +func (m *QueryPoolBatchDepositMsgResponse) Reset() { *m = QueryPoolBatchDepositMsgResponse{} } +func (m *QueryPoolBatchDepositMsgResponse) String() string { return proto.CompactTextString(m) } +func (*QueryPoolBatchDepositMsgResponse) ProtoMessage() {} +func (*QueryPoolBatchDepositMsgResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_456c121a8965f63a, []int{17} +} + +func (m *QueryPoolBatchDepositMsgResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryPoolBatchDepositMsgResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryPoolBatchDepositMsgResponse.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 *QueryPoolBatchDepositMsgResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryPoolBatchDepositMsgResponse.Merge(m, src) +} + +func (m *QueryPoolBatchDepositMsgResponse) XXX_Size() int { + return m.Size() +} + +func (m *QueryPoolBatchDepositMsgResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryPoolBatchDepositMsgResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryPoolBatchDepositMsgResponse proto.InternalMessageInfo + +func (m *QueryPoolBatchDepositMsgResponse) GetDeposit() DepositMsgState { + if m != nil { + return m.Deposit + } + return DepositMsgState{} +} + +// the request type for the QueryPoolBatchWithdraw RPC method. Requestable +// including specified pool_id and pagination offset, limit, key. +type QueryPoolBatchWithdrawMsgsRequest struct { + // id of the target pool for query + PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` + // pagination defines an optional pagination for the request. + Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryPoolBatchWithdrawMsgsRequest) Reset() { *m = QueryPoolBatchWithdrawMsgsRequest{} } +func (m *QueryPoolBatchWithdrawMsgsRequest) String() string { return proto.CompactTextString(m) } +func (*QueryPoolBatchWithdrawMsgsRequest) ProtoMessage() {} +func (*QueryPoolBatchWithdrawMsgsRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_456c121a8965f63a, []int{18} +} + +func (m *QueryPoolBatchWithdrawMsgsRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryPoolBatchWithdrawMsgsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryPoolBatchWithdrawMsgsRequest.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 *QueryPoolBatchWithdrawMsgsRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryPoolBatchWithdrawMsgsRequest.Merge(m, src) +} + +func (m *QueryPoolBatchWithdrawMsgsRequest) XXX_Size() int { + return m.Size() +} + +func (m *QueryPoolBatchWithdrawMsgsRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryPoolBatchWithdrawMsgsRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryPoolBatchWithdrawMsgsRequest proto.InternalMessageInfo + +func (m *QueryPoolBatchWithdrawMsgsRequest) GetPoolId() uint64 { + if m != nil { + return m.PoolId + } + return 0 +} + +func (m *QueryPoolBatchWithdrawMsgsRequest) GetPagination() *query.PageRequest { + if m != nil { + return m.Pagination + } + return nil +} + +// the request type for the QueryPoolBatchWithdraw RPC method. requestable +// including specified pool_id and msg_index. +type QueryPoolBatchWithdrawMsgRequest struct { + // id of the target pool for query + PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` + // target msg_index of the pool + MsgIndex uint64 `protobuf:"varint,2,opt,name=msg_index,json=msgIndex,proto3" json:"msg_index,omitempty"` +} + +func (m *QueryPoolBatchWithdrawMsgRequest) Reset() { *m = QueryPoolBatchWithdrawMsgRequest{} } +func (m *QueryPoolBatchWithdrawMsgRequest) String() string { return proto.CompactTextString(m) } +func (*QueryPoolBatchWithdrawMsgRequest) ProtoMessage() {} +func (*QueryPoolBatchWithdrawMsgRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_456c121a8965f63a, []int{19} +} + +func (m *QueryPoolBatchWithdrawMsgRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryPoolBatchWithdrawMsgRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryPoolBatchWithdrawMsgRequest.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 *QueryPoolBatchWithdrawMsgRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryPoolBatchWithdrawMsgRequest.Merge(m, src) +} + +func (m *QueryPoolBatchWithdrawMsgRequest) XXX_Size() int { + return m.Size() +} + +func (m *QueryPoolBatchWithdrawMsgRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryPoolBatchWithdrawMsgRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryPoolBatchWithdrawMsgRequest proto.InternalMessageInfo + +func (m *QueryPoolBatchWithdrawMsgRequest) GetPoolId() uint64 { + if m != nil { + return m.PoolId + } + return 0 +} + +func (m *QueryPoolBatchWithdrawMsgRequest) GetMsgIndex() uint64 { + if m != nil { + return m.MsgIndex + } + return 0 +} + +// the response type for the QueryPoolBatchWithdraw RPC method. This includes a +// list of all currently existing withdraw messages of the batch and paging +// results that contain next_key and total count. +type QueryPoolBatchWithdrawMsgsResponse struct { + Withdraws []WithdrawMsgState `protobuf:"bytes,1,rep,name=withdraws,proto3" json:"withdraws"` + // pagination defines the pagination in the response. Not supported on this + // version. + Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryPoolBatchWithdrawMsgsResponse) Reset() { *m = QueryPoolBatchWithdrawMsgsResponse{} } +func (m *QueryPoolBatchWithdrawMsgsResponse) String() string { return proto.CompactTextString(m) } +func (*QueryPoolBatchWithdrawMsgsResponse) ProtoMessage() {} +func (*QueryPoolBatchWithdrawMsgsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_456c121a8965f63a, []int{20} +} + +func (m *QueryPoolBatchWithdrawMsgsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryPoolBatchWithdrawMsgsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryPoolBatchWithdrawMsgsResponse.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 *QueryPoolBatchWithdrawMsgsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryPoolBatchWithdrawMsgsResponse.Merge(m, src) +} + +func (m *QueryPoolBatchWithdrawMsgsResponse) XXX_Size() int { + return m.Size() +} + +func (m *QueryPoolBatchWithdrawMsgsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryPoolBatchWithdrawMsgsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryPoolBatchWithdrawMsgsResponse proto.InternalMessageInfo + +func (m *QueryPoolBatchWithdrawMsgsResponse) GetWithdraws() []WithdrawMsgState { + if m != nil { + return m.Withdraws + } + return nil +} + +func (m *QueryPoolBatchWithdrawMsgsResponse) GetPagination() *query.PageResponse { + if m != nil { + return m.Pagination + } + return nil +} + +// the response type for the QueryPoolBatchWithdrawMsg RPC method. This includes +// a batch swap message of the batch. +type QueryPoolBatchWithdrawMsgResponse struct { + Withdraw WithdrawMsgState `protobuf:"bytes,1,opt,name=withdraw,proto3" json:"withdraw"` +} + +func (m *QueryPoolBatchWithdrawMsgResponse) Reset() { *m = QueryPoolBatchWithdrawMsgResponse{} } +func (m *QueryPoolBatchWithdrawMsgResponse) String() string { return proto.CompactTextString(m) } +func (*QueryPoolBatchWithdrawMsgResponse) ProtoMessage() {} +func (*QueryPoolBatchWithdrawMsgResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_456c121a8965f63a, []int{21} +} + +func (m *QueryPoolBatchWithdrawMsgResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryPoolBatchWithdrawMsgResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryPoolBatchWithdrawMsgResponse.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 *QueryPoolBatchWithdrawMsgResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryPoolBatchWithdrawMsgResponse.Merge(m, src) +} + +func (m *QueryPoolBatchWithdrawMsgResponse) XXX_Size() int { + return m.Size() +} + +func (m *QueryPoolBatchWithdrawMsgResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryPoolBatchWithdrawMsgResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryPoolBatchWithdrawMsgResponse proto.InternalMessageInfo + +func (m *QueryPoolBatchWithdrawMsgResponse) GetWithdraw() WithdrawMsgState { + if m != nil { + return m.Withdraw + } + return WithdrawMsgState{} +} + +func init() { + proto.RegisterType((*QueryLiquidityPoolRequest)(nil), "cyber.liquidity.v1beta1.QueryLiquidityPoolRequest") + proto.RegisterType((*QueryLiquidityPoolResponse)(nil), "cyber.liquidity.v1beta1.QueryLiquidityPoolResponse") + proto.RegisterType((*QueryLiquidityPoolByPoolCoinDenomRequest)(nil), "cyber.liquidity.v1beta1.QueryLiquidityPoolByPoolCoinDenomRequest") + proto.RegisterType((*QueryLiquidityPoolByReserveAccRequest)(nil), "cyber.liquidity.v1beta1.QueryLiquidityPoolByReserveAccRequest") + proto.RegisterType((*QueryLiquidityPoolBatchRequest)(nil), "cyber.liquidity.v1beta1.QueryLiquidityPoolBatchRequest") + proto.RegisterType((*QueryLiquidityPoolBatchResponse)(nil), "cyber.liquidity.v1beta1.QueryLiquidityPoolBatchResponse") + proto.RegisterType((*QueryLiquidityPoolsRequest)(nil), "cyber.liquidity.v1beta1.QueryLiquidityPoolsRequest") + proto.RegisterType((*QueryLiquidityPoolsResponse)(nil), "cyber.liquidity.v1beta1.QueryLiquidityPoolsResponse") + proto.RegisterType((*QueryParamsRequest)(nil), "cyber.liquidity.v1beta1.QueryParamsRequest") + proto.RegisterType((*QueryParamsResponse)(nil), "cyber.liquidity.v1beta1.QueryParamsResponse") + proto.RegisterType((*QueryPoolBatchSwapMsgsRequest)(nil), "cyber.liquidity.v1beta1.QueryPoolBatchSwapMsgsRequest") + proto.RegisterType((*QueryPoolBatchSwapMsgRequest)(nil), "cyber.liquidity.v1beta1.QueryPoolBatchSwapMsgRequest") + proto.RegisterType((*QueryPoolBatchSwapMsgsResponse)(nil), "cyber.liquidity.v1beta1.QueryPoolBatchSwapMsgsResponse") + proto.RegisterType((*QueryPoolBatchSwapMsgResponse)(nil), "cyber.liquidity.v1beta1.QueryPoolBatchSwapMsgResponse") + proto.RegisterType((*QueryPoolBatchDepositMsgsRequest)(nil), "cyber.liquidity.v1beta1.QueryPoolBatchDepositMsgsRequest") + proto.RegisterType((*QueryPoolBatchDepositMsgRequest)(nil), "cyber.liquidity.v1beta1.QueryPoolBatchDepositMsgRequest") + proto.RegisterType((*QueryPoolBatchDepositMsgsResponse)(nil), "cyber.liquidity.v1beta1.QueryPoolBatchDepositMsgsResponse") + proto.RegisterType((*QueryPoolBatchDepositMsgResponse)(nil), "cyber.liquidity.v1beta1.QueryPoolBatchDepositMsgResponse") + proto.RegisterType((*QueryPoolBatchWithdrawMsgsRequest)(nil), "cyber.liquidity.v1beta1.QueryPoolBatchWithdrawMsgsRequest") + proto.RegisterType((*QueryPoolBatchWithdrawMsgRequest)(nil), "cyber.liquidity.v1beta1.QueryPoolBatchWithdrawMsgRequest") + proto.RegisterType((*QueryPoolBatchWithdrawMsgsResponse)(nil), "cyber.liquidity.v1beta1.QueryPoolBatchWithdrawMsgsResponse") + proto.RegisterType((*QueryPoolBatchWithdrawMsgResponse)(nil), "cyber.liquidity.v1beta1.QueryPoolBatchWithdrawMsgResponse") +} + +func init() { + proto.RegisterFile("cyber/liquidity/v1beta1/query.proto", fileDescriptor_456c121a8965f63a) +} + +var fileDescriptor_456c121a8965f63a = []byte{ + // 1129 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x58, 0xdf, 0x6f, 0xdb, 0x54, + 0x14, 0xee, 0x1d, 0x69, 0xd7, 0x9e, 0x69, 0xfc, 0xb8, 0x2b, 0xda, 0xe6, 0x75, 0x49, 0x67, 0xb4, + 0xb5, 0x63, 0x10, 0xab, 0xed, 0xb6, 0x34, 0x9d, 0x36, 0xc8, 0x56, 0xb6, 0x15, 0x56, 0x69, 0x64, + 0x43, 0x43, 0xbc, 0x14, 0xc7, 0xb9, 0x72, 0x2d, 0x25, 0xbe, 0x6e, 0xae, 0xbb, 0xae, 0xaa, 0x2a, + 0x21, 0xe0, 0x15, 0x09, 0x89, 0xbf, 0x00, 0x89, 0x37, 0xf8, 0x03, 0x78, 0xe0, 0x01, 0x89, 0x97, + 0x3d, 0x20, 0x31, 0xa9, 0x2f, 0x7b, 0x40, 0x68, 0xb4, 0xfc, 0x21, 0xc8, 0xf7, 0x5e, 0x3b, 0x4e, + 0x62, 0x27, 0xb9, 0x5e, 0xb5, 0x97, 0xaa, 0xbe, 0x39, 0xdf, 0x39, 0xdf, 0x77, 0xce, 0x49, 0xfc, + 0xd9, 0xf0, 0x8e, 0xb5, 0x5d, 0x23, 0x2d, 0xa3, 0xe1, 0x6c, 0x6c, 0x3a, 0x75, 0xc7, 0xdf, 0x36, + 0x1e, 0xcf, 0xd5, 0x88, 0x6f, 0xce, 0x19, 0x1b, 0x9b, 0xa4, 0xb5, 0x5d, 0xf4, 0x5a, 0xd4, 0xa7, + 0xf8, 0x24, 0x0f, 0x2a, 0x46, 0x41, 0x45, 0x19, 0xa4, 0x4d, 0xda, 0xd4, 0xa6, 0x3c, 0xc6, 0x08, + 0xfe, 0x13, 0xe1, 0xda, 0x4c, 0x5a, 0xce, 0x76, 0x02, 0x11, 0x38, 0x65, 0x53, 0x6a, 0x37, 0x88, + 0x61, 0x7a, 0x8e, 0x61, 0xba, 0x2e, 0xf5, 0x4d, 0xdf, 0xa1, 0x2e, 0x93, 0x9f, 0xbe, 0x6b, 0x51, + 0xd6, 0xa4, 0xcc, 0xa8, 0x99, 0x8c, 0x08, 0x3a, 0x51, 0x22, 0xcf, 0xb4, 0x1d, 0x97, 0x07, 0x8b, + 0x58, 0xfd, 0x32, 0x9c, 0xfe, 0x34, 0x88, 0xb8, 0x17, 0x56, 0xb8, 0x4f, 0x69, 0xa3, 0x4a, 0x36, + 0x36, 0x09, 0xf3, 0xf1, 0x49, 0x38, 0xea, 0x51, 0xda, 0x58, 0x73, 0xea, 0xa7, 0xd0, 0x34, 0x9a, + 0xcd, 0x55, 0xc7, 0x82, 0xcb, 0x95, 0xba, 0xfe, 0x19, 0x68, 0x49, 0x28, 0xe6, 0x51, 0x97, 0x11, + 0x5c, 0x82, 0x5c, 0x10, 0xc7, 0x31, 0xc7, 0xe6, 0xcf, 0x16, 0x53, 0x9a, 0x50, 0x0c, 0x40, 0x37, + 0x73, 0x4f, 0xff, 0x29, 0x8c, 0x54, 0x39, 0x40, 0xaf, 0xc2, 0x6c, 0x6f, 0xda, 0x9b, 0xfc, 0xef, + 0x2d, 0xea, 0xb8, 0xcb, 0xc4, 0xa5, 0xcd, 0x90, 0xdb, 0x05, 0x78, 0x83, 0x73, 0xb3, 0xa8, 0xe3, + 0xae, 0xd5, 0x83, 0x4f, 0x78, 0xbd, 0x89, 0xea, 0x71, 0x2f, 0x1e, 0xae, 0xdf, 0x85, 0xf3, 0x49, + 0x39, 0xab, 0x84, 0x91, 0xd6, 0x63, 0x52, 0xb1, 0xac, 0x30, 0x61, 0x01, 0x8e, 0xb5, 0xc4, 0xe1, + 0x9a, 0x69, 0x59, 0x32, 0x19, 0xb4, 0xa2, 0x38, 0xbd, 0x0c, 0xf9, 0x84, 0x4c, 0xa6, 0x6f, 0xad, + 0x0f, 0xec, 0x97, 0x09, 0x85, 0x54, 0xa8, 0x6c, 0xda, 0x0d, 0x18, 0xad, 0x05, 0x07, 0xb2, 0x6b, + 0x7a, 0xff, 0xae, 0x05, 0x91, 0xb2, 0x75, 0x02, 0xa6, 0xd7, 0x93, 0x46, 0xc2, 0x42, 0x66, 0xb7, + 0x01, 0xda, 0xa3, 0x97, 0x25, 0x2e, 0x14, 0xc5, 0x9e, 0x14, 0x83, 0x3d, 0x29, 0x8a, 0xb5, 0x8d, + 0x8a, 0x98, 0x36, 0x91, 0xd8, 0x6a, 0x0c, 0xa9, 0xff, 0x88, 0xe0, 0x4c, 0x62, 0x19, 0xa9, 0xa2, + 0x0c, 0xa3, 0x81, 0x64, 0x76, 0x0a, 0x4d, 0xbf, 0x36, 0xec, 0xec, 0x05, 0x02, 0xdf, 0xe9, 0xa0, + 0x78, 0x84, 0x53, 0x9c, 0x19, 0x48, 0x51, 0xd4, 0xed, 0xe0, 0x38, 0x09, 0x98, 0x53, 0xbc, 0x6f, + 0xb6, 0xcc, 0x66, 0xd8, 0x01, 0xfd, 0x21, 0x9c, 0xe8, 0x38, 0x95, 0x84, 0xaf, 0xc3, 0x98, 0xc7, + 0x4f, 0x64, 0x53, 0x0a, 0xe9, 0x8c, 0x79, 0x98, 0xe4, 0x2c, 0x41, 0xfa, 0x57, 0x08, 0xce, 0x8a, + 0xb4, 0xe1, 0x54, 0x1e, 0x6c, 0x99, 0xde, 0x2a, 0xb3, 0xd9, 0xa0, 0x9d, 0xe8, 0x1a, 0xc9, 0x91, + 0xcc, 0x23, 0x79, 0x08, 0x53, 0x89, 0x0c, 0x06, 0x12, 0x38, 0x03, 0x13, 0x4d, 0x66, 0xaf, 0x39, + 0x6e, 0x9d, 0x3c, 0xe1, 0xf5, 0x73, 0xd5, 0xf1, 0x26, 0xb3, 0x57, 0x82, 0x6b, 0xfd, 0x17, 0x24, + 0xb7, 0x3d, 0x41, 0x98, 0x6c, 0x5d, 0x05, 0x46, 0xd9, 0x96, 0xe9, 0x85, 0xb3, 0x3e, 0x9f, 0xda, + 0x39, 0x89, 0x7c, 0xe0, 0x9b, 0x3e, 0x09, 0x67, 0xce, 0x91, 0x87, 0x37, 0xf3, 0x2f, 0x53, 0xc6, + 0x10, 0x91, 0xfd, 0x00, 0x72, 0x41, 0x49, 0x39, 0x65, 0x25, 0xae, 0x1c, 0xa8, 0x7f, 0x83, 0x60, + 0xba, 0xb3, 0xc4, 0x32, 0xf1, 0x28, 0x73, 0xfc, 0x57, 0x3a, 0xec, 0x47, 0xf2, 0x87, 0x24, 0x81, + 0xc4, 0xcb, 0xcd, 0xfb, 0x57, 0x04, 0xe7, 0xfa, 0xc8, 0x93, 0x5d, 0xfc, 0x18, 0xc6, 0xeb, 0xe2, + 0x38, 0x9c, 0xfa, 0x6c, 0x6a, 0x27, 0xdb, 0xf8, 0x78, 0x33, 0x23, 0xfc, 0xe1, 0xcd, 0xbe, 0x91, + 0x3e, 0x98, 0x88, 0xf8, 0x5d, 0x38, 0x2a, 0x0b, 0xcb, 0x0d, 0x50, 0xe5, 0x1d, 0xc2, 0xf5, 0x6f, + 0x7b, 0x1a, 0xf5, 0xc8, 0xf1, 0xd7, 0xeb, 0x2d, 0x73, 0xeb, 0x95, 0x2e, 0xc2, 0xe7, 0xdd, 0xa2, + 0x63, 0x2c, 0x5e, 0x6e, 0x13, 0x7e, 0x43, 0xa0, 0xf7, 0x13, 0x28, 0x3b, 0xba, 0x0a, 0x13, 0x5b, + 0xf2, 0x3c, 0xdc, 0x85, 0x8b, 0xa9, 0x3d, 0x8d, 0x65, 0x88, 0x37, 0xb5, 0x9d, 0xe1, 0xf0, 0xb6, + 0xc1, 0xeb, 0x33, 0x9e, 0x88, 0xfc, 0x27, 0x30, 0x1e, 0x96, 0x96, 0xfb, 0xa0, 0xcc, 0x3d, 0x4a, + 0x30, 0xff, 0x02, 0xc3, 0x28, 0x2f, 0x89, 0x7f, 0x42, 0xf0, 0x7a, 0xe7, 0x8d, 0x11, 0x2f, 0xa4, + 0xe6, 0x4d, 0xbf, 0x5b, 0x6b, 0x97, 0xd5, 0x40, 0x42, 0x94, 0x3e, 0xf3, 0xf5, 0xde, 0x7f, 0x3f, + 0x1c, 0x39, 0x87, 0x0b, 0x86, 0xf4, 0x7f, 0xbd, 0x3e, 0x52, 0xdc, 0x69, 0x7f, 0x46, 0x70, 0xbc, + 0x23, 0x07, 0x9e, 0x57, 0x28, 0x18, 0x92, 0x5c, 0x50, 0xc2, 0x48, 0x8e, 0x73, 0x9c, 0xe3, 0x25, + 0x7c, 0x71, 0x00, 0x47, 0x63, 0x47, 0x6e, 0xee, 0x2e, 0xfe, 0x17, 0xc1, 0x54, 0x3f, 0x43, 0x88, + 0x2b, 0x0a, 0x44, 0x92, 0xcd, 0x64, 0x36, 0x2d, 0x2b, 0x5c, 0xcb, 0x2d, 0x5c, 0x19, 0xa4, 0xa5, + 0xcb, 0xa7, 0x4a, 0x6d, 0xed, 0x83, 0x5d, 0xbc, 0x87, 0xe0, 0x74, 0xaa, 0x41, 0xc5, 0x37, 0x94, + 0x04, 0xf6, 0x38, 0xdb, 0x6c, 0xea, 0x2a, 0x5c, 0xdd, 0x35, 0x5c, 0x1e, 0xa4, 0x2e, 0x66, 0x9a, + 0x8d, 0x9d, 0xd8, 0xc5, 0x2e, 0xfe, 0x1d, 0x01, 0xee, 0x75, 0xbc, 0xb8, 0xa4, 0x22, 0x27, 0x66, + 0xaf, 0xb5, 0x45, 0x75, 0xa0, 0x14, 0x53, 0xe2, 0x62, 0xe6, 0xb0, 0x31, 0xf4, 0xda, 0x19, 0xdc, + 0x55, 0xe3, 0x3f, 0x10, 0xbc, 0xd5, 0xe3, 0x80, 0xf0, 0xd5, 0xfe, 0x44, 0xd2, 0xbc, 0xa0, 0x56, + 0x52, 0xc6, 0x49, 0xfe, 0xd7, 0x39, 0xff, 0x12, 0xbe, 0xa2, 0xc8, 0xdf, 0x10, 0x36, 0xeb, 0x4f, + 0x04, 0x6f, 0x76, 0x27, 0xc7, 0x57, 0xd4, 0xc8, 0x84, 0x1a, 0xae, 0xaa, 0xc2, 0x54, 0xbf, 0x2d, + 0x89, 0x12, 0x8c, 0x9d, 0xe8, 0x86, 0xb5, 0x8b, 0xff, 0x42, 0x30, 0x99, 0x64, 0x53, 0x70, 0x79, + 0x48, 0x6e, 0xbd, 0xce, 0x4d, 0x5b, 0xca, 0x02, 0x95, 0xd2, 0x3e, 0xe4, 0xd2, 0x96, 0xf0, 0xa2, + 0xaa, 0xb4, 0xc8, 0x0b, 0x3d, 0x47, 0x70, 0x22, 0xa1, 0x04, 0x5e, 0x54, 0x66, 0x15, 0xea, 0x29, + 0x67, 0x40, 0x4a, 0x39, 0xf7, 0xb8, 0x9c, 0xdb, 0x78, 0x39, 0xab, 0x9c, 0x8e, 0x61, 0xed, 0x21, + 0x78, 0x3b, 0xd1, 0x49, 0xe0, 0x61, 0x5b, 0x9e, 0xe0, 0xaf, 0xb4, 0x6b, 0x99, 0xb0, 0xaa, 0x3f, + 0x6d, 0xdd, 0x02, 0xdb, 0x76, 0xe5, 0xef, 0xf8, 0x0a, 0xc6, 0x8a, 0x0c, 0xbd, 0x82, 0xbd, 0x76, + 0x4d, 0x5b, 0xca, 0x02, 0x95, 0x92, 0x56, 0xb9, 0xa4, 0x3b, 0xf8, 0xa3, 0xcc, 0x92, 0x3a, 0x86, + 0xf6, 0x1d, 0x82, 0x31, 0xf1, 0xbc, 0x8b, 0x2f, 0x0d, 0x60, 0x15, 0x7f, 0xc8, 0xd6, 0xde, 0x1b, + 0x2e, 0x58, 0x92, 0x9e, 0xe5, 0xa4, 0x75, 0x3c, 0xdd, 0x87, 0xb4, 0x78, 0xe8, 0x5e, 0x7d, 0xba, + 0x9f, 0x47, 0xcf, 0xf6, 0xf3, 0xe8, 0xc5, 0x7e, 0x1e, 0x7d, 0x7f, 0x90, 0x1f, 0x79, 0x76, 0x90, + 0x1f, 0x79, 0x7e, 0x90, 0x1f, 0xf9, 0x62, 0xc1, 0x76, 0xfc, 0xf5, 0xcd, 0x5a, 0xd1, 0xa2, 0x4d, + 0x83, 0xd7, 0xb6, 0xa8, 0x6b, 0xb7, 0x08, 0x63, 0x86, 0x4d, 0xdf, 0x17, 0xaf, 0xd3, 0x9e, 0xc4, + 0xf2, 0xfa, 0xdb, 0x1e, 0x61, 0xb5, 0x31, 0xfe, 0xee, 0x6b, 0xe1, 0xff, 0x00, 0x00, 0x00, 0xff, + 0xff, 0xa6, 0xdb, 0xfb, 0x91, 0xc4, 0x13, 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ context.Context + _ 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 { + // Get existing liquidity pools. + LiquidityPools(ctx context.Context, in *QueryLiquidityPoolsRequest, opts ...grpc.CallOption) (*QueryLiquidityPoolsResponse, error) + // Get specific liquidity pool. + LiquidityPool(ctx context.Context, in *QueryLiquidityPoolRequest, opts ...grpc.CallOption) (*QueryLiquidityPoolResponse, error) + // Get specific liquidity pool corresponding to the pool_coin_denom. + LiquidityPoolByPoolCoinDenom(ctx context.Context, in *QueryLiquidityPoolByPoolCoinDenomRequest, opts ...grpc.CallOption) (*QueryLiquidityPoolResponse, error) + // Get specific liquidity pool corresponding to the reserve account. + LiquidityPoolByReserveAcc(ctx context.Context, in *QueryLiquidityPoolByReserveAccRequest, opts ...grpc.CallOption) (*QueryLiquidityPoolResponse, error) + // Get the pool's current batch. + LiquidityPoolBatch(ctx context.Context, in *QueryLiquidityPoolBatchRequest, opts ...grpc.CallOption) (*QueryLiquidityPoolBatchResponse, error) + // Get all swap messages in the pool's current batch. + PoolBatchSwapMsgs(ctx context.Context, in *QueryPoolBatchSwapMsgsRequest, opts ...grpc.CallOption) (*QueryPoolBatchSwapMsgsResponse, error) + // Get a specific swap message in the pool's current batch. + PoolBatchSwapMsg(ctx context.Context, in *QueryPoolBatchSwapMsgRequest, opts ...grpc.CallOption) (*QueryPoolBatchSwapMsgResponse, error) + // Get all deposit messages in the pool's current batch. + PoolBatchDepositMsgs(ctx context.Context, in *QueryPoolBatchDepositMsgsRequest, opts ...grpc.CallOption) (*QueryPoolBatchDepositMsgsResponse, error) + // Get a specific deposit message in the pool's current batch. + PoolBatchDepositMsg(ctx context.Context, in *QueryPoolBatchDepositMsgRequest, opts ...grpc.CallOption) (*QueryPoolBatchDepositMsgResponse, error) + // Get all withdraw messages in the pool's current batch. + PoolBatchWithdrawMsgs(ctx context.Context, in *QueryPoolBatchWithdrawMsgsRequest, opts ...grpc.CallOption) (*QueryPoolBatchWithdrawMsgsResponse, error) + // Get a specific withdraw message in the pool's current batch. + PoolBatchWithdrawMsg(ctx context.Context, in *QueryPoolBatchWithdrawMsgRequest, opts ...grpc.CallOption) (*QueryPoolBatchWithdrawMsgResponse, error) + // Get all parameters of the liquidity 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) LiquidityPools(ctx context.Context, in *QueryLiquidityPoolsRequest, opts ...grpc.CallOption) (*QueryLiquidityPoolsResponse, error) { + out := new(QueryLiquidityPoolsResponse) + err := c.cc.Invoke(ctx, "/cyber.liquidity.v1beta1.Query/LiquidityPools", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) LiquidityPool(ctx context.Context, in *QueryLiquidityPoolRequest, opts ...grpc.CallOption) (*QueryLiquidityPoolResponse, error) { + out := new(QueryLiquidityPoolResponse) + err := c.cc.Invoke(ctx, "/cyber.liquidity.v1beta1.Query/LiquidityPool", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) LiquidityPoolByPoolCoinDenom(ctx context.Context, in *QueryLiquidityPoolByPoolCoinDenomRequest, opts ...grpc.CallOption) (*QueryLiquidityPoolResponse, error) { + out := new(QueryLiquidityPoolResponse) + err := c.cc.Invoke(ctx, "/cyber.liquidity.v1beta1.Query/LiquidityPoolByPoolCoinDenom", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) LiquidityPoolByReserveAcc(ctx context.Context, in *QueryLiquidityPoolByReserveAccRequest, opts ...grpc.CallOption) (*QueryLiquidityPoolResponse, error) { + out := new(QueryLiquidityPoolResponse) + err := c.cc.Invoke(ctx, "/cyber.liquidity.v1beta1.Query/LiquidityPoolByReserveAcc", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) LiquidityPoolBatch(ctx context.Context, in *QueryLiquidityPoolBatchRequest, opts ...grpc.CallOption) (*QueryLiquidityPoolBatchResponse, error) { + out := new(QueryLiquidityPoolBatchResponse) + err := c.cc.Invoke(ctx, "/cyber.liquidity.v1beta1.Query/LiquidityPoolBatch", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) PoolBatchSwapMsgs(ctx context.Context, in *QueryPoolBatchSwapMsgsRequest, opts ...grpc.CallOption) (*QueryPoolBatchSwapMsgsResponse, error) { + out := new(QueryPoolBatchSwapMsgsResponse) + err := c.cc.Invoke(ctx, "/cyber.liquidity.v1beta1.Query/PoolBatchSwapMsgs", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) PoolBatchSwapMsg(ctx context.Context, in *QueryPoolBatchSwapMsgRequest, opts ...grpc.CallOption) (*QueryPoolBatchSwapMsgResponse, error) { + out := new(QueryPoolBatchSwapMsgResponse) + err := c.cc.Invoke(ctx, "/cyber.liquidity.v1beta1.Query/PoolBatchSwapMsg", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) PoolBatchDepositMsgs(ctx context.Context, in *QueryPoolBatchDepositMsgsRequest, opts ...grpc.CallOption) (*QueryPoolBatchDepositMsgsResponse, error) { + out := new(QueryPoolBatchDepositMsgsResponse) + err := c.cc.Invoke(ctx, "/cyber.liquidity.v1beta1.Query/PoolBatchDepositMsgs", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) PoolBatchDepositMsg(ctx context.Context, in *QueryPoolBatchDepositMsgRequest, opts ...grpc.CallOption) (*QueryPoolBatchDepositMsgResponse, error) { + out := new(QueryPoolBatchDepositMsgResponse) + err := c.cc.Invoke(ctx, "/cyber.liquidity.v1beta1.Query/PoolBatchDepositMsg", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) PoolBatchWithdrawMsgs(ctx context.Context, in *QueryPoolBatchWithdrawMsgsRequest, opts ...grpc.CallOption) (*QueryPoolBatchWithdrawMsgsResponse, error) { + out := new(QueryPoolBatchWithdrawMsgsResponse) + err := c.cc.Invoke(ctx, "/cyber.liquidity.v1beta1.Query/PoolBatchWithdrawMsgs", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) PoolBatchWithdrawMsg(ctx context.Context, in *QueryPoolBatchWithdrawMsgRequest, opts ...grpc.CallOption) (*QueryPoolBatchWithdrawMsgResponse, error) { + out := new(QueryPoolBatchWithdrawMsgResponse) + err := c.cc.Invoke(ctx, "/cyber.liquidity.v1beta1.Query/PoolBatchWithdrawMsg", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { + out := new(QueryParamsResponse) + err := c.cc.Invoke(ctx, "/cyber.liquidity.v1beta1.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 { + // Get existing liquidity pools. + LiquidityPools(context.Context, *QueryLiquidityPoolsRequest) (*QueryLiquidityPoolsResponse, error) + // Get specific liquidity pool. + LiquidityPool(context.Context, *QueryLiquidityPoolRequest) (*QueryLiquidityPoolResponse, error) + // Get specific liquidity pool corresponding to the pool_coin_denom. + LiquidityPoolByPoolCoinDenom(context.Context, *QueryLiquidityPoolByPoolCoinDenomRequest) (*QueryLiquidityPoolResponse, error) + // Get specific liquidity pool corresponding to the reserve account. + LiquidityPoolByReserveAcc(context.Context, *QueryLiquidityPoolByReserveAccRequest) (*QueryLiquidityPoolResponse, error) + // Get the pool's current batch. + LiquidityPoolBatch(context.Context, *QueryLiquidityPoolBatchRequest) (*QueryLiquidityPoolBatchResponse, error) + // Get all swap messages in the pool's current batch. + PoolBatchSwapMsgs(context.Context, *QueryPoolBatchSwapMsgsRequest) (*QueryPoolBatchSwapMsgsResponse, error) + // Get a specific swap message in the pool's current batch. + PoolBatchSwapMsg(context.Context, *QueryPoolBatchSwapMsgRequest) (*QueryPoolBatchSwapMsgResponse, error) + // Get all deposit messages in the pool's current batch. + PoolBatchDepositMsgs(context.Context, *QueryPoolBatchDepositMsgsRequest) (*QueryPoolBatchDepositMsgsResponse, error) + // Get a specific deposit message in the pool's current batch. + PoolBatchDepositMsg(context.Context, *QueryPoolBatchDepositMsgRequest) (*QueryPoolBatchDepositMsgResponse, error) + // Get all withdraw messages in the pool's current batch. + PoolBatchWithdrawMsgs(context.Context, *QueryPoolBatchWithdrawMsgsRequest) (*QueryPoolBatchWithdrawMsgsResponse, error) + // Get a specific withdraw message in the pool's current batch. + PoolBatchWithdrawMsg(context.Context, *QueryPoolBatchWithdrawMsgRequest) (*QueryPoolBatchWithdrawMsgResponse, error) + // Get all parameters of the liquidity module. + Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) +} + +// UnimplementedQueryServer can be embedded to have forward compatible implementations. +type UnimplementedQueryServer struct{} + +func (*UnimplementedQueryServer) LiquidityPools(ctx context.Context, req *QueryLiquidityPoolsRequest) (*QueryLiquidityPoolsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method LiquidityPools not implemented") +} + +func (*UnimplementedQueryServer) LiquidityPool(ctx context.Context, req *QueryLiquidityPoolRequest) (*QueryLiquidityPoolResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method LiquidityPool not implemented") +} + +func (*UnimplementedQueryServer) LiquidityPoolByPoolCoinDenom(ctx context.Context, req *QueryLiquidityPoolByPoolCoinDenomRequest) (*QueryLiquidityPoolResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method LiquidityPoolByPoolCoinDenom not implemented") +} + +func (*UnimplementedQueryServer) LiquidityPoolByReserveAcc(ctx context.Context, req *QueryLiquidityPoolByReserveAccRequest) (*QueryLiquidityPoolResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method LiquidityPoolByReserveAcc not implemented") +} + +func (*UnimplementedQueryServer) LiquidityPoolBatch(ctx context.Context, req *QueryLiquidityPoolBatchRequest) (*QueryLiquidityPoolBatchResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method LiquidityPoolBatch not implemented") +} + +func (*UnimplementedQueryServer) PoolBatchSwapMsgs(ctx context.Context, req *QueryPoolBatchSwapMsgsRequest) (*QueryPoolBatchSwapMsgsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method PoolBatchSwapMsgs not implemented") +} + +func (*UnimplementedQueryServer) PoolBatchSwapMsg(ctx context.Context, req *QueryPoolBatchSwapMsgRequest) (*QueryPoolBatchSwapMsgResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method PoolBatchSwapMsg not implemented") +} + +func (*UnimplementedQueryServer) PoolBatchDepositMsgs(ctx context.Context, req *QueryPoolBatchDepositMsgsRequest) (*QueryPoolBatchDepositMsgsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method PoolBatchDepositMsgs not implemented") +} + +func (*UnimplementedQueryServer) PoolBatchDepositMsg(ctx context.Context, req *QueryPoolBatchDepositMsgRequest) (*QueryPoolBatchDepositMsgResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method PoolBatchDepositMsg not implemented") +} + +func (*UnimplementedQueryServer) PoolBatchWithdrawMsgs(ctx context.Context, req *QueryPoolBatchWithdrawMsgsRequest) (*QueryPoolBatchWithdrawMsgsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method PoolBatchWithdrawMsgs not implemented") +} + +func (*UnimplementedQueryServer) PoolBatchWithdrawMsg(ctx context.Context, req *QueryPoolBatchWithdrawMsgRequest) (*QueryPoolBatchWithdrawMsgResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method PoolBatchWithdrawMsg not implemented") +} + +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_LiquidityPools_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryLiquidityPoolsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).LiquidityPools(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cyber.liquidity.v1beta1.Query/LiquidityPools", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).LiquidityPools(ctx, req.(*QueryLiquidityPoolsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_LiquidityPool_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryLiquidityPoolRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).LiquidityPool(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cyber.liquidity.v1beta1.Query/LiquidityPool", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).LiquidityPool(ctx, req.(*QueryLiquidityPoolRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_LiquidityPoolByPoolCoinDenom_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryLiquidityPoolByPoolCoinDenomRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).LiquidityPoolByPoolCoinDenom(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cyber.liquidity.v1beta1.Query/LiquidityPoolByPoolCoinDenom", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).LiquidityPoolByPoolCoinDenom(ctx, req.(*QueryLiquidityPoolByPoolCoinDenomRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_LiquidityPoolByReserveAcc_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryLiquidityPoolByReserveAccRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).LiquidityPoolByReserveAcc(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cyber.liquidity.v1beta1.Query/LiquidityPoolByReserveAcc", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).LiquidityPoolByReserveAcc(ctx, req.(*QueryLiquidityPoolByReserveAccRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_LiquidityPoolBatch_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryLiquidityPoolBatchRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).LiquidityPoolBatch(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cyber.liquidity.v1beta1.Query/LiquidityPoolBatch", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).LiquidityPoolBatch(ctx, req.(*QueryLiquidityPoolBatchRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_PoolBatchSwapMsgs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryPoolBatchSwapMsgsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).PoolBatchSwapMsgs(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cyber.liquidity.v1beta1.Query/PoolBatchSwapMsgs", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).PoolBatchSwapMsgs(ctx, req.(*QueryPoolBatchSwapMsgsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_PoolBatchSwapMsg_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryPoolBatchSwapMsgRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).PoolBatchSwapMsg(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cyber.liquidity.v1beta1.Query/PoolBatchSwapMsg", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).PoolBatchSwapMsg(ctx, req.(*QueryPoolBatchSwapMsgRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_PoolBatchDepositMsgs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryPoolBatchDepositMsgsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).PoolBatchDepositMsgs(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cyber.liquidity.v1beta1.Query/PoolBatchDepositMsgs", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).PoolBatchDepositMsgs(ctx, req.(*QueryPoolBatchDepositMsgsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_PoolBatchDepositMsg_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryPoolBatchDepositMsgRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).PoolBatchDepositMsg(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cyber.liquidity.v1beta1.Query/PoolBatchDepositMsg", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).PoolBatchDepositMsg(ctx, req.(*QueryPoolBatchDepositMsgRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_PoolBatchWithdrawMsgs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryPoolBatchWithdrawMsgsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).PoolBatchWithdrawMsgs(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cyber.liquidity.v1beta1.Query/PoolBatchWithdrawMsgs", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).PoolBatchWithdrawMsgs(ctx, req.(*QueryPoolBatchWithdrawMsgsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_PoolBatchWithdrawMsg_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryPoolBatchWithdrawMsgRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).PoolBatchWithdrawMsg(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cyber.liquidity.v1beta1.Query/PoolBatchWithdrawMsg", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).PoolBatchWithdrawMsg(ctx, req.(*QueryPoolBatchWithdrawMsgRequest)) + } + return interceptor(ctx, in, info, handler) +} + +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: "/cyber.liquidity.v1beta1.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 = grpc.ServiceDesc{ + ServiceName: "cyber.liquidity.v1beta1.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "LiquidityPools", + Handler: _Query_LiquidityPools_Handler, + }, + { + MethodName: "LiquidityPool", + Handler: _Query_LiquidityPool_Handler, + }, + { + MethodName: "LiquidityPoolByPoolCoinDenom", + Handler: _Query_LiquidityPoolByPoolCoinDenom_Handler, + }, + { + MethodName: "LiquidityPoolByReserveAcc", + Handler: _Query_LiquidityPoolByReserveAcc_Handler, + }, + { + MethodName: "LiquidityPoolBatch", + Handler: _Query_LiquidityPoolBatch_Handler, + }, + { + MethodName: "PoolBatchSwapMsgs", + Handler: _Query_PoolBatchSwapMsgs_Handler, + }, + { + MethodName: "PoolBatchSwapMsg", + Handler: _Query_PoolBatchSwapMsg_Handler, + }, + { + MethodName: "PoolBatchDepositMsgs", + Handler: _Query_PoolBatchDepositMsgs_Handler, + }, + { + MethodName: "PoolBatchDepositMsg", + Handler: _Query_PoolBatchDepositMsg_Handler, + }, + { + MethodName: "PoolBatchWithdrawMsgs", + Handler: _Query_PoolBatchWithdrawMsgs_Handler, + }, + { + MethodName: "PoolBatchWithdrawMsg", + Handler: _Query_PoolBatchWithdrawMsg_Handler, + }, + { + MethodName: "Params", + Handler: _Query_Params_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "cyber/liquidity/v1beta1/query.proto", +} + +func (m *QueryLiquidityPoolRequest) 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 *QueryLiquidityPoolRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryLiquidityPoolRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.PoolId != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.PoolId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *QueryLiquidityPoolResponse) 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 *QueryLiquidityPoolResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryLiquidityPoolResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Pool.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 (m *QueryLiquidityPoolByPoolCoinDenomRequest) 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 *QueryLiquidityPoolByPoolCoinDenomRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryLiquidityPoolByPoolCoinDenomRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.PoolCoinDenom) > 0 { + i -= len(m.PoolCoinDenom) + copy(dAtA[i:], m.PoolCoinDenom) + i = encodeVarintQuery(dAtA, i, uint64(len(m.PoolCoinDenom))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryLiquidityPoolByReserveAccRequest) 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 *QueryLiquidityPoolByReserveAccRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryLiquidityPoolByReserveAccRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ReserveAcc) > 0 { + i -= len(m.ReserveAcc) + copy(dAtA[i:], m.ReserveAcc) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ReserveAcc))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryLiquidityPoolBatchRequest) 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 *QueryLiquidityPoolBatchRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryLiquidityPoolBatchRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.PoolId != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.PoolId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *QueryLiquidityPoolBatchResponse) 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 *QueryLiquidityPoolBatchResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryLiquidityPoolBatchResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Batch.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 (m *QueryLiquidityPoolsRequest) 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 *QueryLiquidityPoolsRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryLiquidityPoolsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Pagination != nil { + { + size, err := m.Pagination.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 (m *QueryLiquidityPoolsResponse) 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 *QueryLiquidityPoolsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryLiquidityPoolsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Pagination != nil { + { + size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.Pools) > 0 { + for iNdEx := len(m.Pools) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Pools[iNdEx].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 (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 (m *QueryPoolBatchSwapMsgsRequest) 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 *QueryPoolBatchSwapMsgsRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryPoolBatchSwapMsgsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Pagination != nil { + { + size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.PoolId != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.PoolId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *QueryPoolBatchSwapMsgRequest) 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 *QueryPoolBatchSwapMsgRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryPoolBatchSwapMsgRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.MsgIndex != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.MsgIndex)) + i-- + dAtA[i] = 0x10 + } + if m.PoolId != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.PoolId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *QueryPoolBatchSwapMsgsResponse) 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 *QueryPoolBatchSwapMsgsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryPoolBatchSwapMsgsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Pagination != nil { + { + size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.Swaps) > 0 { + for iNdEx := len(m.Swaps) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Swaps[iNdEx].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 (m *QueryPoolBatchSwapMsgResponse) 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 *QueryPoolBatchSwapMsgResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryPoolBatchSwapMsgResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Swap.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 (m *QueryPoolBatchDepositMsgsRequest) 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 *QueryPoolBatchDepositMsgsRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryPoolBatchDepositMsgsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Pagination != nil { + { + size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.PoolId != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.PoolId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *QueryPoolBatchDepositMsgRequest) 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 *QueryPoolBatchDepositMsgRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryPoolBatchDepositMsgRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.MsgIndex != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.MsgIndex)) + i-- + dAtA[i] = 0x10 + } + if m.PoolId != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.PoolId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *QueryPoolBatchDepositMsgsResponse) 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 *QueryPoolBatchDepositMsgsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryPoolBatchDepositMsgsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Pagination != nil { + { + size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.Deposits) > 0 { + for iNdEx := len(m.Deposits) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Deposits[iNdEx].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 (m *QueryPoolBatchDepositMsgResponse) 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 *QueryPoolBatchDepositMsgResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryPoolBatchDepositMsgResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Deposit.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 (m *QueryPoolBatchWithdrawMsgsRequest) 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 *QueryPoolBatchWithdrawMsgsRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryPoolBatchWithdrawMsgsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Pagination != nil { + { + size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if m.PoolId != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.PoolId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *QueryPoolBatchWithdrawMsgRequest) 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 *QueryPoolBatchWithdrawMsgRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryPoolBatchWithdrawMsgRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.MsgIndex != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.MsgIndex)) + i-- + dAtA[i] = 0x10 + } + if m.PoolId != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.PoolId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *QueryPoolBatchWithdrawMsgsResponse) 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 *QueryPoolBatchWithdrawMsgsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryPoolBatchWithdrawMsgsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Pagination != nil { + { + size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.Withdraws) > 0 { + for iNdEx := len(m.Withdraws) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Withdraws[iNdEx].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 (m *QueryPoolBatchWithdrawMsgResponse) 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 *QueryPoolBatchWithdrawMsgResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryPoolBatchWithdrawMsgResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Withdraw.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 *QueryLiquidityPoolRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PoolId != 0 { + n += 1 + sovQuery(uint64(m.PoolId)) + } + return n +} + +func (m *QueryLiquidityPoolResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Pool.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + +func (m *QueryLiquidityPoolByPoolCoinDenomRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.PoolCoinDenom) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryLiquidityPoolByReserveAccRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.ReserveAcc) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryLiquidityPoolBatchRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PoolId != 0 { + n += 1 + sovQuery(uint64(m.PoolId)) + } + return n +} + +func (m *QueryLiquidityPoolBatchResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Batch.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + +func (m *QueryLiquidityPoolsRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryLiquidityPoolsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Pools) > 0 { + for _, e := range m.Pools { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } + } + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +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 (m *QueryPoolBatchSwapMsgsRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PoolId != 0 { + n += 1 + sovQuery(uint64(m.PoolId)) + } + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryPoolBatchSwapMsgRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PoolId != 0 { + n += 1 + sovQuery(uint64(m.PoolId)) + } + if m.MsgIndex != 0 { + n += 1 + sovQuery(uint64(m.MsgIndex)) + } + return n +} + +func (m *QueryPoolBatchSwapMsgsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Swaps) > 0 { + for _, e := range m.Swaps { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } + } + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryPoolBatchSwapMsgResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Swap.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + +func (m *QueryPoolBatchDepositMsgsRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PoolId != 0 { + n += 1 + sovQuery(uint64(m.PoolId)) + } + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryPoolBatchDepositMsgRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PoolId != 0 { + n += 1 + sovQuery(uint64(m.PoolId)) + } + if m.MsgIndex != 0 { + n += 1 + sovQuery(uint64(m.MsgIndex)) + } + return n +} + +func (m *QueryPoolBatchDepositMsgsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Deposits) > 0 { + for _, e := range m.Deposits { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } + } + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryPoolBatchDepositMsgResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Deposit.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + +func (m *QueryPoolBatchWithdrawMsgsRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PoolId != 0 { + n += 1 + sovQuery(uint64(m.PoolId)) + } + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryPoolBatchWithdrawMsgRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PoolId != 0 { + n += 1 + sovQuery(uint64(m.PoolId)) + } + if m.MsgIndex != 0 { + n += 1 + sovQuery(uint64(m.MsgIndex)) + } + return n +} + +func (m *QueryPoolBatchWithdrawMsgsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Withdraws) > 0 { + for _, e := range m.Withdraws { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } + } + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryPoolBatchWithdrawMsgResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Withdraw.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 *QueryLiquidityPoolRequest) 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: QueryLiquidityPoolRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryLiquidityPoolRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) + } + m.PoolId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PoolId |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + 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 *QueryLiquidityPoolResponse) 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: QueryLiquidityPoolResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryLiquidityPoolResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pool", 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.Pool.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 (m *QueryLiquidityPoolByPoolCoinDenomRequest) 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: QueryLiquidityPoolByPoolCoinDenomRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryLiquidityPoolByPoolCoinDenomRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolCoinDenom", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + 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 ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PoolCoinDenom = string(dAtA[iNdEx:postIndex]) + 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 (m *QueryLiquidityPoolByReserveAccRequest) 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: QueryLiquidityPoolByReserveAccRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryLiquidityPoolByReserveAccRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ReserveAcc", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + 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 ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ReserveAcc = string(dAtA[iNdEx:postIndex]) + 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 (m *QueryLiquidityPoolBatchRequest) 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: QueryLiquidityPoolBatchRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryLiquidityPoolBatchRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) + } + m.PoolId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PoolId |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + 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 *QueryLiquidityPoolBatchResponse) 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: QueryLiquidityPoolBatchResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryLiquidityPoolBatchResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Batch", 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.Batch.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 (m *QueryLiquidityPoolsRequest) 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: QueryLiquidityPoolsRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryLiquidityPoolsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pagination", 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 m.Pagination == nil { + m.Pagination = &query.PageRequest{} + } + if err := m.Pagination.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 (m *QueryLiquidityPoolsResponse) 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: QueryLiquidityPoolsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryLiquidityPoolsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pools", 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 + } + m.Pools = append(m.Pools, Pool{}) + if err := m.Pools[len(m.Pools)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pagination", 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 m.Pagination == nil { + m.Pagination = &query.PageResponse{} + } + if err := m.Pagination.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 (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 (m *QueryPoolBatchSwapMsgsRequest) 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: QueryPoolBatchSwapMsgsRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryPoolBatchSwapMsgsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) + } + m.PoolId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PoolId |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pagination", 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 m.Pagination == nil { + m.Pagination = &query.PageRequest{} + } + if err := m.Pagination.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 (m *QueryPoolBatchSwapMsgRequest) 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: QueryPoolBatchSwapMsgRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryPoolBatchSwapMsgRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) + } + m.PoolId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PoolId |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MsgIndex", wireType) + } + m.MsgIndex = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MsgIndex |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + 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 *QueryPoolBatchSwapMsgsResponse) 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: QueryPoolBatchSwapMsgsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryPoolBatchSwapMsgsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Swaps", 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 + } + m.Swaps = append(m.Swaps, SwapMsgState{}) + if err := m.Swaps[len(m.Swaps)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pagination", 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 m.Pagination == nil { + m.Pagination = &query.PageResponse{} + } + if err := m.Pagination.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 (m *QueryPoolBatchSwapMsgResponse) 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: QueryPoolBatchSwapMsgResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryPoolBatchSwapMsgResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Swap", 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.Swap.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 (m *QueryPoolBatchDepositMsgsRequest) 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: QueryPoolBatchDepositMsgsRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryPoolBatchDepositMsgsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) + } + m.PoolId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PoolId |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pagination", 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 m.Pagination == nil { + m.Pagination = &query.PageRequest{} + } + if err := m.Pagination.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 (m *QueryPoolBatchDepositMsgRequest) 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: QueryPoolBatchDepositMsgRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryPoolBatchDepositMsgRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) + } + m.PoolId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PoolId |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MsgIndex", wireType) + } + m.MsgIndex = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MsgIndex |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + 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 *QueryPoolBatchDepositMsgsResponse) 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: QueryPoolBatchDepositMsgsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryPoolBatchDepositMsgsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Deposits", 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 + } + m.Deposits = append(m.Deposits, DepositMsgState{}) + if err := m.Deposits[len(m.Deposits)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pagination", 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 m.Pagination == nil { + m.Pagination = &query.PageResponse{} + } + if err := m.Pagination.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 (m *QueryPoolBatchDepositMsgResponse) 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: QueryPoolBatchDepositMsgResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryPoolBatchDepositMsgResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Deposit", 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.Deposit.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 (m *QueryPoolBatchWithdrawMsgsRequest) 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: QueryPoolBatchWithdrawMsgsRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryPoolBatchWithdrawMsgsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) + } + m.PoolId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PoolId |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pagination", 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 m.Pagination == nil { + m.Pagination = &query.PageRequest{} + } + if err := m.Pagination.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 (m *QueryPoolBatchWithdrawMsgRequest) 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: QueryPoolBatchWithdrawMsgRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryPoolBatchWithdrawMsgRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) + } + m.PoolId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PoolId |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MsgIndex", wireType) + } + m.MsgIndex = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MsgIndex |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + 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 *QueryPoolBatchWithdrawMsgsResponse) 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: QueryPoolBatchWithdrawMsgsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryPoolBatchWithdrawMsgsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Withdraws", 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 + } + m.Withdraws = append(m.Withdraws, WithdrawMsgState{}) + if err := m.Withdraws[len(m.Withdraws)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pagination", 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 m.Pagination == nil { + m.Pagination = &query.PageResponse{} + } + if err := m.Pagination.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 (m *QueryPoolBatchWithdrawMsgResponse) 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: QueryPoolBatchWithdrawMsgResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryPoolBatchWithdrawMsgResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Withdraw", 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.Withdraw.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/liquidity/types/query.pb.gw.go b/x/liquidity/types/query.pb.gw.go new file mode 100644 index 00000000..f1eef421 --- /dev/null +++ b/x/liquidity/types/query.pb.gw.go @@ -0,0 +1,1310 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: cyber/liquidity/v1beta1/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 + _ io.Reader + _ status.Status + _ = runtime.String + _ = utilities.NewDoubleArray + _ = descriptor.ForMessage + _ = metadata.Join +) + +var filter_Query_LiquidityPools_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} + +func request_Query_LiquidityPools_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryLiquidityPoolsRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_LiquidityPools_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.LiquidityPools(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err +} + +func local_request_Query_LiquidityPools_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryLiquidityPoolsRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_LiquidityPools_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.LiquidityPools(ctx, &protoReq) + return msg, metadata, err +} + +func request_Query_LiquidityPool_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryLiquidityPoolRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["pool_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") + } + + protoReq.PoolId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) + } + + msg, err := client.LiquidityPool(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err +} + +func local_request_Query_LiquidityPool_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryLiquidityPoolRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["pool_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") + } + + protoReq.PoolId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) + } + + msg, err := server.LiquidityPool(ctx, &protoReq) + return msg, metadata, err +} + +func request_Query_LiquidityPoolByPoolCoinDenom_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryLiquidityPoolByPoolCoinDenomRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["pool_coin_denom"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_coin_denom") + } + + protoReq.PoolCoinDenom, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_coin_denom", err) + } + + msg, err := client.LiquidityPoolByPoolCoinDenom(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err +} + +func local_request_Query_LiquidityPoolByPoolCoinDenom_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryLiquidityPoolByPoolCoinDenomRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["pool_coin_denom"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_coin_denom") + } + + protoReq.PoolCoinDenom, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_coin_denom", err) + } + + msg, err := server.LiquidityPoolByPoolCoinDenom(ctx, &protoReq) + return msg, metadata, err +} + +func request_Query_LiquidityPoolByReserveAcc_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryLiquidityPoolByReserveAccRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["reserve_acc"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "reserve_acc") + } + + protoReq.ReserveAcc, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "reserve_acc", err) + } + + msg, err := client.LiquidityPoolByReserveAcc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err +} + +func local_request_Query_LiquidityPoolByReserveAcc_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryLiquidityPoolByReserveAccRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["reserve_acc"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "reserve_acc") + } + + protoReq.ReserveAcc, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "reserve_acc", err) + } + + msg, err := server.LiquidityPoolByReserveAcc(ctx, &protoReq) + return msg, metadata, err +} + +func request_Query_LiquidityPoolBatch_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryLiquidityPoolBatchRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["pool_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") + } + + protoReq.PoolId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) + } + + msg, err := client.LiquidityPoolBatch(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err +} + +func local_request_Query_LiquidityPoolBatch_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryLiquidityPoolBatchRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["pool_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") + } + + protoReq.PoolId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) + } + + msg, err := server.LiquidityPoolBatch(ctx, &protoReq) + return msg, metadata, err +} + +var filter_Query_PoolBatchSwapMsgs_0 = &utilities.DoubleArray{Encoding: map[string]int{"pool_id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} + +func request_Query_PoolBatchSwapMsgs_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryPoolBatchSwapMsgsRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["pool_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") + } + + protoReq.PoolId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) + } + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_PoolBatchSwapMsgs_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.PoolBatchSwapMsgs(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err +} + +func local_request_Query_PoolBatchSwapMsgs_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryPoolBatchSwapMsgsRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["pool_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") + } + + protoReq.PoolId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) + } + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_PoolBatchSwapMsgs_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.PoolBatchSwapMsgs(ctx, &protoReq) + return msg, metadata, err +} + +func request_Query_PoolBatchSwapMsg_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryPoolBatchSwapMsgRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["pool_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") + } + + protoReq.PoolId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) + } + + val, ok = pathParams["msg_index"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "msg_index") + } + + protoReq.MsgIndex, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "msg_index", err) + } + + msg, err := client.PoolBatchSwapMsg(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err +} + +func local_request_Query_PoolBatchSwapMsg_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryPoolBatchSwapMsgRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["pool_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") + } + + protoReq.PoolId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) + } + + val, ok = pathParams["msg_index"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "msg_index") + } + + protoReq.MsgIndex, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "msg_index", err) + } + + msg, err := server.PoolBatchSwapMsg(ctx, &protoReq) + return msg, metadata, err +} + +var filter_Query_PoolBatchDepositMsgs_0 = &utilities.DoubleArray{Encoding: map[string]int{"pool_id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} + +func request_Query_PoolBatchDepositMsgs_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryPoolBatchDepositMsgsRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["pool_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") + } + + protoReq.PoolId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) + } + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_PoolBatchDepositMsgs_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.PoolBatchDepositMsgs(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err +} + +func local_request_Query_PoolBatchDepositMsgs_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryPoolBatchDepositMsgsRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["pool_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") + } + + protoReq.PoolId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) + } + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_PoolBatchDepositMsgs_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.PoolBatchDepositMsgs(ctx, &protoReq) + return msg, metadata, err +} + +func request_Query_PoolBatchDepositMsg_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryPoolBatchDepositMsgRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["pool_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") + } + + protoReq.PoolId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) + } + + val, ok = pathParams["msg_index"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "msg_index") + } + + protoReq.MsgIndex, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "msg_index", err) + } + + msg, err := client.PoolBatchDepositMsg(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err +} + +func local_request_Query_PoolBatchDepositMsg_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryPoolBatchDepositMsgRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["pool_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") + } + + protoReq.PoolId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) + } + + val, ok = pathParams["msg_index"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "msg_index") + } + + protoReq.MsgIndex, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "msg_index", err) + } + + msg, err := server.PoolBatchDepositMsg(ctx, &protoReq) + return msg, metadata, err +} + +var filter_Query_PoolBatchWithdrawMsgs_0 = &utilities.DoubleArray{Encoding: map[string]int{"pool_id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} + +func request_Query_PoolBatchWithdrawMsgs_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryPoolBatchWithdrawMsgsRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["pool_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") + } + + protoReq.PoolId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) + } + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_PoolBatchWithdrawMsgs_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.PoolBatchWithdrawMsgs(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err +} + +func local_request_Query_PoolBatchWithdrawMsgs_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryPoolBatchWithdrawMsgsRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["pool_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") + } + + protoReq.PoolId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) + } + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_PoolBatchWithdrawMsgs_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.PoolBatchWithdrawMsgs(ctx, &protoReq) + return msg, metadata, err +} + +func request_Query_PoolBatchWithdrawMsg_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryPoolBatchWithdrawMsgRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["pool_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") + } + + protoReq.PoolId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) + } + + val, ok = pathParams["msg_index"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "msg_index") + } + + protoReq.MsgIndex, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "msg_index", err) + } + + msg, err := client.PoolBatchWithdrawMsg(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err +} + +func local_request_Query_PoolBatchWithdrawMsg_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryPoolBatchWithdrawMsgRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["pool_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") + } + + protoReq.PoolId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) + } + + val, ok = pathParams["msg_index"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "msg_index") + } + + protoReq.MsgIndex, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "msg_index", err) + } + + msg, err := server.PoolBatchWithdrawMsg(ctx, &protoReq) + return msg, metadata, err +} + +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_LiquidityPools_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_LiquidityPools_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_LiquidityPools_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_LiquidityPool_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_LiquidityPool_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_LiquidityPool_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_LiquidityPoolByPoolCoinDenom_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_LiquidityPoolByPoolCoinDenom_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_LiquidityPoolByPoolCoinDenom_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_LiquidityPoolByReserveAcc_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_LiquidityPoolByReserveAcc_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_LiquidityPoolByReserveAcc_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_LiquidityPoolBatch_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_LiquidityPoolBatch_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_LiquidityPoolBatch_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_PoolBatchSwapMsgs_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_PoolBatchSwapMsgs_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_PoolBatchSwapMsgs_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_PoolBatchSwapMsg_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_PoolBatchSwapMsg_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_PoolBatchSwapMsg_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_PoolBatchDepositMsgs_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_PoolBatchDepositMsgs_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_PoolBatchDepositMsgs_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_PoolBatchDepositMsg_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_PoolBatchDepositMsg_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_PoolBatchDepositMsg_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_PoolBatchWithdrawMsgs_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_PoolBatchWithdrawMsgs_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_PoolBatchWithdrawMsgs_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_PoolBatchWithdrawMsg_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_PoolBatchWithdrawMsg_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_PoolBatchWithdrawMsg_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + 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_LiquidityPools_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_LiquidityPools_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_LiquidityPools_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_LiquidityPool_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_LiquidityPool_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_LiquidityPool_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_LiquidityPoolByPoolCoinDenom_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_LiquidityPoolByPoolCoinDenom_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_LiquidityPoolByPoolCoinDenom_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_LiquidityPoolByReserveAcc_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_LiquidityPoolByReserveAcc_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_LiquidityPoolByReserveAcc_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_LiquidityPoolBatch_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_LiquidityPoolBatch_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_LiquidityPoolBatch_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_PoolBatchSwapMsgs_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_PoolBatchSwapMsgs_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_PoolBatchSwapMsgs_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_PoolBatchSwapMsg_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_PoolBatchSwapMsg_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_PoolBatchSwapMsg_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_PoolBatchDepositMsgs_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_PoolBatchDepositMsgs_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_PoolBatchDepositMsgs_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_PoolBatchDepositMsg_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_PoolBatchDepositMsg_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_PoolBatchDepositMsg_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_PoolBatchWithdrawMsgs_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_PoolBatchWithdrawMsgs_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_PoolBatchWithdrawMsgs_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_PoolBatchWithdrawMsg_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_PoolBatchWithdrawMsg_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_PoolBatchWithdrawMsg_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + 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_LiquidityPools_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmos", "liquidity", "v1beta1", "pools"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_LiquidityPool_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"cosmos", "liquidity", "v1beta1", "pools", "pool_id"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_LiquidityPoolByPoolCoinDenom_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4, 1, 0, 4, 1, 5, 4}, []string{"cosmos", "liquidity", "v1beta1", "pools", "pool_coin_denom"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_LiquidityPoolByReserveAcc_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4, 1, 0, 4, 1, 5, 4}, []string{"cosmos", "liquidity", "v1beta1", "pools", "reserve_acc"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_LiquidityPoolBatch_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"cosmos", "liquidity", "v1beta1", "pools", "pool_id", "batch"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_PoolBatchSwapMsgs_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5, 2, 6}, []string{"cosmos", "liquidity", "v1beta1", "pools", "pool_id", "batch", "swaps"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_PoolBatchSwapMsg_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5, 2, 6, 1, 0, 4, 1, 5, 7}, []string{"cosmos", "liquidity", "v1beta1", "pools", "pool_id", "batch", "swaps", "msg_index"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_PoolBatchDepositMsgs_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5, 2, 6}, []string{"cosmos", "liquidity", "v1beta1", "pools", "pool_id", "batch", "deposits"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_PoolBatchDepositMsg_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5, 2, 6, 1, 0, 4, 1, 5, 7}, []string{"cosmos", "liquidity", "v1beta1", "pools", "pool_id", "batch", "deposits", "msg_index"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_PoolBatchWithdrawMsgs_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5, 2, 6}, []string{"cosmos", "liquidity", "v1beta1", "pools", "pool_id", "batch", "withdraws"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_PoolBatchWithdrawMsg_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5, 2, 6, 1, 0, 4, 1, 5, 7}, []string{"cosmos", "liquidity", "v1beta1", "pools", "pool_id", "batch", "withdraws", "msg_index"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmos", "liquidity", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) +) + +var ( + forward_Query_LiquidityPools_0 = runtime.ForwardResponseMessage + + forward_Query_LiquidityPool_0 = runtime.ForwardResponseMessage + + forward_Query_LiquidityPoolByPoolCoinDenom_0 = runtime.ForwardResponseMessage + + forward_Query_LiquidityPoolByReserveAcc_0 = runtime.ForwardResponseMessage + + forward_Query_LiquidityPoolBatch_0 = runtime.ForwardResponseMessage + + forward_Query_PoolBatchSwapMsgs_0 = runtime.ForwardResponseMessage + + forward_Query_PoolBatchSwapMsg_0 = runtime.ForwardResponseMessage + + forward_Query_PoolBatchDepositMsgs_0 = runtime.ForwardResponseMessage + + forward_Query_PoolBatchDepositMsg_0 = runtime.ForwardResponseMessage + + forward_Query_PoolBatchWithdrawMsgs_0 = runtime.ForwardResponseMessage + + forward_Query_PoolBatchWithdrawMsg_0 = runtime.ForwardResponseMessage + + forward_Query_Params_0 = runtime.ForwardResponseMessage +) diff --git a/x/liquidity/types/swap.go b/x/liquidity/types/swap.go new file mode 100644 index 00000000..7707adde --- /dev/null +++ b/x/liquidity/types/swap.go @@ -0,0 +1,619 @@ +package types + +import ( + "sort" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// Type of match +type MatchType int + +const ( + ExactMatch MatchType = iota + 1 + NoMatch + FractionalMatch +) + +// Direction of price +type PriceDirection int + +const ( + Increasing PriceDirection = iota + 1 + Decreasing + Staying +) + +// Direction of order +type OrderDirection int + +const ( + DirectionXtoY OrderDirection = iota + 1 + DirectionYtoX +) + +// Type of order map to index at price, having the pointer list of the swap batch message. +type Order struct { + Price sdk.Dec + BuyOfferAmt sdk.Int + SellOfferAmt sdk.Int + SwapMsgStates []*SwapMsgState +} + +// OrderBook is a list of orders +type OrderBook []Order + +// Len implements sort.Interface for OrderBook +func (orderBook OrderBook) Len() int { return len(orderBook) } + +// Less implements sort.Interface for OrderBook +func (orderBook OrderBook) Less(i, j int) bool { + return orderBook[i].Price.LT(orderBook[j].Price) +} + +// Swap implements sort.Interface for OrderBook +func (orderBook OrderBook) Swap(i, j int) { orderBook[i], orderBook[j] = orderBook[j], orderBook[i] } + +// increasing sort orderbook by order price +func (orderBook OrderBook) Sort() { + sort.Slice(orderBook, func(i, j int) bool { + return orderBook[i].Price.LT(orderBook[j].Price) + }) +} + +// decreasing sort orderbook by order price +func (orderBook OrderBook) Reverse() { + sort.Slice(orderBook, func(i, j int) bool { + return orderBook[i].Price.GT(orderBook[j].Price) + }) +} + +// Get number of not matched messages on the list. +func CountNotMatchedMsgs(swapMsgStates []*SwapMsgState) int { + cnt := 0 + for _, m := range swapMsgStates { + if m.Executed && !m.Succeeded { + cnt++ + } + } + return cnt +} + +// Get number of fractional matched messages on the list. +func CountFractionalMatchedMsgs(swapMsgStates []*SwapMsgState) int { + cnt := 0 + for _, m := range swapMsgStates { + if m.Executed && m.Succeeded && !m.ToBeDeleted { + cnt++ + } + } + return cnt +} + +// Order map type indexed by order price at price +type OrderMap map[string]Order + +// Make orderbook by sort orderMap. +func (orderMap OrderMap) SortOrderBook() (orderBook OrderBook) { + for _, o := range orderMap { + orderBook = append(orderBook, o) + } + orderBook.Sort() + return orderBook +} + +// struct of swap matching result of the batch +type BatchResult struct { + MatchType MatchType + PriceDirection PriceDirection + SwapPrice sdk.Dec + EX sdk.Dec + EY sdk.Dec + OriginalEX sdk.Int + OriginalEY sdk.Int + PoolX sdk.Dec + PoolY sdk.Dec + TransactAmt sdk.Dec +} + +// return of zero object, to avoid nil +func NewBatchResult() BatchResult { + return BatchResult{ + SwapPrice: sdk.ZeroDec(), + EX: sdk.ZeroDec(), + EY: sdk.ZeroDec(), + OriginalEX: sdk.ZeroInt(), + OriginalEY: sdk.ZeroInt(), + PoolX: sdk.ZeroDec(), + PoolY: sdk.ZeroDec(), + TransactAmt: sdk.ZeroDec(), + } +} + +// struct of swap matching result of each Batch swap message +type MatchResult struct { + OrderDirection OrderDirection + OrderMsgIndex uint64 + OrderPrice sdk.Dec + OfferCoinAmt sdk.Dec + TransactedCoinAmt sdk.Dec + ExchangedDemandCoinAmt sdk.Dec + OfferCoinFeeAmt sdk.Dec + ExchangedCoinFeeAmt sdk.Dec + SwapMsgState *SwapMsgState +} + +// The price and coins of swap messages in orderbook are calculated +// to derive match result with the price direction. +func (orderBook OrderBook) Match(x, y sdk.Dec) (BatchResult, bool) { + currentPrice := x.Quo(y) + priceDirection := orderBook.PriceDirection(currentPrice) + if priceDirection == Staying { + return orderBook.CalculateMatchStay(currentPrice), true + } + return orderBook.CalculateMatch(priceDirection, x, y) +} + +// Check orderbook validity naively +func (orderBook OrderBook) Validate(currentPrice sdk.Dec) bool { + if !currentPrice.IsPositive() { + return false + } + maxBuyOrderPrice := sdk.ZeroDec() + minSellOrderPrice := sdk.NewDec(1000000000000) + for _, order := range orderBook { + if order.BuyOfferAmt.IsPositive() && order.Price.GT(maxBuyOrderPrice) { + maxBuyOrderPrice = order.Price + } + if order.SellOfferAmt.IsPositive() && (order.Price.LT(minSellOrderPrice)) { + minSellOrderPrice = order.Price + } + } + if maxBuyOrderPrice.GT(minSellOrderPrice) || + maxBuyOrderPrice.Quo(currentPrice).GT(sdk.MustNewDecFromStr("1.10")) || + minSellOrderPrice.Quo(currentPrice).LT(sdk.MustNewDecFromStr("0.90")) { + return false + } + return true +} + +// Calculate results for orderbook matching with unchanged price case +func (orderBook OrderBook) CalculateMatchStay(currentPrice sdk.Dec) (r BatchResult) { + r = NewBatchResult() + r.SwapPrice = currentPrice + r.OriginalEX, r.OriginalEY = orderBook.ExecutableAmt(r.SwapPrice) + r.EX = r.OriginalEX.ToLegacyDec() + r.EY = r.OriginalEY.ToLegacyDec() + r.PriceDirection = Staying + + s := r.SwapPrice.Mul(r.EY) + if r.EX.IsZero() || r.EY.IsZero() { + r.MatchType = NoMatch + } else if r.EX.Equal(s) { // Normalization to an integrator for easy determination of exactMatch + r.MatchType = ExactMatch + } else { + // Decimal Error, When calculating the Executable value, conservatively Truncated decimal + r.MatchType = FractionalMatch + if r.EX.GT(s) { + r.EX = s + } else if r.EX.LT(s) { + r.EY = r.EX.Quo(r.SwapPrice) + } + } + return +} + +// Calculates the batch results with the logic for each direction +func (orderBook OrderBook) CalculateMatch(direction PriceDirection, x, y sdk.Dec) (maxScenario BatchResult, found bool) { + currentPrice := x.Quo(y) + lastOrderPrice := currentPrice + var matchScenarios []BatchResult + start, end, delta := 0, len(orderBook)-1, 1 + if direction == Decreasing { + start, end, delta = end, start, -1 + } + for i := start; i != end+delta; i += delta { + order := orderBook[i] + if (direction == Increasing && order.Price.LT(currentPrice)) || + (direction == Decreasing && order.Price.GT(currentPrice)) { + continue + } else { + orderPrice := order.Price + r := orderBook.CalculateSwap(direction, x, y, orderPrice, lastOrderPrice) + // Check to see if it exceeds a value that can be a decimal error + if (direction == Increasing && r.PoolY.Sub(r.EX.Quo(r.SwapPrice)).GTE(sdk.OneDec())) || + (direction == Decreasing && r.PoolX.Sub(r.EY.Mul(r.SwapPrice)).GTE(sdk.OneDec())) { + continue + } + matchScenarios = append(matchScenarios, r) + lastOrderPrice = orderPrice + } + } + maxScenario = NewBatchResult() + for _, s := range matchScenarios { + MEX, MEY := orderBook.MustExecutableAmt(s.SwapPrice) + if s.EX.GTE(MEX.ToLegacyDec()) && s.EY.GTE(MEY.ToLegacyDec()) { + if s.MatchType == ExactMatch && s.TransactAmt.IsPositive() { + maxScenario = s + found = true + break + } else if s.TransactAmt.GT(maxScenario.TransactAmt) { + maxScenario = s + found = true + } + } + } + maxScenario.PriceDirection = direction + return maxScenario, found +} + +// CalculateSwap calculates the batch result. +func (orderBook OrderBook) CalculateSwap(direction PriceDirection, x, y, orderPrice, lastOrderPrice sdk.Dec) BatchResult { + r := NewBatchResult() + r.OriginalEX, r.OriginalEY = orderBook.ExecutableAmt(lastOrderPrice.Add(orderPrice).Quo(sdk.NewDec(2))) + r.EX = r.OriginalEX.ToLegacyDec() + r.EY = r.OriginalEY.ToLegacyDec() + + r.SwapPrice = x.Add(r.EX.MulInt64(2)).Quo(y.Add(r.EY.MulInt64(2))) // P_s = (X + 2EX) / (Y + 2EY) + + if direction == Increasing { + r.PoolY = r.SwapPrice.Mul(y).Sub(x).Quo(r.SwapPrice.MulInt64(2)) // (P_s * Y - X / 2P_s) + if lastOrderPrice.LT(r.SwapPrice) && r.SwapPrice.LT(orderPrice) && !r.PoolY.IsNegative() { + if r.EX.IsZero() && r.EY.IsZero() { + r.MatchType = NoMatch + } else { + r.MatchType = ExactMatch + } + } + } else if direction == Decreasing { + r.PoolX = x.Sub(r.SwapPrice.Mul(y)).QuoInt64(2) // (X - P_s * Y) / 2 + if orderPrice.LT(r.SwapPrice) && r.SwapPrice.LT(lastOrderPrice) && !r.PoolX.IsNegative() { + if r.EX.IsZero() && r.EY.IsZero() { + r.MatchType = NoMatch + } else { + r.MatchType = ExactMatch + } + } + } + + if r.MatchType == 0 { + r.OriginalEX, r.OriginalEY = orderBook.ExecutableAmt(orderPrice) + r.EX = r.OriginalEX.ToLegacyDec() + r.EY = r.OriginalEY.ToLegacyDec() + r.SwapPrice = orderPrice + // When calculating the Pool value, conservatively Truncated decimal, so Ceil it to reduce the decimal error + if direction == Increasing { + r.PoolY = r.SwapPrice.Mul(y).Sub(x).Quo(r.SwapPrice.MulInt64(2)) // (P_s * Y - X) / 2P_s + r.EX = sdk.MinDec(r.EX, r.EY.Add(r.PoolY).Mul(r.SwapPrice)).Ceil() + r.EY = sdk.MaxDec(sdk.MinDec(r.EY, r.EX.Quo(r.SwapPrice).Sub(r.PoolY)), sdk.ZeroDec()).Ceil() + } else if direction == Decreasing { + r.PoolX = x.Sub(r.SwapPrice.Mul(y)).QuoInt64(2) // (X - P_s * Y) / 2 + r.EY = sdk.MinDec(r.EY, r.EX.Add(r.PoolX).Quo(r.SwapPrice)).Ceil() + r.EX = sdk.MaxDec(sdk.MinDec(r.EX, r.EY.Mul(r.SwapPrice).Sub(r.PoolX)), sdk.ZeroDec()).Ceil() + } + r.MatchType = FractionalMatch + } + + if direction == Increasing { + if r.SwapPrice.LT(x.Quo(y)) || r.PoolY.IsNegative() { + r.TransactAmt = sdk.ZeroDec() + } else { + r.TransactAmt = sdk.MinDec(r.EX, r.EY.Add(r.PoolY).Mul(r.SwapPrice)) + } + } else if direction == Decreasing { + if r.SwapPrice.GT(x.Quo(y)) || r.PoolX.IsNegative() { + r.TransactAmt = sdk.ZeroDec() + } else { + r.TransactAmt = sdk.MinDec(r.EY, r.EX.Add(r.PoolX).Quo(r.SwapPrice)) + } + } + return r +} + +// Get Price direction of the orderbook with current Price +func (orderBook OrderBook) PriceDirection(currentPrice sdk.Dec) PriceDirection { + buyAmtOverCurrentPrice := sdk.ZeroDec() + buyAmtAtCurrentPrice := sdk.ZeroDec() + sellAmtUnderCurrentPrice := sdk.ZeroDec() + sellAmtAtCurrentPrice := sdk.ZeroDec() + + for _, order := range orderBook { + if order.Price.GT(currentPrice) { + buyAmtOverCurrentPrice = buyAmtOverCurrentPrice.Add(order.BuyOfferAmt.ToLegacyDec()) + } else if order.Price.Equal(currentPrice) { + buyAmtAtCurrentPrice = buyAmtAtCurrentPrice.Add(order.BuyOfferAmt.ToLegacyDec()) + sellAmtAtCurrentPrice = sellAmtAtCurrentPrice.Add(order.SellOfferAmt.ToLegacyDec()) + } else if order.Price.LT(currentPrice) { + sellAmtUnderCurrentPrice = sellAmtUnderCurrentPrice.Add(order.SellOfferAmt.ToLegacyDec()) + } + } + if buyAmtOverCurrentPrice.GT(currentPrice.Mul(sellAmtUnderCurrentPrice.Add(sellAmtAtCurrentPrice))) { + return Increasing + } else if currentPrice.Mul(sellAmtUnderCurrentPrice).GT(buyAmtOverCurrentPrice.Add(buyAmtAtCurrentPrice)) { + return Decreasing + } + return Staying +} + +// calculate the executable amount of the orderbook for each X, Y +func (orderBook OrderBook) ExecutableAmt(swapPrice sdk.Dec) (executableBuyAmtX, executableSellAmtY sdk.Int) { + executableBuyAmtX = sdk.ZeroInt() + executableSellAmtY = sdk.ZeroInt() + for _, order := range orderBook { + if order.Price.GTE(swapPrice) { + executableBuyAmtX = executableBuyAmtX.Add(order.BuyOfferAmt) + } + if order.Price.LTE(swapPrice) { + executableSellAmtY = executableSellAmtY.Add(order.SellOfferAmt) + } + } + return +} + +// Check swap executable amount validity of the orderbook +func (orderBook OrderBook) MustExecutableAmt(swapPrice sdk.Dec) (mustExecutableBuyAmtX, mustExecutableSellAmtY sdk.Int) { + mustExecutableBuyAmtX = sdk.ZeroInt() + mustExecutableSellAmtY = sdk.ZeroInt() + for _, order := range orderBook { + if order.Price.GT(swapPrice) { + mustExecutableBuyAmtX = mustExecutableBuyAmtX.Add(order.BuyOfferAmt) + } + if order.Price.LT(swapPrice) { + mustExecutableSellAmtY = mustExecutableSellAmtY.Add(order.SellOfferAmt) + } + } + return +} + +// make orderMap key as swap price, value as Buy, Sell Amount from swap msgs, with split as Buy xToY, Sell yToX msg list. +func MakeOrderMap(swapMsgs []*SwapMsgState, denomX, denomY string, onlyNotMatched bool) (OrderMap, []*SwapMsgState, []*SwapMsgState) { + orderMap := make(OrderMap) + var xToY []*SwapMsgState // buying Y from X + var yToX []*SwapMsgState // selling Y for X + for _, m := range swapMsgs { + if onlyNotMatched && (m.ToBeDeleted || m.RemainingOfferCoin.IsZero()) { + continue + } + order := Order{ + Price: m.Msg.OrderPrice, + BuyOfferAmt: sdk.ZeroInt(), + SellOfferAmt: sdk.ZeroInt(), + } + orderPriceString := m.Msg.OrderPrice.String() + switch { + // buying Y from X + case m.Msg.OfferCoin.Denom == denomX: + xToY = append(xToY, m) + if o, ok := orderMap[orderPriceString]; ok { + order = o + order.BuyOfferAmt = o.BuyOfferAmt.Add(m.RemainingOfferCoin.Amount) + } else { + order.BuyOfferAmt = m.RemainingOfferCoin.Amount + } + // selling Y for X + case m.Msg.OfferCoin.Denom == denomY: + yToX = append(yToX, m) + if o, ok := orderMap[orderPriceString]; ok { + order = o + order.SellOfferAmt = o.SellOfferAmt.Add(m.RemainingOfferCoin.Amount) + } else { + order.SellOfferAmt = m.RemainingOfferCoin.Amount + } + default: + panic(ErrInvalidDenom) + } + order.SwapMsgStates = append(order.SwapMsgStates, m) + orderMap[orderPriceString] = order + } + return orderMap, xToY, yToX +} + +// check validity state of the batch swap messages, and set to delete state to height timeout expired order +func ValidateStateAndExpireOrders(swapMsgStates []*SwapMsgState, currentHeight int64, expireThisHeight bool) { + for _, order := range swapMsgStates { + if !order.Executed { + panic("not executed") + } + if order.RemainingOfferCoin.IsZero() { + if !order.Succeeded || !order.ToBeDeleted { + panic("broken state consistency for not matched order") + } + continue + } + // set toDelete, expired msgs + if currentHeight > order.OrderExpiryHeight { + if order.Succeeded || !order.ToBeDeleted { + panic("broken state consistency for fractional matched order") + } + continue + } + if expireThisHeight && currentHeight == order.OrderExpiryHeight { + order.ToBeDeleted = true + } + } +} + +// Check swap price validity using list of match result. +func CheckSwapPrice(matchResultXtoY, matchResultYtoX []MatchResult, swapPrice sdk.Dec) bool { + if len(matchResultXtoY) == 0 && len(matchResultYtoX) == 0 { + return true + } + // Check if it is greater than a value that can be a decimal error + for _, m := range matchResultXtoY { + if m.TransactedCoinAmt.Quo(swapPrice).Sub(m.ExchangedDemandCoinAmt).Abs().GT(sdk.OneDec()) { + return false + } + } + for _, m := range matchResultYtoX { + if m.TransactedCoinAmt.Mul(swapPrice).Sub(m.ExchangedDemandCoinAmt).Abs().GT(sdk.OneDec()) { + return false + } + } + return !swapPrice.IsZero() +} + +// Find matched orders and set status for msgs +func FindOrderMatch(direction OrderDirection, swapMsgStates []*SwapMsgState, executableAmt, swapPrice sdk.Dec, height int64) ( + matchResults []MatchResult, poolXDelta, poolYDelta sdk.Dec, +) { + poolXDelta = sdk.ZeroDec() + poolYDelta = sdk.ZeroDec() + + if executableAmt.IsZero() { + return + } + + if direction == DirectionXtoY { + sort.SliceStable(swapMsgStates, func(i, j int) bool { + return swapMsgStates[i].Msg.OrderPrice.GT(swapMsgStates[j].Msg.OrderPrice) + }) + } else if direction == DirectionYtoX { + sort.SliceStable(swapMsgStates, func(i, j int) bool { + return swapMsgStates[i].Msg.OrderPrice.LT(swapMsgStates[j].Msg.OrderPrice) + }) + } + + matchAmt := sdk.ZeroInt() + accumMatchAmt := sdk.ZeroInt() + var matchedSwapMsgStates []*SwapMsgState //nolint:prealloc + + for i, order := range swapMsgStates { + // include the matched order in matchAmt, matchedSwapMsgStates + if (direction == DirectionXtoY && order.Msg.OrderPrice.LT(swapPrice)) || + (direction == DirectionYtoX && order.Msg.OrderPrice.GT(swapPrice)) { + break + } + + matchAmt = matchAmt.Add(order.RemainingOfferCoin.Amount) + matchedSwapMsgStates = append(matchedSwapMsgStates, order) + + if i == len(swapMsgStates)-1 || !swapMsgStates[i+1].Msg.OrderPrice.Equal(order.Msg.OrderPrice) { + if matchAmt.IsPositive() { + var fractionalMatchRatio sdk.Dec + if accumMatchAmt.Add(matchAmt).ToLegacyDec().GTE(executableAmt) { + fractionalMatchRatio = executableAmt.Sub(accumMatchAmt.ToLegacyDec()).Quo(matchAmt.ToLegacyDec()) + if fractionalMatchRatio.GT(sdk.NewDec(1)) { + panic("fractionalMatchRatio should be between 0 and 1") + } + } else { + fractionalMatchRatio = sdk.OneDec() + } + if !fractionalMatchRatio.IsPositive() { + fractionalMatchRatio = sdk.OneDec() + } + for _, matchOrder := range matchedSwapMsgStates { + offerAmt := matchOrder.RemainingOfferCoin.Amount.ToLegacyDec() + matchResult := MatchResult{ + OrderDirection: direction, + OfferCoinAmt: offerAmt, + // TransactedCoinAmt is a value that should not be lost, so Ceil it conservatively considering the decimal error. + TransactedCoinAmt: offerAmt.Mul(fractionalMatchRatio).Ceil(), + SwapMsgState: matchOrder, + } + if matchResult.OfferCoinAmt.Sub(matchResult.TransactedCoinAmt).LTE(sdk.OneDec()) { + // Use ReservedOfferCoinFee to avoid decimal errors when OfferCoinAmt and TransactedCoinAmt are almost equal in value. + matchResult.OfferCoinFeeAmt = matchResult.SwapMsgState.ReservedOfferCoinFee.Amount.ToLegacyDec() + } else { + matchResult.OfferCoinFeeAmt = matchResult.SwapMsgState.ReservedOfferCoinFee.Amount.ToLegacyDec().Mul(fractionalMatchRatio) + } + if direction == DirectionXtoY { + matchResult.ExchangedDemandCoinAmt = matchResult.TransactedCoinAmt.Quo(swapPrice) + matchResult.ExchangedCoinFeeAmt = matchResult.OfferCoinFeeAmt.Quo(swapPrice) + } else if direction == DirectionYtoX { + matchResult.ExchangedDemandCoinAmt = matchResult.TransactedCoinAmt.Mul(swapPrice) + matchResult.ExchangedCoinFeeAmt = matchResult.OfferCoinFeeAmt.Mul(swapPrice) + } + // Check for differences above maximum decimal error + if matchResult.TransactedCoinAmt.GT(matchResult.OfferCoinAmt) { + panic("bad TransactedCoinAmt") + } + if matchResult.OfferCoinFeeAmt.GT(matchResult.OfferCoinAmt) && matchResult.OfferCoinFeeAmt.GT(sdk.OneDec()) { + panic("bad OfferCoinFeeAmt") + } + matchResults = append(matchResults, matchResult) + if direction == DirectionXtoY { + poolXDelta = poolXDelta.Add(matchResult.TransactedCoinAmt) + poolYDelta = poolYDelta.Sub(matchResult.ExchangedDemandCoinAmt) + } else if direction == DirectionYtoX { + poolXDelta = poolXDelta.Sub(matchResult.ExchangedDemandCoinAmt) + poolYDelta = poolYDelta.Add(matchResult.TransactedCoinAmt) + } + } + accumMatchAmt = accumMatchAmt.Add(matchAmt) + } + + matchAmt = sdk.ZeroInt() + matchedSwapMsgStates = matchedSwapMsgStates[:0] + } + } + return matchResults, poolXDelta, poolYDelta +} + +// UpdateSwapMsgStates updates SwapMsgStates using the MatchResults. +func UpdateSwapMsgStates(x, y sdk.Dec, xToY, yToX []*SwapMsgState, matchResultXtoY, matchResultYtoX []MatchResult) ( + []*SwapMsgState, []*SwapMsgState, sdk.Dec, sdk.Dec, sdk.Dec, sdk.Dec, +) { + sort.SliceStable(xToY, func(i, j int) bool { + return xToY[i].Msg.OrderPrice.GT(xToY[j].Msg.OrderPrice) + }) + sort.SliceStable(yToX, func(i, j int) bool { + return yToX[i].Msg.OrderPrice.LT(yToX[j].Msg.OrderPrice) + }) + + poolXDelta := sdk.ZeroDec() + poolYDelta := sdk.ZeroDec() + + // Variables to accumulate and offset the values of int 1 caused by decimal error + decimalErrorX := sdk.ZeroDec() + decimalErrorY := sdk.ZeroDec() + + for _, match := range append(matchResultXtoY, matchResultYtoX...) { + sms := match.SwapMsgState + if match.OrderDirection == DirectionXtoY { + poolXDelta = poolXDelta.Add(match.TransactedCoinAmt) + poolYDelta = poolYDelta.Sub(match.ExchangedDemandCoinAmt) + } else { + poolXDelta = poolXDelta.Sub(match.ExchangedDemandCoinAmt) + poolYDelta = poolYDelta.Add(match.TransactedCoinAmt) + } + if sms.RemainingOfferCoin.Amount.ToLegacyDec().Sub(match.TransactedCoinAmt).LTE(sdk.OneDec()) { + // when RemainingOfferCoin and TransactedCoinAmt are almost equal in value, corrects the decimal error and processes as a exact match. + sms.ExchangedOfferCoin.Amount = sms.ExchangedOfferCoin.Amount.Add(match.TransactedCoinAmt.TruncateInt()) + sms.RemainingOfferCoin.Amount = sms.RemainingOfferCoin.Amount.Sub(match.TransactedCoinAmt.TruncateInt()) + sms.ReservedOfferCoinFee.Amount = sms.ReservedOfferCoinFee.Amount.Sub(match.OfferCoinFeeAmt.TruncateInt()) + if sms.ExchangedOfferCoin.IsNegative() || sms.RemainingOfferCoin.IsNegative() || sms.ReservedOfferCoinFee.IsNegative() { + panic("negative coin amount after update") + } + if sms.RemainingOfferCoin.Amount.Equal(sdk.OneInt()) { + decimalErrorY = decimalErrorY.Add(sdk.OneDec()) + sms.RemainingOfferCoin.Amount = sdk.ZeroInt() + } + if !sms.RemainingOfferCoin.IsZero() || sms.ExchangedOfferCoin.Amount.GT(sms.Msg.OfferCoin.Amount) || + sms.ReservedOfferCoinFee.Amount.GT(sdk.OneInt()) { + panic("invalid state after update") + } else { + sms.Succeeded = true + sms.ToBeDeleted = true + } + } else { + // fractional match + sms.ExchangedOfferCoin.Amount = sms.ExchangedOfferCoin.Amount.Add(match.TransactedCoinAmt.TruncateInt()) + sms.RemainingOfferCoin.Amount = sms.RemainingOfferCoin.Amount.Sub(match.TransactedCoinAmt.TruncateInt()) + sms.ReservedOfferCoinFee.Amount = sms.ReservedOfferCoinFee.Amount.Sub(match.OfferCoinFeeAmt.TruncateInt()) + if sms.ExchangedOfferCoin.IsNegative() || sms.RemainingOfferCoin.IsNegative() || sms.ReservedOfferCoinFee.IsNegative() { + panic("negative coin amount after update") + } + sms.Succeeded = true + sms.ToBeDeleted = false + } + } + + // Offset accumulated decimal error values + poolXDelta = poolXDelta.Add(decimalErrorX) + poolYDelta = poolYDelta.Add(decimalErrorY) + + x = x.Add(poolXDelta) + y = y.Add(poolYDelta) + + return xToY, yToX, x, y, poolXDelta, poolYDelta +} diff --git a/x/liquidity/types/tx.pb.go b/x/liquidity/types/tx.pb.go new file mode 100644 index 00000000..76e6d4c6 --- /dev/null +++ b/x/liquidity/types/tx.pb.go @@ -0,0 +1,2116 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cyber/liquidity/v1beta1/tx.proto + +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 "github.com/cosmos/cosmos-sdk/types" + types "github.com/cosmos/cosmos-sdk/types" + _ "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" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = proto.Marshal + _ = fmt.Errorf + _ = 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 + +// MsgCreatePool defines an sdk.Msg type that supports submitting a create +// liquidity pool tx. +// +// See: +// https://github.com/gravity-devs/liquidity/blob/develop/x/liquidity/spec/04_messages.md +type MsgCreatePool struct { + PoolCreatorAddress string `protobuf:"bytes,1,opt,name=pool_creator_address,json=poolCreatorAddress,proto3" json:"pool_creator_address,omitempty" yaml:"pool_creator_address"` + // id of the target pool type, must match the value in the pool. Only + // pool-type-id 1 is supported. + PoolTypeId uint32 `protobuf:"varint,2,opt,name=pool_type_id,json=poolTypeId,proto3" json:"pool_type_id,omitempty" yaml:"pool_type_id"` + // reserve coin pair of the pool to deposit. + DepositCoins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,4,rep,name=deposit_coins,json=depositCoins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"deposit_coins" yaml:"deposit_coins"` +} + +func (m *MsgCreatePool) Reset() { *m = MsgCreatePool{} } +func (m *MsgCreatePool) String() string { return proto.CompactTextString(m) } +func (*MsgCreatePool) ProtoMessage() {} +func (*MsgCreatePool) Descriptor() ([]byte, []int) { + return fileDescriptor_d6c6519f5f802cc0, []int{0} +} + +func (m *MsgCreatePool) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *MsgCreatePool) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgCreatePool.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 *MsgCreatePool) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgCreatePool.Merge(m, src) +} + +func (m *MsgCreatePool) XXX_Size() int { + return m.Size() +} + +func (m *MsgCreatePool) XXX_DiscardUnknown() { + xxx_messageInfo_MsgCreatePool.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgCreatePool proto.InternalMessageInfo + +// MsgCreatePoolResponse defines the Msg/CreatePool response type. +type MsgCreatePoolResponse struct{} + +func (m *MsgCreatePoolResponse) Reset() { *m = MsgCreatePoolResponse{} } +func (m *MsgCreatePoolResponse) String() string { return proto.CompactTextString(m) } +func (*MsgCreatePoolResponse) ProtoMessage() {} +func (*MsgCreatePoolResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_d6c6519f5f802cc0, []int{1} +} + +func (m *MsgCreatePoolResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *MsgCreatePoolResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgCreatePoolResponse.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 *MsgCreatePoolResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgCreatePoolResponse.Merge(m, src) +} + +func (m *MsgCreatePoolResponse) XXX_Size() int { + return m.Size() +} + +func (m *MsgCreatePoolResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgCreatePoolResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgCreatePoolResponse proto.InternalMessageInfo + +// `MsgDepositWithinBatch defines` an `sdk.Msg` type that supports submitting +// a deposit request to the batch of the liquidity pool. +// Deposit is submitted to the batch of the Liquidity pool with the specified +// `pool_id`, `deposit_coins` for reserve. +// This request is stacked in the batch of the liquidity pool, is not processed +// immediately, and is processed in the `endblock` at the same time as other +// requests. +// +// See: +// https://github.com/gravity-devs/liquidity/blob/develop/x/liquidity/spec/04_messages.md +type MsgDepositWithinBatch struct { + DepositorAddress string `protobuf:"bytes,1,opt,name=depositor_address,json=depositorAddress,proto3" json:"depositor_address,omitempty" yaml:"depositor_address"` + // id of the target pool + PoolId uint64 `protobuf:"varint,2,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty" yaml:"pool_id"` + // reserve coin pair of the pool to deposit + DepositCoins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,3,rep,name=deposit_coins,json=depositCoins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"deposit_coins" yaml:"deposit_coins"` +} + +func (m *MsgDepositWithinBatch) Reset() { *m = MsgDepositWithinBatch{} } +func (m *MsgDepositWithinBatch) String() string { return proto.CompactTextString(m) } +func (*MsgDepositWithinBatch) ProtoMessage() {} +func (*MsgDepositWithinBatch) Descriptor() ([]byte, []int) { + return fileDescriptor_d6c6519f5f802cc0, []int{2} +} + +func (m *MsgDepositWithinBatch) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *MsgDepositWithinBatch) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgDepositWithinBatch.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 *MsgDepositWithinBatch) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgDepositWithinBatch.Merge(m, src) +} + +func (m *MsgDepositWithinBatch) XXX_Size() int { + return m.Size() +} + +func (m *MsgDepositWithinBatch) XXX_DiscardUnknown() { + xxx_messageInfo_MsgDepositWithinBatch.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgDepositWithinBatch proto.InternalMessageInfo + +// MsgDepositWithinBatchResponse defines the Msg/DepositWithinBatch response +// type. +type MsgDepositWithinBatchResponse struct{} + +func (m *MsgDepositWithinBatchResponse) Reset() { *m = MsgDepositWithinBatchResponse{} } +func (m *MsgDepositWithinBatchResponse) String() string { return proto.CompactTextString(m) } +func (*MsgDepositWithinBatchResponse) ProtoMessage() {} +func (*MsgDepositWithinBatchResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_d6c6519f5f802cc0, []int{3} +} + +func (m *MsgDepositWithinBatchResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *MsgDepositWithinBatchResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgDepositWithinBatchResponse.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 *MsgDepositWithinBatchResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgDepositWithinBatchResponse.Merge(m, src) +} + +func (m *MsgDepositWithinBatchResponse) XXX_Size() int { + return m.Size() +} + +func (m *MsgDepositWithinBatchResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgDepositWithinBatchResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgDepositWithinBatchResponse proto.InternalMessageInfo + +// `MsgWithdrawWithinBatch` defines an `sdk.Msg` type that supports submitting +// a withdraw request to the batch of the liquidity pool. +// Withdraw is submitted to the batch from the Liquidity pool with the +// specified `pool_id`, `pool_coin` of the pool. +// This request is stacked in the batch of the liquidity pool, is not processed +// immediately, and is processed in the `endblock` at the same time as other +// requests. +// +// See: +// https://github.com/gravity-devs/liquidity/blob/develop/x/liquidity/spec/04_messages.md +type MsgWithdrawWithinBatch struct { + WithdrawerAddress string `protobuf:"bytes,1,opt,name=withdrawer_address,json=withdrawerAddress,proto3" json:"withdrawer_address,omitempty" yaml:"withdrawer_address"` + // id of the target pool + PoolId uint64 `protobuf:"varint,2,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty" yaml:"pool_id"` + PoolCoin types.Coin `protobuf:"bytes,3,opt,name=pool_coin,json=poolCoin,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coin" json:"pool_coin" yaml:"pool_coin"` +} + +func (m *MsgWithdrawWithinBatch) Reset() { *m = MsgWithdrawWithinBatch{} } +func (m *MsgWithdrawWithinBatch) String() string { return proto.CompactTextString(m) } +func (*MsgWithdrawWithinBatch) ProtoMessage() {} +func (*MsgWithdrawWithinBatch) Descriptor() ([]byte, []int) { + return fileDescriptor_d6c6519f5f802cc0, []int{4} +} + +func (m *MsgWithdrawWithinBatch) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *MsgWithdrawWithinBatch) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgWithdrawWithinBatch.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 *MsgWithdrawWithinBatch) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgWithdrawWithinBatch.Merge(m, src) +} + +func (m *MsgWithdrawWithinBatch) XXX_Size() int { + return m.Size() +} + +func (m *MsgWithdrawWithinBatch) XXX_DiscardUnknown() { + xxx_messageInfo_MsgWithdrawWithinBatch.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgWithdrawWithinBatch proto.InternalMessageInfo + +// MsgWithdrawWithinBatchResponse defines the Msg/WithdrawWithinBatch response +// type. +type MsgWithdrawWithinBatchResponse struct{} + +func (m *MsgWithdrawWithinBatchResponse) Reset() { *m = MsgWithdrawWithinBatchResponse{} } +func (m *MsgWithdrawWithinBatchResponse) String() string { return proto.CompactTextString(m) } +func (*MsgWithdrawWithinBatchResponse) ProtoMessage() {} +func (*MsgWithdrawWithinBatchResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_d6c6519f5f802cc0, []int{5} +} + +func (m *MsgWithdrawWithinBatchResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *MsgWithdrawWithinBatchResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgWithdrawWithinBatchResponse.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 *MsgWithdrawWithinBatchResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgWithdrawWithinBatchResponse.Merge(m, src) +} + +func (m *MsgWithdrawWithinBatchResponse) XXX_Size() int { + return m.Size() +} + +func (m *MsgWithdrawWithinBatchResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgWithdrawWithinBatchResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgWithdrawWithinBatchResponse proto.InternalMessageInfo + +// `MsgSwapWithinBatch` defines an sdk.Msg type that supports submitting a swap +// offer request to the batch of the liquidity pool. Submit swap offer to the +// liquidity pool batch with the specified the `pool_id`, `swap_type_id`, +// `demand_coin_denom` with the coin and the price you're offering +// and `offer_coin_fee` must be half of offer coin amount * current +// `params.swap_fee_rate` and ceil for reservation to pay fees. This request is +// stacked in the batch of the liquidity pool, is not processed immediately, and +// is processed in the `endblock` at the same time as other requests. You must +// request the same fields as the pool. Only the default `swap_type_id` 1 is +// supported. +// +// See: https://github.com/gravity-devs/liquidity/tree/develop/doc +// https://github.com/gravity-devs/liquidity/blob/develop/x/liquidity/spec/04_messages.md +type MsgSwapWithinBatch struct { + // address of swap requester + SwapRequesterAddress string `protobuf:"bytes,1,opt,name=swap_requester_address,json=swapRequesterAddress,proto3" json:"swap_requester_address,omitempty" yaml:"swap_requester_address"` + // id of swap type, must match the value in the pool. Only `swap_type_id` 1 is + // supported. + PoolId uint64 `protobuf:"varint,2,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty" yaml:"pool_id"` + // id of swap type. Must match the value in the pool. + SwapTypeId uint32 `protobuf:"varint,3,opt,name=swap_type_id,json=swapTypeId,proto3" json:"swap_type_id,omitempty" yaml:"swap_type_id"` + // offer sdk.coin for the swap request, must match the denom in the pool. + OfferCoin types.Coin `protobuf:"bytes,4,opt,name=offer_coin,json=offerCoin,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coin" json:"offer_coin" yaml:"offer_coin"` + // denom of demand coin to be exchanged on the swap request, must match the + // denom in the pool. + DemandCoinDenom string `protobuf:"bytes,5,opt,name=demand_coin_denom,json=demandCoinDenom,proto3" json:"demand_coin_denom,omitempty" yaml:"demand_coin_denom"` + // half of offer coin amount * params.swap_fee_rate and ceil for reservation + // to pay fees. + OfferCoinFee types.Coin `protobuf:"bytes,6,opt,name=offer_coin_fee,json=offerCoinFee,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coin" json:"offer_coin_fee" yaml:"offer_coin_fee"` + // limit order price for the order, the price is the exchange ratio of X/Y + // where X is the amount of the first coin and Y is the amount + // of the second coin when their denoms are sorted alphabetically. + OrderPrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,7,opt,name=order_price,json=orderPrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"order_price" yaml:"order_price"` +} + +func (m *MsgSwapWithinBatch) Reset() { *m = MsgSwapWithinBatch{} } +func (m *MsgSwapWithinBatch) String() string { return proto.CompactTextString(m) } +func (*MsgSwapWithinBatch) ProtoMessage() {} +func (*MsgSwapWithinBatch) Descriptor() ([]byte, []int) { + return fileDescriptor_d6c6519f5f802cc0, []int{6} +} + +func (m *MsgSwapWithinBatch) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *MsgSwapWithinBatch) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgSwapWithinBatch.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 *MsgSwapWithinBatch) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgSwapWithinBatch.Merge(m, src) +} + +func (m *MsgSwapWithinBatch) XXX_Size() int { + return m.Size() +} + +func (m *MsgSwapWithinBatch) XXX_DiscardUnknown() { + xxx_messageInfo_MsgSwapWithinBatch.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgSwapWithinBatch proto.InternalMessageInfo + +// MsgSwapWithinBatchResponse defines the Msg/Swap response type. +type MsgSwapWithinBatchResponse struct{} + +func (m *MsgSwapWithinBatchResponse) Reset() { *m = MsgSwapWithinBatchResponse{} } +func (m *MsgSwapWithinBatchResponse) String() string { return proto.CompactTextString(m) } +func (*MsgSwapWithinBatchResponse) ProtoMessage() {} +func (*MsgSwapWithinBatchResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_d6c6519f5f802cc0, []int{7} +} + +func (m *MsgSwapWithinBatchResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *MsgSwapWithinBatchResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgSwapWithinBatchResponse.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 *MsgSwapWithinBatchResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgSwapWithinBatchResponse.Merge(m, src) +} + +func (m *MsgSwapWithinBatchResponse) XXX_Size() int { + return m.Size() +} + +func (m *MsgSwapWithinBatchResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgSwapWithinBatchResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgSwapWithinBatchResponse proto.InternalMessageInfo + +func init() { + proto.RegisterType((*MsgCreatePool)(nil), "cyber.liquidity.v1beta1.MsgCreatePool") + proto.RegisterType((*MsgCreatePoolResponse)(nil), "cyber.liquidity.v1beta1.MsgCreatePoolResponse") + proto.RegisterType((*MsgDepositWithinBatch)(nil), "cyber.liquidity.v1beta1.MsgDepositWithinBatch") + proto.RegisterType((*MsgDepositWithinBatchResponse)(nil), "cyber.liquidity.v1beta1.MsgDepositWithinBatchResponse") + proto.RegisterType((*MsgWithdrawWithinBatch)(nil), "cyber.liquidity.v1beta1.MsgWithdrawWithinBatch") + proto.RegisterType((*MsgWithdrawWithinBatchResponse)(nil), "cyber.liquidity.v1beta1.MsgWithdrawWithinBatchResponse") + proto.RegisterType((*MsgSwapWithinBatch)(nil), "cyber.liquidity.v1beta1.MsgSwapWithinBatch") + proto.RegisterType((*MsgSwapWithinBatchResponse)(nil), "cyber.liquidity.v1beta1.MsgSwapWithinBatchResponse") +} + +func init() { proto.RegisterFile("cyber/liquidity/v1beta1/tx.proto", fileDescriptor_d6c6519f5f802cc0) } + +var fileDescriptor_d6c6519f5f802cc0 = []byte{ + // 864 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x96, 0xbf, 0x6f, 0xdb, 0x46, + 0x14, 0xc7, 0x45, 0xcb, 0x71, 0xe2, 0x8b, 0x9d, 0xc6, 0x17, 0x25, 0xa6, 0xd5, 0x84, 0x14, 0x38, + 0xa4, 0x06, 0x02, 0x93, 0x48, 0xdc, 0x36, 0x70, 0xb6, 0xca, 0x42, 0x91, 0x0e, 0x02, 0x02, 0xa6, + 0x40, 0x81, 0x2e, 0x04, 0x45, 0x9e, 0xa9, 0x43, 0x25, 0x1e, 0xc3, 0xa3, 0xab, 0x08, 0x2d, 0xda, + 0x35, 0xdd, 0xfa, 0x27, 0x64, 0xee, 0x58, 0x74, 0xec, 0xd4, 0x29, 0xe8, 0x14, 0x14, 0x1d, 0x8a, + 0x0e, 0x6c, 0x61, 0x2f, 0x9d, 0xf9, 0x17, 0x14, 0xf7, 0x83, 0x14, 0x25, 0xd1, 0x8a, 0x94, 0x25, + 0x13, 0x79, 0xf7, 0xbe, 0xef, 0xbd, 0x7b, 0x9f, 0xbb, 0x7b, 0x24, 0x68, 0x79, 0xe3, 0x1e, 0x8a, + 0xad, 0x01, 0x7e, 0x76, 0x8a, 0x7d, 0x9c, 0x8c, 0xad, 0xaf, 0xef, 0xf7, 0x50, 0xe2, 0xde, 0xb7, + 0x92, 0xe7, 0x66, 0x14, 0x93, 0x84, 0xc0, 0x5d, 0xae, 0x30, 0x0b, 0x85, 0x29, 0x15, 0xcd, 0x46, + 0x40, 0x02, 0xc2, 0x35, 0x16, 0x7b, 0x13, 0xf2, 0xa6, 0xe6, 0x11, 0x3a, 0x24, 0xd4, 0xea, 0xb9, + 0x14, 0x15, 0xc1, 0x3c, 0x82, 0x43, 0x69, 0xdf, 0x13, 0x76, 0x47, 0x38, 0x8a, 0x81, 0x30, 0x19, + 0xbf, 0xaf, 0x81, 0xed, 0x2e, 0x0d, 0x8e, 0x63, 0xe4, 0x26, 0xe8, 0x09, 0x21, 0x03, 0x88, 0x41, + 0x23, 0x22, 0x64, 0xe0, 0x78, 0x6c, 0x8a, 0xc4, 0x8e, 0xeb, 0xfb, 0x31, 0xa2, 0x54, 0x55, 0x5a, + 0xca, 0xfe, 0x66, 0xfb, 0x61, 0x96, 0xea, 0xef, 0x8f, 0xdd, 0xe1, 0xe0, 0x91, 0x51, 0xa5, 0x32, + 0xfe, 0xf8, 0xe5, 0xa0, 0x21, 0x13, 0x7c, 0x22, 0xa6, 0x9e, 0x26, 0x31, 0x0e, 0x03, 0x1b, 0x32, + 0xf9, 0xb1, 0x50, 0x4b, 0x0b, 0x3c, 0x02, 0x5b, 0x3c, 0x48, 0x32, 0x8e, 0x90, 0x83, 0x7d, 0x75, + 0xad, 0xa5, 0xec, 0x6f, 0xb7, 0x77, 0xb3, 0x54, 0xbf, 0x51, 0x4a, 0x21, 0xad, 0x86, 0x0d, 0xd8, + 0xf0, 0xf3, 0x71, 0x84, 0x3e, 0xf3, 0xe1, 0x0b, 0x05, 0x6c, 0xfb, 0x28, 0x22, 0x14, 0x27, 0x0e, + 0xab, 0x94, 0xaa, 0xeb, 0xad, 0xfa, 0xfe, 0xd5, 0x07, 0x7b, 0xa6, 0xcc, 0xce, 0x58, 0xe4, 0xd8, + 0xcc, 0x63, 0x82, 0xc3, 0xf6, 0xe3, 0x57, 0xa9, 0x5e, 0xcb, 0x52, 0xbd, 0x21, 0x62, 0x4f, 0x79, + 0x1b, 0x3f, 0xfd, 0xa3, 0xef, 0x07, 0x38, 0xe9, 0x9f, 0xf6, 0x4c, 0x8f, 0x0c, 0x25, 0x23, 0xf9, + 0x38, 0xa0, 0xfe, 0x57, 0x16, 0x5b, 0x05, 0xe5, 0x81, 0xa8, 0xbd, 0x25, 0x7d, 0xf9, 0xe8, 0xd1, + 0x95, 0x17, 0x2f, 0xf5, 0xda, 0x7f, 0x2f, 0xf5, 0x9a, 0xb1, 0x0b, 0x6e, 0x4e, 0xb1, 0xb4, 0x11, + 0x8d, 0x48, 0x48, 0x91, 0xf1, 0xeb, 0x1a, 0xb7, 0x74, 0x84, 0xdb, 0x17, 0x38, 0xe9, 0xe3, 0xb0, + 0xed, 0x26, 0x5e, 0x1f, 0xba, 0x60, 0x47, 0x06, 0x9b, 0x43, 0xfd, 0x61, 0x96, 0xea, 0xea, 0xd4, + 0x5a, 0x97, 0xe1, 0x7c, 0xbd, 0xd0, 0xe6, 0x94, 0xef, 0x81, 0xcb, 0x9c, 0xa3, 0x04, 0xbc, 0xde, + 0x86, 0x59, 0xaa, 0x5f, 0x2b, 0x01, 0x66, 0x6c, 0x37, 0xd8, 0x5b, 0x25, 0xd7, 0xfa, 0xbb, 0xe7, + 0xaa, 0x83, 0x3b, 0x95, 0xf4, 0x0a, 0xbe, 0x3f, 0xaf, 0x81, 0x5b, 0x5d, 0x1a, 0x30, 0x93, 0x1f, + 0xbb, 0xa3, 0x32, 0x60, 0x1f, 0xc0, 0x91, 0x9c, 0x46, 0xb3, 0x84, 0x3f, 0xca, 0x52, 0x7d, 0x4f, + 0xac, 0x7a, 0x5e, 0x73, 0x31, 0xe2, 0x9d, 0x89, 0xf8, 0xad, 0x18, 0x7f, 0x03, 0x36, 0xc5, 0xdd, + 0x21, 0x38, 0x54, 0xeb, 0x2d, 0x65, 0x31, 0xde, 0x63, 0x89, 0xf7, 0x7a, 0xf9, 0xd6, 0x11, 0x1c, + 0x32, 0xb4, 0x1f, 0x2c, 0x89, 0xd6, 0xbe, 0xc2, 0x6f, 0x1f, 0xc1, 0x61, 0x89, 0x6a, 0x0b, 0x68, + 0xd5, 0xcc, 0x0a, 0xac, 0xbf, 0x5d, 0x02, 0xb0, 0x4b, 0x83, 0xa7, 0x23, 0x37, 0x2a, 0x23, 0x25, + 0xe0, 0x16, 0x1d, 0xb9, 0x91, 0x13, 0xa3, 0x67, 0xa7, 0x88, 0x26, 0x73, 0x58, 0x8f, 0xb2, 0x54, + 0xbf, 0x23, 0x56, 0x5b, 0xad, 0xbb, 0x18, 0x6d, 0x83, 0x39, 0xd8, 0xb9, 0xfe, 0xad, 0xe8, 0x1e, + 0x81, 0x2d, 0x9e, 0x35, 0x6f, 0x2a, 0xf5, 0xd9, 0xa6, 0x52, 0xb6, 0x1a, 0x36, 0x60, 0x43, 0xd9, + 0x54, 0xbe, 0x03, 0x80, 0x9c, 0x9c, 0xa0, 0x58, 0xec, 0xcc, 0xfa, 0x9b, 0x76, 0xa6, 0x23, 0x77, + 0x66, 0x47, 0xc4, 0x9d, 0xb8, 0xae, 0xb4, 0x35, 0x9b, 0xdc, 0x8f, 0xbd, 0xc2, 0xc7, 0xac, 0x19, + 0x0c, 0xdd, 0xd0, 0xe7, 0x51, 0x1c, 0x1f, 0x85, 0x64, 0xa8, 0x5e, 0xe2, 0x4c, 0x6f, 0x97, 0x9b, + 0xc1, 0x8c, 0xc4, 0xb0, 0xdf, 0x13, 0x73, 0x2c, 0x48, 0x87, 0xcd, 0xc0, 0x1f, 0x14, 0x70, 0x6d, + 0xb2, 0x1e, 0xe7, 0x04, 0x21, 0x75, 0xe3, 0x4d, 0xe5, 0xe4, 0xf7, 0xf8, 0xe6, 0x6c, 0x39, 0xcc, + 0x7d, 0xa5, 0x92, 0xb6, 0x8a, 0x92, 0x3e, 0x45, 0x08, 0x52, 0x70, 0x95, 0xc4, 0x3e, 0x8a, 0x9d, + 0x28, 0xc6, 0x1e, 0x52, 0x2f, 0xf3, 0x7a, 0x6c, 0x96, 0xec, 0xef, 0x54, 0xbf, 0xbb, 0x44, 0xcc, + 0x0e, 0xf2, 0xb2, 0x54, 0x87, 0x72, 0x59, 0x93, 0x50, 0xec, 0x18, 0x01, 0x59, 0x4e, 0x07, 0x79, + 0x36, 0xe0, 0xb6, 0x27, 0xcc, 0x54, 0x3a, 0xe6, 0xb7, 0x41, 0x73, 0xfe, 0x0c, 0xe7, 0x47, 0xfc, + 0xc1, 0x9f, 0x75, 0x50, 0xef, 0xd2, 0x00, 0xfa, 0x00, 0x94, 0xbe, 0x81, 0x77, 0xcd, 0x0b, 0x3e, + 0xc0, 0xe6, 0x54, 0x7f, 0x6f, 0x9a, 0xcb, 0xe9, 0xf2, 0x6c, 0xf0, 0x5b, 0x00, 0x2b, 0xbe, 0x01, + 0x0b, 0xa3, 0xcc, 0xeb, 0x9b, 0x1f, 0xaf, 0xa6, 0x2f, 0xb2, 0x7f, 0x0f, 0x6e, 0x54, 0x75, 0x48, + 0x6b, 0x51, 0xb8, 0x0a, 0x87, 0xe6, 0xc3, 0x15, 0x1d, 0x8a, 0x05, 0xf4, 0xc1, 0x3a, 0xdb, 0x07, + 0x78, 0x6f, 0x51, 0x80, 0x99, 0x9d, 0x6a, 0x1e, 0xae, 0x20, 0xce, 0x33, 0xb5, 0xbb, 0xaf, 0xce, + 0x34, 0xe5, 0xf5, 0x99, 0xa6, 0xfc, 0x7b, 0xa6, 0x29, 0x3f, 0x9e, 0x6b, 0xb5, 0xd7, 0xe7, 0x5a, + 0xed, 0xaf, 0x73, 0xad, 0xf6, 0xe5, 0x61, 0xf9, 0xc0, 0xb1, 0xc0, 0x1e, 0x09, 0x03, 0xd6, 0x65, + 0xac, 0x80, 0x1c, 0x88, 0x1f, 0xb3, 0xe7, 0xa5, 0x5f, 0x33, 0x7e, 0x02, 0x7b, 0x1b, 0xfc, 0x67, + 0xe9, 0xf0, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0x7a, 0x2f, 0xd4, 0x33, 0xba, 0x09, 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ context.Context + _ 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 { + // Submit a create liquidity pool message. + CreatePool(ctx context.Context, in *MsgCreatePool, opts ...grpc.CallOption) (*MsgCreatePoolResponse, error) + // Submit a deposit to the liquidity pool batch. + DepositWithinBatch(ctx context.Context, in *MsgDepositWithinBatch, opts ...grpc.CallOption) (*MsgDepositWithinBatchResponse, error) + // Submit a withdraw from the liquidity pool batch. + WithdrawWithinBatch(ctx context.Context, in *MsgWithdrawWithinBatch, opts ...grpc.CallOption) (*MsgWithdrawWithinBatchResponse, error) + // Submit a swap to the liquidity pool batch. + Swap(ctx context.Context, in *MsgSwapWithinBatch, opts ...grpc.CallOption) (*MsgSwapWithinBatchResponse, error) +} + +type msgClient struct { + cc grpc1.ClientConn +} + +func NewMsgClient(cc grpc1.ClientConn) MsgClient { + return &msgClient{cc} +} + +func (c *msgClient) CreatePool(ctx context.Context, in *MsgCreatePool, opts ...grpc.CallOption) (*MsgCreatePoolResponse, error) { + out := new(MsgCreatePoolResponse) + err := c.cc.Invoke(ctx, "/cyber.liquidity.v1beta1.Msg/CreatePool", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) DepositWithinBatch(ctx context.Context, in *MsgDepositWithinBatch, opts ...grpc.CallOption) (*MsgDepositWithinBatchResponse, error) { + out := new(MsgDepositWithinBatchResponse) + err := c.cc.Invoke(ctx, "/cyber.liquidity.v1beta1.Msg/DepositWithinBatch", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) WithdrawWithinBatch(ctx context.Context, in *MsgWithdrawWithinBatch, opts ...grpc.CallOption) (*MsgWithdrawWithinBatchResponse, error) { + out := new(MsgWithdrawWithinBatchResponse) + err := c.cc.Invoke(ctx, "/cyber.liquidity.v1beta1.Msg/WithdrawWithinBatch", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) Swap(ctx context.Context, in *MsgSwapWithinBatch, opts ...grpc.CallOption) (*MsgSwapWithinBatchResponse, error) { + out := new(MsgSwapWithinBatchResponse) + err := c.cc.Invoke(ctx, "/cyber.liquidity.v1beta1.Msg/Swap", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// MsgServer is the server API for Msg service. +type MsgServer interface { + // Submit a create liquidity pool message. + CreatePool(context.Context, *MsgCreatePool) (*MsgCreatePoolResponse, error) + // Submit a deposit to the liquidity pool batch. + DepositWithinBatch(context.Context, *MsgDepositWithinBatch) (*MsgDepositWithinBatchResponse, error) + // Submit a withdraw from the liquidity pool batch. + WithdrawWithinBatch(context.Context, *MsgWithdrawWithinBatch) (*MsgWithdrawWithinBatchResponse, error) + // Submit a swap to the liquidity pool batch. + Swap(context.Context, *MsgSwapWithinBatch) (*MsgSwapWithinBatchResponse, error) +} + +// UnimplementedMsgServer can be embedded to have forward compatible implementations. +type UnimplementedMsgServer struct{} + +func (*UnimplementedMsgServer) CreatePool(ctx context.Context, req *MsgCreatePool) (*MsgCreatePoolResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method CreatePool not implemented") +} + +func (*UnimplementedMsgServer) DepositWithinBatch(ctx context.Context, req *MsgDepositWithinBatch) (*MsgDepositWithinBatchResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method DepositWithinBatch not implemented") +} + +func (*UnimplementedMsgServer) WithdrawWithinBatch(ctx context.Context, req *MsgWithdrawWithinBatch) (*MsgWithdrawWithinBatchResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method WithdrawWithinBatch not implemented") +} + +func (*UnimplementedMsgServer) Swap(ctx context.Context, req *MsgSwapWithinBatch) (*MsgSwapWithinBatchResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Swap not implemented") +} + +func RegisterMsgServer(s grpc1.Server, srv MsgServer) { + s.RegisterService(&_Msg_serviceDesc, srv) +} + +func _Msg_CreatePool_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgCreatePool) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).CreatePool(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cyber.liquidity.v1beta1.Msg/CreatePool", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).CreatePool(ctx, req.(*MsgCreatePool)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_DepositWithinBatch_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgDepositWithinBatch) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).DepositWithinBatch(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cyber.liquidity.v1beta1.Msg/DepositWithinBatch", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).DepositWithinBatch(ctx, req.(*MsgDepositWithinBatch)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_WithdrawWithinBatch_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgWithdrawWithinBatch) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).WithdrawWithinBatch(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cyber.liquidity.v1beta1.Msg/WithdrawWithinBatch", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).WithdrawWithinBatch(ctx, req.(*MsgWithdrawWithinBatch)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_Swap_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgSwapWithinBatch) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).Swap(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cyber.liquidity.v1beta1.Msg/Swap", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).Swap(ctx, req.(*MsgSwapWithinBatch)) + } + return interceptor(ctx, in, info, handler) +} + +var _Msg_serviceDesc = grpc.ServiceDesc{ + ServiceName: "cyber.liquidity.v1beta1.Msg", + HandlerType: (*MsgServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "CreatePool", + Handler: _Msg_CreatePool_Handler, + }, + { + MethodName: "DepositWithinBatch", + Handler: _Msg_DepositWithinBatch_Handler, + }, + { + MethodName: "WithdrawWithinBatch", + Handler: _Msg_WithdrawWithinBatch_Handler, + }, + { + MethodName: "Swap", + Handler: _Msg_Swap_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "cyber/liquidity/v1beta1/tx.proto", +} + +func (m *MsgCreatePool) 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 *MsgCreatePool) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgCreatePool) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.DepositCoins) > 0 { + for iNdEx := len(m.DepositCoins) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.DepositCoins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + } + if m.PoolTypeId != 0 { + i = encodeVarintTx(dAtA, i, uint64(m.PoolTypeId)) + i-- + dAtA[i] = 0x10 + } + if len(m.PoolCreatorAddress) > 0 { + i -= len(m.PoolCreatorAddress) + copy(dAtA[i:], m.PoolCreatorAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.PoolCreatorAddress))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgCreatePoolResponse) 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 *MsgCreatePoolResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgCreatePoolResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *MsgDepositWithinBatch) 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 *MsgDepositWithinBatch) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgDepositWithinBatch) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.DepositCoins) > 0 { + for iNdEx := len(m.DepositCoins) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.DepositCoins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + if m.PoolId != 0 { + i = encodeVarintTx(dAtA, i, uint64(m.PoolId)) + i-- + dAtA[i] = 0x10 + } + if len(m.DepositorAddress) > 0 { + i -= len(m.DepositorAddress) + copy(dAtA[i:], m.DepositorAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.DepositorAddress))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgDepositWithinBatchResponse) 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 *MsgDepositWithinBatchResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgDepositWithinBatchResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *MsgWithdrawWithinBatch) 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 *MsgWithdrawWithinBatch) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgWithdrawWithinBatch) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.PoolCoin.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + if m.PoolId != 0 { + i = encodeVarintTx(dAtA, i, uint64(m.PoolId)) + i-- + dAtA[i] = 0x10 + } + if len(m.WithdrawerAddress) > 0 { + i -= len(m.WithdrawerAddress) + copy(dAtA[i:], m.WithdrawerAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.WithdrawerAddress))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgWithdrawWithinBatchResponse) 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 *MsgWithdrawWithinBatchResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgWithdrawWithinBatchResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *MsgSwapWithinBatch) 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 *MsgSwapWithinBatch) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgSwapWithinBatch) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size := m.OrderPrice.Size() + i -= size + if _, err := m.OrderPrice.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x3a + { + size, err := m.OfferCoinFee.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + if len(m.DemandCoinDenom) > 0 { + i -= len(m.DemandCoinDenom) + copy(dAtA[i:], m.DemandCoinDenom) + i = encodeVarintTx(dAtA, i, uint64(len(m.DemandCoinDenom))) + i-- + dAtA[i] = 0x2a + } + { + size, err := m.OfferCoin.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + if m.SwapTypeId != 0 { + i = encodeVarintTx(dAtA, i, uint64(m.SwapTypeId)) + i-- + dAtA[i] = 0x18 + } + if m.PoolId != 0 { + i = encodeVarintTx(dAtA, i, uint64(m.PoolId)) + i-- + dAtA[i] = 0x10 + } + if len(m.SwapRequesterAddress) > 0 { + i -= len(m.SwapRequesterAddress) + copy(dAtA[i:], m.SwapRequesterAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.SwapRequesterAddress))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgSwapWithinBatchResponse) 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 *MsgSwapWithinBatchResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgSwapWithinBatchResponse) 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 *MsgCreatePool) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.PoolCreatorAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if m.PoolTypeId != 0 { + n += 1 + sovTx(uint64(m.PoolTypeId)) + } + if len(m.DepositCoins) > 0 { + for _, e := range m.DepositCoins { + l = e.Size() + n += 1 + l + sovTx(uint64(l)) + } + } + return n +} + +func (m *MsgCreatePoolResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *MsgDepositWithinBatch) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.DepositorAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if m.PoolId != 0 { + n += 1 + sovTx(uint64(m.PoolId)) + } + if len(m.DepositCoins) > 0 { + for _, e := range m.DepositCoins { + l = e.Size() + n += 1 + l + sovTx(uint64(l)) + } + } + return n +} + +func (m *MsgDepositWithinBatchResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *MsgWithdrawWithinBatch) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.WithdrawerAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if m.PoolId != 0 { + n += 1 + sovTx(uint64(m.PoolId)) + } + l = m.PoolCoin.Size() + n += 1 + l + sovTx(uint64(l)) + return n +} + +func (m *MsgWithdrawWithinBatchResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *MsgSwapWithinBatch) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.SwapRequesterAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if m.PoolId != 0 { + n += 1 + sovTx(uint64(m.PoolId)) + } + if m.SwapTypeId != 0 { + n += 1 + sovTx(uint64(m.SwapTypeId)) + } + l = m.OfferCoin.Size() + n += 1 + l + sovTx(uint64(l)) + l = len(m.DemandCoinDenom) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = m.OfferCoinFee.Size() + n += 1 + l + sovTx(uint64(l)) + l = m.OrderPrice.Size() + n += 1 + l + sovTx(uint64(l)) + return n +} + +func (m *MsgSwapWithinBatchResponse) 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 *MsgCreatePool) 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: MsgCreatePool: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgCreatePool: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolCreatorAddress", 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.PoolCreatorAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolTypeId", wireType) + } + m.PoolTypeId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PoolTypeId |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DepositCoins", 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 + } + m.DepositCoins = append(m.DepositCoins, types.Coin{}) + if err := m.DepositCoins[len(m.DepositCoins)-1].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 *MsgCreatePoolResponse) 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: MsgCreatePoolResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgCreatePoolResponse: 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 (m *MsgDepositWithinBatch) 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: MsgDepositWithinBatch: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgDepositWithinBatch: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DepositorAddress", 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.DepositorAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) + } + m.PoolId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PoolId |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DepositCoins", 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 + } + m.DepositCoins = append(m.DepositCoins, types.Coin{}) + if err := m.DepositCoins[len(m.DepositCoins)-1].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 *MsgDepositWithinBatchResponse) 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: MsgDepositWithinBatchResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgDepositWithinBatchResponse: 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 (m *MsgWithdrawWithinBatch) 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: MsgWithdrawWithinBatch: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgWithdrawWithinBatch: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field WithdrawerAddress", 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.WithdrawerAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) + } + m.PoolId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PoolId |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolCoin", 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.PoolCoin.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 *MsgWithdrawWithinBatchResponse) 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: MsgWithdrawWithinBatchResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgWithdrawWithinBatchResponse: 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 (m *MsgSwapWithinBatch) 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: MsgSwapWithinBatch: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgSwapWithinBatch: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SwapRequesterAddress", 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.SwapRequesterAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) + } + m.PoolId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PoolId |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field SwapTypeId", wireType) + } + m.SwapTypeId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.SwapTypeId |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field OfferCoin", 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.OfferCoin.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DemandCoinDenom", 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.DemandCoinDenom = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field OfferCoinFee", 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.OfferCoinFee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field OrderPrice", 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 + } + if err := m.OrderPrice.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 *MsgSwapWithinBatchResponse) 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: MsgSwapWithinBatchResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgSwapWithinBatchResponse: 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/liquidity/types/utils.go b/x/liquidity/types/utils.go new file mode 100644 index 00000000..03371286 --- /dev/null +++ b/x/liquidity/types/utils.go @@ -0,0 +1,126 @@ +package types + +import ( + "crypto/sha256" + "fmt" + "sort" + "strings" + + "cosmossdk.io/math" + "github.com/cometbft/cometbft/crypto" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/address" +) + +// AlphabeticalDenomPair returns denom pairs that are alphabetically sorted. +func AlphabeticalDenomPair(denom1, denom2 string) (resDenom1, resDenom2 string) { + if denom1 > denom2 { + return denom2, denom1 + } + return denom1, denom2 +} + +// SortDenoms sorts denoms in alphabetical order. +func SortDenoms(denoms []string) []string { + sort.Strings(denoms) + return denoms +} + +// GetPoolReserveAcc returns the address of the pool's reserve account. +func GetPoolReserveAcc(poolName string, len32 bool) sdk.AccAddress { + if len32 { + // The rules are temporarily added for testing on 32-length bytes addresses of ADR-28 and are subject to change. + poolCoinDenom := GetPoolCoinDenom(poolName) + poolCoinDenom = strings.TrimPrefix(poolCoinDenom, PoolCoinDenomPrefix) + return sdk.AccAddress(address.Module(ModuleName, []byte(poolCoinDenom))) + } + return sdk.AccAddress(crypto.AddressHash([]byte(poolName))) +} + +// GetPoolCoinDenom returns the denomination of the pool coin. +func GetPoolCoinDenom(poolName string) string { + // Originally pool coin denom has prefix with / splitter, but removed prefix for pass validation of ibc-transfer + return fmt.Sprintf("%s%X", PoolCoinDenomPrefix, sha256.Sum256([]byte(poolName))) +} + +// GetReserveAcc extracts and returns reserve account from pool coin denom. +func GetReserveAcc(poolCoinDenom string, len32 bool) (sdk.AccAddress, error) { + if err := sdk.ValidateDenom(poolCoinDenom); err != nil { + return nil, err + } + if !strings.HasPrefix(poolCoinDenom, PoolCoinDenomPrefix) { + return nil, ErrInvalidDenom + } + poolCoinDenom = strings.TrimPrefix(poolCoinDenom, PoolCoinDenomPrefix) + if len(poolCoinDenom) != 64 { + return nil, ErrInvalidDenom + } + if len32 { + // The rules are temporarily added for testing on 32-length bytes addresses of ADR-28 and are subject to change. + return sdk.AccAddress(address.Module(ModuleName, []byte(poolCoinDenom))), nil + } + return sdk.AccAddressFromHexUnsafe(poolCoinDenom[:40]) +} + +// GetCoinsTotalAmount returns total amount of all coins in sdk.Coins. +func GetCoinsTotalAmount(coins sdk.Coins) math.Int { + totalAmount := sdk.ZeroInt() + for _, coin := range coins { + totalAmount = totalAmount.Add(coin.Amount) + } + return totalAmount +} + +// ValidateReserveCoinLimit checks if total amounts of depositCoins exceed maxReserveCoinAmount. +func ValidateReserveCoinLimit(maxReserveCoinAmount math.Int, depositCoins sdk.Coins) error { + totalAmount := GetCoinsTotalAmount(depositCoins) + if maxReserveCoinAmount.IsZero() { + return nil + } else if totalAmount.GT(maxReserveCoinAmount) { + return ErrExceededReserveCoinLimit + } else { + return nil + } +} + +func GetOfferCoinFee(offerCoin sdk.Coin, swapFeeRate sdk.Dec) sdk.Coin { + if swapFeeRate.IsZero() { + return sdk.NewCoin(offerCoin.Denom, sdk.ZeroInt()) + } + // apply half-ratio swap fee rate and ceiling + // see https://github.com/tendermint/liquidity/issues/41 for details + return sdk.NewCoin(offerCoin.Denom, sdk.NewDecFromInt(offerCoin.Amount).Mul(swapFeeRate.QuoInt64(2)).Ceil().TruncateInt()) // Ceil(offerCoin.Amount * (swapFeeRate/2)) +} + +func MustParseCoinsNormalized(coinStr string) sdk.Coins { + coins, err := sdk.ParseCoinsNormalized(coinStr) + if err != nil { + panic(err) + } + return coins +} + +//nolint:staticcheck +func CheckOverflow(a, b math.Int) (err error) { + defer func() { + if r := recover(); r != nil { + err = ErrOverflowAmount + } + }() + a.Mul(b) + a.Quo(b) + b.Quo(a) + return nil +} + +func CheckOverflowWithDec(a, b sdk.Dec) (err error) { + defer func() { + if r := recover(); r != nil { + err = ErrOverflowAmount + } + }() + a.Mul(b) + a.Quo(b) + b.Quo(a) + return nil +}