From 9b9595b447d91f1a2693cfc05a456244c62b3673 Mon Sep 17 00:00:00 2001 From: Cosmic Vagabond <121588426+cosmic-vagabond@users.noreply.github.com> Date: Sat, 2 Dec 2023 09:48:50 +0100 Subject: [PATCH] Refactor/margin features (#289) * refactor: use builtin coins method instead of asset index * feat: simplified code structure + partial close completion * feat: add min collateral query and discount and swap fee features to margin * feat: add migrator * feat: improved open estimation query * test: fix --- config.yml | 6 + docs/static/openapi.yml | 2136 ++++------------- proto/elys/margin/params.proto | 4 + proto/elys/margin/query.proto | 52 +- proto/elys/margin/tx.proto | 17 +- proto/elys/margin/types.proto | 61 +- wasmbindings/types/types.go | 1 + x/amm/client/wasm/query_amm_price_by_denom.go | 2 +- x/amm/keeper/apply_discount_test.go | 60 - x/amm/keeper/calc_in_route_spot_price.go | 9 +- x/amm/keeper/calc_in_route_spot_price_test.go | 8 +- x/amm/keeper/calc_out_route_spot_price.go | 9 +- .../keeper/calc_out_route_spot_price_test.go | 8 +- x/amm/keeper/calc_swap_estimation_by_denom.go | 11 +- .../calc_swap_estimation_by_denom_test.go | 6 +- x/amm/keeper/msg_server_swap_by_denom.go | 2 +- x/amm/keeper/query_swap_estimation.go | 2 +- .../keeper/query_swap_estimation_by_denom.go | 2 +- x/amm/keeper/route_exact_amount_in.go | 2 +- x/amm/keeper/route_exact_amount_out.go | 2 +- x/amm/{keeper => types}/apply_discount.go | 2 +- x/amm/types/apply_discount_test.go | 63 + x/amm/types/calc_in_amt_given_out.go | 4 +- x/amm/types/calc_out_amt_given_in.go | 4 +- x/amm/types/query.pb.gw.go | 40 +- x/leveragelp/types/mocks/bank_keeper.go | 435 ++++ x/margin/client/cli/query.go | 1 + x/margin/client/cli/query_mtp_test.go | 51 +- x/margin/client/cli/query_open_estimation.go | 95 + x/margin/client/cli/tx.go | 1 + x/margin/client/cli/tx_close.go | 4 +- x/margin/client/cli/tx_close_test.go | 2 +- x/margin/client/cli/tx_open.go | 23 +- x/margin/client/cli/tx_open_test.go | 3 +- x/margin/client/wasm/msg_open.go | 10 +- x/margin/client/wasm/querier.go | 2 + x/margin/client/wasm/query_min_collateral.go | 22 + x/margin/keeper/begin_blocker.go | 6 +- x/margin/keeper/begin_blocker_process_mtp.go | 79 +- x/margin/keeper/calc_min_collateral.go | 25 + .../keeper/calc_mtp_consolidate_collateral.go | 30 +- .../keeper/calc_mtp_interest_liabilities.go | 17 +- .../calc_mtp_take_profit_borrow_rate.go | 32 +- .../calc_mtp_take_profit_liabilities.go | 26 +- x/margin/keeper/check_same_asset_position.go | 2 +- .../keeper/check_same_asset_position_test.go | 13 +- x/margin/keeper/close.go | 29 +- x/margin/keeper/close_long.go | 76 +- x/margin/keeper/close_long_test.go | 119 +- x/margin/keeper/close_short.go | 75 +- x/margin/keeper/close_short_test.go | 108 +- x/margin/keeper/emit_open_event.go | 2 +- x/margin/keeper/estimate_and_repay.go | 30 +- x/margin/keeper/events.go | 10 +- x/margin/keeper/force_close_long.go | 44 +- x/margin/keeper/force_close_short.go | 44 +- x/margin/keeper/generate_open_event.go | 28 - x/margin/keeper/get_first_valid_pool.go | 13 +- x/margin/keeper/get_first_valid_pool_test.go | 19 +- x/margin/keeper/handle_borrow_interest.go | 8 +- .../keeper/handle_borrow_interest_payment.go | 22 +- .../keeper/handle_funding_fee_collection.go | 35 +- .../keeper/handle_funding_fee_distribution.go | 27 +- x/margin/keeper/invariant_check.go | 4 +- x/margin/keeper/invariant_check_test.go | 7 +- x/margin/keeper/keeper.go | 126 +- x/margin/keeper/keeper_test.go | 29 +- x/margin/keeper/open.go | 9 +- x/margin/keeper/open_consolidate.go | 11 +- x/margin/keeper/open_consolidate_long.go | 12 +- x/margin/keeper/open_consolidate_short.go | 14 +- x/margin/keeper/open_long.go | 9 +- x/margin/keeper/open_long_process.go | 39 +- x/margin/keeper/open_long_test.go | 138 +- x/margin/keeper/open_short.go | 9 +- x/margin/keeper/open_short_process.go | 50 +- x/margin/keeper/open_short_test.go | 185 +- x/margin/keeper/open_test.go | 63 +- x/margin/keeper/params.go | 4 + x/margin/keeper/prepare_pools.go | 4 +- x/margin/keeper/query_open_estimation.go | 73 + x/margin/keeper/query_open_estimation_test.go | 107 + x/margin/keeper/repay.go | 110 +- x/margin/keeper/take_out_custody.go | 7 +- x/margin/keeper/update_mtp_health.go | 51 +- x/margin/migrations/v4_migration.go | 24 + x/margin/module.go | 4 +- .../types/calc_mtp_take_profit_custodies.go | 17 - .../types/calc_mtp_take_profit_custody.go | 12 + x/margin/types/calc_take_amount.go | 9 +- x/margin/types/errors.go | 4 + x/margin/types/expected_keepers.go | 43 +- x/margin/types/generate_open_event.go | 23 + x/margin/types/generate_open_event_test.go | 67 + x/margin/types/get_margin_pool_balance.go | 11 +- x/margin/types/get_mtp_asset_index.go | 22 - x/margin/types/get_trading_asset.go | 8 - x/margin/types/get_trading_asset_test.go | 37 - x/margin/types/mocks/amm_keeper.go | 157 ++ x/margin/types/mocks/close_long_checker.go | 76 +- x/margin/types/mocks/close_short_checker.go | 76 +- x/margin/types/mocks/open_checker.go | 37 +- x/margin/types/mocks/open_long_checker.go | 44 +- x/margin/types/mocks/open_short_checker.go | 44 +- x/margin/types/msgs.go | 17 +- x/margin/types/params.go | 21 + x/margin/types/params.pb.go | 150 +- x/margin/types/pool.go | 130 +- x/margin/types/query.pb.go | 1604 +++++++++++-- x/margin/types/query.pb.gw.go | 117 +- x/margin/types/reached_take_profit_price.go | 15 + x/margin/types/tx.pb.go | 286 +-- x/margin/types/types.go | 61 +- x/margin/types/types.pb.go | 977 ++++---- x/parameter/types/query.pb.gw.go | 7 +- 115 files changed, 5351 insertions(+), 3891 deletions(-) delete mode 100644 x/amm/keeper/apply_discount_test.go rename x/amm/{keeper => types}/apply_discount.go (95%) create mode 100644 x/amm/types/apply_discount_test.go create mode 100644 x/leveragelp/types/mocks/bank_keeper.go create mode 100644 x/margin/client/cli/query_open_estimation.go create mode 100644 x/margin/client/wasm/query_min_collateral.go create mode 100644 x/margin/keeper/calc_min_collateral.go delete mode 100644 x/margin/keeper/generate_open_event.go create mode 100644 x/margin/keeper/query_open_estimation.go create mode 100644 x/margin/keeper/query_open_estimation_test.go create mode 100644 x/margin/migrations/v4_migration.go delete mode 100644 x/margin/types/calc_mtp_take_profit_custodies.go create mode 100644 x/margin/types/calc_mtp_take_profit_custody.go create mode 100644 x/margin/types/generate_open_event.go create mode 100644 x/margin/types/generate_open_event_test.go delete mode 100644 x/margin/types/get_mtp_asset_index.go delete mode 100644 x/margin/types/get_trading_asset.go delete mode 100644 x/margin/types/get_trading_asset_test.go create mode 100644 x/margin/types/reached_take_profit_price.go diff --git a/config.yml b/config.yml index 050c17a29..5ba07336e 100644 --- a/config.yml +++ b/config.yml @@ -458,6 +458,12 @@ genesis: incremental_borrow_interest_payment_enabled: true whitelisting_enabled: false invariant_check_epoch: day + take_profit_borrow_interest_rate_min: "0.00000003" + funding_fee_base_rate: "0.0003" + funding_fee_max_rate: "0.001" + funding_fee_min_rate: "-0.001" + funding_fee_collection_address: "elys1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqnrec2l" + swap_fee: "0.001" stablestake: params: deposit_denom: "uusdc" diff --git a/docs/static/openapi.yml b/docs/static/openapi.yml index 03160d814..cc8a5d6cf 100644 --- a/docs/static/openapi.yml +++ b/docs/static/openapi.yml @@ -40696,7 +40696,7 @@ paths: - Query /elys-network/elys/margin/is-whitelisted: get: - summary: Queries a list of IsWhitelisted items. + summary: Is an address whitelisted? operationId: ElysMarginIsWhitelisted responses: '200': @@ -40735,7 +40735,7 @@ paths: - Query /elys-network/elys/margin/mtp/{address}/{id}: get: - summary: Queries a list of MTP items. + summary: Queries a single mtp position given its address and id. operationId: ElysMarginMTP responses: '200': @@ -40748,116 +40748,32 @@ paths: properties: address: type: string - collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. + collateral_asset: + type: string + trading_asset: + type: string + liabilities_asset: + type: string + custody_asset: + type: string + collateral: + type: string liabilities: type: string - borrow_interest_paid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. - borrow_interest_paid_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. - borrow_interest_unpaid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. - custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. + borrow_interest_paid_collateral: + type: string + borrow_interest_paid_custody: + type: string + borrow_interest_unpaid_collateral: + type: string + custody: + type: string take_profit_liabilities: type: string - take_profit_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. - leverages: - type: array - items: - type: string + take_profit_custody: + type: string + leverage: + type: string mtp_health: type: string position: @@ -40881,76 +40797,18 @@ paths: type: string take_profit_borrow_rate: type: string - funding_fee_paid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. + funding_fee_paid_collateral: + type: string title: funding fee paid - funding_fee_paid_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. - funding_fee_received_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. + funding_fee_paid_custody: + type: string + funding_fee_received_collateral: + type: string title: funding fee received - funding_fee_received_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. + funding_fee_received_custody: + type: string + open_price: + type: string default: description: An unexpected error response. schema: @@ -40983,7 +40841,7 @@ paths: - Query /elys-network/elys/margin/mtps-by-pool/{amm_pool_id}/{pagination.key}: get: - summary: Queries a list of GetPositionsByPool items. + summary: Queries a list of mtp positions by pool. operationId: ElysMarginGetPositionsByPool responses: '200': @@ -40998,122 +40856,32 @@ paths: properties: address: type: string - collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. + collateral_asset: + type: string + trading_asset: + type: string + liabilities_asset: + type: string + custody_asset: + type: string + collateral: + type: string liabilities: type: string - borrow_interest_paid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. - borrow_interest_paid_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. - borrow_interest_unpaid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. - custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. + borrow_interest_paid_collateral: + type: string + borrow_interest_paid_custody: + type: string + borrow_interest_unpaid_collateral: + type: string + custody: + type: string take_profit_liabilities: type: string - take_profit_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. - leverages: - type: array - items: - type: string + take_profit_custody: + type: string + leverage: + type: string mtp_health: type: string position: @@ -41137,80 +40905,18 @@ paths: type: string take_profit_borrow_rate: type: string - funding_fee_paid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. + funding_fee_paid_collateral: + type: string title: funding fee paid - funding_fee_paid_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. - funding_fee_received_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. + funding_fee_paid_custody: + type: string + funding_fee_received_collateral: + type: string title: funding fee received - funding_fee_received_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. + funding_fee_received_custody: + type: string + open_price: + type: string pagination: type: object properties: @@ -41323,7 +41029,7 @@ paths: - Query /elys-network/elys/margin/mtps-for-address/{address}/{pagination.key}: get: - summary: Queries a list of GetPositionsForAddress items. + summary: Queries a list of mtp positions for a given address. operationId: ElysMarginGetPositionsForAddress responses: '200': @@ -41338,122 +41044,32 @@ paths: properties: address: type: string - collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. + collateral_asset: + type: string + trading_asset: + type: string + liabilities_asset: + type: string + custody_asset: + type: string + collateral: + type: string liabilities: type: string - borrow_interest_paid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. - borrow_interest_paid_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. - borrow_interest_unpaid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. - custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. + borrow_interest_paid_collateral: + type: string + borrow_interest_paid_custody: + type: string + borrow_interest_unpaid_collateral: + type: string + custody: + type: string take_profit_liabilities: type: string - take_profit_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. - leverages: - type: array - items: - type: string + take_profit_custody: + type: string + leverage: + type: string mtp_health: type: string position: @@ -41477,80 +41093,18 @@ paths: type: string take_profit_borrow_rate: type: string - funding_fee_paid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. + funding_fee_paid_collateral: + type: string title: funding fee paid - funding_fee_paid_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. - funding_fee_received_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. + funding_fee_paid_custody: + type: string + funding_fee_received_collateral: + type: string title: funding fee received - funding_fee_received_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. + funding_fee_received_custody: + type: string + open_price: + type: string pagination: type: object properties: @@ -41660,6 +41214,155 @@ paths: type: boolean tags: - Query + /elys-network/elys/margin/open-estimation: + get: + summary: Queries an estimation of a new open position details. + operationId: ElysMarginOpenEstimation + responses: + '200': + description: A successful response. + schema: + type: object + properties: + position: + type: string + enum: + - UNSPECIFIED + - LONG + - SHORT + default: UNSPECIFIED + leverage: + type: string + trading_asset: + type: string + collateral: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + min_collateral: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + valid_collateral: + type: boolean + position_size: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + swap_fee: + type: string + discount: + type: string + open_price: + type: string + take_profit_price: + type: string + liquidation_price: + type: string + estimated_pnl: + type: string + available_liquidity: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + default: + description: An unexpected error response. + schema: + type: object + properties: + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + '@type': + type: string + additionalProperties: {} + parameters: + - name: position + in: query + required: false + type: string + enum: + - UNSPECIFIED + - LONG + - SHORT + default: UNSPECIFIED + - name: leverage + in: query + required: false + type: string + - name: trading_asset + in: query + required: false + type: string + - name: collateral.denom + in: query + required: false + type: string + - name: collateral.amount + in: query + required: false + type: string + - name: discount + in: query + required: false + type: string + - name: take_profit_price + in: query + required: false + type: string + tags: + - Query /elys-network/elys/margin/params: get: summary: Parameters queries the parameters of the module. @@ -41724,6 +41427,8 @@ paths: type: string funding_fee_collection_address: type: string + swap_fee: + type: string description: ParamsResponse is response type for the Query/Params RPC method. default: description: An unexpected error response. @@ -41747,7 +41452,7 @@ paths: - Query /elys-network/elys/margin/pool/{index}: get: - summary: Queries a list of Pool items. + summary: Queries a single pool given its index. operationId: ElysMarginPool responses: '200': @@ -41843,6 +41548,7 @@ paths: - Query /elys-network/elys/margin/pool/{pagination.key}: get: + summary: Queries a list of all pools. operationId: ElysMarginPools responses: '200': @@ -42019,7 +41725,7 @@ paths: - Query /elys-network/elys/margin/positions/{pagination.key}: get: - summary: Queries a list of GetPositions items. + summary: Queries a list of positions. operationId: ElysMarginGetPositions responses: '200': @@ -42034,122 +41740,32 @@ paths: properties: address: type: string - collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. + collateral_asset: + type: string + trading_asset: + type: string + liabilities_asset: + type: string + custody_asset: + type: string + collateral: + type: string liabilities: type: string - borrow_interest_paid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. - borrow_interest_paid_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. - borrow_interest_unpaid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. - custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. + borrow_interest_paid_collateral: + type: string + borrow_interest_paid_custody: + type: string + borrow_interest_unpaid_collateral: + type: string + custody: + type: string take_profit_liabilities: type: string - take_profit_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. - leverages: - type: array - items: - type: string + take_profit_custody: + type: string + leverage: + type: string mtp_health: type: string position: @@ -42173,80 +41789,18 @@ paths: type: string take_profit_borrow_rate: type: string - funding_fee_paid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. + funding_fee_paid_collateral: + type: string title: funding fee paid - funding_fee_paid_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. - funding_fee_received_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. + funding_fee_paid_custody: + type: string + funding_fee_received_collateral: + type: string title: funding fee received - funding_fee_received_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an - amount. - - - NOTE: The amount field is an Int which implements the - custom method - - signatures required by gogoproto. + funding_fee_received_custody: + type: string + open_price: + type: string pagination: type: object properties: @@ -42354,7 +41908,7 @@ paths: - Query /elys-network/elys/margin/status: get: - summary: Queries a list of GetStatus items. + summary: Retuns the total number of open and lifetime mtps. operationId: ElysMarginGetStatus responses: '200': @@ -42390,7 +41944,7 @@ paths: - Query /elys-network/elys/margin/whitelist/{pagination.key}: get: - summary: Queries a list of GetWhitelist items. + summary: Queries a list of whitelisted addresses. operationId: ElysMarginGetWhitelist responses: '200': @@ -85214,98 +84768,32 @@ definitions: properties: address: type: string - collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: |- - Coin defines a token with a denomination and an amount. - - NOTE: The amount field is an Int which implements the custom method - signatures required by gogoproto. + collateral_asset: + type: string + trading_asset: + type: string + liabilities_asset: + type: string + custody_asset: + type: string + collateral: + type: string liabilities: type: string - borrow_interest_paid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: |- - Coin defines a token with a denomination and an amount. - - NOTE: The amount field is an Int which implements the custom method - signatures required by gogoproto. - borrow_interest_paid_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: |- - Coin defines a token with a denomination and an amount. - - NOTE: The amount field is an Int which implements the custom method - signatures required by gogoproto. - borrow_interest_unpaid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: |- - Coin defines a token with a denomination and an amount. - - NOTE: The amount field is an Int which implements the custom method - signatures required by gogoproto. - custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: |- - Coin defines a token with a denomination and an amount. - - NOTE: The amount field is an Int which implements the custom method - signatures required by gogoproto. + borrow_interest_paid_collateral: + type: string + borrow_interest_paid_custody: + type: string + borrow_interest_unpaid_collateral: + type: string + custody: + type: string take_profit_liabilities: type: string - take_profit_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: |- - Coin defines a token with a denomination and an amount. - - NOTE: The amount field is an Int which implements the custom method - signatures required by gogoproto. - leverages: - type: array - items: - type: string + take_profit_custody: + type: string + leverage: + type: string mtp_health: type: string position: @@ -85329,64 +84817,18 @@ definitions: type: string take_profit_borrow_rate: type: string - funding_fee_paid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: |- - Coin defines a token with a denomination and an amount. - - NOTE: The amount field is an Int which implements the custom method - signatures required by gogoproto. + funding_fee_paid_collateral: + type: string title: funding fee paid - funding_fee_paid_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: |- - Coin defines a token with a denomination and an amount. - - NOTE: The amount field is an Int which implements the custom method - signatures required by gogoproto. - funding_fee_received_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: |- - Coin defines a token with a denomination and an amount. - - NOTE: The amount field is an Int which implements the custom method - signatures required by gogoproto. + funding_fee_paid_custody: + type: string + funding_fee_received_collateral: + type: string title: funding fee received - funding_fee_received_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: |- - Coin defines a token with a denomination and an amount. - - NOTE: The amount field is an Int which implements the custom method - signatures required by gogoproto. + funding_fee_received_custody: + type: string + open_price: + type: string elys.margin.MTPResponse: type: object properties: @@ -85395,116 +84837,32 @@ definitions: properties: address: type: string - collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. + collateral_asset: + type: string + trading_asset: + type: string + liabilities_asset: + type: string + custody_asset: + type: string + collateral: + type: string liabilities: type: string - borrow_interest_paid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - borrow_interest_paid_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - borrow_interest_unpaid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. + borrow_interest_paid_collateral: + type: string + borrow_interest_paid_custody: + type: string + borrow_interest_unpaid_collateral: + type: string + custody: + type: string take_profit_liabilities: type: string - take_profit_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - leverages: - type: array - items: - type: string + take_profit_custody: + type: string + leverage: + type: string mtp_health: type: string position: @@ -85528,100 +84886,18 @@ definitions: type: string take_profit_borrow_rate: type: string - funding_fee_paid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. + funding_fee_paid_collateral: + type: string title: funding fee paid - funding_fee_paid_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - funding_fee_received_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. + funding_fee_paid_custody: + type: string + funding_fee_received_collateral: + type: string title: funding fee received - funding_fee_received_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - elys.margin.MsgBrokerCloseResponse: - type: object - properties: - id: - type: string - format: uint64 - amount: - type: object - properties: - denom: + funding_fee_received_custody: type: string - amount: + open_price: type: string - description: |- - Coin defines a token with a denomination and an amount. - - NOTE: The amount field is an Int which implements the custom method - signatures required by gogoproto. - elys.margin.MsgBrokerOpenResponse: - type: object - properties: - id: - type: string - format: uint64 elys.margin.MsgCloseResponse: type: object properties: @@ -85629,17 +84905,7 @@ definitions: type: string format: uint64 amount: - type: object - properties: - denom: - type: string - amount: - type: string - description: |- - Coin defines a token with a denomination and an amount. - - NOTE: The amount field is an Int which implements the custom method - signatures required by gogoproto. + type: string elys.margin.MsgDewhitelistResponse: type: object elys.margin.MsgOpenResponse: @@ -85707,6 +84973,8 @@ definitions: type: string funding_fee_collection_address: type: string + swap_fee: + type: string description: Params defines the parameters for the module. elys.margin.ParamsResponse: type: object @@ -85765,6 +85033,8 @@ definitions: type: string funding_fee_collection_address: type: string + swap_fee: + type: string description: ParamsResponse is response type for the Query/Params RPC method. elys.margin.Pool: type: object @@ -85860,116 +85130,32 @@ definitions: properties: address: type: string - collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. + collateral_asset: + type: string + trading_asset: + type: string + liabilities_asset: + type: string + custody_asset: + type: string + collateral: + type: string liabilities: type: string - borrow_interest_paid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - borrow_interest_paid_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - borrow_interest_unpaid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - take_profit_liabilities: + borrow_interest_paid_collateral: + type: string + borrow_interest_paid_custody: + type: string + borrow_interest_unpaid_collateral: + type: string + custody: + type: string + take_profit_liabilities: + type: string + take_profit_custody: + type: string + leverage: type: string - take_profit_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - leverages: - type: array - items: - type: string mtp_health: type: string position: @@ -85993,76 +85179,18 @@ definitions: type: string take_profit_borrow_rate: type: string - funding_fee_paid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. + funding_fee_paid_collateral: + type: string title: funding fee paid - funding_fee_paid_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - funding_fee_received_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. + funding_fee_paid_custody: + type: string + funding_fee_received_collateral: + type: string title: funding fee received - funding_fee_received_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. + funding_fee_received_custody: + type: string + open_price: + type: string pagination: type: object properties: @@ -86099,116 +85227,32 @@ definitions: properties: address: type: string - collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. + collateral_asset: + type: string + trading_asset: + type: string + liabilities_asset: + type: string + custody_asset: + type: string + collateral: + type: string liabilities: type: string - borrow_interest_paid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - borrow_interest_paid_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - borrow_interest_unpaid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. + borrow_interest_paid_collateral: + type: string + borrow_interest_paid_custody: + type: string + borrow_interest_unpaid_collateral: + type: string + custody: + type: string take_profit_liabilities: type: string - take_profit_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - leverages: - type: array - items: - type: string + take_profit_custody: + type: string + leverage: + type: string mtp_health: type: string position: @@ -86232,76 +85276,18 @@ definitions: type: string take_profit_borrow_rate: type: string - funding_fee_paid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. + funding_fee_paid_collateral: + type: string title: funding fee paid - funding_fee_paid_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - funding_fee_received_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. + funding_fee_paid_custody: + type: string + funding_fee_received_collateral: + type: string title: funding fee received - funding_fee_received_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. + funding_fee_received_custody: + type: string + open_price: + type: string pagination: type: object properties: @@ -86338,116 +85324,32 @@ definitions: properties: address: type: string - collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. + collateral_asset: + type: string + trading_asset: + type: string + liabilities_asset: + type: string + custody_asset: + type: string + collateral: + type: string liabilities: type: string - borrow_interest_paid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - borrow_interest_paid_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - borrow_interest_unpaid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. + borrow_interest_paid_collateral: + type: string + borrow_interest_paid_custody: + type: string + borrow_interest_unpaid_collateral: + type: string + custody: + type: string take_profit_liabilities: type: string - take_profit_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - leverages: - type: array - items: - type: string + take_profit_custody: + type: string + leverage: + type: string mtp_health: type: string position: @@ -86471,76 +85373,18 @@ definitions: type: string take_profit_borrow_rate: type: string - funding_fee_paid_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. + funding_fee_paid_collateral: + type: string title: funding fee paid - funding_fee_paid_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. - funding_fee_received_collaterals: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. + funding_fee_paid_custody: + type: string + funding_fee_received_collateral: + type: string title: funding fee received - funding_fee_received_custodies: - type: array - items: - type: object - properties: - denom: - type: string - amount: - type: string - description: >- - Coin defines a token with a denomination and an amount. - - - NOTE: The amount field is an Int which implements the custom - method - - signatures required by gogoproto. + funding_fee_received_custody: + type: string + open_price: + type: string pagination: type: object properties: @@ -86721,6 +85565,82 @@ definitions: title: >- funding rate, if positive longs pay shorts, if negative shorts pay longs + elys.margin.QueryOpenEstimationResponse: + type: object + properties: + position: + type: string + enum: + - UNSPECIFIED + - LONG + - SHORT + default: UNSPECIFIED + leverage: + type: string + trading_asset: + type: string + collateral: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + min_collateral: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + valid_collateral: + type: boolean + position_size: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + swap_fee: + type: string + discount: + type: string + open_price: + type: string + take_profit_price: + type: string + liquidation_price: + type: string + estimated_pnl: + type: string + available_liquidity: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. elys.margin.StatusResponse: type: object properties: diff --git a/proto/elys/margin/params.proto b/proto/elys/margin/params.proto index e1555ed5c..805433079 100644 --- a/proto/elys/margin/params.proto +++ b/proto/elys/margin/params.proto @@ -80,4 +80,8 @@ message Params { (gogoproto.nullable) = false ]; string funding_fee_collection_address = 24; + string swap_fee = 25 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", + (gogoproto.nullable) = false + ]; } diff --git a/proto/elys/margin/query.proto b/proto/elys/margin/query.proto index d3025d681..bcbe9d3ee 100644 --- a/proto/elys/margin/query.proto +++ b/proto/elys/margin/query.proto @@ -8,6 +8,7 @@ import "cosmos/base/query/v1beta1/pagination.proto"; import "elys/margin/params.proto"; import "elys/margin/types.proto"; import "elys/margin/pool.proto"; +import "cosmos/base/v1beta1/coin.proto"; option go_package = "github.com/elys-network/elys/x/margin/types"; @@ -20,57 +21,65 @@ service Query { } - // Queries a list of GetPositions items. + // Queries a list of positions. rpc GetPositions (PositionsRequest) returns (PositionsResponse) { option (google.api.http).get = "/elys-network/elys/margin/positions/{pagination.key}"; } - // Queries a list of GetPositionsByPool items. + // Queries a list of mtp positions by pool. rpc GetPositionsByPool (PositionsByPoolRequest) returns (PositionsByPoolResponse) { option (google.api.http).get = "/elys-network/elys/margin/mtps-by-pool/{amm_pool_id}/{pagination.key}"; } - // Queries a list of GetStatus items. + // Retuns the total number of open and lifetime mtps. rpc GetStatus (StatusRequest) returns (StatusResponse) { option (google.api.http).get = "/elys-network/elys/margin/status"; } - - // Queries a list of GetPositionsForAddress items. + + // Queries a list of mtp positions for a given address. rpc GetPositionsForAddress (PositionsForAddressRequest) returns (PositionsForAddressResponse) { option (google.api.http).get = "/elys-network/elys/margin/mtps-for-address/{address}/{pagination.key}"; } - // Queries a list of GetWhitelist items. + // Queries a list of whitelisted addresses. rpc GetWhitelist (WhitelistRequest) returns (WhitelistResponse) { option (google.api.http).get = "/elys-network/elys/margin/whitelist/{pagination.key}"; } - // Queries a list of IsWhitelisted items. + // Is an address whitelisted? rpc IsWhitelisted (IsWhitelistedRequest) returns (IsWhitelistedResponse) { option (google.api.http).get = "/elys-network/elys/margin/is-whitelisted"; } - // Queries a list of Pool items. + // Queries a single pool given its index. rpc Pool (QueryGetPoolRequest) returns (QueryGetPoolResponse) { option (google.api.http).get = "/elys-network/elys/margin/pool/{index}"; } + + // Queries a list of all pools. rpc Pools (QueryAllPoolRequest) returns (QueryAllPoolResponse) { option (google.api.http).get = "/elys-network/elys/margin/pool/{pagination.key}"; } - // Queries a list of MTP items. + // Queries a single mtp position given its address and id. rpc MTP (MTPRequest) returns (MTPResponse) { option (google.api.http).get = "/elys-network/elys/margin/mtp/{address}/{id}"; } + + // Queries an estimation of a new open position details. + rpc OpenEstimation (QueryOpenEstimationRequest) returns (QueryOpenEstimationResponse) { + option (google.api.http).get = "/elys-network/elys/margin/open-estimation"; + + } } // ParamsRequest is request type for the Query/Params RPC method. message ParamsRequest {} @@ -162,3 +171,28 @@ message MTPResponse { MTP mtp = 1; } +message QueryOpenEstimationRequest { + Position position = 1; + string leverage = 2 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; + string trading_asset = 3; + cosmos.base.v1beta1.Coin collateral = 4 [(gogoproto.nullable) = false ] ; + string discount = 5 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; + string take_profit_price = 6 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; +} + +message QueryOpenEstimationResponse { + Position position = 1; + string leverage = 2 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; + string trading_asset = 3; + cosmos.base.v1beta1.Coin collateral = 4 [(gogoproto.nullable) = false ] ; + cosmos.base.v1beta1.Coin min_collateral = 5 [(gogoproto.nullable) = false ] ; + bool valid_collateral = 6; + cosmos.base.v1beta1.Coin position_size = 7 [(gogoproto.nullable) = false ] ; + string swap_fee = 8 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; + string discount = 9 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; + string open_price = 10 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; + string take_profit_price = 11 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; + string liquidation_price = 12 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; + string estimated_pnl = 13 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", (gogoproto.nullable) = false]; + cosmos.base.v1beta1.Coin available_liquidity = 14 [(gogoproto.nullable) = false ] ; +} diff --git a/proto/elys/margin/tx.proto b/proto/elys/margin/tx.proto index 59ce0c6d2..1265c71a2 100644 --- a/proto/elys/margin/tx.proto +++ b/proto/elys/margin/tx.proto @@ -20,12 +20,11 @@ service Msg { } message MsgOpen { string creator = 1; - string collateral_asset = 2; - string collateral_amount = 3 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", (gogoproto.nullable) = false]; - string borrow_asset = 4; - Position position = 5; - string leverage = 6 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; - string take_profit_price = 7 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; + Position position = 2; + string leverage = 3 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; + string trading_asset = 4; + cosmos.base.v1beta1.Coin collateral = 5 [(gogoproto.nullable) = false ] ; + string take_profit_price = 6 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; } message MsgOpenResponse { @@ -35,14 +34,16 @@ message MsgOpenResponse { message MsgClose { string creator = 1; uint64 id = 2; - cosmos.base.v1beta1.Coin amount = 3 [ + string amount = 3 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", (gogoproto.nullable) = false ]; } message MsgCloseResponse { uint64 id = 1; - cosmos.base.v1beta1.Coin amount = 2 [ + string amount = 2 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", (gogoproto.nullable) = false ]; } diff --git a/proto/elys/margin/types.proto b/proto/elys/margin/types.proto index b2187efc8..2db3bc49b 100644 --- a/proto/elys/margin/types.proto +++ b/proto/elys/margin/types.proto @@ -5,7 +5,6 @@ package elys.margin; option go_package = "github.com/elys-network/elys/x/margin/types"; import "gogoproto/gogo.proto"; -import "cosmos/base/v1beta1/coin.proto"; enum Position { UNSPECIFIED = 0; @@ -15,71 +14,89 @@ enum Position { message MTP { string address = 1; - repeated cosmos.base.v1beta1.Coin collaterals = 2 [ + string collateral_asset = 2; + string trading_asset = 3; + string liabilities_asset = 4; + string custody_asset = 5; + string collateral = 6 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", (gogoproto.nullable) = false ]; - string liabilities = 3 [ + string liabilities = 7 [ (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", (gogoproto.nullable) = false ]; - repeated cosmos.base.v1beta1.Coin borrow_interest_paid_collaterals = 4 [ + string borrow_interest_paid_collateral = 8 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", (gogoproto.nullable) = false ]; - repeated cosmos.base.v1beta1.Coin borrow_interest_paid_custodies = 5 [ + string borrow_interest_paid_custody = 9 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", (gogoproto.nullable) = false ]; - repeated cosmos.base.v1beta1.Coin borrow_interest_unpaid_collaterals = 6 [ + string borrow_interest_unpaid_collateral = 10 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", (gogoproto.nullable) = false ]; - repeated cosmos.base.v1beta1.Coin custodies = 7 [ + string custody = 11 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", (gogoproto.nullable) = false ]; - string take_profit_liabilities = 8 [ + string take_profit_liabilities = 12 [ (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", (gogoproto.nullable) = false ]; - repeated cosmos.base.v1beta1.Coin take_profit_custodies = 9 [ + string take_profit_custody = 13 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", (gogoproto.nullable) = false ]; - repeated string leverages = 10 [ + string leverage = 14 [ (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false ]; - string mtp_health = 11 [ + string mtp_health = 15 [ (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false ]; - Position position = 12; - uint64 id = 13; - uint64 amm_pool_id = 14; - string consolidate_leverage = 15 [ + Position position = 16; + uint64 id = 17; + uint64 amm_pool_id = 18; + string consolidate_leverage = 19 [ (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false ]; - string sum_collateral = 16 [ + string sum_collateral = 20 [ (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", (gogoproto.nullable) = false ]; - string take_profit_price = 17 [ + string take_profit_price = 21 [ (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false ]; - string take_profit_borrow_rate = 18 [ + string take_profit_borrow_rate = 22 [ (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false ]; // funding fee paid - repeated cosmos.base.v1beta1.Coin funding_fee_paid_collaterals = 19 [ + string funding_fee_paid_collateral = 23 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", (gogoproto.nullable) = false ]; - repeated cosmos.base.v1beta1.Coin funding_fee_paid_custodies = 20 [ + string funding_fee_paid_custody = 24 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", (gogoproto.nullable) = false ]; // funding fee received - repeated cosmos.base.v1beta1.Coin funding_fee_received_collaterals = 21 [ + string funding_fee_received_collateral = 25 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", + (gogoproto.nullable) = false + ]; + string funding_fee_received_custody = 26 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", (gogoproto.nullable) = false ]; - repeated cosmos.base.v1beta1.Coin funding_fee_received_custodies = 22 [ + string open_price = 27 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false ]; } diff --git a/wasmbindings/types/types.go b/wasmbindings/types/types.go index e13ecb953..c85d9d4ed 100644 --- a/wasmbindings/types/types.go +++ b/wasmbindings/types/types.go @@ -179,6 +179,7 @@ type ElysQuery struct { MarginPool *margintypes.QueryGetPoolRequest `json:"margin_pool,omitempty"` MarginPools *margintypes.QueryAllPoolRequest `json:"margin_pools,omitempty"` MarginMTP *margintypes.MTPRequest `json:"margin_mtp,omitempty"` + MarginOpenEstimation *margintypes.QueryOpenEstimationRequest `json:"margin_open_estimation,omitempty"` // oracle queriers OracleParams *oracletypes.QueryParamsRequest `json:"oracle_params,omitempty"` diff --git a/x/amm/client/wasm/query_amm_price_by_denom.go b/x/amm/client/wasm/query_amm_price_by_denom.go index 5314e7582..c42614adb 100644 --- a/x/amm/client/wasm/query_amm_price_by_denom.go +++ b/x/amm/client/wasm/query_amm_price_by_denom.go @@ -38,7 +38,7 @@ func (oq *Querier) queryAmmPriceByDenom(ctx sdk.Context, query *ammtypes.QueryAM tokenIn := query.TokenIn discount := query.Discount - spotPrice, _, _, _, _, err := oq.keeper.CalcInRouteSpotPrice(ctx, tokenIn, routes, discount) + spotPrice, _, _, _, _, err := oq.keeper.CalcInRouteSpotPrice(ctx, tokenIn, routes, discount, sdk.ZeroDec()) if err != nil { return nil, errorsmod.Wrap(err, "failed to get in route by denom") } diff --git a/x/amm/keeper/apply_discount_test.go b/x/amm/keeper/apply_discount_test.go deleted file mode 100644 index 8e1e0ea31..000000000 --- a/x/amm/keeper/apply_discount_test.go +++ /dev/null @@ -1,60 +0,0 @@ -package keeper_test - -import ( - "github.com/cosmos/cosmos-sdk/types" - "github.com/elys-network/elys/x/amm/keeper" -) - -func (suite *KeeperTestSuite) TestApplyDiscount() { - // Define test cases - tests := []struct { - name string - swapFee types.Dec - discount types.Dec - wantFee types.Dec - }{ - { - name: "Zero discount", - swapFee: types.NewDecWithPrec(100, 2), // 1.00 as an example - discount: types.ZeroDec(), - wantFee: types.NewDecWithPrec(100, 2), - }, - { - name: "Positive discount with valid broker address", - swapFee: types.NewDecWithPrec(100, 2), - discount: types.NewDecWithPrec(10, 2), // 0.10 (10%) - wantFee: types.NewDecWithPrec(90, 2), // 0.90 after discount - }, - { - name: "Boundary value for discount", - swapFee: types.NewDecWithPrec(100, 2), - discount: types.NewDecWithPrec(9999, 4), // 0.9999 (99.99%) - wantFee: types.NewDecWithPrec(1, 4), // 0.01 after discount - }, - { - name: "Discount greater than swap fee", - swapFee: types.NewDecWithPrec(50, 2), // 0.50 - discount: types.NewDecWithPrec(75, 2), // 0.75 - wantFee: types.NewDecWithPrec(125, 3), - }, - { - name: "Zero swap fee with valid discount", - swapFee: types.ZeroDec(), - discount: types.NewDecWithPrec(10, 2), - wantFee: types.ZeroDec(), - }, - { - name: "Large discount with valid broker address", - swapFee: types.NewDecWithPrec(100, 2), - discount: types.NewDecWithPrec(9000, 4), // 0.90 (90%) - wantFee: types.NewDecWithPrec(10, 2), // 0.10 after discount - }, - } - - for _, tc := range tests { - suite.Run(tc.name, func() { - fee := keeper.ApplyDiscount(tc.swapFee, tc.discount) - suite.Require().Equal(tc.wantFee, fee) - }) - } -} diff --git a/x/amm/keeper/calc_in_route_spot_price.go b/x/amm/keeper/calc_in_route_spot_price.go index 21a023aa8..9ed73a568 100644 --- a/x/amm/keeper/calc_in_route_spot_price.go +++ b/x/amm/keeper/calc_in_route_spot_price.go @@ -6,7 +6,7 @@ import ( ) // CalcInRouteSpotPrice calculates the spot price of the given token and in route -func (k Keeper) CalcInRouteSpotPrice(ctx sdk.Context, tokenIn sdk.Coin, routes []*types.SwapAmountInRoute, discount sdk.Dec) (sdk.Dec, sdk.Coin, sdk.Dec, sdk.Dec, sdk.Coin, error) { +func (k Keeper) CalcInRouteSpotPrice(ctx sdk.Context, tokenIn sdk.Coin, routes []*types.SwapAmountInRoute, discount sdk.Dec, overrideSwapFee sdk.Dec) (sdk.Dec, sdk.Coin, sdk.Dec, sdk.Dec, sdk.Coin, error) { if routes == nil || len(routes) == 0 { return sdk.ZeroDec(), sdk.Coin{}, sdk.ZeroDec(), sdk.ZeroDec(), sdk.Coin{}, types.ErrEmptyRoutes } @@ -35,8 +35,13 @@ func (k Keeper) CalcInRouteSpotPrice(ctx sdk.Context, tokenIn sdk.Coin, routes [ // Get Pool swap fee swapFee := pool.GetPoolParams().SwapFee + // Override swap fee if applicable + if overrideSwapFee.IsPositive() { + swapFee = overrideSwapFee + } + // Apply discount to swap fee - swapFee = ApplyDiscount(swapFee, discount) + swapFee = types.ApplyDiscount(swapFee, discount) // Calculate the total discounted swap fee totalDiscountedSwapFee = totalDiscountedSwapFee.Add(swapFee) diff --git a/x/amm/keeper/calc_in_route_spot_price_test.go b/x/amm/keeper/calc_in_route_spot_price_test.go index e0be32dd8..1ab5e85d5 100644 --- a/x/amm/keeper/calc_in_route_spot_price_test.go +++ b/x/amm/keeper/calc_in_route_spot_price_test.go @@ -20,7 +20,7 @@ func TestCalcInRouteSpotPrice(t *testing.T) { accountedPoolKeeper.On("GetAccountedBalance", ctx, uint64(1), "denom1").Return(sdk.NewInt(1000)) accountedPoolKeeper.On("GetAccountedBalance", ctx, uint64(1), "denom2").Return(sdk.NewInt(1000)) routes := []*types.SwapAmountInRoute{{PoolId: 1, TokenOutDenom: "denom2"}} - spotPrice, _, _, _, _, err := k.CalcInRouteSpotPrice(ctx, tokenIn, routes, sdk.ZeroDec()) + spotPrice, _, _, _, _, err := k.CalcInRouteSpotPrice(ctx, tokenIn, routes, sdk.ZeroDec(), sdk.ZeroDec()) require.NoError(t, err) require.NotZero(t, spotPrice) accountedPoolKeeper.AssertExpectations(t) @@ -34,17 +34,17 @@ func TestCalcInRouteSpotPrice(t *testing.T) { {PoolId: 2, TokenOutDenom: "baseCurrency"}, {PoolId: 3, TokenOutDenom: "denom3"}, } - spotPrice, _, _, _, _, err = k.CalcInRouteSpotPrice(ctx, tokenIn, routes, sdk.ZeroDec()) + spotPrice, _, _, _, _, err = k.CalcInRouteSpotPrice(ctx, tokenIn, routes, sdk.ZeroDec(), sdk.ZeroDec()) require.NoError(t, err) require.NotZero(t, spotPrice) accountedPoolKeeper.AssertExpectations(t) // Test no routes - _, _, _, _, _, err = k.CalcInRouteSpotPrice(ctx, tokenIn, nil, sdk.ZeroDec()) + _, _, _, _, _, err = k.CalcInRouteSpotPrice(ctx, tokenIn, nil, sdk.ZeroDec(), sdk.ZeroDec()) require.Error(t, err) // Test invalid pool routes = []*types.SwapAmountInRoute{{PoolId: 9999, TokenOutDenom: "denom2"}} - _, _, _, _, _, err = k.CalcInRouteSpotPrice(ctx, tokenIn, routes, sdk.ZeroDec()) + _, _, _, _, _, err = k.CalcInRouteSpotPrice(ctx, tokenIn, routes, sdk.ZeroDec(), sdk.ZeroDec()) require.Error(t, err) } diff --git a/x/amm/keeper/calc_out_route_spot_price.go b/x/amm/keeper/calc_out_route_spot_price.go index 30dc42c1d..7deb55809 100644 --- a/x/amm/keeper/calc_out_route_spot_price.go +++ b/x/amm/keeper/calc_out_route_spot_price.go @@ -6,7 +6,7 @@ import ( ) // CalcOutRouteSpotPrice calculates the spot price of the given token and out route -func (k Keeper) CalcOutRouteSpotPrice(ctx sdk.Context, tokenOut sdk.Coin, routes []*types.SwapAmountOutRoute, discount sdk.Dec) (sdk.Dec, sdk.Coin, sdk.Dec, sdk.Dec, sdk.Coin, error) { +func (k Keeper) CalcOutRouteSpotPrice(ctx sdk.Context, tokenOut sdk.Coin, routes []*types.SwapAmountOutRoute, discount sdk.Dec, overrideSwapFee sdk.Dec) (sdk.Dec, sdk.Coin, sdk.Dec, sdk.Dec, sdk.Coin, error) { if routes == nil || len(routes) == 0 { return sdk.ZeroDec(), sdk.Coin{}, sdk.ZeroDec(), sdk.ZeroDec(), sdk.Coin{}, types.ErrEmptyRoutes } @@ -35,8 +35,13 @@ func (k Keeper) CalcOutRouteSpotPrice(ctx sdk.Context, tokenOut sdk.Coin, routes // Get Pool swap fee swapFee := pool.GetPoolParams().SwapFee + // Override swap fee if applicable + if overrideSwapFee.IsPositive() { + swapFee = overrideSwapFee + } + // Apply discount - swapFee = ApplyDiscount(swapFee, discount) + swapFee = types.ApplyDiscount(swapFee, discount) // Calculate the total discounted swap fee totalDiscountedSwapFee = totalDiscountedSwapFee.Add(swapFee) diff --git a/x/amm/keeper/calc_out_route_spot_price_test.go b/x/amm/keeper/calc_out_route_spot_price_test.go index b72e85777..00c4d2a5f 100644 --- a/x/amm/keeper/calc_out_route_spot_price_test.go +++ b/x/amm/keeper/calc_out_route_spot_price_test.go @@ -18,7 +18,7 @@ func TestCalcOutRouteSpotPrice(t *testing.T) { accountedPoolKeeper.On("GetAccountedBalance", ctx, uint64(1), "denom2").Return(sdk.NewInt(1000)) accountedPoolKeeper.On("GetAccountedBalance", ctx, uint64(1), "denom1").Return(sdk.NewInt(1000)) routes := []*types.SwapAmountOutRoute{{PoolId: 1, TokenInDenom: "denom1"}} - spotPrice, _, _, _, _, err := k.CalcOutRouteSpotPrice(ctx, tokenOut, routes, sdk.ZeroDec()) + spotPrice, _, _, _, _, err := k.CalcOutRouteSpotPrice(ctx, tokenOut, routes, sdk.ZeroDec(), sdk.ZeroDec()) require.NoError(t, err) require.NotZero(t, spotPrice) accountedPoolKeeper.AssertExpectations(t) @@ -33,17 +33,17 @@ func TestCalcOutRouteSpotPrice(t *testing.T) { {PoolId: 3, TokenInDenom: "baseCurrency"}, {PoolId: 2, TokenInDenom: "denom1"}, } - spotPrice, _, _, _, _, err = k.CalcOutRouteSpotPrice(ctx, tokenOut, routes, sdk.ZeroDec()) + spotPrice, _, _, _, _, err = k.CalcOutRouteSpotPrice(ctx, tokenOut, routes, sdk.ZeroDec(), sdk.ZeroDec()) require.NoError(t, err) require.NotZero(t, spotPrice) accountedPoolKeeper.AssertExpectations(t) // Test no routes - _, _, _, _, _, err = k.CalcOutRouteSpotPrice(ctx, tokenOut, nil, sdk.ZeroDec()) + _, _, _, _, _, err = k.CalcOutRouteSpotPrice(ctx, tokenOut, nil, sdk.ZeroDec(), sdk.ZeroDec()) require.Error(t, err) // Test invalid pool routes = []*types.SwapAmountOutRoute{{PoolId: 9999, TokenInDenom: "denom2"}} - _, _, _, _, _, err = k.CalcOutRouteSpotPrice(ctx, tokenOut, routes, sdk.ZeroDec()) + _, _, _, _, _, err = k.CalcOutRouteSpotPrice(ctx, tokenOut, routes, sdk.ZeroDec(), sdk.ZeroDec()) require.Error(t, err) } diff --git a/x/amm/keeper/calc_swap_estimation_by_denom.go b/x/amm/keeper/calc_swap_estimation_by_denom.go index 8b21f01d5..582daad62 100644 --- a/x/amm/keeper/calc_swap_estimation_by_denom.go +++ b/x/amm/keeper/calc_swap_estimation_by_denom.go @@ -13,12 +13,13 @@ func (k Keeper) CalcSwapEstimationByDenom( denomOut string, baseCurrency string, discount sdk.Dec, + overrideSwapFee sdk.Dec, ) ( inRoute []*types.SwapAmountInRoute, outRoute []*types.SwapAmountOutRoute, outAmount sdk.Coin, spotPrice sdk.Dec, - swapFee sdk.Dec, + swapFeeOut sdk.Dec, discountOut sdk.Dec, availableLiquidity sdk.Coin, err error, @@ -29,11 +30,11 @@ func (k Keeper) CalcSwapEstimationByDenom( if err != nil { return nil, nil, sdk.Coin{}, sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec(), sdk.Coin{}, err } - spotPrice, tokenOut, swapFee, _, availableLiquidity, err := k.CalcInRouteSpotPrice(ctx, amount, inRoute, discount) + spotPrice, tokenOut, swapFeeOut, _, availableLiquidity, err := k.CalcInRouteSpotPrice(ctx, amount, inRoute, discount, overrideSwapFee) if err != nil { return nil, nil, sdk.Coin{}, sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec(), sdk.Coin{}, err } - return inRoute, nil, tokenOut, spotPrice, swapFee, discount, availableLiquidity, nil + return inRoute, nil, tokenOut, spotPrice, swapFeeOut, discount, availableLiquidity, nil } // if amount denom is equal to denomOut, calculate swap estimation by denomOut @@ -42,11 +43,11 @@ func (k Keeper) CalcSwapEstimationByDenom( if err != nil { return nil, nil, sdk.Coin{}, sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec(), sdk.Coin{}, err } - spotPrice, tokenIn, swapFee, _, availableLiquidity, err := k.CalcOutRouteSpotPrice(ctx, amount, outRoute, discount) + spotPrice, tokenIn, swapFeeOut, _, availableLiquidity, err := k.CalcOutRouteSpotPrice(ctx, amount, outRoute, discount, overrideSwapFee) if err != nil { return nil, nil, sdk.Coin{}, sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec(), sdk.Coin{}, err } - return nil, outRoute, tokenIn, spotPrice, swapFee, discount, availableLiquidity, nil + return nil, outRoute, tokenIn, spotPrice, swapFeeOut, discount, availableLiquidity, nil } // if amount denom is neither equal to denomIn nor denomOut, return error diff --git a/x/amm/keeper/calc_swap_estimation_by_denom_test.go b/x/amm/keeper/calc_swap_estimation_by_denom_test.go index 885486ad1..0825e9fa9 100644 --- a/x/amm/keeper/calc_swap_estimation_by_denom_test.go +++ b/x/amm/keeper/calc_swap_estimation_by_denom_test.go @@ -16,7 +16,7 @@ func TestCalcSwapEstimationByDenom(t *testing.T) { amount := sdk.NewCoin("denom1", sdk.NewInt(100)) accountedPoolKeeper.On("GetAccountedBalance", ctx, uint64(1), "denom1").Return(sdk.NewInt(1000)) accountedPoolKeeper.On("GetAccountedBalance", ctx, uint64(1), "denom2").Return(sdk.NewInt(1000)) - inRoute, outRoute, tokenOut, spotPrice, _, _, _, err := k.CalcSwapEstimationByDenom(ctx, amount, "denom1", "denom2", "baseCurrency", sdk.ZeroDec()) + inRoute, outRoute, tokenOut, spotPrice, _, _, _, err := k.CalcSwapEstimationByDenom(ctx, amount, "denom1", "denom2", "baseCurrency", sdk.ZeroDec(), sdk.ZeroDec()) require.NoError(t, err) require.NotNil(t, inRoute) require.Nil(t, outRoute) @@ -27,7 +27,7 @@ func TestCalcSwapEstimationByDenom(t *testing.T) { amount = sdk.NewCoin("denom2", sdk.NewInt(100)) accountedPoolKeeper.On("GetAccountedBalance", ctx, uint64(1), "denom2").Return(sdk.NewInt(1000)) accountedPoolKeeper.On("GetAccountedBalance", ctx, uint64(1), "denom1").Return(sdk.NewInt(1000)) - inRoute, outRoute, tokenOut, spotPrice, _, _, _, err = k.CalcSwapEstimationByDenom(ctx, amount, "denom1", "denom2", "baseCurrency", sdk.ZeroDec()) + inRoute, outRoute, tokenOut, spotPrice, _, _, _, err = k.CalcSwapEstimationByDenom(ctx, amount, "denom1", "denom2", "baseCurrency", sdk.ZeroDec(), sdk.ZeroDec()) require.NoError(t, err) require.Nil(t, inRoute) require.NotNil(t, outRoute) @@ -36,6 +36,6 @@ func TestCalcSwapEstimationByDenom(t *testing.T) { // Test with invalid amount denom amount = sdk.NewCoin("invalid", sdk.NewInt(1000)) - _, _, _, _, _, _, _, err = k.CalcSwapEstimationByDenom(ctx, amount, "denom1", "denom2", "baseCurrency", sdk.ZeroDec()) + _, _, _, _, _, _, _, err = k.CalcSwapEstimationByDenom(ctx, amount, "denom1", "denom2", "baseCurrency", sdk.ZeroDec(), sdk.ZeroDec()) require.Error(t, err) } diff --git a/x/amm/keeper/msg_server_swap_by_denom.go b/x/amm/keeper/msg_server_swap_by_denom.go index bfb595a18..d042b27b8 100644 --- a/x/amm/keeper/msg_server_swap_by_denom.go +++ b/x/amm/keeper/msg_server_swap_by_denom.go @@ -24,7 +24,7 @@ func (k msgServer) SwapByDenom(goCtx context.Context, msg *types.MsgSwapByDenom) } baseCurrency := entry.Denom - inRoute, outRoute, _, spotPrice, _, _, _, err := k.CalcSwapEstimationByDenom(ctx, msg.Amount, msg.DenomIn, msg.DenomOut, baseCurrency, msg.Discount) + inRoute, outRoute, _, spotPrice, _, _, _, err := k.CalcSwapEstimationByDenom(ctx, msg.Amount, msg.DenomIn, msg.DenomOut, baseCurrency, msg.Discount, sdk.ZeroDec()) if err != nil { return nil, err } diff --git a/x/amm/keeper/query_swap_estimation.go b/x/amm/keeper/query_swap_estimation.go index 5737e5ce7..d21aba4ea 100644 --- a/x/amm/keeper/query_swap_estimation.go +++ b/x/amm/keeper/query_swap_estimation.go @@ -16,7 +16,7 @@ func (k Keeper) SwapEstimation(goCtx context.Context, req *types.QuerySwapEstima ctx := sdk.UnwrapSDKContext(goCtx) - spotPrice, tokenOut, swapFee, discount, availableLiquidity, err := k.CalcInRouteSpotPrice(ctx, req.TokenIn, req.Routes, req.Discount) + spotPrice, tokenOut, swapFee, discount, availableLiquidity, err := k.CalcInRouteSpotPrice(ctx, req.TokenIn, req.Routes, req.Discount, sdk.ZeroDec()) if err != nil { return nil, err } diff --git a/x/amm/keeper/query_swap_estimation_by_denom.go b/x/amm/keeper/query_swap_estimation_by_denom.go index 7b4600e5b..0def6ddf5 100644 --- a/x/amm/keeper/query_swap_estimation_by_denom.go +++ b/x/amm/keeper/query_swap_estimation_by_denom.go @@ -27,7 +27,7 @@ func (k Keeper) SwapEstimationByDenom(goCtx context.Context, req *types.QuerySwa _ = baseCurrency - inRoute, outRoute, amount, spotPrice, swapFee, discount, availableLiquidity, err := k.CalcSwapEstimationByDenom(ctx, req.Amount, req.DenomIn, req.DenomOut, baseCurrency, req.Discount) + inRoute, outRoute, amount, spotPrice, swapFee, discount, availableLiquidity, err := k.CalcSwapEstimationByDenom(ctx, req.Amount, req.DenomIn, req.DenomOut, baseCurrency, req.Discount, sdk.ZeroDec()) if err != nil { return nil, err } diff --git a/x/amm/keeper/route_exact_amount_in.go b/x/amm/keeper/route_exact_amount_in.go index cff9feaf9..5d17a2dc4 100644 --- a/x/amm/keeper/route_exact_amount_in.go +++ b/x/amm/keeper/route_exact_amount_in.go @@ -81,7 +81,7 @@ func (k Keeper) RouteExactAmountIn( if discount.IsPositive() && sender.String() != brokerAddress { return math.Int{}, sdk.ZeroDec(), sdk.ZeroDec(), sdkerrors.Wrapf(types.ErrInvalidDiscount, "discount %s is positive and signer address %s is not broker address %s", discount, sender, brokerAddress) } - swapFee = ApplyDiscount(swapFee, discount) + swapFee = types.ApplyDiscount(swapFee, discount) // Calculate the total discounted swap fee totalDiscountedSwapFee = totalDiscountedSwapFee.Add(swapFee) diff --git a/x/amm/keeper/route_exact_amount_out.go b/x/amm/keeper/route_exact_amount_out.go index 29937e444..dd6071f61 100644 --- a/x/amm/keeper/route_exact_amount_out.go +++ b/x/amm/keeper/route_exact_amount_out.go @@ -107,7 +107,7 @@ func (k Keeper) RouteExactAmountOut(ctx sdk.Context, if discount.IsPositive() && sender.String() != brokerAddress { return math.Int{}, sdk.ZeroDec(), sdk.ZeroDec(), sdkerrors.Wrapf(types.ErrInvalidDiscount, "discount %s is positive and signer address %s is not broker address %s", discount, sender, brokerAddress) } - swapFee = ApplyDiscount(swapFee, discount) + swapFee = types.ApplyDiscount(swapFee, discount) // Calculate the total discounted swap fee totalDiscountedSwapFee = totalDiscountedSwapFee.Add(swapFee) diff --git a/x/amm/keeper/apply_discount.go b/x/amm/types/apply_discount.go similarity index 95% rename from x/amm/keeper/apply_discount.go rename to x/amm/types/apply_discount.go index 2c64a039a..ba05e3178 100644 --- a/x/amm/keeper/apply_discount.go +++ b/x/amm/types/apply_discount.go @@ -1,4 +1,4 @@ -package keeper +package types import ( sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/amm/types/apply_discount_test.go b/x/amm/types/apply_discount_test.go new file mode 100644 index 000000000..922c19e12 --- /dev/null +++ b/x/amm/types/apply_discount_test.go @@ -0,0 +1,63 @@ +package types_test + +import ( + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/elys-network/elys/x/amm/types" + "github.com/stretchr/testify/require" +) + +func TestApplyDiscount(t *testing.T) { + // Define test cases + tests := []struct { + name string + swapFee sdk.Dec + discount sdk.Dec + wantFee sdk.Dec + }{ + { + name: "Zero discount", + swapFee: sdk.NewDecWithPrec(100, 2), // 1.00 as an example + discount: sdk.ZeroDec(), + wantFee: sdk.NewDecWithPrec(100, 2), + }, + { + name: "Positive discount with valid broker address", + swapFee: sdk.NewDecWithPrec(100, 2), + discount: sdk.NewDecWithPrec(10, 2), // 0.10 (10%) + wantFee: sdk.NewDecWithPrec(90, 2), // 0.90 after discount + }, + { + name: "Boundary value for discount", + swapFee: sdk.NewDecWithPrec(100, 2), + discount: sdk.NewDecWithPrec(9999, 4), // 0.9999 (99.99%) + wantFee: sdk.NewDecWithPrec(1, 4), // 0.01 after discount + }, + { + name: "Discount greater than swap fee", + swapFee: sdk.NewDecWithPrec(50, 2), // 0.50 + discount: sdk.NewDecWithPrec(75, 2), // 0.75 + wantFee: sdk.NewDecWithPrec(125, 3), + }, + { + name: "Zero swap fee with valid discount", + swapFee: sdk.ZeroDec(), + discount: sdk.NewDecWithPrec(10, 2), + wantFee: sdk.ZeroDec(), + }, + { + name: "Large discount with valid broker address", + swapFee: sdk.NewDecWithPrec(100, 2), + discount: sdk.NewDecWithPrec(9000, 4), // 0.90 (90%) + wantFee: sdk.NewDecWithPrec(10, 2), // 0.10 after discount + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + fee := types.ApplyDiscount(tc.swapFee, tc.discount) + require.Equal(t, tc.wantFee, fee) + }) + } +} diff --git a/x/amm/types/calc_in_amt_given_out.go b/x/amm/types/calc_in_amt_given_out.go index d891c5178..0bb5267f0 100644 --- a/x/amm/types/calc_in_amt_given_out.go +++ b/x/amm/types/calc_in_amt_given_out.go @@ -35,14 +35,14 @@ func (p Pool) CalcInAmtGivenOut( poolTokenOutBalance := sdk.NewDecFromInt(poolAssetOut.Token.Amount) // accounted pool balance acountedPoolAssetOutAmt := accountedPool.GetAccountedBalance(ctx, p.PoolId, poolAssetOut.Token.Denom) - if acountedPoolAssetOutAmt.GT(sdk.ZeroInt()) { + if acountedPoolAssetOutAmt.IsPositive() { poolTokenOutBalance = sdk.NewDecFromInt(acountedPoolAssetOutAmt) } poolTokenInBalance := sdk.NewDecFromInt(poolAssetIn.Token.Amount) // accounted pool balance acountedPoolAssetInAmt := accountedPool.GetAccountedBalance(ctx, p.PoolId, poolAssetIn.Token.Denom) - if acountedPoolAssetInAmt.GT(sdk.ZeroInt()) { + if acountedPoolAssetInAmt.IsPositive() { poolTokenInBalance = sdk.NewDecFromInt(acountedPoolAssetInAmt) } diff --git a/x/amm/types/calc_out_amt_given_in.go b/x/amm/types/calc_out_amt_given_in.go index 0423b7d29..d8121f478 100644 --- a/x/amm/types/calc_out_amt_given_in.go +++ b/x/amm/types/calc_out_amt_given_in.go @@ -25,14 +25,14 @@ func (p Pool) CalcOutAmtGivenIn( poolTokenInBalance := sdk.NewDecFromInt(poolAssetIn.Token.Amount) // accounted pool balance acountedPoolAssetInAmt := accountedPool.GetAccountedBalance(ctx, p.PoolId, poolAssetIn.Token.Denom) - if acountedPoolAssetInAmt.GT(sdk.ZeroInt()) { + if acountedPoolAssetInAmt.IsPositive() { poolTokenInBalance = sdk.NewDecFromInt(acountedPoolAssetInAmt) } poolTokenOutBalance := sdk.NewDecFromInt(poolAssetOut.Token.Amount) // accounted pool balance acountedPoolAssetOutAmt := accountedPool.GetAccountedBalance(ctx, p.PoolId, poolAssetOut.Token.Denom) - if acountedPoolAssetOutAmt.GT(sdk.ZeroInt()) { + if acountedPoolAssetOutAmt.IsPositive() { poolTokenOutBalance = sdk.NewDecFromInt(acountedPoolAssetOutAmt) } diff --git a/x/amm/types/query.pb.gw.go b/x/amm/types/query.pb.gw.go index 3d2479816..389049bcc 100644 --- a/x/amm/types/query.pb.gw.go +++ b/x/amm/types/query.pb.gw.go @@ -20,6 +20,7 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) @@ -30,6 +31,7 @@ var _ status.Status var _ = runtime.String var _ = utilities.NewDoubleArray var _ = descriptor.ForMessage +var _ = metadata.Join func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq QueryParamsRequest @@ -604,12 +606,14 @@ func local_request_Query_SwapEstimationByDenom_0(ctx context.Context, marshaler // 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 (such as grpc.SendHeader, etc) to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. +// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { @@ -617,6 +621,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv 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) @@ -630,6 +635,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_Pool_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 { @@ -637,6 +644,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_Pool_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) @@ -650,6 +658,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_PoolAll_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 { @@ -657,6 +667,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_PoolAll_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) @@ -670,6 +681,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_DenomLiquidity_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 { @@ -677,6 +690,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_DenomLiquidity_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) @@ -690,6 +704,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_DenomLiquidityAll_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 { @@ -697,6 +713,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_DenomLiquidityAll_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) @@ -710,6 +727,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_SwapEstimation_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 { @@ -717,6 +736,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_SwapEstimation_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) @@ -730,6 +750,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_SlippageTrack_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 { @@ -737,6 +759,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_SlippageTrack_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) @@ -750,6 +773,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_SlippageTrackAll_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 { @@ -757,6 +782,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_SlippageTrackAll_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) @@ -770,6 +796,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_Balance_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 { @@ -777,6 +805,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_Balance_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) @@ -790,6 +819,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_InRouteByDenom_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 { @@ -797,6 +828,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_InRouteByDenom_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) @@ -810,6 +842,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_OutRouteByDenom_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 { @@ -817,6 +851,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_OutRouteByDenom_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) @@ -830,6 +865,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_SwapEstimationByDenom_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 { @@ -837,6 +874,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_SwapEstimationByDenom_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) diff --git a/x/leveragelp/types/mocks/bank_keeper.go b/x/leveragelp/types/mocks/bank_keeper.go new file mode 100644 index 000000000..03d64abb9 --- /dev/null +++ b/x/leveragelp/types/mocks/bank_keeper.go @@ -0,0 +1,435 @@ +// Code generated by mockery v2.32.4. DO NOT EDIT. + +package mocks + +import ( + types "github.com/cosmos/cosmos-sdk/types" + mock "github.com/stretchr/testify/mock" +) + +// BankKeeper is an autogenerated mock type for the BankKeeper type +type BankKeeper struct { + mock.Mock +} + +type BankKeeper_Expecter struct { + mock *mock.Mock +} + +func (_m *BankKeeper) EXPECT() *BankKeeper_Expecter { + return &BankKeeper_Expecter{mock: &_m.Mock} +} + +// BlockedAddr provides a mock function with given fields: addr +func (_m *BankKeeper) BlockedAddr(addr types.AccAddress) bool { + ret := _m.Called(addr) + + var r0 bool + if rf, ok := ret.Get(0).(func(types.AccAddress) bool); ok { + r0 = rf(addr) + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// BankKeeper_BlockedAddr_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockedAddr' +type BankKeeper_BlockedAddr_Call struct { + *mock.Call +} + +// BlockedAddr is a helper method to define mock.On call +// - addr types.AccAddress +func (_e *BankKeeper_Expecter) BlockedAddr(addr interface{}) *BankKeeper_BlockedAddr_Call { + return &BankKeeper_BlockedAddr_Call{Call: _e.mock.On("BlockedAddr", addr)} +} + +func (_c *BankKeeper_BlockedAddr_Call) Run(run func(addr types.AccAddress)) *BankKeeper_BlockedAddr_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.AccAddress)) + }) + return _c +} + +func (_c *BankKeeper_BlockedAddr_Call) Return(_a0 bool) *BankKeeper_BlockedAddr_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *BankKeeper_BlockedAddr_Call) RunAndReturn(run func(types.AccAddress) bool) *BankKeeper_BlockedAddr_Call { + _c.Call.Return(run) + return _c +} + +// GetAllBalances provides a mock function with given fields: ctx, addr +func (_m *BankKeeper) GetAllBalances(ctx types.Context, addr types.AccAddress) types.Coins { + ret := _m.Called(ctx, addr) + + var r0 types.Coins + if rf, ok := ret.Get(0).(func(types.Context, types.AccAddress) types.Coins); ok { + r0 = rf(ctx, addr) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(types.Coins) + } + } + + return r0 +} + +// BankKeeper_GetAllBalances_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAllBalances' +type BankKeeper_GetAllBalances_Call struct { + *mock.Call +} + +// GetAllBalances is a helper method to define mock.On call +// - ctx types.Context +// - addr types.AccAddress +func (_e *BankKeeper_Expecter) GetAllBalances(ctx interface{}, addr interface{}) *BankKeeper_GetAllBalances_Call { + return &BankKeeper_GetAllBalances_Call{Call: _e.mock.On("GetAllBalances", ctx, addr)} +} + +func (_c *BankKeeper_GetAllBalances_Call) Run(run func(ctx types.Context, addr types.AccAddress)) *BankKeeper_GetAllBalances_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(types.AccAddress)) + }) + return _c +} + +func (_c *BankKeeper_GetAllBalances_Call) Return(_a0 types.Coins) *BankKeeper_GetAllBalances_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *BankKeeper_GetAllBalances_Call) RunAndReturn(run func(types.Context, types.AccAddress) types.Coins) *BankKeeper_GetAllBalances_Call { + _c.Call.Return(run) + return _c +} + +// GetBalance provides a mock function with given fields: ctx, addr, denom +func (_m *BankKeeper) GetBalance(ctx types.Context, addr types.AccAddress, denom string) types.Coin { + ret := _m.Called(ctx, addr, denom) + + var r0 types.Coin + if rf, ok := ret.Get(0).(func(types.Context, types.AccAddress, string) types.Coin); ok { + r0 = rf(ctx, addr, denom) + } else { + r0 = ret.Get(0).(types.Coin) + } + + return r0 +} + +// BankKeeper_GetBalance_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBalance' +type BankKeeper_GetBalance_Call struct { + *mock.Call +} + +// GetBalance is a helper method to define mock.On call +// - ctx types.Context +// - addr types.AccAddress +// - denom string +func (_e *BankKeeper_Expecter) GetBalance(ctx interface{}, addr interface{}, denom interface{}) *BankKeeper_GetBalance_Call { + return &BankKeeper_GetBalance_Call{Call: _e.mock.On("GetBalance", ctx, addr, denom)} +} + +func (_c *BankKeeper_GetBalance_Call) Run(run func(ctx types.Context, addr types.AccAddress, denom string)) *BankKeeper_GetBalance_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(types.AccAddress), args[2].(string)) + }) + return _c +} + +func (_c *BankKeeper_GetBalance_Call) Return(_a0 types.Coin) *BankKeeper_GetBalance_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *BankKeeper_GetBalance_Call) RunAndReturn(run func(types.Context, types.AccAddress, string) types.Coin) *BankKeeper_GetBalance_Call { + _c.Call.Return(run) + return _c +} + +// HasBalance provides a mock function with given fields: ctx, addr, amt +func (_m *BankKeeper) HasBalance(ctx types.Context, addr types.AccAddress, amt types.Coin) bool { + ret := _m.Called(ctx, addr, amt) + + var r0 bool + if rf, ok := ret.Get(0).(func(types.Context, types.AccAddress, types.Coin) bool); ok { + r0 = rf(ctx, addr, amt) + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// BankKeeper_HasBalance_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HasBalance' +type BankKeeper_HasBalance_Call struct { + *mock.Call +} + +// HasBalance is a helper method to define mock.On call +// - ctx types.Context +// - addr types.AccAddress +// - amt types.Coin +func (_e *BankKeeper_Expecter) HasBalance(ctx interface{}, addr interface{}, amt interface{}) *BankKeeper_HasBalance_Call { + return &BankKeeper_HasBalance_Call{Call: _e.mock.On("HasBalance", ctx, addr, amt)} +} + +func (_c *BankKeeper_HasBalance_Call) Run(run func(ctx types.Context, addr types.AccAddress, amt types.Coin)) *BankKeeper_HasBalance_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(types.AccAddress), args[2].(types.Coin)) + }) + return _c +} + +func (_c *BankKeeper_HasBalance_Call) Return(_a0 bool) *BankKeeper_HasBalance_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *BankKeeper_HasBalance_Call) RunAndReturn(run func(types.Context, types.AccAddress, types.Coin) bool) *BankKeeper_HasBalance_Call { + _c.Call.Return(run) + return _c +} + +// SendCoins provides a mock function with given fields: ctx, fromAddr, toAddr, amt +func (_m *BankKeeper) SendCoins(ctx types.Context, fromAddr types.AccAddress, toAddr types.AccAddress, amt types.Coins) error { + ret := _m.Called(ctx, fromAddr, toAddr, amt) + + var r0 error + if rf, ok := ret.Get(0).(func(types.Context, types.AccAddress, types.AccAddress, types.Coins) error); ok { + r0 = rf(ctx, fromAddr, toAddr, amt) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// BankKeeper_SendCoins_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendCoins' +type BankKeeper_SendCoins_Call struct { + *mock.Call +} + +// SendCoins is a helper method to define mock.On call +// - ctx types.Context +// - fromAddr types.AccAddress +// - toAddr types.AccAddress +// - amt types.Coins +func (_e *BankKeeper_Expecter) SendCoins(ctx interface{}, fromAddr interface{}, toAddr interface{}, amt interface{}) *BankKeeper_SendCoins_Call { + return &BankKeeper_SendCoins_Call{Call: _e.mock.On("SendCoins", ctx, fromAddr, toAddr, amt)} +} + +func (_c *BankKeeper_SendCoins_Call) Run(run func(ctx types.Context, fromAddr types.AccAddress, toAddr types.AccAddress, amt types.Coins)) *BankKeeper_SendCoins_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(types.AccAddress), args[2].(types.AccAddress), args[3].(types.Coins)) + }) + return _c +} + +func (_c *BankKeeper_SendCoins_Call) Return(_a0 error) *BankKeeper_SendCoins_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *BankKeeper_SendCoins_Call) RunAndReturn(run func(types.Context, types.AccAddress, types.AccAddress, types.Coins) error) *BankKeeper_SendCoins_Call { + _c.Call.Return(run) + return _c +} + +// SendCoinsFromAccountToModule provides a mock function with given fields: ctx, senderAddr, recipientModule, amt +func (_m *BankKeeper) SendCoinsFromAccountToModule(ctx types.Context, senderAddr types.AccAddress, recipientModule string, amt types.Coins) error { + ret := _m.Called(ctx, senderAddr, recipientModule, amt) + + var r0 error + if rf, ok := ret.Get(0).(func(types.Context, types.AccAddress, string, types.Coins) error); ok { + r0 = rf(ctx, senderAddr, recipientModule, amt) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// BankKeeper_SendCoinsFromAccountToModule_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendCoinsFromAccountToModule' +type BankKeeper_SendCoinsFromAccountToModule_Call struct { + *mock.Call +} + +// SendCoinsFromAccountToModule is a helper method to define mock.On call +// - ctx types.Context +// - senderAddr types.AccAddress +// - recipientModule string +// - amt types.Coins +func (_e *BankKeeper_Expecter) SendCoinsFromAccountToModule(ctx interface{}, senderAddr interface{}, recipientModule interface{}, amt interface{}) *BankKeeper_SendCoinsFromAccountToModule_Call { + return &BankKeeper_SendCoinsFromAccountToModule_Call{Call: _e.mock.On("SendCoinsFromAccountToModule", ctx, senderAddr, recipientModule, amt)} +} + +func (_c *BankKeeper_SendCoinsFromAccountToModule_Call) Run(run func(ctx types.Context, senderAddr types.AccAddress, recipientModule string, amt types.Coins)) *BankKeeper_SendCoinsFromAccountToModule_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(types.AccAddress), args[2].(string), args[3].(types.Coins)) + }) + return _c +} + +func (_c *BankKeeper_SendCoinsFromAccountToModule_Call) Return(_a0 error) *BankKeeper_SendCoinsFromAccountToModule_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *BankKeeper_SendCoinsFromAccountToModule_Call) RunAndReturn(run func(types.Context, types.AccAddress, string, types.Coins) error) *BankKeeper_SendCoinsFromAccountToModule_Call { + _c.Call.Return(run) + return _c +} + +// SendCoinsFromModuleToAccount provides a mock function with given fields: ctx, senderModule, recipientAddr, amt +func (_m *BankKeeper) SendCoinsFromModuleToAccount(ctx types.Context, senderModule string, recipientAddr types.AccAddress, amt types.Coins) error { + ret := _m.Called(ctx, senderModule, recipientAddr, amt) + + var r0 error + if rf, ok := ret.Get(0).(func(types.Context, string, types.AccAddress, types.Coins) error); ok { + r0 = rf(ctx, senderModule, recipientAddr, amt) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// BankKeeper_SendCoinsFromModuleToAccount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendCoinsFromModuleToAccount' +type BankKeeper_SendCoinsFromModuleToAccount_Call struct { + *mock.Call +} + +// SendCoinsFromModuleToAccount is a helper method to define mock.On call +// - ctx types.Context +// - senderModule string +// - recipientAddr types.AccAddress +// - amt types.Coins +func (_e *BankKeeper_Expecter) SendCoinsFromModuleToAccount(ctx interface{}, senderModule interface{}, recipientAddr interface{}, amt interface{}) *BankKeeper_SendCoinsFromModuleToAccount_Call { + return &BankKeeper_SendCoinsFromModuleToAccount_Call{Call: _e.mock.On("SendCoinsFromModuleToAccount", ctx, senderModule, recipientAddr, amt)} +} + +func (_c *BankKeeper_SendCoinsFromModuleToAccount_Call) Run(run func(ctx types.Context, senderModule string, recipientAddr types.AccAddress, amt types.Coins)) *BankKeeper_SendCoinsFromModuleToAccount_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(string), args[2].(types.AccAddress), args[3].(types.Coins)) + }) + return _c +} + +func (_c *BankKeeper_SendCoinsFromModuleToAccount_Call) Return(_a0 error) *BankKeeper_SendCoinsFromModuleToAccount_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *BankKeeper_SendCoinsFromModuleToAccount_Call) RunAndReturn(run func(types.Context, string, types.AccAddress, types.Coins) error) *BankKeeper_SendCoinsFromModuleToAccount_Call { + _c.Call.Return(run) + return _c +} + +// SendCoinsFromModuleToModule provides a mock function with given fields: ctx, senderModule, recipientModule, amt +func (_m *BankKeeper) SendCoinsFromModuleToModule(ctx types.Context, senderModule string, recipientModule string, amt types.Coins) error { + ret := _m.Called(ctx, senderModule, recipientModule, amt) + + var r0 error + if rf, ok := ret.Get(0).(func(types.Context, string, string, types.Coins) error); ok { + r0 = rf(ctx, senderModule, recipientModule, amt) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// BankKeeper_SendCoinsFromModuleToModule_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendCoinsFromModuleToModule' +type BankKeeper_SendCoinsFromModuleToModule_Call struct { + *mock.Call +} + +// SendCoinsFromModuleToModule is a helper method to define mock.On call +// - ctx types.Context +// - senderModule string +// - recipientModule string +// - amt types.Coins +func (_e *BankKeeper_Expecter) SendCoinsFromModuleToModule(ctx interface{}, senderModule interface{}, recipientModule interface{}, amt interface{}) *BankKeeper_SendCoinsFromModuleToModule_Call { + return &BankKeeper_SendCoinsFromModuleToModule_Call{Call: _e.mock.On("SendCoinsFromModuleToModule", ctx, senderModule, recipientModule, amt)} +} + +func (_c *BankKeeper_SendCoinsFromModuleToModule_Call) Run(run func(ctx types.Context, senderModule string, recipientModule string, amt types.Coins)) *BankKeeper_SendCoinsFromModuleToModule_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(string), args[2].(string), args[3].(types.Coins)) + }) + return _c +} + +func (_c *BankKeeper_SendCoinsFromModuleToModule_Call) Return(_a0 error) *BankKeeper_SendCoinsFromModuleToModule_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *BankKeeper_SendCoinsFromModuleToModule_Call) RunAndReturn(run func(types.Context, string, string, types.Coins) error) *BankKeeper_SendCoinsFromModuleToModule_Call { + _c.Call.Return(run) + return _c +} + +// SpendableCoins provides a mock function with given fields: ctx, addr +func (_m *BankKeeper) SpendableCoins(ctx types.Context, addr types.AccAddress) types.Coins { + ret := _m.Called(ctx, addr) + + var r0 types.Coins + if rf, ok := ret.Get(0).(func(types.Context, types.AccAddress) types.Coins); ok { + r0 = rf(ctx, addr) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(types.Coins) + } + } + + return r0 +} + +// BankKeeper_SpendableCoins_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SpendableCoins' +type BankKeeper_SpendableCoins_Call struct { + *mock.Call +} + +// SpendableCoins is a helper method to define mock.On call +// - ctx types.Context +// - addr types.AccAddress +func (_e *BankKeeper_Expecter) SpendableCoins(ctx interface{}, addr interface{}) *BankKeeper_SpendableCoins_Call { + return &BankKeeper_SpendableCoins_Call{Call: _e.mock.On("SpendableCoins", ctx, addr)} +} + +func (_c *BankKeeper_SpendableCoins_Call) Run(run func(ctx types.Context, addr types.AccAddress)) *BankKeeper_SpendableCoins_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(types.AccAddress)) + }) + return _c +} + +func (_c *BankKeeper_SpendableCoins_Call) Return(_a0 types.Coins) *BankKeeper_SpendableCoins_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *BankKeeper_SpendableCoins_Call) RunAndReturn(run func(types.Context, types.AccAddress) types.Coins) *BankKeeper_SpendableCoins_Call { + _c.Call.Return(run) + return _c +} + +// NewBankKeeper creates a new instance of BankKeeper. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBankKeeper(t interface { + mock.TestingT + Cleanup(func()) +}) *BankKeeper { + mock := &BankKeeper{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/x/margin/client/cli/query.go b/x/margin/client/cli/query.go index ddef65c83..7af45e0ea 100644 --- a/x/margin/client/cli/query.go +++ b/x/margin/client/cli/query.go @@ -34,6 +34,7 @@ func GetQueryCmd(queryRoute string) *cobra.Command { cmd.AddCommand(CmdListPool()) cmd.AddCommand(CmdShowPool()) cmd.AddCommand(CmdMtp()) + cmd.AddCommand(CmdOpenEstimation()) // this line is used by starport scaffolding # 1 diff --git a/x/margin/client/cli/query_mtp_test.go b/x/margin/client/cli/query_mtp_test.go index 9e847a77a..b28213864 100644 --- a/x/margin/client/cli/query_mtp_test.go +++ b/x/margin/client/cli/query_mtp_test.go @@ -17,7 +17,7 @@ import ( "github.com/elys-network/elys/testutil/network" "github.com/elys-network/elys/x/margin/client/cli" "github.com/elys-network/elys/x/margin/types" - paramtypes "github.com/elys-network/elys/x/parameter/types" + ptypes "github.com/elys-network/elys/x/parameter/types" ) // Prevent strconv unused error @@ -36,28 +36,33 @@ func networkWithMTPObjects(t *testing.T, n int) (*network.Network, []*types.MTP) cfg := network.DefaultConfig() for i := 0; i < n; i++ { mtp := types.MTP{ - Address: addr[i].String(), - Collaterals: []sdk.Coin{sdk.NewCoin(paramtypes.BaseCurrency, sdk.NewInt(0))}, - Liabilities: sdk.NewInt(0), - BorrowInterestPaidCollaterals: []sdk.Coin{sdk.NewCoin(paramtypes.BaseCurrency, sdk.NewInt(0))}, - BorrowInterestPaidCustodies: []sdk.Coin{sdk.NewCoin("ATOM", sdk.NewInt(0))}, - BorrowInterestUnpaidCollaterals: []sdk.Coin{sdk.NewCoin(paramtypes.BaseCurrency, sdk.NewInt(0))}, - Custodies: []sdk.Coin{sdk.NewCoin("ATOM", sdk.NewInt(0))}, - TakeProfitLiabilities: sdk.NewInt(0), - TakeProfitCustodies: []sdk.Coin{sdk.NewCoin("ATOM", sdk.NewInt(0))}, - Leverages: []sdk.Dec{sdk.NewDec(0)}, - MtpHealth: sdk.NewDec(0), - Position: types.Position_LONG, - Id: (uint64)(i + 1), - AmmPoolId: (uint64)(i + 1), - ConsolidateLeverage: sdk.ZeroDec(), - SumCollateral: sdk.ZeroInt(), - TakeProfitPrice: sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), - TakeProfitBorrowRate: sdk.OneDec(), - FundingFeePaidCollaterals: []sdk.Coin{sdk.NewCoin(paramtypes.BaseCurrency, sdk.NewInt(0))}, - FundingFeePaidCustodies: []sdk.Coin{sdk.NewCoin("ATOM", sdk.NewInt(0))}, - FundingFeeReceivedCollaterals: []sdk.Coin{sdk.NewCoin(paramtypes.BaseCurrency, sdk.NewInt(0))}, - FundingFeeReceivedCustodies: []sdk.Coin{sdk.NewCoin("ATOM", sdk.NewInt(0))}, + Address: addr[i].String(), + CollateralAsset: ptypes.BaseCurrency, + TradingAsset: "ATOM", + LiabilitiesAsset: ptypes.BaseCurrency, + CustodyAsset: "ATOM", + Collateral: sdk.NewInt(0), + Liabilities: sdk.NewInt(0), + BorrowInterestPaidCollateral: sdk.NewInt(0), + BorrowInterestPaidCustody: sdk.NewInt(0), + BorrowInterestUnpaidCollateral: sdk.NewInt(0), + Custody: sdk.NewInt(0), + TakeProfitLiabilities: sdk.NewInt(0), + TakeProfitCustody: sdk.NewInt(0), + Leverage: sdk.NewDec(0), + MtpHealth: sdk.NewDec(0), + Position: types.Position_LONG, + Id: (uint64)(i + 1), + AmmPoolId: (uint64)(i + 1), + ConsolidateLeverage: sdk.ZeroDec(), + SumCollateral: sdk.ZeroInt(), + TakeProfitPrice: sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), + TakeProfitBorrowRate: sdk.OneDec(), + FundingFeePaidCollateral: sdk.NewInt(0), + FundingFeePaidCustody: sdk.NewInt(0), + FundingFeeReceivedCollateral: sdk.NewInt(0), + FundingFeeReceivedCustody: sdk.NewInt(0), + OpenPrice: sdk.NewDec(0), } mtps = append(mtps, &mtp) diff --git a/x/margin/client/cli/query_open_estimation.go b/x/margin/client/cli/query_open_estimation.go new file mode 100644 index 000000000..85b502b0e --- /dev/null +++ b/x/margin/client/cli/query_open_estimation.go @@ -0,0 +1,95 @@ +package cli + +import ( + "errors" + "strconv" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/elys-network/elys/x/margin/types" + "github.com/spf13/cobra" +) + +var _ = strconv.Itoa(0) + +func CmdOpenEstimation() *cobra.Command { + cmd := &cobra.Command{ + Use: "open-estimation [position] [leverage] [trading-asset] [collateral]", + Short: "Query open-estimation", + Example: "elysd q margin open-estimation long 5 uatom 100000000uusdc", + Args: cobra.ExactArgs(4), + RunE: func(cmd *cobra.Command, args []string) (err error) { + reqPosition := types.GetPositionFromString(args[0]) + + reqLeverage, err := sdk.NewDecFromStr(args[1]) + if err != nil { + return err + } + + reqTradingAsset := args[2] + + reqCollateral, err := sdk.ParseCoinNormalized(args[3]) + if err != nil { + return err + } + + discountStr, err := cmd.Flags().GetString(FlagDiscount) + if err != nil { + return err + } + discount, err := sdk.NewDecFromStr(discountStr) + if err != nil { + return err + } + + takeProfitPriceStr, err := cmd.Flags().GetString(flagTakeProfitPrice) + if err != nil { + return err + } + + var takeProfitPrice sdk.Dec + if takeProfitPriceStr != types.InfinitePriceString { + takeProfitPrice, err = sdk.NewDecFromStr(takeProfitPriceStr) + if err != nil { + return errors.New("invalid take profit price") + } + } else { + takeProfitPrice, err = sdk.NewDecFromStr(types.TakeProfitPriceDefault) + if err != nil { + return errors.New("failed to set default take profit price") + } + } + + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + + params := &types.QueryOpenEstimationRequest{ + Position: reqPosition, + Leverage: reqLeverage, + TradingAsset: reqTradingAsset, + Collateral: reqCollateral, + Discount: discount, + TakeProfitPrice: takeProfitPrice, + } + + res, err := queryClient.OpenEstimation(cmd.Context(), params) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + cmd.Flags().String(FlagDiscount, "0.0", "discount to apply to the swap fee") + cmd.Flags().String(flagTakeProfitPrice, types.InfinitePriceString, "Optional take profit price") + + return cmd +} diff --git a/x/margin/client/cli/tx.go b/x/margin/client/cli/tx.go index f021d75de..1acbea0d7 100644 --- a/x/margin/client/cli/tx.go +++ b/x/margin/client/cli/tx.go @@ -16,6 +16,7 @@ var ( ) const ( + FlagDiscount = "discount" flagTakeProfitPrice = "take-profit" flagPacketTimeoutTimestamp = "packet-timeout-timestamp" listSeparator = "," diff --git a/x/margin/client/cli/tx_close.go b/x/margin/client/cli/tx_close.go index da407ffba..0c37bce6f 100644 --- a/x/margin/client/cli/tx_close.go +++ b/x/margin/client/cli/tx_close.go @@ -35,8 +35,8 @@ func CmdClose() *cobra.Command { return errors.New("invalid mtp id") } - argAmount, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { + argAmount, ok := sdk.NewIntFromString(args[1]) + if !ok { return errors.New("invalid amount") } diff --git a/x/margin/client/cli/tx_close_test.go b/x/margin/client/cli/tx_close_test.go index dfc329080..b7e80d441 100644 --- a/x/margin/client/cli/tx_close_test.go +++ b/x/margin/client/cli/tx_close_test.go @@ -23,7 +23,7 @@ func TestClosePosition(t *testing.T) { // ... args := []string{ "1", - "10000000uusd", + "10000000", "--from=" + val.Address.String(), "-y", } diff --git a/x/margin/client/cli/tx_open.go b/x/margin/client/cli/tx_open.go index 8ab5cc8ff..203483c68 100644 --- a/x/margin/client/cli/tx_open.go +++ b/x/margin/client/cli/tx_open.go @@ -16,13 +16,13 @@ var _ = strconv.Itoa(0) func CmdOpen() *cobra.Command { cmd := &cobra.Command{ - Use: "open [position] [leverage] [collateral-asset] [collateral-amount] [borrow-asset] [flags]", + Use: "open [position] [leverage] [trading-asset] [collateral] [flags]", Short: "Open margin position", Example: `Infinte profitability: -elysd tx margin open long 5 uusdc 100000000 uatom --from=treasury --keyring-backend=test --chain-id=elystestnet-1 --yes --gas=1000000 +elysd tx margin open long 5 uatom 100000000uusdc --from=treasury --keyring-backend=test --chain-id=elystestnet-1 --yes --gas=1000000 Finite profitability: -elysd tx margin open short 5 uusdc 100000000 uatom --take-profit 100 --from=treasury --keyring-backend=test --chain-id=elystestnet-1 --yes --gas=1000000`, - Args: cobra.ExactArgs(5), +elysd tx margin open short 5 uatom 100000000uusdc --take-profit 100 --from=treasury --keyring-backend=test --chain-id=elystestnet-1 --yes --gas=1000000`, + Args: cobra.ExactArgs(4), RunE: func(cmd *cobra.Command, args []string) (err error) { clientCtx, err := client.GetClientTxContext(cmd) if err != nil { @@ -41,15 +41,13 @@ elysd tx margin open short 5 uusdc 100000000 uatom --take-profit 100 --from=trea return err } - argCollateralAsset := args[2] + argTradingAsset := args[2] - argCollateralAmount, ok := sdk.NewIntFromString(args[3]) - if !ok { - return errors.New("invalid collateral amount") + argCollateral, err := sdk.ParseCoinNormalized(args[3]) + if err != nil { + return err } - argBorrowAsset := args[4] - takeProfitPriceStr, err := cmd.Flags().GetString(flagTakeProfitPrice) if err != nil { return err @@ -70,11 +68,10 @@ elysd tx margin open short 5 uusdc 100000000 uatom --take-profit 100 --from=trea msg := types.NewMsgOpen( signer.String(), - argCollateralAsset, - argCollateralAmount, - argBorrowAsset, argPosition, argLeverage, + argTradingAsset, + argCollateral, takeProfitPrice, ) diff --git a/x/margin/client/cli/tx_open_test.go b/x/margin/client/cli/tx_open_test.go index 32752e196..5cfb00419 100644 --- a/x/margin/client/cli/tx_open_test.go +++ b/x/margin/client/cli/tx_open_test.go @@ -33,9 +33,8 @@ func TestOpenPosition(t *testing.T) { args := []string{ "open", "1.5", - ptypes.BaseCurrency, - "1000", "uatom", + "1000" + ptypes.BaseCurrency, "--from=" + val.Address.String(), "-y", } diff --git a/x/margin/client/wasm/msg_open.go b/x/margin/client/wasm/msg_open.go index 8e3cf1ec2..2cc622250 100644 --- a/x/margin/client/wasm/msg_open.go +++ b/x/margin/client/wasm/msg_open.go @@ -4,7 +4,6 @@ import ( "encoding/json" errorsmod "cosmossdk.io/errors" - cosmos_sdk_math "cosmossdk.io/math" wasmvmtypes "github.com/CosmWasm/wasmvm/types" sdk "github.com/cosmos/cosmos-sdk/types" marginkeeper "github.com/elys-network/elys/x/margin/keeper" @@ -42,7 +41,14 @@ func PerformMsgOpen(f *marginkeeper.Keeper, ctx sdk.Context, contractAddr sdk.Ac } msgServer := marginkeeper.NewMsgServerImpl(*f) - msgMsgOpen := margintypes.NewMsgOpen(msgOpen.Creator, msgOpen.CollateralAsset, cosmos_sdk_math.Int(msgOpen.CollateralAmount), msgOpen.BorrowAsset, msgOpen.Position, msgOpen.Leverage, msgOpen.TakeProfitPrice) + msgMsgOpen := margintypes.NewMsgOpen( + msgOpen.Creator, + msgOpen.Position, + msgOpen.Leverage, + msgOpen.TradingAsset, + msgOpen.Collateral, + msgOpen.TakeProfitPrice, + ) if err := msgMsgOpen.ValidateBasic(); err != nil { return nil, errorsmod.Wrap(err, "failed validating msgMsgOpen") diff --git a/x/margin/client/wasm/querier.go b/x/margin/client/wasm/querier.go index e254ecbfd..360377e32 100644 --- a/x/margin/client/wasm/querier.go +++ b/x/margin/client/wasm/querier.go @@ -39,6 +39,8 @@ func (oq *Querier) HandleQuery(ctx sdk.Context, query wasmbindingstypes.ElysQuer return oq.queryPools(ctx, query.MarginPools) case query.MarginMTP != nil: return oq.queryMtp(ctx, query.MarginMTP) + case query.MarginOpenEstimation != nil: + return oq.queryOpenEstimation(ctx, query.MarginOpenEstimation) default: // This handler cannot handle the query return nil, wasmbindingstypes.ErrCannotHandleQuery diff --git a/x/margin/client/wasm/query_min_collateral.go b/x/margin/client/wasm/query_min_collateral.go new file mode 100644 index 000000000..f41cd949f --- /dev/null +++ b/x/margin/client/wasm/query_min_collateral.go @@ -0,0 +1,22 @@ +package wasm + +import ( + "encoding/json" + + errorsmod "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/elys-network/elys/x/margin/types" +) + +func (oq *Querier) queryOpenEstimation(ctx sdk.Context, query *types.QueryOpenEstimationRequest) ([]byte, error) { + res, err := oq.keeper.OpenEstimation(ctx, query) + if err != nil { + return nil, errorsmod.Wrap(err, "failed to get min collateral") + } + + responseBytes, err := json.Marshal(res) + if err != nil { + return nil, errorsmod.Wrap(err, "failed to serialize min collateral response") + } + return responseBytes, nil +} diff --git a/x/margin/keeper/begin_blocker.go b/x/margin/keeper/begin_blocker.go index fd8b73b0b..b78443500 100644 --- a/x/margin/keeper/begin_blocker.go +++ b/x/margin/keeper/begin_blocker.go @@ -50,7 +50,11 @@ func (k Keeper) BeginBlocker(ctx sdk.Context) { // k.TrackSQBeginBlock(ctx, pool) mtps, _, _ := k.GetMTPsForPool(ctx, pool.AmmPoolId, nil) for _, mtp := range mtps { - BeginBlockerProcessMTP(ctx, k, mtp, pool, ammPool, baseCurrency) + err := BeginBlockerProcessMTP(ctx, k, mtp, pool, ammPool, baseCurrency) + if err != nil { + ctx.Logger().Error(err.Error()) + continue // ? + } } _ = k.HandleFundingFeeDistribution(ctx, mtps, &pool, ammPool, baseCurrency) } diff --git a/x/margin/keeper/begin_blocker_process_mtp.go b/x/margin/keeper/begin_blocker_process_mtp.go index 55cf3763c..5326a465a 100644 --- a/x/margin/keeper/begin_blocker_process_mtp.go +++ b/x/margin/keeper/begin_blocker_process_mtp.go @@ -11,7 +11,7 @@ import ( "github.com/elys-network/elys/x/margin/types" ) -func BeginBlockerProcessMTP(ctx sdk.Context, k Keeper, mtp *types.MTP, pool types.Pool, ammPool ammtypes.Pool, baseCurrency string) { +func BeginBlockerProcessMTP(ctx sdk.Context, k Keeper, mtp *types.MTP, pool types.Pool, ammPool ammtypes.Pool, baseCurrency string) error { defer func() { if r := recover(); r != nil { if msg, ok := r.(string); ok { @@ -24,93 +24,74 @@ func BeginBlockerProcessMTP(ctx sdk.Context, k Keeper, mtp *types.MTP, pool type // calculate mtp take profit liablities, delta x_tp_l = delta y_tp_c * current price (take profit liabilities = take profit custody * current price) mtp.TakeProfitLiabilities, err = k.CalcMTPTakeProfitLiability(ctx, mtp, baseCurrency) if err != nil { - ctx.Logger().Error(errors.Wrap(err, fmt.Sprintf("error calculating mtp take profit liabilities: %s", mtp.String())).Error()) - return + return errors.Wrap(err, fmt.Sprintf("error calculating mtp take profit liabilities: %s", mtp.String())) } // calculate and update take profit borrow rate mtp.TakeProfitBorrowRate, err = k.CalcMTPTakeProfitBorrowRate(ctx, mtp) if err != nil { - ctx.Logger().Error(errors.Wrap(err, fmt.Sprintf("error calculating mtp take profit borrow rate: %s", mtp.String())).Error()) - return + return errors.Wrap(err, fmt.Sprintf("error calculating mtp take profit borrow rate: %s", mtp.String())) } h, err := k.UpdateMTPHealth(ctx, *mtp, ammPool, baseCurrency) if err != nil { - ctx.Logger().Error(errors.Wrap(err, fmt.Sprintf("error updating mtp health: %s", mtp.String())).Error()) - return + return errors.Wrap(err, fmt.Sprintf("error updating mtp health: %s", mtp.String())) } mtp.MtpHealth = h // compute borrow interest // TODO: missing fields - for _, custody := range mtp.Custodies { - custodyAsset := custody.Denom - // Retrieve AmmPool - ammPool, err := k.GetAmmPool(ctx, mtp.AmmPoolId, custodyAsset) - if err != nil { - ctx.Logger().Error(errors.Wrap(err, fmt.Sprintf("error retrieving amm pool: %d", mtp.AmmPoolId)).Error()) - return - } - for _, collateral := range mtp.Collaterals { - collateralAsset := collateral.Denom - // Handle Borrow Interest if within epoch position - if err := k.HandleBorrowInterest(ctx, mtp, &pool, ammPool, collateralAsset, custodyAsset); err != nil { - ctx.Logger().Error(errors.Wrap(err, fmt.Sprintf("error handling borrow interest payment: %s", collateralAsset)).Error()) - return - } - if err := k.HandleFundingFeeCollection(ctx, mtp, &pool, ammPool, collateralAsset, custodyAsset); err != nil { - ctx.Logger().Error(errors.Wrap(err, fmt.Sprintf("error handling funding fee collection: %s", collateralAsset)).Error()) - return - } - } + // Handle Borrow Interest if within epoch position + if err := k.HandleBorrowInterest(ctx, mtp, &pool, ammPool); err != nil { + return errors.Wrap(err, fmt.Sprintf("error handling borrow interest payment: %s", mtp.CollateralAsset)) + } + if err := k.HandleFundingFeeCollection(ctx, mtp, &pool, ammPool, baseCurrency); err != nil { + return errors.Wrap(err, fmt.Sprintf("error handling funding fee collection: %s", mtp.CollateralAsset)) } _ = k.SetMTP(ctx, mtp) - var mustForceClose bool = false - for _, custody := range mtp.Custodies { - assetPrice, err := k.EstimateSwap(ctx, sdk.NewCoin(custody.Denom, sdk.OneInt()), baseCurrency, ammPool) - if err != nil { - ctx.Logger().Error(errors.Wrap(err, fmt.Sprintf("error estimating swap: %s", custody.Denom)).Error()) - continue - } - if mtp.TakeProfitPrice.GT(sdk.NewDecFromInt(assetPrice)) { - // flag position as must force close - mustForceClose = true - break - } - ctx.Logger().Error(fmt.Sprintf("skipping force close on position %s because take profit price %s is less than asset price %s", mtp.String(), mtp.TakeProfitPrice.String(), sdk.NewDecFromInt(assetPrice).String())) - } - // check MTP health against threshold safetyFactor := k.GetSafetyFactor(ctx) + var mustForceClose bool = false - if mtp.MtpHealth.GT(safetyFactor) { - ctx.Logger().Error(errors.Wrap(types.ErrMTPHealthy, "skipping executing force close because mtp is healthy").Error()) + if mtp.MtpHealth.LTE(safetyFactor) { + // flag position as must force close + mustForceClose = true } else { + ctx.Logger().Error(errors.Wrap(types.ErrMTPHealthy, "skipping executing force close because mtp is healthy").Error()) + } + + assetPrice, err := k.EstimateSwap(ctx, sdk.NewCoin(mtp.CustodyAsset, sdk.OneInt()), baseCurrency, ammPool) + if err != nil { + return errors.Wrap(err, fmt.Sprintf("error estimating swap: %s", mtp.CustodyAsset)) + } + if types.ReachedTakeProfitPrice(mtp, assetPrice) { // flag position as must force close mustForceClose = true + } else { + ctx.Logger().Error(fmt.Sprintf("skipping force close on position %s because take profit price %s <> %s", mtp.String(), mtp.TakeProfitPrice.String(), assetPrice.String())) } // if flag is false, then skip force close if !mustForceClose { - return + return nil } var repayAmount sdk.Int switch mtp.Position { case types.Position_LONG: - repayAmount, err = k.ForceCloseLong(ctx, mtp, &pool, true) + repayAmount, err = k.ForceCloseLong(ctx, mtp, &pool, true, baseCurrency) case types.Position_SHORT: - repayAmount, err = k.ForceCloseShort(ctx, mtp, &pool, true) + repayAmount, err = k.ForceCloseShort(ctx, mtp, &pool, true, baseCurrency) default: - ctx.Logger().Error(errors.Wrap(types.ErrInvalidPosition, fmt.Sprintf("invalid position type: %s", mtp.Position)).Error()) + return errors.Wrap(types.ErrInvalidPosition, fmt.Sprintf("invalid position type: %s", mtp.Position)) } if err == nil { // Emit event if position was closed k.EmitForceClose(ctx, mtp, repayAmount, "") } else { - ctx.Logger().Error(errors.Wrap(err, "error executing force close").Error()) + return errors.Wrap(err, "error executing force close") } + return nil } diff --git a/x/margin/keeper/calc_min_collateral.go b/x/margin/keeper/calc_min_collateral.go new file mode 100644 index 000000000..c3a764e48 --- /dev/null +++ b/x/margin/keeper/calc_min_collateral.go @@ -0,0 +1,25 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/elys-network/elys/x/margin/types" +) + +// CalcMinCollateral calculates the minimum collateral required to open a position +func (k Keeper) CalcMinCollateral(ctx sdk.Context, leverage sdk.Dec) (sdk.Int, error) { + // leverage must be greater than 1 + if leverage.LTE(sdk.NewDec(1)) { + return sdk.ZeroInt(), sdkerrors.Wrapf(types.ErrInvalidLeverage, "leverage must be greater than 1") + } + + // get min borrow rate + borrowInterestRateMin := k.GetBorrowInterestRateMin(ctx) + + // min_collateral = ( 1 / (( leverage - 1 ) * borrow_interest_rate_min )) / 10 ^ collateral_decimals + minCollateral := sdk.NewDec(1).Quo( + leverage.Sub(sdk.NewDec(1)).Mul(borrowInterestRateMin), + ) + + return minCollateral.TruncateInt(), nil +} diff --git a/x/margin/keeper/calc_mtp_consolidate_collateral.go b/x/margin/keeper/calc_mtp_consolidate_collateral.go index 8b0881889..26650e36e 100644 --- a/x/margin/keeper/calc_mtp_consolidate_collateral.go +++ b/x/margin/keeper/calc_mtp_consolidate_collateral.go @@ -7,24 +7,22 @@ import ( func (k Keeper) CalcMTPConsolidateCollateral(ctx sdk.Context, mtp *types.MTP, baseCurrency string) error { consolidateCollateral := sdk.ZeroInt() - for _, asset := range mtp.Collaterals { - if asset.Denom == baseCurrency { - consolidateCollateral = consolidateCollateral.Add(asset.Amount) - } else { - // swap into base currency - _, ammPool, _, err := k.OpenChecker.PreparePools(ctx, asset.Denom) - if err != nil { - return err - } - - collateralAmtIn := sdk.NewCoin(asset.Denom, asset.Amount) - C, err := k.EstimateSwapGivenOut(ctx, collateralAmtIn, baseCurrency, ammPool) - if err != nil { - return err - } + if mtp.CollateralAsset == baseCurrency { + consolidateCollateral = consolidateCollateral.Add(mtp.Collateral) + } else { + // swap into base currency + _, ammPool, _, err := k.OpenChecker.PreparePools(ctx, mtp.CollateralAsset, mtp.CustodyAsset) + if err != nil { + return err + } - consolidateCollateral = consolidateCollateral.Add(C) + collateralAmtIn := sdk.NewCoin(mtp.CollateralAsset, mtp.Collateral) + C, err := k.EstimateSwapGivenOut(ctx, collateralAmtIn, baseCurrency, ammPool) + if err != nil { + return err } + + consolidateCollateral = consolidateCollateral.Add(C) } mtp.SumCollateral = consolidateCollateral diff --git a/x/margin/keeper/calc_mtp_interest_liabilities.go b/x/margin/keeper/calc_mtp_interest_liabilities.go index 86a87e36d..ef39a845a 100644 --- a/x/margin/keeper/calc_mtp_interest_liabilities.go +++ b/x/margin/keeper/calc_mtp_interest_liabilities.go @@ -8,7 +8,7 @@ import ( "github.com/elys-network/elys/x/margin/types" ) -func (k Keeper) CalcMTPBorrowInterestLiabilities(ctx sdk.Context, mtp *types.MTP, borrowInterestRate sdk.Dec, epochPosition, epochLength int64, ammPool ammtypes.Pool, collateralAsset string, baseCurrency string) (sdk.Int, error) { +func (k Keeper) CalcMTPBorrowInterestLiabilities(ctx sdk.Context, mtp *types.MTP, borrowInterestRate sdk.Dec, epochPosition, epochLength int64, ammPool ammtypes.Pool, baseCurrency string) (sdk.Int, error) { // Ensure borrow interest rate or liabilities are not zero to avoid division by zero if borrowInterestRate.IsZero() || mtp.Liabilities.IsZero() { return sdk.ZeroInt(), types.ErrAmountTooLow @@ -18,23 +18,22 @@ func (k Keeper) CalcMTPBorrowInterestLiabilities(ctx sdk.Context, mtp *types.MTP rate.SetFloat64(borrowInterestRate.MustFloat64()) - collateralIndex, _ := types.GetMTPAssetIndex(mtp, collateralAsset, "") - unpaidCollaterals := sdk.ZeroInt() + unpaidCollateral := sdk.ZeroInt() // Calculate collateral borrow interests in base currency - if mtp.Collaterals[collateralIndex].Denom == baseCurrency { - unpaidCollaterals = unpaidCollaterals.Add(mtp.BorrowInterestUnpaidCollaterals[collateralIndex].Amount) + if mtp.CollateralAsset == baseCurrency { + unpaidCollateral = unpaidCollateral.Add(mtp.BorrowInterestUnpaidCollateral) } else { // Liability is in base currency, so convert it to base currency - unpaidCollateralIn := sdk.NewCoin(mtp.Collaterals[collateralIndex].Denom, mtp.BorrowInterestUnpaidCollaterals[collateralIndex].Amount) + unpaidCollateralIn := sdk.NewCoin(mtp.CollateralAsset, mtp.BorrowInterestUnpaidCollateral) C, err := k.EstimateSwapGivenOut(ctx, unpaidCollateralIn, baseCurrency, ammPool) if err != nil { return sdk.ZeroInt(), err } - unpaidCollaterals = unpaidCollaterals.Add(C) + unpaidCollateral = unpaidCollateral.Add(C) } - liabilitiesRational.SetInt(mtp.Liabilities.BigInt().Add(mtp.Liabilities.BigInt(), unpaidCollaterals.BigInt())) + liabilitiesRational.SetInt(mtp.Liabilities.BigInt().Add(mtp.Liabilities.BigInt(), unpaidCollateral.BigInt())) borrowInterestRational.Mul(&rate, &liabilitiesRational) if epochPosition > 0 { // prorate borrow interest if within epoch @@ -46,7 +45,7 @@ func (k Keeper) CalcMTPBorrowInterestLiabilities(ctx sdk.Context, mtp *types.MTP borrowInterestNew := borrowInterestRational.Num().Quo(borrowInterestRational.Num(), borrowInterestRational.Denom()) - borrowInterestNewInt := sdk.NewIntFromBigInt(borrowInterestNew.Add(borrowInterestNew, unpaidCollaterals.BigInt())) + borrowInterestNewInt := sdk.NewIntFromBigInt(borrowInterestNew.Add(borrowInterestNew, unpaidCollateral.BigInt())) // round up to lowest digit if borrow interest too low and rate not 0 if borrowInterestNewInt.IsZero() && !borrowInterestRate.IsZero() { borrowInterestNewInt = sdk.NewInt(1) diff --git a/x/margin/keeper/calc_mtp_take_profit_borrow_rate.go b/x/margin/keeper/calc_mtp_take_profit_borrow_rate.go index 2d2495605..0d58d5135 100644 --- a/x/margin/keeper/calc_mtp_take_profit_borrow_rate.go +++ b/x/margin/keeper/calc_mtp_take_profit_borrow_rate.go @@ -6,36 +6,22 @@ import ( ) func (k Keeper) CalcMTPTakeProfitBorrowRate(ctx sdk.Context, mtp *types.MTP) (sdk.Dec, error) { - // Check if there are any takeProfitCustodies to avoid division by zero - if len(mtp.TakeProfitCustodies) == 0 { - return sdk.ZeroDec(), nil + // Ensure mtp.Custody is not zero to avoid division by zero + if mtp.Custody.IsZero() { + return sdk.ZeroDec(), types.ErrAmountTooLow } - var totalTakeProfitBorrowRate sdk.Dec = sdk.ZeroDec() - for takeProfitCustodyIndex, takeProfitCustody := range mtp.TakeProfitCustodies { - // Ensure mtp.Custodies[takeProfitCustodyIndex].Amount is not zero to avoid division by zero - if mtp.Custodies[takeProfitCustodyIndex].Amount.IsZero() { - return sdk.ZeroDec(), types.ErrAmountTooLow - } + // Calculate the borrow rate for this takeProfitCustody + takeProfitBorrowRateInt := mtp.TakeProfitCustody.Quo(mtp.Custody) - // Calculate the borrow rate for this takeProfitCustody - takeProfitBorrowRateInt := takeProfitCustody.Amount.Quo(mtp.Custodies[takeProfitCustodyIndex].Amount) - - // Convert takeProfitBorrowRateInt from sdk.Int to sdk.Dec - takeProfitBorrowRateDec := sdk.NewDecFromInt(takeProfitBorrowRateInt) - - // Add this take profit borrow rate to the total - totalTakeProfitBorrowRate = totalTakeProfitBorrowRate.Add(takeProfitBorrowRateDec) - } - - // Calculate the average take profit borrow rate - averageTakeProfitBorrowRate := totalTakeProfitBorrowRate.Quo(sdk.NewDec(int64(len(mtp.TakeProfitCustodies)))) + // Convert takeProfitBorrowRateInt from sdk.Int to sdk.Dec + takeProfitBorrowRateDec := sdk.NewDecFromInt(takeProfitBorrowRateInt) // Get Margin Params params := k.GetParams(ctx) // Use TakeProfitBorrowInterestRateMin param as minimum take profit borrow rate - averageTakeProfitBorrowRate = sdk.MaxDec(averageTakeProfitBorrowRate, params.TakeProfitBorrowInterestRateMin) + takeProfitBorrowRate := sdk.MaxDec(takeProfitBorrowRateDec, params.TakeProfitBorrowInterestRateMin) - return averageTakeProfitBorrowRate, nil + return takeProfitBorrowRate, nil } diff --git a/x/margin/keeper/calc_mtp_take_profit_liabilities.go b/x/margin/keeper/calc_mtp_take_profit_liabilities.go index 320c06063..8222a7e21 100644 --- a/x/margin/keeper/calc_mtp_take_profit_liabilities.go +++ b/x/margin/keeper/calc_mtp_take_profit_liabilities.go @@ -6,21 +6,19 @@ import ( ) func (k Keeper) CalcMTPTakeProfitLiability(ctx sdk.Context, mtp *types.MTP, baseCurrency string) (sdk.Int, error) { - takeProfitLiabilities := sdk.ZeroInt() - for _, takeProfitCustody := range mtp.TakeProfitCustodies { - takeProfitCustodyAsset := takeProfitCustody.Denom - // Retrieve AmmPool - ammPool, err := k.GetAmmPool(ctx, mtp.AmmPoolId, takeProfitCustodyAsset) - if err != nil { - return sdk.ZeroInt(), err - } + // Retrieve AmmPool + ammPool, err := k.GetAmmPool(ctx, mtp.AmmPoolId, mtp.CustodyAsset) + if err != nil { + return sdk.ZeroInt(), err + } + + // build take profit custody coin + takeProfitCustody := sdk.NewCoin(mtp.CustodyAsset, mtp.TakeProfitCustody) - // convert custody amount to base currency - C, err := k.EstimateSwap(ctx, takeProfitCustody, baseCurrency, ammPool) - if err != nil { - return sdk.ZeroInt(), err - } - takeProfitLiabilities = takeProfitLiabilities.Add(C) + // convert custody amount to base currency + takeProfitLiabilities, err := k.EstimateSwap(ctx, takeProfitCustody, baseCurrency, ammPool) + if err != nil { + return sdk.ZeroInt(), err } return takeProfitLiabilities, nil diff --git a/x/margin/keeper/check_same_asset_position.go b/x/margin/keeper/check_same_asset_position.go index f6554460b..285302455 100644 --- a/x/margin/keeper/check_same_asset_position.go +++ b/x/margin/keeper/check_same_asset_position.go @@ -8,7 +8,7 @@ import ( func (k Keeper) CheckSameAssetPosition(ctx sdk.Context, msg *types.MsgOpen) *types.MTP { mtps := k.GetAllMTPs(ctx) for _, mtp := range mtps { - if mtp.Address == msg.Creator && mtp.Position == msg.Position { + if mtp.Address == msg.Creator && mtp.Position == msg.Position && mtp.CollateralAsset == msg.Collateral.Denom && mtp.CustodyAsset == msg.TradingAsset { return &mtp } } diff --git a/x/margin/keeper/check_same_asset_position_test.go b/x/margin/keeper/check_same_asset_position_test.go index 964bc9c9c..fd73135db 100644 --- a/x/margin/keeper/check_same_asset_position_test.go +++ b/x/margin/keeper/check_same_asset_position_test.go @@ -17,16 +17,15 @@ func TestCheckSameAssetPosition_NewPosition(t *testing.T) { k := app.MarginKeeper - mtp := types.NewMTP("creator", ptypes.BaseCurrency, ptypes.ATOM, types.Position_LONG, sdk.NewDec(5), sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), 1) + mtp := types.NewMTP("creator", ptypes.BaseCurrency, ptypes.ATOM, ptypes.BaseCurrency, ptypes.ATOM, types.Position_LONG, sdk.NewDec(5), sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), 1) k.SetMTP(ctx, mtp) msg := &types.MsgOpen{ - Creator: "creator", - CollateralAsset: ptypes.ATOM, - CollateralAmount: sdk.NewInt(100), - BorrowAsset: ptypes.ATOM, - Position: types.Position_SHORT, - Leverage: sdk.NewDec(1), + Creator: "creator", + Position: types.Position_SHORT, + Leverage: sdk.NewDec(1), + TradingAsset: ptypes.ATOM, + Collateral: sdk.NewCoin(ptypes.ATOM, sdk.NewInt(100)), } mtp = k.CheckSameAssetPosition(ctx, msg) diff --git a/x/margin/keeper/close.go b/x/margin/keeper/close.go index 4c38cc843..973caed7f 100644 --- a/x/margin/keeper/close.go +++ b/x/margin/keeper/close.go @@ -1,11 +1,14 @@ package keeper import ( + "fmt" "strconv" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + assetprofiletypes "github.com/elys-network/elys/x/assetprofile/types" "github.com/elys-network/elys/x/margin/types" + ptypes "github.com/elys-network/elys/x/parameter/types" ) func (k Keeper) Close(ctx sdk.Context, msg *types.MsgClose) (*types.MsgCloseResponse, error) { @@ -14,16 +17,22 @@ func (k Keeper) Close(ctx sdk.Context, msg *types.MsgClose) (*types.MsgCloseResp return nil, err } + entry, found := k.apKeeper.GetEntry(ctx, ptypes.BaseCurrency) + if !found { + return nil, sdkerrors.Wrapf(assetprofiletypes.ErrAssetProfileNotFound, "asset %s not found", ptypes.BaseCurrency) + } + baseCurrency := entry.Denom + var closedMtp *types.MTP var repayAmount sdk.Int switch mtp.Position { case types.Position_LONG: - closedMtp, repayAmount, err = k.CloseLong(ctx, msg) + closedMtp, repayAmount, err = k.CloseLong(ctx, msg, baseCurrency) if err != nil { return nil, err } case types.Position_SHORT: - closedMtp, repayAmount, err = k.CloseShort(ctx, msg) + closedMtp, repayAmount, err = k.CloseShort(ctx, msg, baseCurrency) if err != nil { return nil, err } @@ -31,22 +40,18 @@ func (k Keeper) Close(ctx sdk.Context, msg *types.MsgClose) (*types.MsgCloseResp return nil, sdkerrors.Wrap(types.ErrInvalidPosition, mtp.Position.String()) } - collateralIndex := len(mtp.Collaterals) - 1 - custodyIndex := len(mtp.Custodies) - 1 - mtpPosIndex := len(mtp.Leverages) - 1 - ctx.EventManager().EmitEvent(sdk.NewEvent(types.EventClose, sdk.NewAttribute("id", strconv.FormatInt(int64(closedMtp.Id), 10)), sdk.NewAttribute("position", closedMtp.Position.String()), sdk.NewAttribute("address", closedMtp.Address), - sdk.NewAttribute("collateral", closedMtp.Collaterals[collateralIndex].String()), - sdk.NewAttribute("custody", closedMtp.Custodies[custodyIndex].String()), + sdk.NewAttribute("collateral", closedMtp.Collateral.String()), + sdk.NewAttribute("custody", closedMtp.Custody.String()), sdk.NewAttribute("repay_amount", repayAmount.String()), - sdk.NewAttribute("leverage", closedMtp.Leverages[mtpPosIndex].String()), + sdk.NewAttribute("leverage", fmt.Sprintf("%s", closedMtp.Leverage)), sdk.NewAttribute("liabilities", closedMtp.Liabilities.String()), - sdk.NewAttribute("borrow_interest_paid_collateral", mtp.BorrowInterestPaidCollaterals[collateralIndex].String()), - sdk.NewAttribute("borrow_interest_paid_custody", mtp.BorrowInterestPaidCustodies[custodyIndex].String()), - sdk.NewAttribute("borrow_interest_unpaid_collateral", closedMtp.BorrowInterestUnpaidCollaterals[collateralIndex].String()), + sdk.NewAttribute("borrow_interest_paid_collateral", mtp.BorrowInterestPaidCollateral.String()), + sdk.NewAttribute("borrow_interest_paid_custody", mtp.BorrowInterestPaidCustody.String()), + sdk.NewAttribute("borrow_interest_unpaid_collateral", closedMtp.BorrowInterestUnpaidCollateral.String()), sdk.NewAttribute("health", closedMtp.MtpHealth.String()), )) diff --git a/x/margin/keeper/close_long.go b/x/margin/keeper/close_long.go index 83be406d7..97a53ddda 100644 --- a/x/margin/keeper/close_long.go +++ b/x/margin/keeper/close_long.go @@ -6,58 +6,50 @@ import ( "github.com/elys-network/elys/x/margin/types" ) -func (k Keeper) CloseLong(ctx sdk.Context, msg *types.MsgClose) (*types.MTP, sdk.Int, error) { +func (k Keeper) CloseLong(ctx sdk.Context, msg *types.MsgClose, baseCurrency string) (*types.MTP, sdk.Int, error) { // Retrieve MTP mtp, err := k.CloseLongChecker.GetMTP(ctx, msg.Creator, msg.Id) if err != nil { return nil, sdk.ZeroInt(), err } + if msg.Amount.GT(mtp.Custody) || msg.Amount.IsNegative() { + return nil, sdk.ZeroInt(), types.ErrInvalidCloseSize + } + // Retrieve Pool pool, found := k.CloseLongChecker.GetPool(ctx, mtp.AmmPoolId) if !found { return nil, sdk.ZeroInt(), sdkerrors.Wrap(types.ErrInvalidBorrowingAsset, "invalid pool id") } - repayAmount := sdk.ZeroInt() - for _, custody := range mtp.Custodies { - custodyAsset := custody.Denom - // Retrieve AmmPool - ammPool, err := k.CloseLongChecker.GetAmmPool(ctx, mtp.AmmPoolId, custodyAsset) - if err != nil { - return nil, sdk.ZeroInt(), err - } - - for _, collateral := range mtp.Collaterals { - collateralAsset := collateral.Denom - // Handle Borrow Interest if within epoch position - if err := k.CloseLongChecker.HandleBorrowInterest(ctx, &mtp, &pool, ammPool, collateralAsset, custodyAsset); err != nil { - return nil, sdk.ZeroInt(), err - } - } - - // Take out custody - err = k.CloseLongChecker.TakeOutCustody(ctx, mtp, &pool, custodyAsset) - if err != nil { - return nil, sdk.ZeroInt(), err - } - - for _, collateral := range mtp.Collaterals { - collateralAsset := collateral.Denom - // Estimate swap and repay - repayAmt, err := k.CloseLongChecker.EstimateAndRepay(ctx, mtp, pool, ammPool, collateralAsset, custodyAsset) - if err != nil { - return nil, sdk.ZeroInt(), err - } - - repayAmount = repayAmount.Add(repayAmt) - } - - // Hooks after margin position closed - if k.hooks != nil { - k.hooks.AfterMarginPositionClosed(ctx, ammPool, pool) - } - } - - return &mtp, repayAmount, nil + // Retrieve AmmPool + ammPool, err := k.CloseLongChecker.GetAmmPool(ctx, mtp.AmmPoolId, mtp.CustodyAsset) + if err != nil { + return nil, sdk.ZeroInt(), err + } + + // Handle Borrow Interest if within epoch position + if err := k.CloseLongChecker.HandleBorrowInterest(ctx, &mtp, &pool, ammPool); err != nil { + return nil, sdk.ZeroInt(), err + } + + // Take out custody + err = k.CloseLongChecker.TakeOutCustody(ctx, mtp, &pool, msg.Amount) + if err != nil { + return nil, sdk.ZeroInt(), err + } + + // Estimate swap and repay + repayAmt, err := k.CloseLongChecker.EstimateAndRepay(ctx, mtp, pool, ammPool, msg.Amount, baseCurrency) + if err != nil { + return nil, sdk.ZeroInt(), err + } + + // Hooks after margin position closed + if k.hooks != nil { + k.hooks.AfterMarginPositionClosed(ctx, ammPool, pool) + } + + return &mtp, repayAmt, nil } diff --git a/x/margin/keeper/close_long_test.go b/x/margin/keeper/close_long_test.go index 91b4759fd..8d57e54e4 100644 --- a/x/margin/keeper/close_long_test.go +++ b/x/margin/keeper/close_long_test.go @@ -29,19 +29,52 @@ func TestCloseLong_MtpNotFound(t *testing.T) { msg = &types.MsgClose{ Creator: "creator", Id: 1, + Amount: sdk.NewInt(100), } ) // Mock behavior mockChecker.On("GetMTP", ctx, msg.Creator, msg.Id).Return(types.MTP{}, types.ErrMTPDoesNotExist) - _, _, err := k.CloseLong(ctx, msg) + _, _, err := k.CloseLong(ctx, msg, ptypes.BaseCurrency) // Expect an error about the mtp not existing assert.True(t, errors.Is(err, types.ErrMTPDoesNotExist)) mockChecker.AssertExpectations(t) } +func TestCloseLong_InvalidCloseSize(t *testing.T) { + // Setup the mock checker + mockChecker := new(mocks.CloseLongChecker) + + // Create an instance of Keeper with the mock checker + k := keeper.Keeper{ + CloseLongChecker: mockChecker, + } + + var ( + ctx = sdk.Context{} // Mock or setup a context + msg = &types.MsgClose{ + Creator: "creator", + Id: 1, + Amount: sdk.NewInt(100), + } + mtp = types.MTP{ + AmmPoolId: 2, + Custody: sdk.NewInt(0), + } + ) + + // Mock behavior + mockChecker.On("GetMTP", ctx, msg.Creator, msg.Id).Return(mtp, nil) + + _, _, err := k.CloseLong(ctx, msg, ptypes.BaseCurrency) + + // Expect an error about the pool not existing + assert.True(t, errors.Is(err, types.ErrInvalidCloseSize)) + mockChecker.AssertExpectations(t) +} + func TestCloseLong_PoolNotFound(t *testing.T) { // Setup the mock checker mockChecker := new(mocks.CloseLongChecker) @@ -56,9 +89,11 @@ func TestCloseLong_PoolNotFound(t *testing.T) { msg = &types.MsgClose{ Creator: "creator", Id: 1, + Amount: sdk.NewInt(100), } mtp = types.MTP{ AmmPoolId: 2, + Custody: sdk.NewInt(100), } ) @@ -66,7 +101,7 @@ func TestCloseLong_PoolNotFound(t *testing.T) { mockChecker.On("GetMTP", ctx, msg.Creator, msg.Id).Return(mtp, nil) mockChecker.On("GetPool", ctx, mtp.AmmPoolId).Return(types.Pool{}, false) - _, _, err := k.CloseLong(ctx, msg) + _, _, err := k.CloseLong(ctx, msg, ptypes.BaseCurrency) // Expect an error about the pool not existing assert.True(t, errors.Is(err, types.ErrInvalidBorrowingAsset)) @@ -87,19 +122,21 @@ func TestCloseLong_AmmPoolNotFound(t *testing.T) { msg = &types.MsgClose{ Creator: "creator", Id: 1, + Amount: sdk.NewInt(100), } mtp = types.MTP{ - AmmPoolId: 2, - Custodies: []sdk.Coin{sdk.NewCoin("uatom", sdk.NewInt(0))}, + AmmPoolId: 2, + CustodyAsset: "uatom", + Custody: sdk.NewInt(100), } ) // Mock behavior mockChecker.On("GetMTP", ctx, msg.Creator, msg.Id).Return(mtp, nil) mockChecker.On("GetPool", ctx, mtp.AmmPoolId).Return(types.Pool{}, true) - mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.Custodies[0].Denom).Return(ammtypes.Pool{}, sdkerrors.Wrap(types.ErrPoolDoesNotExist, mtp.Custodies[0].Denom)) + mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.CustodyAsset).Return(ammtypes.Pool{}, sdkerrors.Wrap(types.ErrPoolDoesNotExist, mtp.CustodyAsset)) - _, _, err := k.CloseLong(ctx, msg) + _, _, err := k.CloseLong(ctx, msg, ptypes.BaseCurrency) // Expect an error about the pool not existing assert.True(t, errors.Is(err, types.ErrPoolDoesNotExist)) @@ -120,11 +157,14 @@ func TestCloseLong_ErrorHandleBorrowInterest(t *testing.T) { msg = &types.MsgClose{ Creator: "creator", Id: 1, + Amount: sdk.NewInt(100), } mtp = types.MTP{ - AmmPoolId: 2, - Collaterals: []sdk.Coin{sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(0))}, - Custodies: []sdk.Coin{sdk.NewCoin("uatom", sdk.NewInt(0))}, + AmmPoolId: 2, + CollateralAsset: ptypes.BaseCurrency, + CustodyAsset: "uatom", + Collateral: sdk.NewInt(0), + Custody: sdk.NewInt(100), } pool = types.Pool{ BorrowInterestRate: math.LegacyNewDec(2), @@ -135,10 +175,10 @@ func TestCloseLong_ErrorHandleBorrowInterest(t *testing.T) { // Mock behavior mockChecker.On("GetMTP", ctx, msg.Creator, msg.Id).Return(mtp, nil) mockChecker.On("GetPool", ctx, mtp.AmmPoolId).Return(pool, true) - mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.Custodies[0].Denom).Return(ammPool, nil) - mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool, mtp.Collaterals[0].Denom, mtp.Custodies[0].Denom).Return(errors.New("error executing handle borrow interest")) + mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.CustodyAsset).Return(ammPool, nil) + mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(errors.New("error executing handle borrow interest")) - _, _, err := k.CloseLong(ctx, msg) + _, _, err := k.CloseLong(ctx, msg, ptypes.BaseCurrency) // Expect an error about handle borrow interest assert.Equal(t, errors.New("error executing handle borrow interest"), err) @@ -159,11 +199,14 @@ func TestCloseLong_ErrorTakeOutCustody(t *testing.T) { msg = &types.MsgClose{ Creator: "creator", Id: 1, + Amount: sdk.NewInt(100), } mtp = types.MTP{ - AmmPoolId: 2, - Collaterals: []sdk.Coin{sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(0))}, - Custodies: []sdk.Coin{sdk.NewCoin("uatom", sdk.NewInt(0))}, + AmmPoolId: 2, + CollateralAsset: ptypes.BaseCurrency, + CustodyAsset: "uatom", + Collateral: sdk.NewInt(0), + Custody: sdk.NewInt(100), } pool = types.Pool{ BorrowInterestRate: math.LegacyNewDec(2), @@ -174,11 +217,11 @@ func TestCloseLong_ErrorTakeOutCustody(t *testing.T) { // Mock behavior mockChecker.On("GetMTP", ctx, msg.Creator, msg.Id).Return(mtp, nil) mockChecker.On("GetPool", ctx, mtp.AmmPoolId).Return(pool, true) - mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.Custodies[0].Denom).Return(ammPool, nil) - mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool, mtp.Collaterals[0].Denom, mtp.Custodies[0].Denom).Return(nil) - mockChecker.On("TakeOutCustody", ctx, mtp, &pool, mtp.Custodies[0].Denom).Return(errors.New("error executing take out custody")) + mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.CustodyAsset).Return(ammPool, nil) + mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(nil) + mockChecker.On("TakeOutCustody", ctx, mtp, &pool, msg.Amount).Return(errors.New("error executing take out custody")) - _, _, err := k.CloseLong(ctx, msg) + _, _, err := k.CloseLong(ctx, msg, ptypes.BaseCurrency) // Expect an error about take out custody assert.Equal(t, errors.New("error executing take out custody"), err) @@ -199,11 +242,14 @@ func TestCloseLong_ErrorEstimateAndRepay(t *testing.T) { msg = &types.MsgClose{ Creator: "creator", Id: 1, + Amount: sdk.NewInt(100), } mtp = types.MTP{ - AmmPoolId: 2, - Collaterals: []sdk.Coin{sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(0))}, - Custodies: []sdk.Coin{sdk.NewCoin("uatom", sdk.NewInt(0))}, + AmmPoolId: 2, + CollateralAsset: ptypes.BaseCurrency, + CustodyAsset: "uatom", + Collateral: sdk.NewInt(0), + Custody: sdk.NewInt(100), } pool = types.Pool{ BorrowInterestRate: math.LegacyNewDec(2), @@ -214,12 +260,12 @@ func TestCloseLong_ErrorEstimateAndRepay(t *testing.T) { // Mock behavior mockChecker.On("GetMTP", ctx, msg.Creator, msg.Id).Return(mtp, nil) mockChecker.On("GetPool", ctx, mtp.AmmPoolId).Return(pool, true) - mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.Custodies[0].Denom).Return(ammPool, nil) - mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool, mtp.Collaterals[0].Denom, mtp.Custodies[0].Denom).Return(nil) - mockChecker.On("TakeOutCustody", ctx, mtp, &pool, mtp.Custodies[0].Denom).Return(nil) - mockChecker.On("EstimateAndRepay", ctx, mtp, pool, ammPool, mtp.Collaterals[0].Denom, mtp.Custodies[0].Denom).Return(sdk.Int{}, errors.New("error executing estimate and repay")) + mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.CustodyAsset).Return(ammPool, nil) + mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(nil) + mockChecker.On("TakeOutCustody", ctx, mtp, &pool, msg.Amount).Return(nil) + mockChecker.On("EstimateAndRepay", ctx, mtp, pool, ammPool, msg.Amount, ptypes.BaseCurrency).Return(sdk.Int{}, errors.New("error executing estimate and repay")) - _, _, err := k.CloseLong(ctx, msg) + _, _, err := k.CloseLong(ctx, msg, ptypes.BaseCurrency) // Expect an error about estimate and repay assert.Equal(t, errors.New("error executing estimate and repay"), err) @@ -240,11 +286,14 @@ func TestCloseLong_SuccessfulClosingLongPosition(t *testing.T) { msg = &types.MsgClose{ Creator: "creator", Id: 1, + Amount: sdk.NewInt(100), } mtp = types.MTP{ - AmmPoolId: 2, - Collaterals: []sdk.Coin{sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(0))}, - Custodies: []sdk.Coin{sdk.NewCoin("uatom", sdk.NewInt(0))}, + AmmPoolId: 2, + CollateralAsset: ptypes.BaseCurrency, + CustodyAsset: "uatom", + Collateral: sdk.NewInt(0), + Custody: sdk.NewInt(100), } pool = types.Pool{ BorrowInterestRate: math.LegacyNewDec(2), @@ -256,12 +305,12 @@ func TestCloseLong_SuccessfulClosingLongPosition(t *testing.T) { // Mock behavior mockChecker.On("GetMTP", ctx, msg.Creator, msg.Id).Return(mtp, nil) mockChecker.On("GetPool", ctx, mtp.AmmPoolId).Return(pool, true) - mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.Custodies[0].Denom).Return(ammPool, nil) - mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool, mtp.Collaterals[0].Denom, mtp.Custodies[0].Denom).Return(nil) - mockChecker.On("TakeOutCustody", ctx, mtp, &pool, mtp.Custodies[0].Denom).Return(nil) - mockChecker.On("EstimateAndRepay", ctx, mtp, pool, ammPool, mtp.Collaterals[0].Denom, mtp.Custodies[0].Denom).Return(repayAmount, nil) + mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.CustodyAsset).Return(ammPool, nil) + mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(nil) + mockChecker.On("TakeOutCustody", ctx, mtp, &pool, msg.Amount).Return(nil) + mockChecker.On("EstimateAndRepay", ctx, mtp, pool, ammPool, msg.Amount, ptypes.BaseCurrency).Return(repayAmount, nil) - mtpOut, repayAmountOut, err := k.CloseLong(ctx, msg) + mtpOut, repayAmountOut, err := k.CloseLong(ctx, msg, ptypes.BaseCurrency) // Expect no error assert.Nil(t, err) diff --git a/x/margin/keeper/close_short.go b/x/margin/keeper/close_short.go index d870578e3..464d508df 100644 --- a/x/margin/keeper/close_short.go +++ b/x/margin/keeper/close_short.go @@ -6,57 +6,50 @@ import ( "github.com/elys-network/elys/x/margin/types" ) -func (k Keeper) CloseShort(ctx sdk.Context, msg *types.MsgClose) (*types.MTP, sdk.Int, error) { +func (k Keeper) CloseShort(ctx sdk.Context, msg *types.MsgClose, baseCurrency string) (*types.MTP, sdk.Int, error) { // Retrieve MTP mtp, err := k.CloseShortChecker.GetMTP(ctx, msg.Creator, msg.Id) if err != nil { return nil, sdk.ZeroInt(), err } + if msg.Amount.GT(mtp.Custody) || msg.Amount.IsNegative() { + return nil, sdk.ZeroInt(), types.ErrInvalidCloseSize + } + // Retrieve Pool pool, found := k.CloseShortChecker.GetPool(ctx, mtp.AmmPoolId) if !found { return nil, sdk.ZeroInt(), sdkerrors.Wrap(types.ErrInvalidBorrowingAsset, "invalid pool id") } - repayAmount := sdk.ZeroInt() - for _, custody := range mtp.Custodies { - custodyAsset := custody.Denom - // Retrieve AmmPool - ammPool, err := k.CloseShortChecker.GetAmmPool(ctx, mtp.AmmPoolId, custodyAsset) - if err != nil { - return nil, sdk.ZeroInt(), err - } - - for _, collateral := range mtp.Collaterals { - collateralAsset := collateral.Denom - // Handle Borrow Interest if within epoch position - if err := k.CloseShortChecker.HandleBorrowInterest(ctx, &mtp, &pool, ammPool, collateralAsset, custodyAsset); err != nil { - return nil, sdk.ZeroInt(), err - } - } - - // Take out custody - err = k.CloseShortChecker.TakeOutCustody(ctx, mtp, &pool, custodyAsset) - if err != nil { - return nil, sdk.ZeroInt(), err - } - - for _, collateral := range mtp.Collaterals { - collateralAsset := collateral.Denom - // Estimate swap and repay - repayAmt, err := k.CloseShortChecker.EstimateAndRepay(ctx, mtp, pool, ammPool, collateralAsset, custodyAsset) - if err != nil { - return nil, sdk.ZeroInt(), err - } - repayAmount = repayAmount.Add(repayAmt) - } - - // Hooks after margin position closed - if k.hooks != nil { - k.hooks.AfterMarginPositionClosed(ctx, ammPool, pool) - } - } - - return &mtp, repayAmount, nil + // Retrieve AmmPool + ammPool, err := k.CloseShortChecker.GetAmmPool(ctx, mtp.AmmPoolId, mtp.CustodyAsset) + if err != nil { + return nil, sdk.ZeroInt(), err + } + + // Handle Borrow Interest if within epoch position + if err := k.CloseShortChecker.HandleBorrowInterest(ctx, &mtp, &pool, ammPool); err != nil { + return nil, sdk.ZeroInt(), err + } + + // Take out custody + err = k.CloseShortChecker.TakeOutCustody(ctx, mtp, &pool, msg.Amount) + if err != nil { + return nil, sdk.ZeroInt(), err + } + + // Estimate swap and repay + repayAmt, err := k.CloseShortChecker.EstimateAndRepay(ctx, mtp, pool, ammPool, msg.Amount, baseCurrency) + if err != nil { + return nil, sdk.ZeroInt(), err + } + + // Hooks after margin position closed + if k.hooks != nil { + k.hooks.AfterMarginPositionClosed(ctx, ammPool, pool) + } + + return &mtp, repayAmt, nil } diff --git a/x/margin/keeper/close_short_test.go b/x/margin/keeper/close_short_test.go index 6bd60fafa..50461037e 100644 --- a/x/margin/keeper/close_short_test.go +++ b/x/margin/keeper/close_short_test.go @@ -29,19 +29,52 @@ func TestCloseShort_MtpNotFound(t *testing.T) { msg = &types.MsgClose{ Creator: "creator", Id: 1, + Amount: sdk.NewInt(100), } ) // Mock behavior mockChecker.On("GetMTP", ctx, msg.Creator, msg.Id).Return(types.MTP{}, types.ErrMTPDoesNotExist) - _, _, err := k.CloseShort(ctx, msg) + _, _, err := k.CloseShort(ctx, msg, ptypes.BaseCurrency) // Expect an error about the mtp not existing assert.True(t, errors.Is(err, types.ErrMTPDoesNotExist)) mockChecker.AssertExpectations(t) } +func TestCloseShort_InvalidCloseSize(t *testing.T) { + // Setup the mock checker + mockChecker := new(mocks.CloseShortChecker) + + // Create an instance of Keeper with the mock checker + k := keeper.Keeper{ + CloseShortChecker: mockChecker, + } + + var ( + ctx = sdk.Context{} // Mock or setup a context + msg = &types.MsgClose{ + Creator: "creator", + Id: 1, + Amount: sdk.NewInt(100), + } + mtp = types.MTP{ + AmmPoolId: 2, + Custody: sdk.NewInt(0), + } + ) + + // Mock behavior + mockChecker.On("GetMTP", ctx, msg.Creator, msg.Id).Return(mtp, nil) + + _, _, err := k.CloseShort(ctx, msg, ptypes.BaseCurrency) + + // Expect an error about the pool not existing + assert.True(t, errors.Is(err, types.ErrInvalidCloseSize)) + mockChecker.AssertExpectations(t) +} + func TestCloseShort_PoolNotFound(t *testing.T) { // Setup the mock checker mockChecker := new(mocks.CloseShortChecker) @@ -56,9 +89,11 @@ func TestCloseShort_PoolNotFound(t *testing.T) { msg = &types.MsgClose{ Creator: "creator", Id: 1, + Amount: sdk.NewInt(100), } mtp = types.MTP{ AmmPoolId: 2, + Custody: sdk.NewInt(100), } ) @@ -66,7 +101,7 @@ func TestCloseShort_PoolNotFound(t *testing.T) { mockChecker.On("GetMTP", ctx, msg.Creator, msg.Id).Return(mtp, nil) mockChecker.On("GetPool", ctx, mtp.AmmPoolId).Return(types.Pool{}, false) - _, _, err := k.CloseShort(ctx, msg) + _, _, err := k.CloseShort(ctx, msg, ptypes.BaseCurrency) // Expect an error about the pool not existing assert.True(t, errors.Is(err, types.ErrInvalidBorrowingAsset)) @@ -87,19 +122,20 @@ func TestCloseShort_AmmPoolNotFound(t *testing.T) { msg = &types.MsgClose{ Creator: "creator", Id: 1, + Amount: sdk.NewInt(100), } mtp = types.MTP{ AmmPoolId: 2, - Custodies: []sdk.Coin{sdk.NewCoin("uatom", sdk.NewInt(0))}, + Custody: sdk.NewInt(100), } ) // Mock behavior mockChecker.On("GetMTP", ctx, msg.Creator, msg.Id).Return(mtp, nil) mockChecker.On("GetPool", ctx, mtp.AmmPoolId).Return(types.Pool{}, true) - mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.Custodies[0].Denom).Return(ammtypes.Pool{}, sdkerrors.Wrap(types.ErrPoolDoesNotExist, mtp.Custodies[0].Denom)) + mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.CustodyAsset).Return(ammtypes.Pool{}, sdkerrors.Wrap(types.ErrPoolDoesNotExist, mtp.CustodyAsset)) - _, _, err := k.CloseShort(ctx, msg) + _, _, err := k.CloseShort(ctx, msg, ptypes.BaseCurrency) // Expect an error about the pool not existing assert.True(t, errors.Is(err, types.ErrPoolDoesNotExist)) @@ -120,11 +156,12 @@ func TestCloseShort_ErrorHandleBorrowInterest(t *testing.T) { msg = &types.MsgClose{ Creator: "creator", Id: 1, + Amount: sdk.NewInt(100), } mtp = types.MTP{ - AmmPoolId: 2, - Custodies: []sdk.Coin{sdk.NewCoin("uatom", sdk.NewInt(0))}, - Collaterals: []sdk.Coin{sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(0))}, + AmmPoolId: 2, + Custody: sdk.NewInt(100), + Collateral: sdk.NewInt(0), } pool = types.Pool{ BorrowInterestRate: math.LegacyNewDec(2), @@ -135,10 +172,10 @@ func TestCloseShort_ErrorHandleBorrowInterest(t *testing.T) { // Mock behavior mockChecker.On("GetMTP", ctx, msg.Creator, msg.Id).Return(mtp, nil) mockChecker.On("GetPool", ctx, mtp.AmmPoolId).Return(pool, true) - mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.Custodies[0].Denom).Return(ammPool, nil) - mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool, mtp.Collaterals[0].Denom, mtp.Custodies[0].Denom).Return(errors.New("error executing handle borrow interest")) + mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.CustodyAsset).Return(ammPool, nil) + mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(errors.New("error executing handle borrow interest")) - _, _, err := k.CloseShort(ctx, msg) + _, _, err := k.CloseShort(ctx, msg, ptypes.BaseCurrency) // Expect an error about handle borrow interest assert.Equal(t, errors.New("error executing handle borrow interest"), err) @@ -159,11 +196,12 @@ func TestCloseShort_ErrorTakeOutCustody(t *testing.T) { msg = &types.MsgClose{ Creator: "creator", Id: 1, + Amount: sdk.NewInt(100), } mtp = types.MTP{ - AmmPoolId: 2, - Custodies: []sdk.Coin{sdk.NewCoin("uatom", sdk.NewInt(0))}, - Collaterals: []sdk.Coin{sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(0))}, + AmmPoolId: 2, + Custody: sdk.NewInt(100), + Collateral: sdk.NewInt(0), } pool = types.Pool{ BorrowInterestRate: math.LegacyNewDec(2), @@ -174,11 +212,11 @@ func TestCloseShort_ErrorTakeOutCustody(t *testing.T) { // Mock behavior mockChecker.On("GetMTP", ctx, msg.Creator, msg.Id).Return(mtp, nil) mockChecker.On("GetPool", ctx, mtp.AmmPoolId).Return(pool, true) - mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.Custodies[0].Denom).Return(ammPool, nil) - mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool, mtp.Collaterals[0].Denom, mtp.Custodies[0].Denom).Return(nil) - mockChecker.On("TakeOutCustody", ctx, mtp, &pool, mtp.Custodies[0].Denom).Return(errors.New("error executing take out custody")) + mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.CustodyAsset).Return(ammPool, nil) + mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(nil) + mockChecker.On("TakeOutCustody", ctx, mtp, &pool, msg.Amount).Return(errors.New("error executing take out custody")) - _, _, err := k.CloseShort(ctx, msg) + _, _, err := k.CloseShort(ctx, msg, ptypes.BaseCurrency) // Expect an error about take out custody assert.Equal(t, errors.New("error executing take out custody"), err) @@ -199,11 +237,12 @@ func TestCloseShort_ErrorEstimateAndRepay(t *testing.T) { msg = &types.MsgClose{ Creator: "creator", Id: 1, + Amount: sdk.NewInt(100), } mtp = types.MTP{ - AmmPoolId: 2, - Custodies: []sdk.Coin{sdk.NewCoin("uatom", sdk.NewInt(0))}, - Collaterals: []sdk.Coin{sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(0))}, + AmmPoolId: 2, + Custody: sdk.NewInt(100), + Collateral: sdk.NewInt(0), } pool = types.Pool{ BorrowInterestRate: math.LegacyNewDec(2), @@ -214,12 +253,12 @@ func TestCloseShort_ErrorEstimateAndRepay(t *testing.T) { // Mock behavior mockChecker.On("GetMTP", ctx, msg.Creator, msg.Id).Return(mtp, nil) mockChecker.On("GetPool", ctx, mtp.AmmPoolId).Return(pool, true) - mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.Custodies[0].Denom).Return(ammPool, nil) - mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool, mtp.Collaterals[0].Denom, mtp.Custodies[0].Denom).Return(nil) - mockChecker.On("TakeOutCustody", ctx, mtp, &pool, mtp.Custodies[0].Denom).Return(nil) - mockChecker.On("EstimateAndRepay", ctx, mtp, pool, ammPool, mtp.Collaterals[0].Denom, mtp.Custodies[0].Denom).Return(sdk.Int{}, errors.New("error executing estimate and repay")) + mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.CustodyAsset).Return(ammPool, nil) + mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(nil) + mockChecker.On("TakeOutCustody", ctx, mtp, &pool, msg.Amount).Return(nil) + mockChecker.On("EstimateAndRepay", ctx, mtp, pool, ammPool, msg.Amount, ptypes.BaseCurrency).Return(sdk.Int{}, errors.New("error executing estimate and repay")) - _, _, err := k.CloseShort(ctx, msg) + _, _, err := k.CloseShort(ctx, msg, ptypes.BaseCurrency) // Expect an error about estimate and repay assert.Equal(t, errors.New("error executing estimate and repay"), err) @@ -240,11 +279,12 @@ func TestCloseShort_SuccessfulClosingLongPosition(t *testing.T) { msg = &types.MsgClose{ Creator: "creator", Id: 1, + Amount: sdk.NewInt(100), } mtp = types.MTP{ - AmmPoolId: 2, - Custodies: []sdk.Coin{sdk.NewCoin("uatom", sdk.NewInt(0))}, - Collaterals: []sdk.Coin{sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(0))}, + AmmPoolId: 2, + Custody: sdk.NewInt(100), + Collateral: sdk.NewInt(0), } pool = types.Pool{ BorrowInterestRate: math.LegacyNewDec(2), @@ -256,12 +296,12 @@ func TestCloseShort_SuccessfulClosingLongPosition(t *testing.T) { // Mock behavior mockChecker.On("GetMTP", ctx, msg.Creator, msg.Id).Return(mtp, nil) mockChecker.On("GetPool", ctx, mtp.AmmPoolId).Return(pool, true) - mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.Custodies[0].Denom).Return(ammPool, nil) - mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool, mtp.Collaterals[0].Denom, mtp.Custodies[0].Denom).Return(nil) - mockChecker.On("TakeOutCustody", ctx, mtp, &pool, mtp.Custodies[0].Denom).Return(nil) - mockChecker.On("EstimateAndRepay", ctx, mtp, pool, ammPool, mtp.Collaterals[0].Denom, mtp.Custodies[0].Denom).Return(repayAmount, nil) + mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.CustodyAsset).Return(ammPool, nil) + mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(nil) + mockChecker.On("TakeOutCustody", ctx, mtp, &pool, msg.Amount).Return(nil) + mockChecker.On("EstimateAndRepay", ctx, mtp, pool, ammPool, msg.Amount, ptypes.BaseCurrency).Return(repayAmount, nil) - mtpOut, repayAmountOut, err := k.CloseShort(ctx, msg) + mtpOut, repayAmountOut, err := k.CloseShort(ctx, msg, ptypes.BaseCurrency) // Expect no error assert.Nil(t, err) diff --git a/x/margin/keeper/emit_open_event.go b/x/margin/keeper/emit_open_event.go index 964ebefb1..572b5b7b8 100644 --- a/x/margin/keeper/emit_open_event.go +++ b/x/margin/keeper/emit_open_event.go @@ -6,5 +6,5 @@ import ( ) func (k Keeper) EmitOpenEvent(ctx sdk.Context, mtp *types.MTP) { - ctx.EventManager().EmitEvent(k.GenerateOpenEvent(mtp)) + ctx.EventManager().EmitEvent(types.GenerateOpenEvent(mtp)) } diff --git a/x/margin/keeper/estimate_and_repay.go b/x/margin/keeper/estimate_and_repay.go index 52d4c146c..4403cffc4 100644 --- a/x/margin/keeper/estimate_and_repay.go +++ b/x/margin/keeper/estimate_and_repay.go @@ -6,15 +6,31 @@ import ( "github.com/elys-network/elys/x/margin/types" ) -func (k Keeper) EstimateAndRepay(ctx sdk.Context, mtp types.MTP, pool types.Pool, ammPool ammtypes.Pool, collateralAsset string, custodyAsset string) (sdk.Int, error) { - collateralIndex, custodyIndex := types.GetMTPAssetIndex(&mtp, collateralAsset, custodyAsset) - cutodyAmtTokenIn := sdk.NewCoin(mtp.Custodies[custodyIndex].Denom, mtp.Custodies[custodyIndex].Amount) - repayAmount, err := k.EstimateSwap(ctx, cutodyAmtTokenIn, mtp.Collaterals[collateralIndex].Denom, ammPool) - if err != nil { - return sdk.ZeroInt(), err +func (k Keeper) EstimateAndRepay(ctx sdk.Context, mtp types.MTP, pool types.Pool, ammPool ammtypes.Pool, amount sdk.Int, baseCurrency string) (sdk.Int, error) { + // init repay amount + repayAmount := sdk.ZeroInt() + + // if position is long, repay in collateral asset + if mtp.Position == types.Position_LONG { + custodyAmtTokenIn := sdk.NewCoin(mtp.CustodyAsset, amount) + var err error + repayAmount, err = k.EstimateSwap(ctx, custodyAmtTokenIn, mtp.CollateralAsset, ammPool) + if err != nil { + return sdk.ZeroInt(), err + } + } else if mtp.Position == types.Position_SHORT { + // if position is short, repay in trading asset + custodyAmtTokenIn := sdk.NewCoin(mtp.CustodyAsset, amount) + var err error + repayAmount, err = k.EstimateSwap(ctx, custodyAmtTokenIn, mtp.TradingAsset, ammPool) + if err != nil { + return sdk.ZeroInt(), err + } + } else { + return sdk.ZeroInt(), types.ErrInvalidPosition } - if err := k.Repay(ctx, &mtp, &pool, ammPool, repayAmount, false, collateralAsset); err != nil { + if err := k.Repay(ctx, &mtp, &pool, ammPool, repayAmount, false, amount, baseCurrency); err != nil { return sdk.ZeroInt(), err } diff --git a/x/margin/keeper/events.go b/x/margin/keeper/events.go index fa70f06c8..b883c73c9 100644 --- a/x/margin/keeper/events.go +++ b/x/margin/keeper/events.go @@ -21,13 +21,13 @@ func (k Keeper) EmitForceClose(ctx sdk.Context, mtp *types.MTP, repayAmount sdk. sdk.NewAttribute("id", strconv.FormatInt(int64(mtp.Id), 10)), sdk.NewAttribute("position", mtp.Position.String()), sdk.NewAttribute("address", mtp.Address), - sdk.NewAttribute("collaterals", fmt.Sprintf("%s", mtp.Collaterals)), - sdk.NewAttribute("custodies", fmt.Sprintf("%s", mtp.Custodies)), + sdk.NewAttribute("collaterals", mtp.Collateral.String()), + sdk.NewAttribute("custodies", mtp.Custody.String()), sdk.NewAttribute("repay_amount", repayAmount.String()), - sdk.NewAttribute("leverage", fmt.Sprintf("%s", mtp.Leverages)), + sdk.NewAttribute("leverage", fmt.Sprintf("%s", mtp.Leverage)), sdk.NewAttribute("liabilities", mtp.Liabilities.String()), - sdk.NewAttribute("borrow_interest_paid_collaterals", fmt.Sprintf("%s", mtp.BorrowInterestPaidCollaterals)), - sdk.NewAttribute("borrow_interest_paid_custodies", fmt.Sprintf("%s", mtp.BorrowInterestPaidCustodies)), + sdk.NewAttribute("borrow_interest_paid_collaterals", mtp.BorrowInterestPaidCollateral.String()), + sdk.NewAttribute("borrow_interest_paid_custodies", mtp.BorrowInterestPaidCustody.String()), sdk.NewAttribute("health", mtp.MtpHealth.String()), sdk.NewAttribute("closer", closer), )) diff --git a/x/margin/keeper/force_close_long.go b/x/margin/keeper/force_close_long.go index 4c2620e94..ad23dad0d 100644 --- a/x/margin/keeper/force_close_long.go +++ b/x/margin/keeper/force_close_long.go @@ -6,36 +6,30 @@ import ( "github.com/elys-network/elys/x/margin/types" ) -func (k Keeper) ForceCloseLong(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, takeFundPayment bool) (sdk.Int, error) { +func (k Keeper) ForceCloseLong(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, takeFundPayment bool, baseCurrency string) (sdk.Int, error) { repayAmount := sdk.ZeroInt() - for _, custody := range mtp.Custodies { - custodyAsset := custody.Denom - // Retrieve AmmPool - ammPool, err := k.GetAmmPool(ctx, mtp.AmmPoolId, custodyAsset) - if err != nil { - return math.ZeroInt(), err - } + // Retrieve AmmPool + ammPool, err := k.GetAmmPool(ctx, mtp.AmmPoolId, mtp.TradingAsset) + if err != nil { + return math.ZeroInt(), err + } - err = k.TakeOutCustody(ctx, *mtp, pool, custodyAsset) - if err != nil { - return math.ZeroInt(), err - } + err = k.TakeOutCustody(ctx, *mtp, pool, mtp.Custody) + if err != nil { + return math.ZeroInt(), err + } - for _, collateral := range mtp.Collaterals { - collateralAsset := collateral.Denom - // Estimate swap and repay - repayAmt, err := k.EstimateAndRepay(ctx, *mtp, *pool, ammPool, collateralAsset, custodyAsset) - if err != nil { - return math.ZeroInt(), err - } + // Estimate swap and repay + repayAmt, err := k.EstimateAndRepay(ctx, *mtp, *pool, ammPool, mtp.Custody, baseCurrency) + if err != nil { + return math.ZeroInt(), err + } - repayAmount = repayAmount.Add(repayAmt) - } + repayAmount = repayAmount.Add(repayAmt) - // Hooks after margin position closed - if k.hooks != nil { - k.hooks.AfterMarginPositionClosed(ctx, ammPool, *pool) - } + // Hooks after margin position closed + if k.hooks != nil { + k.hooks.AfterMarginPositionClosed(ctx, ammPool, *pool) } return repayAmount, nil diff --git a/x/margin/keeper/force_close_short.go b/x/margin/keeper/force_close_short.go index b50eb2cef..a63e4e025 100644 --- a/x/margin/keeper/force_close_short.go +++ b/x/margin/keeper/force_close_short.go @@ -6,36 +6,30 @@ import ( "github.com/elys-network/elys/x/margin/types" ) -func (k Keeper) ForceCloseShort(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, takeFundPayment bool) (sdk.Int, error) { +func (k Keeper) ForceCloseShort(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, takeFundPayment bool, baseCurrency string) (sdk.Int, error) { repayAmount := sdk.ZeroInt() - for _, custody := range mtp.Custodies { - custodyAsset := custody.Denom - // Retrieve AmmPool - ammPool, err := k.GetAmmPool(ctx, mtp.AmmPoolId, custodyAsset) - if err != nil { - return math.ZeroInt(), err - } + // Retrieve AmmPool + ammPool, err := k.GetAmmPool(ctx, mtp.AmmPoolId, mtp.TradingAsset) + if err != nil { + return math.ZeroInt(), err + } - err = k.TakeOutCustody(ctx, *mtp, pool, custodyAsset) - if err != nil { - return math.ZeroInt(), err - } + err = k.TakeOutCustody(ctx, *mtp, pool, mtp.Custody) + if err != nil { + return math.ZeroInt(), err + } - for _, collateral := range mtp.Collaterals { - collateralAsset := collateral.Denom - // Estimate swap and repay - repayAmt, err := k.EstimateAndRepay(ctx, *mtp, *pool, ammPool, collateralAsset, custodyAsset) - if err != nil { - return math.ZeroInt(), err - } + // Estimate swap and repay + repayAmt, err := k.EstimateAndRepay(ctx, *mtp, *pool, ammPool, mtp.Custody, baseCurrency) + if err != nil { + return math.ZeroInt(), err + } - repayAmount = repayAmount.Add(repayAmt) - } + repayAmount = repayAmount.Add(repayAmt) - // Hooks after margin position closed - if k.hooks != nil { - k.hooks.AfterMarginPositionClosed(ctx, ammPool, *pool) - } + // Hooks after margin position closed + if k.hooks != nil { + k.hooks.AfterMarginPositionClosed(ctx, ammPool, *pool) } return repayAmount, nil diff --git a/x/margin/keeper/generate_open_event.go b/x/margin/keeper/generate_open_event.go deleted file mode 100644 index f66443d96..000000000 --- a/x/margin/keeper/generate_open_event.go +++ /dev/null @@ -1,28 +0,0 @@ -package keeper - -import ( - "strconv" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/elys-network/elys/x/margin/types" -) - -func (k Keeper) GenerateOpenEvent(mtp *types.MTP) sdk.Event { - collateralIndex := len(mtp.Collaterals) - 1 - custodyIndex := len(mtp.Custodies) - 1 - mtpPosIndex := len(mtp.Leverages) - 1 - - return sdk.NewEvent(types.EventOpen, - sdk.NewAttribute("id", strconv.FormatInt(int64(mtp.Id), 10)), - sdk.NewAttribute("position", mtp.Position.String()), - sdk.NewAttribute("address", mtp.Address), - sdk.NewAttribute("collateral", mtp.Collaterals[collateralIndex].String()), - sdk.NewAttribute("custody", mtp.Custodies[custodyIndex].String()), - sdk.NewAttribute("leverage", mtp.Leverages[mtpPosIndex].String()), - sdk.NewAttribute("liabilities", mtp.Liabilities.String()), - sdk.NewAttribute("borrow_interest_paid_collateral", mtp.BorrowInterestPaidCollaterals[collateralIndex].String()), - sdk.NewAttribute("borrow_interest_paid_custody", mtp.BorrowInterestPaidCustodies[custodyIndex].String()), - sdk.NewAttribute("borrow_interest_unpaid_collateral", mtp.BorrowInterestUnpaidCollaterals[collateralIndex].String()), - sdk.NewAttribute("health", mtp.MtpHealth.String()), - ) -} diff --git a/x/margin/keeper/get_first_valid_pool.go b/x/margin/keeper/get_first_valid_pool.go index efb01248b..4dd13aa2f 100644 --- a/x/margin/keeper/get_first_valid_pool.go +++ b/x/margin/keeper/get_first_valid_pool.go @@ -1,15 +1,18 @@ package keeper import ( + "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/elys-network/elys/x/margin/types" ) -func (k Keeper) GetFirstValidPool(ctx sdk.Context, borrowAsset string) (uint64, error) { - poolIds := k.amm.GetAllPoolIdsWithDenom(ctx, borrowAsset) - if len(poolIds) < 1 { - return 0, sdkerrors.Wrap(types.ErrInvalidBorrowingAsset, "invalid collateral asset") +func (k Keeper) GetFirstValidPool(ctx sdk.Context, collateralAsset string, tradingAsset string) (uint64, error) { + denoms := []string{collateralAsset, tradingAsset} + poolId, found := k.amm.GetPoolIdWithAllDenoms(ctx, denoms) + if !found { + return 0, sdkerrors.Wrap(types.ErrPoolDoesNotExist, fmt.Sprintf("%s", denoms)) } - return poolIds[0], nil + return poolId, nil } diff --git a/x/margin/keeper/get_first_valid_pool_test.go b/x/margin/keeper/get_first_valid_pool_test.go index 8dc02aec6..1a8a85664 100644 --- a/x/margin/keeper/get_first_valid_pool_test.go +++ b/x/margin/keeper/get_first_valid_pool_test.go @@ -8,6 +8,7 @@ import ( "github.com/elys-network/elys/x/margin/keeper" "github.com/elys-network/elys/x/margin/types" "github.com/elys-network/elys/x/margin/types/mocks" + ptypes "github.com/elys-network/elys/x/parameter/types" "github.com/stretchr/testify/assert" ) @@ -16,15 +17,17 @@ func TestGetFirstValidPool_NoPoolID(t *testing.T) { k := keeper.NewKeeper(nil, nil, nil, "cosmos1ysxv266l8w76lq0vy44ktzajdr9u9yhlxzlvga", mockAmm, nil, nil, nil, nil) ctx := sdk.Context{} // mock or setup a context + collateralAsset := ptypes.BaseCurrency borrowAsset := "testAsset" + denoms := []string{collateralAsset, borrowAsset} // Mock behavior - mockAmm.On("GetAllPoolIdsWithDenom", ctx, borrowAsset).Return([]uint64{}) + mockAmm.On("GetPoolIdWithAllDenoms", ctx, denoms).Return(uint64(0), false) - _, err := k.GetFirstValidPool(ctx, borrowAsset) + _, err := k.GetFirstValidPool(ctx, collateralAsset, borrowAsset) - // Expect an error about invalid borrowing asset - assert.True(t, errors.Is(err, types.ErrInvalidBorrowingAsset)) + // Expect an error about the pool not existing + assert.True(t, errors.Is(err, types.ErrPoolDoesNotExist)) mockAmm.AssertExpectations(t) } @@ -33,15 +36,17 @@ func TestGetFirstValidPool_ValidPoolID(t *testing.T) { k := keeper.NewKeeper(nil, nil, nil, "cosmos1ysxv266l8w76lq0vy44ktzajdr9u9yhlxzlvga", mockAmm, nil, nil, nil, nil) ctx := sdk.Context{} // mock or setup a context + collateralAsset := ptypes.BaseCurrency borrowAsset := "testAsset" + denoms := []string{collateralAsset, borrowAsset} // Mock behavior - mockAmm.On("GetAllPoolIdsWithDenom", ctx, borrowAsset).Return([]uint64{42, 43, 44}) + mockAmm.On("GetPoolIdWithAllDenoms", ctx, denoms).Return(uint64(1), true) - poolID, err := k.GetFirstValidPool(ctx, borrowAsset) + poolID, err := k.GetFirstValidPool(ctx, collateralAsset, borrowAsset) // Expect no error and the first pool ID to be returned assert.Nil(t, err) - assert.Equal(t, uint64(42), poolID) + assert.Equal(t, uint64(1), poolID) mockAmm.AssertExpectations(t) } diff --git a/x/margin/keeper/handle_borrow_interest.go b/x/margin/keeper/handle_borrow_interest.go index c7394ed39..ec0b3988e 100644 --- a/x/margin/keeper/handle_borrow_interest.go +++ b/x/margin/keeper/handle_borrow_interest.go @@ -9,7 +9,7 @@ import ( ptypes "github.com/elys-network/elys/x/parameter/types" ) -func (k Keeper) HandleBorrowInterest(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool ammtypes.Pool, collateralAsset string, custodyAsset string) error { +func (k Keeper) HandleBorrowInterest(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool ammtypes.Pool) error { epochLength := k.GetEpochLength(ctx) epochPosition := k.GetEpochPosition(ctx, epochLength) if epochPosition <= 0 { @@ -22,14 +22,14 @@ func (k Keeper) HandleBorrowInterest(ctx sdk.Context, mtp *types.MTP, pool *type } baseCurrency := entry.Denom - borrowInterestPayment, err := k.CalcMTPBorrowInterestLiabilities(ctx, mtp, pool.BorrowInterestRate, epochPosition, epochLength, ammPool, collateralAsset, baseCurrency) + borrowInterestPayment, err := k.CalcMTPBorrowInterestLiabilities(ctx, mtp, pool.BorrowInterestRate, epochPosition, epochLength, ammPool, baseCurrency) if err != nil { return err } - finalBorrowInterestPayment := k.HandleBorrowInterestPayment(ctx, collateralAsset, custodyAsset, borrowInterestPayment, mtp, pool, ammPool, baseCurrency) + finalBorrowInterestPayment := k.HandleBorrowInterestPayment(ctx, borrowInterestPayment, mtp, pool, ammPool, baseCurrency) // finalInterestPayment is in custodyAsset - if err := pool.UpdateBlockBorrowInterest(ctx, custodyAsset, finalBorrowInterestPayment, true, mtp.Position); err != nil { + if err := pool.UpdateBlockBorrowInterest(ctx, mtp.CustodyAsset, finalBorrowInterestPayment, true, mtp.Position); err != nil { return err } diff --git a/x/margin/keeper/handle_borrow_interest_payment.go b/x/margin/keeper/handle_borrow_interest_payment.go index 504eeb593..978b9cf07 100644 --- a/x/margin/keeper/handle_borrow_interest_payment.go +++ b/x/margin/keeper/handle_borrow_interest_payment.go @@ -7,35 +7,29 @@ import ( "github.com/elys-network/elys/x/margin/types" ) -func (k Keeper) HandleBorrowInterestPayment(ctx sdk.Context, collateralAsset string, custodyAsset string, borrowInterestPayment sdk.Int, mtp *types.MTP, pool *types.Pool, ammPool ammtypes.Pool, baseCurrency string) sdk.Int { +func (k Keeper) HandleBorrowInterestPayment(ctx sdk.Context, borrowInterestPayment sdk.Int, mtp *types.MTP, pool *types.Pool, ammPool ammtypes.Pool, baseCurrency string) sdk.Int { incrementalBorrowInterestPaymentEnabled := k.GetIncrementalBorrowInterestPaymentEnabled(ctx) // if incremental payment on, pay interest if incrementalBorrowInterestPaymentEnabled { - finalBorrowInterestPayment, err := k.IncrementalBorrowInterestPayment(ctx, collateralAsset, custodyAsset, borrowInterestPayment, mtp, pool, ammPool, baseCurrency) + finalBorrowInterestPayment, err := k.IncrementalBorrowInterestPayment(ctx, borrowInterestPayment, mtp, pool, ammPool, baseCurrency) if err != nil { ctx.Logger().Error(sdkerrors.Wrap(err, "error executing incremental borrow interest payment").Error()) } else { return finalBorrowInterestPayment } } else { // else update unpaid mtp interest - collateralIndex, _ := types.GetMTPAssetIndex(mtp, collateralAsset, "") - if collateralIndex < 0 { - return sdk.ZeroInt() - } - - // collateralAsset is in base currency - if mtp.Collaterals[collateralIndex].Denom == baseCurrency { - mtp.BorrowInterestUnpaidCollaterals[collateralIndex].Amount = borrowInterestPayment - } else { + // collateralAsset is not in base currency + if mtp.CollateralAsset != baseCurrency { // swap amtTokenIn := sdk.NewCoin(baseCurrency, borrowInterestPayment) - borrowInterestPayment, err := k.EstimateSwap(ctx, amtTokenIn, collateralAsset, ammPool) // may need spot price here to not deduct fee + var err error + borrowInterestPayment, err = k.EstimateSwap(ctx, amtTokenIn, mtp.CollateralAsset, ammPool) // may need spot price here to not deduct fee if err != nil { return sdk.ZeroInt() } - - mtp.BorrowInterestUnpaidCollaterals[collateralIndex].Amount = borrowInterestPayment } + + mtp.BorrowInterestUnpaidCollateral = borrowInterestPayment } return sdk.ZeroInt() } diff --git a/x/margin/keeper/handle_funding_fee_collection.go b/x/margin/keeper/handle_funding_fee_collection.go index f4e624e3d..679621bbe 100644 --- a/x/margin/keeper/handle_funding_fee_collection.go +++ b/x/margin/keeper/handle_funding_fee_collection.go @@ -7,7 +7,7 @@ import ( ) // HandleFundingFeeCollection handles funding fee collection -func (k Keeper) HandleFundingFeeCollection(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool ammtypes.Pool, collateralAsset string, custodyAsset string) error { +func (k Keeper) HandleFundingFeeCollection(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool ammtypes.Pool, baseCurrency string) error { // get funding rate fundingRate := pool.FundingRate @@ -21,58 +21,55 @@ func (k Keeper) HandleFundingFeeCollection(ctx sdk.Context, mtp *types.MTP, pool return nil } - // get indexes - collateralIndex, custodyIndex := types.GetMTPAssetIndex(mtp, collateralAsset, custodyAsset) - // Calculate the take amount in custody asset - takeAmountCustody := types.CalcTakeAmount(mtp.Custodies[custodyIndex], custodyAsset, fundingRate) + takeAmountCustodyAmount := types.CalcTakeAmount(mtp.Custody, mtp.CustodyAsset, fundingRate) + + // Build the take amount coin + takeAmountCustody := sdk.NewCoin(mtp.CustodyAsset, takeAmountCustodyAmount) // Swap the take amount to collateral asset - takeAmountCollateralAmount, err := k.EstimateSwap(ctx, takeAmountCustody, collateralAsset, ammPool) + takeAmountCollateralAmount, err := k.EstimateSwap(ctx, takeAmountCustody, mtp.CollateralAsset, ammPool) if err != nil { return err } - // Create the take amount coin - takeAmountCollateral := sdk.NewCoin(collateralAsset, takeAmountCollateralAmount) - // Get funding fee collection address fundingFeeCollectionAddress := k.GetFundingFeeCollectionAddress(ctx) // Transfer take amount in collateral asset to funding fee collection address - _, err = k.TakeFundPayment(ctx, takeAmountCollateral.Amount, collateralAsset, sdk.OneDec(), fundingFeeCollectionAddress, &ammPool) + _, err = k.TakeFundPayment(ctx, takeAmountCollateralAmount, mtp.CollateralAsset, sdk.OneDec(), fundingFeeCollectionAddress, &ammPool) if err != nil { return err } // update mtp custody - mtp.Custodies[custodyIndex] = mtp.Custodies[custodyIndex].Sub(takeAmountCustody) + mtp.Custody = mtp.Custody.Sub(takeAmountCustodyAmount) // add payment to total funding fee paid in collateral asset - mtp.FundingFeePaidCollaterals[collateralIndex] = mtp.FundingFeePaidCollaterals[collateralIndex].Add(takeAmountCollateral) + mtp.FundingFeePaidCollateral = mtp.FundingFeePaidCollateral.Add(takeAmountCollateralAmount) // add payment to total funding fee paid in custody asset - mtp.FundingFeePaidCustodies[custodyIndex] = mtp.FundingFeePaidCustodies[custodyIndex].Add(takeAmountCustody) + mtp.FundingFeePaidCustody = mtp.FundingFeePaidCustody.Add(takeAmountCustodyAmount) // emit event - if !takeAmountCollateral.IsZero() { - k.EmitFundingFeePayment(ctx, mtp, takeAmountCustody.Amount, collateralAsset, types.EventIncrementalPayFund) + if !takeAmountCollateralAmount.IsZero() { + k.EmitFundingFeePayment(ctx, mtp, takeAmountCustody.Amount, mtp.CollateralAsset, types.EventIncrementalPayFund) } // update pool custody balance - err = pool.UpdateCustody(ctx, custodyAsset, takeAmountCustody.Amount, false, mtp.Position) + err = pool.UpdateCustody(ctx, mtp.CustodyAsset, takeAmountCustody.Amount, false, mtp.Position) if err != nil { return err } // update accounted balance for custody side - err = pool.UpdateBalance(ctx, custodyAsset, takeAmountCustody.Amount, false, mtp.Position) + err = pool.UpdateBalance(ctx, mtp.CustodyAsset, takeAmountCustody.Amount, false, mtp.Position) if err != nil { return err } // update accounted balance for collateral side - err = pool.UpdateBalance(ctx, collateralAsset, takeAmountCollateral.Amount, false, mtp.Position) + err = pool.UpdateBalance(ctx, mtp.CollateralAsset, takeAmountCollateralAmount, false, mtp.Position) if err != nil { return err } @@ -87,7 +84,7 @@ func (k Keeper) HandleFundingFeeCollection(ctx sdk.Context, mtp *types.MTP, pool k.SetPool(ctx, *pool) // update mtp health - _, err = k.UpdateMTPHealth(ctx, *mtp, ammPool, custodyAsset) + _, err = k.UpdateMTPHealth(ctx, *mtp, ammPool, baseCurrency) if err != nil { return err } diff --git a/x/margin/keeper/handle_funding_fee_distribution.go b/x/margin/keeper/handle_funding_fee_distribution.go index 1ee389b86..42540efde 100644 --- a/x/margin/keeper/handle_funding_fee_distribution.go +++ b/x/margin/keeper/handle_funding_fee_distribution.go @@ -82,24 +82,17 @@ func (k Keeper) HandleFundingFeeDistribution(ctx sdk.Context, mtps []*types.MTP, } // update received funding fee accounting buckets - for custodyIndex, _ := range mtp.Custodies { - for collateralIndex, collateral := range mtp.Collaterals { - // Swap the take amount to collateral asset - fundingFeeCollateralAmount, err := k.EstimateSwap(ctx, fundingFeeAmount, collateral.Denom, ammPool) - if err != nil { - return err - } - - // Create the take amount coin - fundingFeeCollateral := sdk.NewCoin(collateral.Denom, fundingFeeCollateralAmount) - - // add payment to total funding fee paid in collateral asset - mtp.FundingFeeReceivedCollaterals[collateralIndex] = mtp.FundingFeePaidCollaterals[collateralIndex].Add(fundingFeeCollateral) - - // add payment to total funding fee paid in custody asset - mtp.FundingFeeReceivedCustodies[custodyIndex] = mtp.FundingFeePaidCustodies[custodyIndex].Add(fundingFeeAmount) - } + // Swap the take amount to collateral asset + fundingFeeCollateralAmount, err := k.EstimateSwap(ctx, fundingFeeAmount, mtp.CollateralAsset, ammPool) + if err != nil { + return err } + + // add payment to total funding fee paid in collateral asset + mtp.FundingFeeReceivedCollateral = mtp.FundingFeeReceivedCollateral.Add(fundingFeeCollateralAmount) + + // add payment to total funding fee paid in custody asset + mtp.FundingFeeReceivedCustody = mtp.FundingFeeReceivedCustody.Add(fundingFeeAmount.Amount) } return nil diff --git a/x/margin/keeper/invariant_check.go b/x/margin/keeper/invariant_check.go index 6d75bd0f9..e9cc31002 100644 --- a/x/margin/keeper/invariant_check.go +++ b/x/margin/keeper/invariant_check.go @@ -30,9 +30,7 @@ func (k Keeper) AmmPoolBalanceCheck(ctx sdk.Context, poolId uint64) error { continue } - for i := range mtp.Collaterals { - mtpCollateralBalances = mtpCollateralBalances.Add(sdk.NewCoin(mtp.Collaterals[i].Denom, mtp.Collaterals[i].Amount)) - } + mtpCollateralBalances = mtpCollateralBalances.Add(sdk.NewCoin(mtp.CollateralAsset, mtp.Collateral)) } // bank balance should be ammPool balance + collateral balance diff --git a/x/margin/keeper/invariant_check_test.go b/x/margin/keeper/invariant_check_test.go index 0278376ab..6cc68b4af 100644 --- a/x/margin/keeper/invariant_check_test.go +++ b/x/margin/keeper/invariant_check_test.go @@ -95,11 +95,10 @@ func TestCheckBalanceInvariant_InvalidBalance(t *testing.T) { // Create a margin position open msg msg2 := margintypes.NewMsgOpen( addr[0].String(), - ptypes.BaseCurrency, - sdk.NewInt(100000000), - ptypes.ATOM, margintypes.Position_LONG, sdk.NewDec(5), + ptypes.ATOM, + sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(100000000)), sdk.MustNewDecFromStr(margintypes.TakeProfitPriceDefault), ) @@ -122,7 +121,7 @@ func TestCheckBalanceInvariant_InvalidBalance(t *testing.T) { msg3 := margintypes.NewMsgClose( addr[0].String(), mtpId, - sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(100000000)), + mtps[0].Custody, ) _, err = mk.Close(ctx, msg3) diff --git a/x/margin/keeper/keeper.go b/x/margin/keeper/keeper.go index f1c551971..c5a9da32e 100644 --- a/x/margin/keeper/keeper.go +++ b/x/margin/keeper/keeper.go @@ -17,10 +17,8 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/query" ammtypes "github.com/elys-network/elys/x/amm/types" - assetprofiletypes "github.com/elys-network/elys/x/assetprofile/types" "github.com/elys-network/elys/x/margin/types" pkeeper "github.com/elys-network/elys/x/parameter/keeper" - ptypes "github.com/elys-network/elys/x/parameter/types" ) type ( @@ -141,12 +139,12 @@ func (k Keeper) EstimateSwapGivenOut(ctx sdk.Context, tokenOutAmount sdk.Coin, t return swapResult.Amount, nil } -func (k Keeper) Borrow(ctx sdk.Context, collateralAsset string, custodyAsset string, collateralAmount sdk.Int, custodyAmount sdk.Int, mtp *types.MTP, ammPool *ammtypes.Pool, pool *types.Pool, eta sdk.Dec, baseCurrency string) error { +func (k Keeper) Borrow(ctx sdk.Context, collateralAmount sdk.Int, custodyAmount sdk.Int, mtp *types.MTP, ammPool *ammtypes.Pool, pool *types.Pool, eta sdk.Dec, baseCurrency string) error { mtpAddress, err := sdk.AccAddressFromBech32(mtp.Address) if err != nil { return err } - collateralCoin := sdk.NewCoin(collateralAsset, collateralAmount) + collateralCoin := sdk.NewCoin(mtp.CollateralAsset, collateralAmount) if !k.bankKeeper.HasBalance(ctx, mtpAddress, collateralCoin) { return types.ErrBalanceNotAvailable @@ -157,10 +155,10 @@ func (k Keeper) Borrow(ctx sdk.Context, collateralAsset string, custodyAsset str // If collateral asset is not base currency, should calculate liability in base currency with the given out. // Liability has to be in base currency - if collateralAsset != baseCurrency { + if mtp.CollateralAsset != baseCurrency { // ATOM amount etaAmt := liabilitiesDec.TruncateInt() - etaAmtToken := sdk.NewCoin(collateralAsset, etaAmt) + etaAmtToken := sdk.NewCoin(mtp.CollateralAsset, etaAmt) // Calculate base currency amount given atom out amount and we use it liabilty amount in base currency liabilityAmt, err := k.OpenLongChecker.EstimateSwapGivenOut(ctx, etaAmtToken, baseCurrency, *ammPool) if err != nil { @@ -170,17 +168,23 @@ func (k Keeper) Borrow(ctx sdk.Context, collateralAsset string, custodyAsset str liabilitiesDec = sdk.NewDecFromInt(liabilityAmt) } - collateralIndex, custodyIndex := types.GetMTPAssetIndex(mtp, collateralAsset, custodyAsset) - if collateralIndex < 0 || custodyIndex < 0 { - return sdkerrors.Wrap(types.ErrBalanceNotAvailable, "MTP collateral or custody invalid!") + // If position is short, liabilities should be swapped to liabilities asset + if mtp.Position == types.Position_SHORT { + liabilitiesAmtTokenIn := sdk.NewCoin(baseCurrency, liabilitiesDec.TruncateInt()) + liabilitiesAmt, err := k.OpenShortChecker.EstimateSwap(ctx, liabilitiesAmtTokenIn, mtp.LiabilitiesAsset, *ammPool) + if err != nil { + return err + } + + liabilitiesDec = sdk.NewDecFromInt(liabilitiesAmt) } - mtp.Collaterals[collateralIndex].Amount = mtp.Collaterals[collateralIndex].Amount.Add(collateralAmount) - mtp.Liabilities = mtp.Liabilities.Add(sdk.NewIntFromBigInt(liabilitiesDec.TruncateInt().BigInt())) - mtp.Custodies[custodyIndex].Amount = mtp.Custodies[custodyIndex].Amount.Add(custodyAmount) + mtp.Collateral = collateralAmount + mtp.Liabilities = sdk.NewIntFromBigInt(liabilitiesDec.TruncateInt().BigInt()) + mtp.Custody = custodyAmount // calculate mtp take profit custody, delta y_tp_c = delta x_l / take profit price (take profit custody = liabilities / take profit price) - mtp.TakeProfitCustodies = types.CalcMTPTakeProfitCustodies(mtp) + mtp.TakeProfitCustody = types.CalcMTPTakeProfitCustody(mtp) // calculate mtp take profit liablities, delta x_tp_l = delta y_tp_c * current price (take profit liabilities = take profit custody * current price) mtp.TakeProfitLiabilities, err = k.CalcMTPTakeProfitLiability(ctx, mtp, baseCurrency) @@ -188,10 +192,7 @@ func (k Keeper) Borrow(ctx sdk.Context, collateralAsset string, custodyAsset str return err } - mtp.Leverages = append(mtp.Leverages, eta.Add(sdk.OneDec())) - - // print mtp.CustodyAmount - ctx.Logger().Info(fmt.Sprintf("mtp.CustodyAmount: %s", mtp.Custodies[custodyIndex].Amount.String())) + mtp.Leverage = eta.Add(sdk.OneDec()) h, err := k.UpdateMTPHealth(ctx, *mtp, *ammPool, baseCurrency) // set mtp in func or return h? if err != nil { @@ -211,25 +212,25 @@ func (k Keeper) Borrow(ctx sdk.Context, collateralAsset string, custodyAsset str return err } - err = pool.UpdateBalance(ctx, collateralAsset, collateralAmount, true, mtp.Position) + err = pool.UpdateBalance(ctx, mtp.CollateralAsset, collateralAmount, true, mtp.Position) if err != nil { return err } - // All liability has to be in base currency - err = pool.UpdateLiabilities(ctx, baseCurrency, mtp.Liabilities, true, mtp.Position) + // All liability has to be in liabilities asset + err = pool.UpdateLiabilities(ctx, mtp.LiabilitiesAsset, mtp.Liabilities, true, mtp.Position) if err != nil { return err } - // All take profit liability has to be in base currency - err = pool.UpdateTakeProfitLiabilities(ctx, baseCurrency, mtp.TakeProfitLiabilities, true, mtp.Position) + // All take profit liability has to be in liabilities asset + err = pool.UpdateTakeProfitLiabilities(ctx, mtp.LiabilitiesAsset, mtp.TakeProfitLiabilities, true, mtp.Position) if err != nil { return err } - // All take profit custody has to be in base currency - err = pool.UpdateTakeProfitCustody(ctx, baseCurrency, mtp.TakeProfitCustodies[custodyIndex].Amount, true, mtp.Position) + // All take profit custody has to be in custody asset + err = pool.UpdateTakeProfitCustody(ctx, mtp.CustodyAsset, mtp.TakeProfitCustody, true, mtp.Position) if err != nil { return err } @@ -283,15 +284,13 @@ func (k Keeper) CalculatePoolHealth(ctx sdk.Context, pool *types.Pool) sdk.Dec { } func (k Keeper) TakeInCustody(ctx sdk.Context, mtp types.MTP, pool *types.Pool) error { - for i := range mtp.Custodies { - err := pool.UpdateBalance(ctx, mtp.Custodies[i].Denom, mtp.Custodies[i].Amount, false, mtp.Position) - if err != nil { - return nil - } - err = pool.UpdateCustody(ctx, mtp.Custodies[i].Denom, mtp.Custodies[i].Amount, true, mtp.Position) - if err != nil { - return nil - } + err := pool.UpdateBalance(ctx, mtp.CustodyAsset, mtp.Custody, false, mtp.Position) + if err != nil { + return nil + } + err = pool.UpdateCustody(ctx, mtp.CustodyAsset, mtp.Custody, true, mtp.Position) + if err != nil { + return nil } k.SetPool(ctx, *pool) @@ -299,16 +298,14 @@ func (k Keeper) TakeInCustody(ctx sdk.Context, mtp types.MTP, pool *types.Pool) return nil } -func (k Keeper) IncrementalBorrowInterestPayment(ctx sdk.Context, collateralAsset string, custodyAsset string, borrowInterestPayment sdk.Int, mtp *types.MTP, pool *types.Pool, ammPool ammtypes.Pool, baseCurrency string) (sdk.Int, error) { - collateralIndex, custodyIndex := types.GetMTPAssetIndex(mtp, collateralAsset, custodyAsset) - +func (k Keeper) IncrementalBorrowInterestPayment(ctx sdk.Context, borrowInterestPayment sdk.Int, mtp *types.MTP, pool *types.Pool, ammPool ammtypes.Pool, baseCurrency string) (sdk.Int, error) { // if mtp has unpaid borrow interest, add to payment // convert it into base currency - if mtp.BorrowInterestUnpaidCollaterals[collateralIndex].Amount.GT(sdk.ZeroInt()) { - if mtp.Collaterals[collateralIndex].Denom == baseCurrency { - borrowInterestPayment = borrowInterestPayment.Add(mtp.BorrowInterestUnpaidCollaterals[collateralIndex].Amount) + if mtp.BorrowInterestUnpaidCollateral.IsPositive() { + if mtp.CollateralAsset == baseCurrency { + borrowInterestPayment = borrowInterestPayment.Add(mtp.BorrowInterestUnpaidCollateral) } else { - unpaidCollateralIn := sdk.NewCoin(mtp.Collaterals[collateralIndex].Denom, mtp.BorrowInterestUnpaidCollaterals[collateralIndex].Amount) + unpaidCollateralIn := sdk.NewCoin(mtp.CollateralAsset, mtp.BorrowInterestUnpaidCollateral) C, err := k.EstimateSwapGivenOut(ctx, unpaidCollateralIn, baseCurrency, ammPool) if err != nil { return sdk.ZeroInt(), err @@ -320,65 +317,65 @@ func (k Keeper) IncrementalBorrowInterestPayment(ctx sdk.Context, collateralAsse borrowInterestPaymentTokenIn := sdk.NewCoin(baseCurrency, borrowInterestPayment) // swap borrow interest payment to custody asset for payment - borrowInterestPaymentCustody, err := k.EstimateSwap(ctx, borrowInterestPaymentTokenIn, mtp.Custodies[custodyIndex].Denom, ammPool) + borrowInterestPaymentCustody, err := k.EstimateSwap(ctx, borrowInterestPaymentTokenIn, mtp.CustodyAsset, ammPool) if err != nil { return sdk.ZeroInt(), err } // If collateralAsset is not in base currency, convert it to original asset format - if collateralAsset != baseCurrency { + if mtp.CollateralAsset != baseCurrency { // swap custody amount to collateral for updating borrow interest unpaid amtTokenIn := sdk.NewCoin(baseCurrency, borrowInterestPayment) - borrowInterestPayment, err = k.EstimateSwap(ctx, amtTokenIn, collateralAsset, ammPool) // may need spot price here to not deduct fee + borrowInterestPayment, err = k.EstimateSwap(ctx, amtTokenIn, mtp.CollateralAsset, ammPool) // may need spot price here to not deduct fee if err != nil { return sdk.ZeroInt(), err } } // if paying unpaid borrow interest reset to 0 - mtp.BorrowInterestUnpaidCollaterals[collateralIndex].Amount = sdk.ZeroInt() + mtp.BorrowInterestUnpaidCollateral = sdk.ZeroInt() // edge case, not enough custody to cover payment - if borrowInterestPaymentCustody.GT(mtp.Custodies[custodyIndex].Amount) { + if borrowInterestPaymentCustody.GT(mtp.Custody) { // swap custody amount to collateral for updating borrow interest unpaid - custodyAmtTokenIn := sdk.NewCoin(mtp.Custodies[custodyIndex].Denom, mtp.Custodies[custodyIndex].Amount) - custodyAmountCollateral, err := k.EstimateSwap(ctx, custodyAmtTokenIn, collateralAsset, ammPool) // may need spot price here to not deduct fee + custodyAmtTokenIn := sdk.NewCoin(mtp.CustodyAsset, mtp.Custody) + custodyAmountCollateral, err := k.EstimateSwap(ctx, custodyAmtTokenIn, mtp.CollateralAsset, ammPool) // may need spot price here to not deduct fee if err != nil { return sdk.ZeroInt(), err } - mtp.BorrowInterestUnpaidCollaterals[collateralIndex].Amount = borrowInterestPayment.Sub(custodyAmountCollateral) + mtp.BorrowInterestUnpaidCollateral = mtp.BorrowInterestUnpaidCollateral.Add(borrowInterestPayment).Sub(custodyAmountCollateral) borrowInterestPayment = custodyAmountCollateral - borrowInterestPaymentCustody = mtp.Custodies[custodyIndex].Amount + borrowInterestPaymentCustody = mtp.Custody } // add payment to total paid - collateral - mtp.BorrowInterestPaidCollaterals[collateralIndex].Amount = mtp.BorrowInterestPaidCollaterals[collateralIndex].Amount.Add(borrowInterestPayment) + mtp.BorrowInterestPaidCollateral = mtp.BorrowInterestPaidCollateral.Add(borrowInterestPayment) // add payment to total paid - custody - mtp.BorrowInterestPaidCustodies[custodyIndex].Amount = mtp.BorrowInterestPaidCustodies[custodyIndex].Amount.Add(borrowInterestPaymentCustody) + mtp.BorrowInterestPaidCustody = mtp.BorrowInterestPaidCustody.Add(borrowInterestPaymentCustody) // deduct borrow interest payment from custody amount - mtp.Custodies[custodyIndex].Amount = mtp.Custodies[custodyIndex].Amount.Sub(borrowInterestPaymentCustody) + mtp.Custody = mtp.Custody.Sub(borrowInterestPaymentCustody) takePercentage := k.GetIncrementalBorrowInterestPaymentFundPercentage(ctx) fundAddr := k.GetIncrementalBorrowInterestPaymentFundAddress(ctx) - takeAmount, err := k.TakeFundPayment(ctx, borrowInterestPaymentCustody, mtp.Custodies[custodyIndex].Denom, takePercentage, fundAddr, &ammPool) + takeAmount, err := k.TakeFundPayment(ctx, borrowInterestPaymentCustody, mtp.CustodyAsset, takePercentage, fundAddr, &ammPool) if err != nil { return sdk.ZeroInt(), err } actualBorrowInterestPaymentCustody := borrowInterestPaymentCustody.Sub(takeAmount) if !takeAmount.IsZero() { - k.EmitFundPayment(ctx, mtp, takeAmount, mtp.Custodies[custodyIndex].Denom, types.EventIncrementalPayFund) + k.EmitFundPayment(ctx, mtp, takeAmount, mtp.CustodyAsset, types.EventIncrementalPayFund) } - err = pool.UpdateCustody(ctx, mtp.Custodies[custodyIndex].Denom, borrowInterestPaymentCustody, false, mtp.Position) + err = pool.UpdateCustody(ctx, mtp.CustodyAsset, borrowInterestPaymentCustody, false, mtp.Position) if err != nil { return sdk.ZeroInt(), err } - err = pool.UpdateBalance(ctx, mtp.Custodies[custodyIndex].Denom, actualBorrowInterestPaymentCustody, true, mtp.Position) + err = pool.UpdateBalance(ctx, mtp.CustodyAsset, actualBorrowInterestPaymentCustody, true, mtp.Position) if err != nil { return sdk.ZeroInt(), err } @@ -468,7 +465,7 @@ func (k Keeper) BorrowInterestRateComputation(ctx sdk.Context, pool types.Pool, return newBorrowInterestRate, nil } -func (k Keeper) CheckMinLiabilities(ctx sdk.Context, collateralAmount sdk.Coin, eta sdk.Dec, pool types.Pool, ammPool ammtypes.Pool, custodyAsset string) error { +func (k Keeper) CheckMinLiabilities(ctx sdk.Context, collateralAmount sdk.Coin, eta sdk.Dec, ammPool ammtypes.Pool, custodyAsset string, baseCurrency string) error { var borrowInterestRational, liabilitiesRational, rate big.Rat minBorrowInterestRate := k.GetBorrowInterestRateMin(ctx) @@ -481,16 +478,11 @@ func (k Keeper) CheckMinLiabilities(ctx sdk.Context, collateralAmount sdk.Coin, liabilitiesDec := collateralAmountDec.Mul(eta) liabilities := sdk.NewUint(liabilitiesDec.TruncateInt().Uint64()) - entry, found := k.apKeeper.GetEntry(ctx, ptypes.BaseCurrency) - if !found { - return sdkerrors.Wrapf(assetprofiletypes.ErrAssetProfileNotFound, "asset %s not found", ptypes.BaseCurrency) - } - baseCurrency := entry.Denom - // liabilty has to be always in base currency if collateralAmount.Denom != baseCurrency { outAmt := liabilitiesDec.TruncateInt() outAmtToken := sdk.NewCoin(collateralAmount.Denom, outAmt) + inAmt, err := k.OpenLongChecker.EstimateSwapGivenOut(ctx, outAmtToken, baseCurrency, ammPool) if err != nil { return types.ErrBorrowTooLow @@ -503,7 +495,6 @@ func (k Keeper) CheckMinLiabilities(ctx sdk.Context, collateralAmount sdk.Coin, borrowInterestNew := borrowInterestRational.Num().Quo(borrowInterestRational.Num(), borrowInterestRational.Denom()) samplePayment := sdk.NewInt(borrowInterestNew.Int64()) - if samplePayment.IsZero() && !minBorrowInterestRate.IsZero() { return types.ErrBorrowTooLow } @@ -514,7 +505,14 @@ func (k Keeper) CheckMinLiabilities(ctx sdk.Context, collateralAmount sdk.Coin, return nil } + // If custodyAsset is base currency, custody amount is already checkid in HasSufficientBalance function. + // its liability balance checked in the above if statement, so return + if custodyAsset == baseCurrency { + return nil + } + samplePaymentTokenIn := sdk.NewCoin(collateralAmount.Denom, samplePayment) + // swap borrow interest payment to custody asset _, err := k.EstimateSwap(ctx, samplePaymentTokenIn, custodyAsset, ammPool) if err != nil { diff --git a/x/margin/keeper/keeper_test.go b/x/margin/keeper/keeper_test.go index e280b1a00..a9ce56eb4 100644 --- a/x/margin/keeper/keeper_test.go +++ b/x/margin/keeper/keeper_test.go @@ -7,7 +7,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" simapp "github.com/elys-network/elys/app" "github.com/elys-network/elys/x/margin/types" - paramtypes "github.com/elys-network/elys/x/parameter/types" "github.com/stretchr/testify/require" "github.com/cometbft/cometbft/crypto/ed25519" @@ -27,19 +26,21 @@ func TestSetGetMTP(t *testing.T) { for i := 0; i < 2; i++ { mtp := types.MTP{ - Address: addr[i].String(), - Collaterals: []sdk.Coin{sdk.NewCoin(paramtypes.BaseCurrency, sdk.NewInt(0))}, - Liabilities: sdk.NewInt(0), - BorrowInterestPaidCollaterals: []sdk.Coin{sdk.NewCoin(paramtypes.BaseCurrency, sdk.NewInt(0))}, - BorrowInterestPaidCustodies: []sdk.Coin{sdk.NewCoin("ATOM", sdk.NewInt(0))}, - BorrowInterestUnpaidCollaterals: []sdk.Coin{sdk.NewCoin(paramtypes.BaseCurrency, sdk.NewInt(0))}, - Custodies: []sdk.Coin{sdk.NewCoin("ATOM", sdk.NewInt(0))}, - Leverages: []sdk.Dec{sdk.NewDec(0)}, - MtpHealth: sdk.NewDec(0), - Position: types.Position_LONG, - Id: 0, - ConsolidateLeverage: sdk.ZeroDec(), - SumCollateral: sdk.ZeroInt(), + Address: addr[i].String(), + CollateralAsset: ptypes.BaseCurrency, + CustodyAsset: "ATOM", + Collateral: sdk.NewInt(0), + Liabilities: sdk.NewInt(0), + BorrowInterestPaidCollateral: sdk.NewInt(0), + BorrowInterestPaidCustody: sdk.NewInt(0), + BorrowInterestUnpaidCollateral: sdk.NewInt(0), + Custody: sdk.NewInt(0), + Leverage: sdk.NewDec(0), + MtpHealth: sdk.NewDec(0), + Position: types.Position_LONG, + Id: 0, + ConsolidateLeverage: sdk.ZeroDec(), + SumCollateral: sdk.ZeroInt(), } err := margin.SetMTP(ctx, &mtp) require.NoError(t, err) diff --git a/x/margin/keeper/open.go b/x/margin/keeper/open.go index b64650958..46d20209b 100644 --- a/x/margin/keeper/open.go +++ b/x/margin/keeper/open.go @@ -18,11 +18,11 @@ func (k Keeper) Open(ctx sdk.Context, msg *types.MsgOpen) (*types.MsgOpenRespons // Determine the type of position (long or short) and validate assets accordingly. switch msg.Position { case types.Position_LONG: - if err := types.CheckLongAssets(msg.CollateralAsset, msg.BorrowAsset, baseCurrency); err != nil { + if err := types.CheckLongAssets(msg.Collateral.Denom, msg.TradingAsset, baseCurrency); err != nil { return nil, err } case types.Position_SHORT: - if err := types.CheckShortAssets(msg.CollateralAsset, msg.BorrowAsset, baseCurrency); err != nil { + if err := types.CheckShortAssets(msg.Collateral.Denom, msg.TradingAsset, baseCurrency); err != nil { return nil, err } default: @@ -42,11 +42,8 @@ func (k Keeper) Open(ctx sdk.Context, msg *types.MsgOpen) (*types.MsgOpenRespons return nil, err } - // Get token asset other than base currency - tradingAsset := types.GetTradingAsset(msg.CollateralAsset, msg.BorrowAsset, baseCurrency) - // Get pool id, amm pool, and margin pool - poolId, ammPool, pool, err := k.OpenChecker.PreparePools(ctx, tradingAsset) + poolId, ammPool, pool, err := k.OpenChecker.PreparePools(ctx, msg.Collateral.Denom, msg.TradingAsset) if err != nil { return nil, err } diff --git a/x/margin/keeper/open_consolidate.go b/x/margin/keeper/open_consolidate.go index ea34bfbdc..7cf5a002c 100644 --- a/x/margin/keeper/open_consolidate.go +++ b/x/margin/keeper/open_consolidate.go @@ -7,20 +7,17 @@ import ( ) func (k Keeper) OpenConsolidate(ctx sdk.Context, mtp *types.MTP, msg *types.MsgOpen, baseCurrency string) (*types.MsgOpenResponse, error) { - // Get token asset other than base currency - tradingAsset := types.GetTradingAsset(msg.CollateralAsset, msg.BorrowAsset, baseCurrency) - poolId := mtp.AmmPoolId pool, found := k.OpenLongChecker.GetPool(ctx, poolId) if !found { - return nil, sdkerrors.Wrap(types.ErrPoolDoesNotExist, tradingAsset) + return nil, sdkerrors.Wrap(types.ErrPoolDoesNotExist, mtp.CustodyAsset) } if !k.OpenLongChecker.IsPoolEnabled(ctx, poolId) { - return nil, sdkerrors.Wrap(types.ErrMTPDisabled, tradingAsset) + return nil, sdkerrors.Wrap(types.ErrMTPDisabled, mtp.CustodyAsset) } - ammPool, err := k.OpenLongChecker.GetAmmPool(ctx, poolId, tradingAsset) + ammPool, err := k.OpenLongChecker.GetAmmPool(ctx, poolId, mtp.CustodyAsset) if err != nil { return nil, err } @@ -40,7 +37,7 @@ func (k Keeper) OpenConsolidate(ctx sdk.Context, mtp *types.MTP, msg *types.MsgO return nil, sdkerrors.Wrap(types.ErrInvalidPosition, msg.Position.String()) } - ctx.EventManager().EmitEvent(k.GenerateOpenEvent(mtp)) + ctx.EventManager().EmitEvent(types.GenerateOpenEvent(mtp)) if k.hooks != nil { k.hooks.AfterMarginPositionModified(ctx, ammPool, pool) diff --git a/x/margin/keeper/open_consolidate_long.go b/x/margin/keeper/open_consolidate_long.go index 87a5c7bac..671099ef9 100644 --- a/x/margin/keeper/open_consolidate_long.go +++ b/x/margin/keeper/open_consolidate_long.go @@ -6,14 +6,14 @@ import ( ) func (k Keeper) OpenConsolidateLong(ctx sdk.Context, poolId uint64, mtp *types.MTP, msg *types.MsgOpen, baseCurrency string) (*types.MTP, error) { + if mtp.Leverage != msg.Leverage { + return nil, types.ErrInvalidLeverage + } + maxLeverage := k.OpenLongChecker.GetMaxLeverageParam(ctx) - leverage := sdk.MinDec(msg.Leverage, maxLeverage) + leverage := sdk.MinDec(mtp.Leverage, maxLeverage) eta := leverage.Sub(sdk.OneDec()) - collateralAmountDec := sdk.NewDecFromBigInt(msg.CollateralAmount.BigInt()) - mtp.Leverages = append(mtp.Leverages, leverage) - - mtp.Collaterals = types.AddOrAppendCoin(mtp.Collaterals, sdk.NewCoin(msg.CollateralAsset, sdk.NewInt(0))) - mtp.Custodies = types.AddOrAppendCoin(mtp.Custodies, sdk.NewCoin(msg.BorrowAsset, sdk.NewInt(0))) + collateralAmountDec := sdk.NewDecFromBigInt(msg.Collateral.Amount.BigInt()) return k.ProcessOpenLong(ctx, mtp, leverage, eta, collateralAmountDec, poolId, msg, baseCurrency) } diff --git a/x/margin/keeper/open_consolidate_short.go b/x/margin/keeper/open_consolidate_short.go index 00a3ec0cd..9db641d65 100644 --- a/x/margin/keeper/open_consolidate_short.go +++ b/x/margin/keeper/open_consolidate_short.go @@ -6,14 +6,14 @@ import ( ) func (k Keeper) OpenConsolidateShort(ctx sdk.Context, poolId uint64, mtp *types.MTP, msg *types.MsgOpen, baseCurrency string) (*types.MTP, error) { - maxLeverage := k.OpenShortChecker.GetMaxLeverageParam(ctx) - leverage := sdk.MinDec(msg.Leverage, maxLeverage) - eta := leverage.Sub(sdk.OneDec()) - collateralAmountDec := sdk.NewDecFromBigInt(msg.CollateralAmount.BigInt()) - mtp.Leverages = append(mtp.Leverages, leverage) + if mtp.Leverage != msg.Leverage { + return nil, types.ErrInvalidLeverage + } - mtp.Collaterals = types.AddOrAppendCoin(mtp.Collaterals, sdk.NewCoin(msg.CollateralAsset, sdk.NewInt(0))) - mtp.Custodies = types.AddOrAppendCoin(mtp.Custodies, sdk.NewCoin(msg.BorrowAsset, sdk.NewInt(0))) + maxLeverage := k.OpenLongChecker.GetMaxLeverageParam(ctx) + leverage := sdk.MinDec(mtp.Leverage, maxLeverage) + eta := leverage.Sub(sdk.OneDec()) + collateralAmountDec := sdk.NewDecFromBigInt(msg.Collateral.Amount.BigInt()) return k.ProcessOpenShort(ctx, mtp, leverage, eta, collateralAmountDec, poolId, msg, baseCurrency) } diff --git a/x/margin/keeper/open_long.go b/x/margin/keeper/open_long.go index 157d9be57..da5e0534d 100644 --- a/x/margin/keeper/open_long.go +++ b/x/margin/keeper/open_long.go @@ -3,6 +3,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/elys-network/elys/x/margin/types" + ptypes "github.com/elys-network/elys/x/parameter/types" ) func (k Keeper) OpenLong(ctx sdk.Context, poolId uint64, msg *types.MsgOpen, baseCurrency string) (*types.MTP, error) { @@ -14,10 +15,14 @@ func (k Keeper) OpenLong(ctx sdk.Context, poolId uint64, msg *types.MsgOpen, bas eta := leverage.Sub(sdk.OneDec()) // Convert the collateral amount into a decimal format. - collateralAmountDec := sdk.NewDecFromBigInt(msg.CollateralAmount.BigInt()) + collateralAmountDec := sdk.NewDecFromBigInt(msg.Collateral.Amount.BigInt()) + + // Define the assets + liabilitiesAsset := ptypes.BaseCurrency + custodyAsset := msg.TradingAsset // Initialize a new Margin Trading Position (MTP). - mtp := types.NewMTP(msg.Creator, msg.CollateralAsset, msg.BorrowAsset, msg.Position, leverage, msg.TakeProfitPrice, poolId) + mtp := types.NewMTP(msg.Creator, msg.Collateral.Denom, msg.TradingAsset, liabilitiesAsset, custodyAsset, msg.Position, leverage, msg.TakeProfitPrice, poolId) // Call the function to process the open long logic. return k.ProcessOpenLong(ctx, mtp, leverage, eta, collateralAmountDec, poolId, msg, baseCurrency) diff --git a/x/margin/keeper/open_long_process.go b/x/margin/keeper/open_long_process.go index fdb962652..ebb225a76 100644 --- a/x/margin/keeper/open_long_process.go +++ b/x/margin/keeper/open_long_process.go @@ -7,22 +7,19 @@ import ( ) func (k Keeper) ProcessOpenLong(ctx sdk.Context, mtp *types.MTP, leverage sdk.Dec, eta sdk.Dec, collateralAmountDec sdk.Dec, poolId uint64, msg *types.MsgOpen, baseCurrency string) (*types.MTP, error) { - // Determine the trading asset. - tradingAsset := types.GetTradingAsset(msg.CollateralAsset, msg.BorrowAsset, baseCurrency) - // Fetch the pool associated with the given pool ID. pool, found := k.OpenLongChecker.GetPool(ctx, poolId) if !found { - return nil, sdkerrors.Wrap(types.ErrPoolDoesNotExist, tradingAsset) + return nil, sdkerrors.Wrap(types.ErrPoolDoesNotExist, mtp.TradingAsset) } // Check if the pool is enabled. if !k.OpenLongChecker.IsPoolEnabled(ctx, poolId) { - return nil, sdkerrors.Wrap(types.ErrMTPDisabled, tradingAsset) + return nil, sdkerrors.Wrap(types.ErrMTPDisabled, mtp.TradingAsset) } // Fetch the corresponding AMM (Automated Market Maker) pool. - ammPool, err := k.OpenLongChecker.GetAmmPool(ctx, poolId, tradingAsset) + ammPool, err := k.OpenLongChecker.GetAmmPool(ctx, poolId, mtp.TradingAsset) if err != nil { return nil, err } @@ -31,8 +28,8 @@ func (k Keeper) ProcessOpenLong(ctx sdk.Context, mtp *types.MTP, leverage sdk.De leveragedAmount := sdk.NewInt(collateralAmountDec.Mul(leverage).TruncateInt().Int64()) // If collateral is not base currency, calculate the borrowing amount in base currency and check the balance - if msg.CollateralAsset != baseCurrency { - custodyAmtToken := sdk.NewCoin(msg.CollateralAsset, leveragedAmount) + if mtp.CollateralAsset != baseCurrency { + custodyAmtToken := sdk.NewCoin(mtp.CollateralAsset, leveragedAmount) borrowingAmount, err := k.OpenLongChecker.EstimateSwapGivenOut(ctx, custodyAmtToken, baseCurrency, ammPool) if err != nil { return nil, err @@ -41,37 +38,35 @@ func (k Keeper) ProcessOpenLong(ctx sdk.Context, mtp *types.MTP, leverage sdk.De return nil, sdkerrors.Wrap(types.ErrBorrowTooHigh, borrowingAmount.String()) } } else { - if !types.HasSufficientPoolBalance(ammPool, msg.CollateralAsset, leveragedAmount) { + if !types.HasSufficientPoolBalance(ammPool, mtp.CollateralAsset, leveragedAmount) { return nil, sdkerrors.Wrap(types.ErrBorrowTooHigh, leveragedAmount.String()) } } // Check minimum liabilities. - collateralTokenAmt := sdk.NewCoin(msg.CollateralAsset, msg.CollateralAmount) - err = k.OpenLongChecker.CheckMinLiabilities(ctx, collateralTokenAmt, eta, pool, ammPool, msg.BorrowAsset) + err = k.OpenLongChecker.CheckMinLiabilities(ctx, msg.Collateral, eta, ammPool, mtp.CustodyAsset, baseCurrency) if err != nil { return nil, err } // Calculate custody amount. - leveragedAmtTokenIn := sdk.NewCoin(msg.CollateralAsset, leveragedAmount) - custodyAmount, err := k.OpenLongChecker.EstimateSwap(ctx, leveragedAmtTokenIn, msg.BorrowAsset, ammPool) - if err != nil { - return nil, err - } - - // If the collateral asset is not base currency, custody amount equals to leverage amount - if msg.CollateralAsset != baseCurrency { - custodyAmount = leveragedAmount + custodyAmount := leveragedAmount + // If position is long, calculate custody amount in custody asset + if mtp.CollateralAsset == baseCurrency { + leveragedAmtTokenIn := sdk.NewCoin(mtp.CollateralAsset, leveragedAmount) + custodyAmount, err = k.OpenLongChecker.EstimateSwap(ctx, leveragedAmtTokenIn, mtp.CustodyAsset, ammPool) + if err != nil { + return nil, err + } } // Ensure the AMM pool has enough balance. - if !types.HasSufficientPoolBalance(ammPool, msg.BorrowAsset, custodyAmount) { + if !types.HasSufficientPoolBalance(ammPool, mtp.CustodyAsset, custodyAmount) { return nil, sdkerrors.Wrap(types.ErrCustodyTooHigh, custodyAmount.String()) } // Borrow the asset the user wants to long. - err = k.OpenLongChecker.Borrow(ctx, msg.CollateralAsset, msg.BorrowAsset, msg.CollateralAmount, custodyAmount, mtp, &ammPool, &pool, eta, baseCurrency) + err = k.OpenLongChecker.Borrow(ctx, msg.Collateral.Amount, custodyAmount, mtp, &ammPool, &pool, eta, baseCurrency) if err != nil { return nil, err } diff --git a/x/margin/keeper/open_long_test.go b/x/margin/keeper/open_long_test.go index 2f9501140..c9ae5bcf1 100644 --- a/x/margin/keeper/open_long_test.go +++ b/x/margin/keeper/open_long_test.go @@ -30,10 +30,9 @@ func TestOpenLong_PoolNotFound(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - Leverage: math.LegacyNewDec(10), - CollateralAmount: math.NewInt(1), - CollateralAsset: "aaa", - BorrowAsset: "bbb", + Leverage: math.LegacyNewDec(10), + TradingAsset: "bbb", + Collateral: sdk.NewCoin("aaa", math.NewInt(1)), } poolId = uint64(42) ) @@ -61,10 +60,9 @@ func TestOpenLong_PoolDisabled(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - Leverage: math.LegacyNewDec(10), - CollateralAmount: math.NewInt(1), - CollateralAsset: "aaa", - BorrowAsset: "bbb", + Leverage: math.LegacyNewDec(10), + TradingAsset: "bbb", + Collateral: sdk.NewCoin("aaa", math.NewInt(1)), } poolId = uint64(42) ) @@ -93,12 +91,11 @@ func TestOpenLong_InsufficientLiabilities(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - Leverage: math.LegacyNewDec(2), - CollateralAmount: math.NewInt(1000), - Creator: "", - CollateralAsset: ptypes.BaseCurrency, - BorrowAsset: "uatom", - Position: types.Position_LONG, + Creator: "", + Leverage: math.LegacyNewDec(2), + Position: types.Position_LONG, + TradingAsset: "uatom", + Collateral: sdk.NewCoin(ptypes.BaseCurrency, math.NewInt(1000)), } ammPool = ammtypes.Pool{ PoolId: uint64(42), @@ -122,13 +119,12 @@ func TestOpenLong_InsufficientLiabilities(t *testing.T) { mockChecker.On("GetMaxLeverageParam", ctx).Return(msg.Leverage) mockChecker.On("GetPool", ctx, ammPool.PoolId).Return(pool, true) mockChecker.On("IsPoolEnabled", ctx, ammPool.PoolId).Return(true) - mockChecker.On("GetAmmPool", ctx, ammPool.PoolId, msg.BorrowAsset).Return(ammPool, nil) // Assuming a valid pool is returned + mockChecker.On("GetAmmPool", ctx, ammPool.PoolId, msg.TradingAsset).Return(ammPool, nil) // Assuming a valid pool is returned // Mock the behavior where CheckMinLiabilities returns an error indicating insufficient liabilities liabilityError := errors.New("insufficient liabilities") - collateralTokenAmt := sdk.NewCoin(msg.CollateralAsset, msg.CollateralAmount) - mockChecker.On("CheckMinLiabilities", ctx, collateralTokenAmt, sdk.NewDec(1), pool, ammPool, msg.BorrowAsset).Return(liabilityError) + mockChecker.On("CheckMinLiabilities", ctx, msg.Collateral, sdk.NewDec(1), ammPool, msg.TradingAsset, ptypes.BaseCurrency).Return(liabilityError) _, err := k.OpenLong(ctx, ammPool.PoolId, msg, ptypes.BaseCurrency) @@ -149,12 +145,11 @@ func TestOpenLong_InsufficientAmmPoolBalanceForCustody(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - Leverage: math.LegacyNewDec(10), - CollateralAmount: math.NewInt(1000), - Creator: "", - CollateralAsset: ptypes.BaseCurrency, - BorrowAsset: "uatom", - Position: types.Position_LONG, + Creator: "", + Leverage: math.LegacyNewDec(10), + Position: types.Position_LONG, + TradingAsset: "uatom", + Collateral: sdk.NewCoin(ptypes.BaseCurrency, math.NewInt(1000)), } ammPool = ammtypes.Pool{ PoolId: uint64(42), @@ -177,17 +172,16 @@ func TestOpenLong_InsufficientAmmPoolBalanceForCustody(t *testing.T) { mockChecker.On("GetMaxLeverageParam", ctx).Return(msg.Leverage) mockChecker.On("GetPool", ctx, ammPool.PoolId).Return(pool, true) mockChecker.On("IsPoolEnabled", ctx, ammPool.PoolId).Return(true) - mockChecker.On("GetAmmPool", ctx, ammPool.PoolId, msg.BorrowAsset).Return(ammPool, nil) + mockChecker.On("GetAmmPool", ctx, ammPool.PoolId, msg.TradingAsset).Return(ammPool, nil) - collateralTokenAmt := sdk.NewCoin(msg.CollateralAsset, msg.CollateralAmount) eta := math.LegacyNewDec(9) - mockChecker.On("CheckMinLiabilities", ctx, collateralTokenAmt, eta, pool, ammPool, msg.BorrowAsset).Return(nil) + mockChecker.On("CheckMinLiabilities", ctx, msg.Collateral, eta, ammPool, msg.TradingAsset, ptypes.BaseCurrency).Return(nil) - leveragedAmtTokenIn := sdk.NewCoin(msg.CollateralAsset, math.NewInt(10000)) + leveragedAmtTokenIn := sdk.NewCoin(msg.Collateral.Denom, math.NewInt(10000)) custodyAmount := math.NewInt(99) - mockChecker.On("EstimateSwap", ctx, leveragedAmtTokenIn, msg.BorrowAsset, ammPool).Return(custodyAmount, nil) + mockChecker.On("EstimateSwap", ctx, leveragedAmtTokenIn, msg.TradingAsset, ammPool).Return(custodyAmount, nil) _, err := k.OpenLong(ctx, ammPool.PoolId, msg, ptypes.BaseCurrency) @@ -208,13 +202,12 @@ func TestOpenLong_ErrorsDuringOperations(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - Leverage: math.LegacyNewDec(10), - CollateralAmount: math.NewInt(1000), - Creator: "", - CollateralAsset: ptypes.BaseCurrency, - BorrowAsset: "uatom", - Position: types.Position_LONG, - TakeProfitPrice: sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), + Creator: "", + Leverage: math.LegacyNewDec(10), + Position: types.Position_LONG, + TradingAsset: "uatom", + Collateral: sdk.NewCoin(ptypes.BaseCurrency, math.NewInt(1000)), + TakeProfitPrice: sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), } ammPool = ammtypes.Pool{ PoolId: uint64(42), @@ -238,22 +231,21 @@ func TestOpenLong_ErrorsDuringOperations(t *testing.T) { mockChecker.On("GetMaxLeverageParam", ctx).Return(msg.Leverage) mockChecker.On("GetPool", ctx, ammPool.PoolId).Return(pool, true) mockChecker.On("IsPoolEnabled", ctx, ammPool.PoolId).Return(true) - mockChecker.On("GetAmmPool", ctx, ammPool.PoolId, msg.BorrowAsset).Return(ammPool, nil) + mockChecker.On("GetAmmPool", ctx, ammPool.PoolId, msg.TradingAsset).Return(ammPool, nil) - collateralTokenAmt := sdk.NewCoin(msg.CollateralAsset, msg.CollateralAmount) eta := math.LegacyNewDec(9) - mockChecker.On("CheckMinLiabilities", ctx, collateralTokenAmt, eta, pool, ammPool, msg.BorrowAsset).Return(nil) + mockChecker.On("CheckMinLiabilities", ctx, msg.Collateral, eta, ammPool, msg.TradingAsset, ptypes.BaseCurrency).Return(nil) - leveragedAmtTokenIn := sdk.NewCoin(msg.CollateralAsset, math.NewInt(10000)) + leveragedAmtTokenIn := sdk.NewCoin(msg.Collateral.Denom, math.NewInt(10000)) custodyAmount := math.NewInt(99) - mockChecker.On("EstimateSwap", ctx, leveragedAmtTokenIn, msg.BorrowAsset, ammPool).Return(custodyAmount, nil) + mockChecker.On("EstimateSwap", ctx, leveragedAmtTokenIn, msg.TradingAsset, ammPool).Return(custodyAmount, nil) - mtp := types.NewMTP(msg.Creator, msg.CollateralAsset, msg.BorrowAsset, msg.Position, msg.Leverage, sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), ammPool.PoolId) + mtp := types.NewMTP(msg.Creator, msg.Collateral.Denom, msg.TradingAsset, msg.Collateral.Denom, msg.TradingAsset, msg.Position, msg.Leverage, sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), ammPool.PoolId) borrowError := errors.New("borrow error") - mockChecker.On("Borrow", ctx, msg.CollateralAsset, msg.BorrowAsset, msg.CollateralAmount, custodyAmount, mtp, &ammPool, &pool, eta, ptypes.BaseCurrency).Return(borrowError) + mockChecker.On("Borrow", ctx, msg.Collateral.Amount, custodyAmount, mtp, &ammPool, &pool, eta, ptypes.BaseCurrency).Return(borrowError) _, err := k.OpenLong(ctx, ammPool.PoolId, msg, ptypes.BaseCurrency) @@ -274,13 +266,12 @@ func TestOpenLong_LeverageRatioLessThanSafetyFactor(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - Leverage: math.LegacyNewDec(10), - CollateralAmount: math.NewInt(1000), - Creator: "", - CollateralAsset: ptypes.BaseCurrency, - BorrowAsset: "uatom", - Position: types.Position_LONG, - TakeProfitPrice: sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), + Creator: "", + Leverage: math.LegacyNewDec(10), + Position: types.Position_LONG, + TradingAsset: "uatom", + Collateral: sdk.NewCoin(ptypes.BaseCurrency, math.NewInt(1000)), + TakeProfitPrice: sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), } ammPool = ammtypes.Pool{ PoolId: uint64(42), @@ -304,21 +295,20 @@ func TestOpenLong_LeverageRatioLessThanSafetyFactor(t *testing.T) { mockChecker.On("GetMaxLeverageParam", ctx).Return(msg.Leverage) mockChecker.On("GetPool", ctx, ammPool.PoolId).Return(pool, true) mockChecker.On("IsPoolEnabled", ctx, ammPool.PoolId).Return(true) - mockChecker.On("GetAmmPool", ctx, ammPool.PoolId, msg.BorrowAsset).Return(ammPool, nil) + mockChecker.On("GetAmmPool", ctx, ammPool.PoolId, msg.TradingAsset).Return(ammPool, nil) - collateralTokenAmt := sdk.NewCoin(msg.CollateralAsset, msg.CollateralAmount) eta := math.LegacyNewDec(9) - mockChecker.On("CheckMinLiabilities", ctx, collateralTokenAmt, eta, pool, ammPool, msg.BorrowAsset).Return(nil) + mockChecker.On("CheckMinLiabilities", ctx, msg.Collateral, eta, ammPool, msg.TradingAsset, ptypes.BaseCurrency).Return(nil) - leveragedAmtTokenIn := sdk.NewCoin(msg.CollateralAsset, math.NewInt(10000)) + leveragedAmtTokenIn := sdk.NewCoin(msg.Collateral.Denom, math.NewInt(10000)) custodyAmount := math.NewInt(99) - mockChecker.On("EstimateSwap", ctx, leveragedAmtTokenIn, msg.BorrowAsset, ammPool).Return(custodyAmount, nil) + mockChecker.On("EstimateSwap", ctx, leveragedAmtTokenIn, msg.TradingAsset, ammPool).Return(custodyAmount, nil) - mtp := types.NewMTP(msg.Creator, msg.CollateralAsset, msg.BorrowAsset, msg.Position, msg.Leverage, sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), ammPool.PoolId) + mtp := types.NewMTP(msg.Creator, msg.Collateral.Denom, msg.TradingAsset, msg.Collateral.Denom, msg.TradingAsset, msg.Position, msg.Leverage, sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), ammPool.PoolId) - mockChecker.On("Borrow", ctx, msg.CollateralAsset, msg.BorrowAsset, msg.CollateralAmount, custodyAmount, mtp, &ammPool, &pool, eta, ptypes.BaseCurrency).Return(nil) + mockChecker.On("Borrow", ctx, msg.Collateral.Amount, custodyAmount, mtp, &ammPool, &pool, eta, ptypes.BaseCurrency).Return(nil) mockChecker.On("UpdatePoolHealth", ctx, &pool).Return(nil) mockChecker.On("TakeInCustody", ctx, *mtp, &pool).Return(nil) @@ -346,13 +336,12 @@ func TestOpenLong_Success(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - Leverage: math.LegacyNewDec(10), - CollateralAmount: math.NewInt(1000), - Creator: "", - CollateralAsset: ptypes.BaseCurrency, - BorrowAsset: "uatom", - Position: types.Position_LONG, - TakeProfitPrice: sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), + Creator: "", + Leverage: math.LegacyNewDec(10), + Position: types.Position_LONG, + TradingAsset: "uatom", + Collateral: sdk.NewCoin(ptypes.BaseCurrency, math.NewInt(1000)), + TakeProfitPrice: sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), } ammPool = ammtypes.Pool{ PoolId: uint64(42), @@ -376,21 +365,20 @@ func TestOpenLong_Success(t *testing.T) { mockChecker.On("GetMaxLeverageParam", ctx).Return(msg.Leverage) mockChecker.On("GetPool", ctx, ammPool.PoolId).Return(pool, true) mockChecker.On("IsPoolEnabled", ctx, ammPool.PoolId).Return(true) - mockChecker.On("GetAmmPool", ctx, ammPool.PoolId, msg.BorrowAsset).Return(ammPool, nil) + mockChecker.On("GetAmmPool", ctx, ammPool.PoolId, msg.TradingAsset).Return(ammPool, nil) - collateralTokenAmt := sdk.NewCoin(msg.CollateralAsset, msg.CollateralAmount) eta := math.LegacyNewDec(9) - mockChecker.On("CheckMinLiabilities", ctx, collateralTokenAmt, eta, pool, ammPool, msg.BorrowAsset).Return(nil) + mockChecker.On("CheckMinLiabilities", ctx, msg.Collateral, eta, ammPool, msg.TradingAsset, ptypes.BaseCurrency).Return(nil) - leveragedAmtTokenIn := sdk.NewCoin(msg.CollateralAsset, math.NewInt(10000)) + leveragedAmtTokenIn := sdk.NewCoin(msg.Collateral.Denom, math.NewInt(10000)) custodyAmount := math.NewInt(99) - mockChecker.On("EstimateSwap", ctx, leveragedAmtTokenIn, msg.BorrowAsset, ammPool).Return(custodyAmount, nil) + mockChecker.On("EstimateSwap", ctx, leveragedAmtTokenIn, msg.TradingAsset, ammPool).Return(custodyAmount, nil) - mtp := types.NewMTP(msg.Creator, msg.CollateralAsset, msg.BorrowAsset, msg.Position, msg.Leverage, sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), ammPool.PoolId) + mtp := types.NewMTP(msg.Creator, msg.Collateral.Denom, msg.TradingAsset, msg.Collateral.Denom, msg.TradingAsset, msg.Position, msg.Leverage, sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), ammPool.PoolId) - mockChecker.On("Borrow", ctx, msg.CollateralAsset, msg.BorrowAsset, msg.CollateralAmount, custodyAmount, mtp, &ammPool, &pool, eta, ptypes.BaseCurrency).Return(nil) + mockChecker.On("Borrow", ctx, msg.Collateral.Amount, custodyAmount, mtp, &ammPool, &pool, eta, ptypes.BaseCurrency).Return(nil) mockChecker.On("UpdatePoolHealth", ctx, &pool).Return(nil) mockChecker.On("TakeInCustody", ctx, *mtp, &pool).Return(nil) @@ -491,11 +479,10 @@ func TestOpenLong_BaseCurrency_Collateral(t *testing.T) { // Create a margin position open msg msg2 := types.NewMsgOpen( addr[0].String(), - ptypes.BaseCurrency, - sdk.NewInt(100000000), - ptypes.ATOM, types.Position_LONG, sdk.NewDec(5), + ptypes.ATOM, + sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(100000000)), sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), ) @@ -596,11 +583,10 @@ func TestOpenLong_ATOM_Collateral(t *testing.T) { // Create a margin position open msg msg2 := types.NewMsgOpen( addr[0].String(), - ptypes.ATOM, - sdk.NewInt(10000000), - ptypes.ATOM, types.Position_LONG, sdk.NewDec(5), + ptypes.ATOM, + sdk.NewCoin(ptypes.ATOM, sdk.NewInt(10000000)), sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), ) diff --git a/x/margin/keeper/open_short.go b/x/margin/keeper/open_short.go index 91230625c..b8f69d494 100644 --- a/x/margin/keeper/open_short.go +++ b/x/margin/keeper/open_short.go @@ -3,6 +3,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/elys-network/elys/x/margin/types" + ptypes "github.com/elys-network/elys/x/parameter/types" ) func (k Keeper) OpenShort(ctx sdk.Context, poolId uint64, msg *types.MsgOpen, baseCurrency string) (*types.MTP, error) { @@ -14,10 +15,14 @@ func (k Keeper) OpenShort(ctx sdk.Context, poolId uint64, msg *types.MsgOpen, ba eta := leverage.Sub(sdk.OneDec()) // Convert the collateral amount into a decimal format. - collateralAmountDec := sdk.NewDecFromBigInt(msg.CollateralAmount.BigInt()) + collateralAmountDec := sdk.NewDecFromBigInt(msg.Collateral.Amount.BigInt()) + + // Define the assets + liabilitiesAsset := msg.TradingAsset + custodyAsset := ptypes.BaseCurrency // Initialize a new Margin Trading Position (MTP). - mtp := types.NewMTP(msg.Creator, msg.CollateralAsset, msg.BorrowAsset, msg.Position, leverage, msg.TakeProfitPrice, poolId) + mtp := types.NewMTP(msg.Creator, msg.Collateral.Denom, msg.TradingAsset, liabilitiesAsset, custodyAsset, msg.Position, leverage, msg.TakeProfitPrice, poolId) // Call the function to process the open short logic. return k.ProcessOpenShort(ctx, mtp, leverage, eta, collateralAmountDec, poolId, msg, baseCurrency) diff --git a/x/margin/keeper/open_short_process.go b/x/margin/keeper/open_short_process.go index 857c6eaa1..f8381f32f 100644 --- a/x/margin/keeper/open_short_process.go +++ b/x/margin/keeper/open_short_process.go @@ -7,22 +7,19 @@ import ( ) func (k Keeper) ProcessOpenShort(ctx sdk.Context, mtp *types.MTP, leverage sdk.Dec, eta sdk.Dec, collateralAmountDec sdk.Dec, poolId uint64, msg *types.MsgOpen, baseCurrency string) (*types.MTP, error) { - // Determine the trading asset. - tradingAsset := types.GetTradingAsset(msg.CollateralAsset, msg.BorrowAsset, baseCurrency) - // Fetch the pool associated with the given pool ID. pool, found := k.OpenShortChecker.GetPool(ctx, poolId) if !found { - return nil, sdkerrors.Wrap(types.ErrPoolDoesNotExist, tradingAsset) + return nil, sdkerrors.Wrap(types.ErrPoolDoesNotExist, mtp.TradingAsset) } // Check if the pool is enabled. if !k.OpenShortChecker.IsPoolEnabled(ctx, poolId) { - return nil, sdkerrors.Wrap(types.ErrMTPDisabled, tradingAsset) + return nil, sdkerrors.Wrap(types.ErrMTPDisabled, mtp.TradingAsset) } // Fetch the corresponding AMM (Automated Market Maker) pool. - ammPool, err := k.OpenShortChecker.GetAmmPool(ctx, poolId, tradingAsset) + ammPool, err := k.OpenShortChecker.GetAmmPool(ctx, poolId, mtp.TradingAsset) if err != nil { return nil, err } @@ -30,51 +27,26 @@ func (k Keeper) ProcessOpenShort(ctx sdk.Context, mtp *types.MTP, leverage sdk.D // Calculate the leveraged amount based on the collateral provided and the leverage. leveragedAmount := sdk.NewInt(collateralAmountDec.Mul(leverage).TruncateInt().Int64()) - if msg.CollateralAsset != baseCurrency { + if mtp.CollateralAsset != baseCurrency { return nil, sdkerrors.Wrap(types.ErrInvalidBorrowingAsset, "collateral must be base currency") } - custodyAmtToken := sdk.NewCoin(baseCurrency, leveragedAmount) - borrowingAmount, err := k.OpenShortChecker.EstimateSwapGivenOut(ctx, custodyAmtToken, msg.BorrowAsset, ammPool) - if err != nil { - return nil, err - } - - // check the balance - if !types.HasSufficientPoolBalance(ammPool, baseCurrency, borrowingAmount) { - return nil, sdkerrors.Wrap(types.ErrBorrowTooHigh, borrowingAmount.String()) - } - // Check minimum liabilities. - collateralTokenAmt := sdk.NewCoin(msg.CollateralAsset, msg.CollateralAmount) - err = k.OpenShortChecker.CheckMinLiabilities(ctx, collateralTokenAmt, eta, pool, ammPool, msg.BorrowAsset) + err = k.OpenShortChecker.CheckMinLiabilities(ctx, msg.Collateral, eta, ammPool, mtp.CustodyAsset, baseCurrency) if err != nil { return nil, err } - // Calculate custody amount. - leveragedAmtTokenIn := sdk.NewCoin(msg.BorrowAsset, borrowingAmount) - custodyAmount, err := k.OpenShortChecker.EstimateSwap(ctx, leveragedAmtTokenIn, baseCurrency, ammPool) - if err != nil { - return nil, err - } + // Define custody amount + custodyAmount := leveragedAmount - // Ensure the AMM pool has enough balance. - if !types.HasSufficientPoolBalance(ammPool, baseCurrency, custodyAmount) { - return nil, sdkerrors.Wrap(types.ErrCustodyTooHigh, custodyAmount.String()) - } - - // if position is short then override the custody asset to the base currency - if mtp.Position == types.Position_SHORT { - mtp.Custodies = []sdk.Coin{sdk.NewCoin(baseCurrency, sdk.NewInt(0))} - mtp.BorrowInterestPaidCustodies = []sdk.Coin{sdk.NewCoin(baseCurrency, sdk.NewInt(0))} - mtp.TakeProfitCustodies = []sdk.Coin{sdk.NewCoin(baseCurrency, sdk.NewInt(0))} - mtp.FundingFeePaidCustodies = []sdk.Coin{sdk.NewCoin(baseCurrency, sdk.NewInt(0))} - mtp.FundingFeeReceivedCustodies = []sdk.Coin{sdk.NewCoin(baseCurrency, sdk.NewInt(0))} + // check the balance + if !types.HasSufficientPoolBalance(ammPool, mtp.CustodyAsset, custodyAmount) { + return nil, sdkerrors.Wrap(types.ErrBorrowTooHigh, custodyAmount.String()) } // Borrow the asset the user wants to short. - err = k.OpenShortChecker.Borrow(ctx, msg.CollateralAsset, baseCurrency, msg.CollateralAmount, custodyAmount, mtp, &ammPool, &pool, eta, baseCurrency) + err = k.OpenShortChecker.Borrow(ctx, msg.Collateral.Amount, custodyAmount, mtp, &ammPool, &pool, eta, baseCurrency) if err != nil { return nil, err } diff --git a/x/margin/keeper/open_short_test.go b/x/margin/keeper/open_short_test.go index 7f8c6778d..f37c1f58b 100644 --- a/x/margin/keeper/open_short_test.go +++ b/x/margin/keeper/open_short_test.go @@ -31,10 +31,9 @@ func TestOpenShort_PoolNotFound(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - Leverage: math.LegacyNewDec(10), - CollateralAmount: math.NewInt(1), - CollateralAsset: "aaa", - BorrowAsset: "bbb", + Leverage: math.LegacyNewDec(10), + TradingAsset: "bbb", + Collateral: sdk.NewCoin("aaa", math.NewInt(1)), } poolId = uint64(42) ) @@ -62,10 +61,9 @@ func TestOpenShort_PoolDisabled(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - Leverage: math.LegacyNewDec(10), - CollateralAmount: math.NewInt(1), - CollateralAsset: "aaa", - BorrowAsset: "bbb", + Leverage: math.LegacyNewDec(10), + TradingAsset: "bbb", + Collateral: sdk.NewCoin("aaa", math.NewInt(1)), } poolId = uint64(42) ) @@ -94,12 +92,11 @@ func TestOpenShort_InsufficientLiabilities(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - Leverage: math.LegacyNewDec(2), - CollateralAmount: math.NewInt(1000), - Creator: "", - CollateralAsset: ptypes.BaseCurrency, - BorrowAsset: "uatom", - Position: types.Position_SHORT, + Creator: "", + Leverage: math.LegacyNewDec(2), + Position: types.Position_SHORT, + TradingAsset: "uatom", + Collateral: sdk.NewCoin(ptypes.BaseCurrency, math.NewInt(1000)), } ammPool = ammtypes.Pool{ PoolId: uint64(42), @@ -123,20 +120,12 @@ func TestOpenShort_InsufficientLiabilities(t *testing.T) { mockChecker.On("GetMaxLeverageParam", ctx).Return(msg.Leverage) mockChecker.On("GetPool", ctx, ammPool.PoolId).Return(pool, true) mockChecker.On("IsPoolEnabled", ctx, ammPool.PoolId).Return(true) - mockChecker.On("GetAmmPool", ctx, ammPool.PoolId, msg.BorrowAsset).Return(ammPool, nil) // Assuming a valid pool is returned - - collateralAmountDec := sdk.NewDecFromBigInt(msg.CollateralAmount.BigInt()) - leveragedAmount := sdk.NewInt(collateralAmountDec.Mul(msg.Leverage).TruncateInt().Int64()) - custodyAmtToken := sdk.NewCoin(ptypes.BaseCurrency, leveragedAmount) - borrowingAmount := sdk.NewInt(99) - - mockChecker.On("EstimateSwapGivenOut", ctx, custodyAmtToken, msg.BorrowAsset, ammPool).Return(borrowingAmount, nil) + mockChecker.On("GetAmmPool", ctx, ammPool.PoolId, msg.TradingAsset).Return(ammPool, nil) // Assuming a valid pool is returned // Mock the behavior where CheckMinLiabilities returns an error indicating insufficient liabilities liabilityError := errors.New("insufficient liabilities") - collateralTokenAmt := sdk.NewCoin(msg.CollateralAsset, msg.CollateralAmount) - mockChecker.On("CheckMinLiabilities", ctx, collateralTokenAmt, sdk.NewDec(1), pool, ammPool, msg.BorrowAsset).Return(liabilityError) + mockChecker.On("CheckMinLiabilities", ctx, msg.Collateral, sdk.NewDec(1), ammPool, ptypes.BaseCurrency, ptypes.BaseCurrency).Return(liabilityError) _, err := k.OpenShort(ctx, ammPool.PoolId, msg, ptypes.BaseCurrency) @@ -157,22 +146,21 @@ func TestOpenShort_InsufficientAmmPoolBalanceForCustody(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - Leverage: math.LegacyNewDec(10), - CollateralAmount: math.NewInt(1000), - Creator: "", - CollateralAsset: ptypes.BaseCurrency, - BorrowAsset: "uatom", - Position: types.Position_SHORT, + Creator: "", + Leverage: math.LegacyNewDec(10), + Position: types.Position_SHORT, + TradingAsset: "uatom", + Collateral: sdk.NewCoin(ptypes.BaseCurrency, math.NewInt(1000)), } ammPool = ammtypes.Pool{ PoolId: uint64(42), PoolAssets: []ammtypes.PoolAsset{ { - Token: sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(10000)), + Token: sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(100)), Weight: sdk.NewInt(50), }, { - Token: sdk.NewCoin("uatom", sdk.NewInt(10000)), + Token: sdk.NewCoin("uatom", sdk.NewInt(100)), Weight: sdk.NewInt(50), }, }, @@ -185,29 +173,16 @@ func TestOpenShort_InsufficientAmmPoolBalanceForCustody(t *testing.T) { mockChecker.On("GetMaxLeverageParam", ctx).Return(msg.Leverage) mockChecker.On("GetPool", ctx, ammPool.PoolId).Return(pool, true) mockChecker.On("IsPoolEnabled", ctx, ammPool.PoolId).Return(true) - mockChecker.On("GetAmmPool", ctx, ammPool.PoolId, msg.BorrowAsset).Return(ammPool, nil) - - collateralAmountDec := sdk.NewDecFromBigInt(msg.CollateralAmount.BigInt()) - leveragedAmount := sdk.NewInt(collateralAmountDec.Mul(msg.Leverage).TruncateInt().Int64()) - custodyAmtToken := sdk.NewCoin(ptypes.BaseCurrency, leveragedAmount) - borrowingAmount := sdk.NewInt(99) - - mockChecker.On("EstimateSwapGivenOut", ctx, custodyAmtToken, msg.BorrowAsset, ammPool).Return(borrowingAmount, nil) + mockChecker.On("GetAmmPool", ctx, ammPool.PoolId, msg.TradingAsset).Return(ammPool, nil) - collateralTokenAmt := sdk.NewCoin(msg.CollateralAsset, msg.CollateralAmount) eta := math.LegacyNewDec(9) - mockChecker.On("CheckMinLiabilities", ctx, collateralTokenAmt, eta, pool, ammPool, msg.BorrowAsset).Return(nil) - - leveragedAmtTokenIn := sdk.NewCoin(msg.BorrowAsset, borrowingAmount) - custodyAmount := math.NewInt(100000) - - mockChecker.On("EstimateSwap", ctx, leveragedAmtTokenIn, ptypes.BaseCurrency, ammPool).Return(custodyAmount, nil) + mockChecker.On("CheckMinLiabilities", ctx, msg.Collateral, eta, ammPool, ptypes.BaseCurrency, ptypes.BaseCurrency).Return(nil) _, err := k.OpenShort(ctx, ammPool.PoolId, msg, ptypes.BaseCurrency) // Expect an error about custody amount being too high - assert.True(t, errors.Is(err, types.ErrCustodyTooHigh)) + assert.True(t, errors.Is(err, types.ErrBorrowTooHigh)) mockChecker.AssertExpectations(t) } @@ -223,13 +198,12 @@ func TestOpenShort_ErrorsDuringOperations(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - Leverage: math.LegacyNewDec(10), - CollateralAmount: math.NewInt(1000), - Creator: "", - CollateralAsset: ptypes.BaseCurrency, - BorrowAsset: "uatom", - Position: types.Position_SHORT, - TakeProfitPrice: sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), + Creator: "", + Leverage: math.LegacyNewDec(10), + Position: types.Position_SHORT, + TradingAsset: "uatom", + Collateral: sdk.NewCoin(ptypes.BaseCurrency, math.NewInt(1000)), + TakeProfitPrice: sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), } ammPool = ammtypes.Pool{ PoolId: uint64(42), @@ -253,29 +227,18 @@ func TestOpenShort_ErrorsDuringOperations(t *testing.T) { mockChecker.On("GetMaxLeverageParam", ctx).Return(msg.Leverage) mockChecker.On("GetPool", ctx, ammPool.PoolId).Return(pool, true) mockChecker.On("IsPoolEnabled", ctx, ammPool.PoolId).Return(true) - mockChecker.On("GetAmmPool", ctx, ammPool.PoolId, msg.BorrowAsset).Return(ammPool, nil) - - collateralAmountDec := sdk.NewDecFromBigInt(msg.CollateralAmount.BigInt()) - leveragedAmount := sdk.NewInt(collateralAmountDec.Mul(msg.Leverage).TruncateInt().Int64()) - custodyAmtToken := sdk.NewCoin(ptypes.BaseCurrency, leveragedAmount) - borrowingAmount := sdk.NewInt(99) + mockChecker.On("GetAmmPool", ctx, ammPool.PoolId, msg.TradingAsset).Return(ammPool, nil) - mockChecker.On("EstimateSwapGivenOut", ctx, custodyAmtToken, msg.BorrowAsset, ammPool).Return(borrowingAmount, nil) - - collateralTokenAmt := sdk.NewCoin(msg.CollateralAsset, msg.CollateralAmount) eta := math.LegacyNewDec(9) - mockChecker.On("CheckMinLiabilities", ctx, collateralTokenAmt, eta, pool, ammPool, msg.BorrowAsset).Return(nil) - - leveragedAmtTokenIn := sdk.NewCoin(msg.BorrowAsset, borrowingAmount) - custodyAmount := math.NewInt(199) + mockChecker.On("CheckMinLiabilities", ctx, msg.Collateral, eta, ammPool, ptypes.BaseCurrency, ptypes.BaseCurrency).Return(nil) - mockChecker.On("EstimateSwap", ctx, leveragedAmtTokenIn, ptypes.BaseCurrency, ammPool).Return(custodyAmount, nil) + custodyAmount := sdk.NewDecFromBigInt(msg.Collateral.Amount.BigInt()).Mul(msg.Leverage).TruncateInt() - mtp := types.NewMTP(msg.Creator, msg.CollateralAsset, ptypes.BaseCurrency, msg.Position, msg.Leverage, sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), ammPool.PoolId) + mtp := types.NewMTP(msg.Creator, msg.Collateral.Denom, msg.TradingAsset, msg.TradingAsset, ptypes.BaseCurrency, msg.Position, msg.Leverage, sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), ammPool.PoolId) borrowError := errors.New("borrow error") - mockChecker.On("Borrow", ctx, msg.CollateralAsset, ptypes.BaseCurrency, msg.CollateralAmount, custodyAmount, mtp, &ammPool, &pool, eta, ptypes.BaseCurrency).Return(borrowError) + mockChecker.On("Borrow", ctx, msg.Collateral.Amount, custodyAmount, mtp, &ammPool, &pool, eta, ptypes.BaseCurrency).Return(borrowError) _, err := k.OpenShort(ctx, ammPool.PoolId, msg, ptypes.BaseCurrency) @@ -296,13 +259,12 @@ func TestOpenShort_LeverageRatioLessThanSafetyFactor(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - Leverage: math.LegacyNewDec(10), - CollateralAmount: math.NewInt(1000), - Creator: "", - CollateralAsset: ptypes.BaseCurrency, - BorrowAsset: "uatom", - Position: types.Position_SHORT, - TakeProfitPrice: sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), + Creator: "", + Leverage: math.LegacyNewDec(10), + Position: types.Position_SHORT, + TradingAsset: "uatom", + Collateral: sdk.NewCoin(ptypes.BaseCurrency, math.NewInt(1000)), + TakeProfitPrice: sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), } ammPool = ammtypes.Pool{ PoolId: uint64(42), @@ -326,28 +288,17 @@ func TestOpenShort_LeverageRatioLessThanSafetyFactor(t *testing.T) { mockChecker.On("GetMaxLeverageParam", ctx).Return(msg.Leverage) mockChecker.On("GetPool", ctx, ammPool.PoolId).Return(pool, true) mockChecker.On("IsPoolEnabled", ctx, ammPool.PoolId).Return(true) - mockChecker.On("GetAmmPool", ctx, ammPool.PoolId, msg.BorrowAsset).Return(ammPool, nil) - - collateralAmountDec := sdk.NewDecFromBigInt(msg.CollateralAmount.BigInt()) - leveragedAmount := sdk.NewInt(collateralAmountDec.Mul(msg.Leverage).TruncateInt().Int64()) - custodyAmtToken := sdk.NewCoin(ptypes.BaseCurrency, leveragedAmount) - borrowingAmount := sdk.NewInt(99) + mockChecker.On("GetAmmPool", ctx, ammPool.PoolId, msg.TradingAsset).Return(ammPool, nil) - mockChecker.On("EstimateSwapGivenOut", ctx, custodyAmtToken, msg.BorrowAsset, ammPool).Return(borrowingAmount, nil) - - collateralTokenAmt := sdk.NewCoin(msg.CollateralAsset, msg.CollateralAmount) eta := math.LegacyNewDec(9) - mockChecker.On("CheckMinLiabilities", ctx, collateralTokenAmt, eta, pool, ammPool, msg.BorrowAsset).Return(nil) - - leveragedAmtTokenIn := sdk.NewCoin(msg.BorrowAsset, borrowingAmount) - custodyAmount := math.NewInt(199) + mockChecker.On("CheckMinLiabilities", ctx, msg.Collateral, eta, ammPool, ptypes.BaseCurrency, ptypes.BaseCurrency).Return(nil) - mockChecker.On("EstimateSwap", ctx, leveragedAmtTokenIn, ptypes.BaseCurrency, ammPool).Return(custodyAmount, nil) + custodyAmount := sdk.NewDecFromBigInt(msg.Collateral.Amount.BigInt()).Mul(msg.Leverage).TruncateInt() - mtp := types.NewMTP(msg.Creator, msg.CollateralAsset, ptypes.BaseCurrency, msg.Position, msg.Leverage, sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), ammPool.PoolId) + mtp := types.NewMTP(msg.Creator, msg.Collateral.Denom, msg.TradingAsset, msg.TradingAsset, ptypes.BaseCurrency, msg.Position, msg.Leverage, sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), ammPool.PoolId) - mockChecker.On("Borrow", ctx, msg.CollateralAsset, ptypes.BaseCurrency, msg.CollateralAmount, custodyAmount, mtp, &ammPool, &pool, eta, ptypes.BaseCurrency).Return(nil) + mockChecker.On("Borrow", ctx, msg.Collateral.Amount, custodyAmount, mtp, &ammPool, &pool, eta, ptypes.BaseCurrency).Return(nil) mockChecker.On("UpdatePoolHealth", ctx, &pool).Return(nil) mockChecker.On("TakeInCustody", ctx, *mtp, &pool).Return(nil) @@ -375,13 +326,12 @@ func TestOpenShort_Success(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - Leverage: math.LegacyNewDec(10), - CollateralAmount: math.NewInt(1000), - Creator: "", - CollateralAsset: ptypes.BaseCurrency, - BorrowAsset: "uatom", - Position: types.Position_SHORT, - TakeProfitPrice: sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), + Creator: "", + Leverage: math.LegacyNewDec(10), + Position: types.Position_SHORT, + TradingAsset: "uatom", + Collateral: sdk.NewCoin(ptypes.BaseCurrency, math.NewInt(1000)), + TakeProfitPrice: sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), } ammPool = ammtypes.Pool{ PoolId: uint64(42), @@ -405,28 +355,17 @@ func TestOpenShort_Success(t *testing.T) { mockChecker.On("GetMaxLeverageParam", ctx).Return(msg.Leverage) mockChecker.On("GetPool", ctx, ammPool.PoolId).Return(pool, true) mockChecker.On("IsPoolEnabled", ctx, ammPool.PoolId).Return(true) - mockChecker.On("GetAmmPool", ctx, ammPool.PoolId, msg.BorrowAsset).Return(ammPool, nil) - - collateralAmountDec := sdk.NewDecFromBigInt(msg.CollateralAmount.BigInt()) - leveragedAmount := sdk.NewInt(collateralAmountDec.Mul(msg.Leverage).TruncateInt().Int64()) - custodyAmtToken := sdk.NewCoin(ptypes.BaseCurrency, leveragedAmount) - borrowingAmount := sdk.NewInt(99) + mockChecker.On("GetAmmPool", ctx, ammPool.PoolId, msg.TradingAsset).Return(ammPool, nil) - mockChecker.On("EstimateSwapGivenOut", ctx, custodyAmtToken, msg.BorrowAsset, ammPool).Return(borrowingAmount, nil) - - collateralTokenAmt := sdk.NewCoin(msg.CollateralAsset, msg.CollateralAmount) eta := math.LegacyNewDec(9) - mockChecker.On("CheckMinLiabilities", ctx, collateralTokenAmt, eta, pool, ammPool, msg.BorrowAsset).Return(nil) - - leveragedAmtTokenIn := sdk.NewCoin(msg.BorrowAsset, borrowingAmount) - custodyAmount := math.NewInt(199) + mockChecker.On("CheckMinLiabilities", ctx, msg.Collateral, eta, ammPool, ptypes.BaseCurrency, ptypes.BaseCurrency).Return(nil) - mockChecker.On("EstimateSwap", ctx, leveragedAmtTokenIn, ptypes.BaseCurrency, ammPool).Return(custodyAmount, nil) + custodyAmount := sdk.NewDecFromBigInt(msg.Collateral.Amount.BigInt()).Mul(msg.Leverage).TruncateInt() - mtp := types.NewMTP(msg.Creator, msg.CollateralAsset, ptypes.BaseCurrency, msg.Position, msg.Leverage, sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), ammPool.PoolId) + mtp := types.NewMTP(msg.Creator, msg.Collateral.Denom, msg.TradingAsset, msg.TradingAsset, ptypes.BaseCurrency, msg.Position, msg.Leverage, sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), ammPool.PoolId) - mockChecker.On("Borrow", ctx, msg.CollateralAsset, ptypes.BaseCurrency, msg.CollateralAmount, custodyAmount, mtp, &ammPool, &pool, eta, ptypes.BaseCurrency).Return(nil) + mockChecker.On("Borrow", ctx, msg.Collateral.Amount, custodyAmount, mtp, &ammPool, &pool, eta, ptypes.BaseCurrency).Return(nil) mockChecker.On("UpdatePoolHealth", ctx, &pool).Return(nil) mockChecker.On("TakeInCustody", ctx, *mtp, &pool).Return(nil) @@ -527,11 +466,10 @@ func TestOpenShort_BaseCurrency_Collateral(t *testing.T) { // Create a margin position open msg msg2 := types.NewMsgOpen( addr[0].String(), - ptypes.BaseCurrency, - sdk.NewInt(100000000), - ptypes.ATOM, types.Position_SHORT, - sdk.NewDec(5), + sdk.NewDec(2), + ptypes.ATOM, + sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(100000000)), sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), ) @@ -632,11 +570,10 @@ func TestOpenShort_ATOM_Collateral(t *testing.T) { // Create a margin position open msg msg2 := types.NewMsgOpen( addr[0].String(), - ptypes.ATOM, - sdk.NewInt(10000000), - ptypes.ATOM, types.Position_SHORT, sdk.NewDec(5), + ptypes.ATOM, + sdk.NewCoin(ptypes.ATOM, sdk.NewInt(10000000)), sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), ) diff --git a/x/margin/keeper/open_test.go b/x/margin/keeper/open_test.go index aa7a60455..65bde79ed 100644 --- a/x/margin/keeper/open_test.go +++ b/x/margin/keeper/open_test.go @@ -26,9 +26,9 @@ func TestOpen_ErrorCheckUserAuthorization(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - CollateralAsset: ptypes.BaseCurrency, - BorrowAsset: "uatom", - Position: types.Position_LONG, + Position: types.Position_LONG, + TradingAsset: "uatom", + Collateral: sdk.NewCoin(ptypes.BaseCurrency, sdk.OneInt()), } ) @@ -54,11 +54,10 @@ func TestOpen_ErrorCheckMaxOpenPositions(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - Creator: "creator", - CollateralAsset: ptypes.BaseCurrency, - BorrowAsset: "uatom", - Position: types.Position_LONG, - Leverage: sdk.NewDec(10), + Position: types.Position_LONG, + Leverage: sdk.NewDec(10), + TradingAsset: "uatom", + Collateral: sdk.NewCoin(ptypes.BaseCurrency, sdk.OneInt()), } ) @@ -86,11 +85,11 @@ func TestOpen_ErrorPreparePools(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - Creator: "creator", - CollateralAsset: ptypes.BaseCurrency, - BorrowAsset: "uatom", - Position: types.Position_LONG, - Leverage: sdk.NewDec(10), + Creator: "creator", + Position: types.Position_LONG, + Leverage: sdk.NewDec(10), + TradingAsset: "uatom", + Collateral: sdk.NewCoin(ptypes.BaseCurrency, sdk.OneInt()), } ) @@ -99,7 +98,7 @@ func TestOpen_ErrorPreparePools(t *testing.T) { mockChecker.On("CheckUserAuthorization", ctx, msg).Return(nil) mockChecker.On("CheckSameAssetPosition", ctx, msg).Return(nil) mockChecker.On("CheckMaxOpenPositions", ctx).Return(nil) - mockChecker.On("PreparePools", ctx, msg.BorrowAsset).Return(uint64(0), ammtypes.Pool{}, types.Pool{}, errors.New("error executing prepare pools")) + mockChecker.On("PreparePools", ctx, msg.Collateral.Denom, msg.TradingAsset).Return(uint64(0), ammtypes.Pool{}, types.Pool{}, errors.New("error executing prepare pools")) _, err := k.Open(ctx, msg) @@ -119,9 +118,9 @@ func TestOpen_ErrorCheckPoolHealth(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - CollateralAsset: ptypes.BaseCurrency, - BorrowAsset: "uatom", - Position: types.Position_LONG, + Position: types.Position_LONG, + TradingAsset: "uatom", + Collateral: sdk.NewCoin(ptypes.BaseCurrency, sdk.OneInt()), } poolId = uint64(1) ) @@ -131,7 +130,7 @@ func TestOpen_ErrorCheckPoolHealth(t *testing.T) { mockChecker.On("CheckUserAuthorization", ctx, msg).Return(nil) mockChecker.On("CheckSameAssetPosition", ctx, msg).Return(nil) mockChecker.On("CheckMaxOpenPositions", ctx).Return(nil) - mockChecker.On("PreparePools", ctx, msg.BorrowAsset).Return(poolId, ammtypes.Pool{}, types.Pool{}, nil) + mockChecker.On("PreparePools", ctx, msg.Collateral.Denom, msg.TradingAsset).Return(poolId, ammtypes.Pool{}, types.Pool{}, nil) mockChecker.On("CheckPoolHealth", ctx, poolId).Return(sdkerrors.Wrap(types.ErrInvalidBorrowingAsset, "invalid collateral asset")) _, err := k.Open(ctx, msg) @@ -152,8 +151,8 @@ func TestOpen_ErrorInvalidPosition(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - CollateralAsset: ptypes.BaseCurrency, - BorrowAsset: "uatom", + TradingAsset: "uatom", + Collateral: sdk.NewCoin(ptypes.BaseCurrency, sdk.OneInt()), } ) @@ -178,9 +177,9 @@ func TestOpen_ErrorOpenLong(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - CollateralAsset: ptypes.BaseCurrency, - BorrowAsset: "uatom", - Position: types.Position_LONG, + Position: types.Position_LONG, + TradingAsset: "uatom", + Collateral: sdk.NewCoin(ptypes.BaseCurrency, sdk.OneInt()), } poolId = uint64(1) ) @@ -190,7 +189,7 @@ func TestOpen_ErrorOpenLong(t *testing.T) { mockChecker.On("CheckUserAuthorization", ctx, msg).Return(nil) mockChecker.On("CheckSameAssetPosition", ctx, msg).Return(nil) mockChecker.On("CheckMaxOpenPositions", ctx).Return(nil) - mockChecker.On("PreparePools", ctx, msg.BorrowAsset).Return(poolId, ammtypes.Pool{}, types.Pool{}, nil) + mockChecker.On("PreparePools", ctx, msg.Collateral.Denom, msg.TradingAsset).Return(poolId, ammtypes.Pool{}, types.Pool{}, nil) mockChecker.On("CheckPoolHealth", ctx, poolId).Return(nil) mockChecker.On("OpenLong", ctx, poolId, msg, ptypes.BaseCurrency).Return(&types.MTP{}, errors.New("error executing open long")) @@ -212,9 +211,9 @@ func TestOpen_ErrorOpenShort(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - CollateralAsset: ptypes.BaseCurrency, - BorrowAsset: "uatom", - Position: types.Position_SHORT, + Position: types.Position_SHORT, + TradingAsset: "uatom", + Collateral: sdk.NewCoin(ptypes.BaseCurrency, sdk.OneInt()), } poolId = uint64(1) ) @@ -224,7 +223,7 @@ func TestOpen_ErrorOpenShort(t *testing.T) { mockChecker.On("CheckUserAuthorization", ctx, msg).Return(nil) mockChecker.On("CheckSameAssetPosition", ctx, msg).Return(nil) mockChecker.On("CheckMaxOpenPositions", ctx).Return(nil) - mockChecker.On("PreparePools", ctx, msg.BorrowAsset).Return(poolId, ammtypes.Pool{}, types.Pool{}, nil) + mockChecker.On("PreparePools", ctx, msg.Collateral.Denom, msg.TradingAsset).Return(poolId, ammtypes.Pool{}, types.Pool{}, nil) mockChecker.On("CheckPoolHealth", ctx, poolId).Return(nil) mockChecker.On("OpenShort", ctx, poolId, msg, ptypes.BaseCurrency).Return(&types.MTP{}, errors.New("error executing open short")) @@ -246,9 +245,9 @@ func TestOpen_Successful(t *testing.T) { var ( ctx = sdk.Context{} // Mock or setup a context msg = &types.MsgOpen{ - CollateralAsset: ptypes.BaseCurrency, - BorrowAsset: "uatom", - Position: types.Position_SHORT, + Position: types.Position_SHORT, + TradingAsset: "uatom", + Collateral: sdk.NewCoin(ptypes.BaseCurrency, sdk.OneInt()), } poolId = uint64(1) mtp = &types.MTP{} @@ -259,7 +258,7 @@ func TestOpen_Successful(t *testing.T) { mockChecker.On("CheckUserAuthorization", ctx, msg).Return(nil) mockChecker.On("CheckSameAssetPosition", ctx, msg).Return(nil) mockChecker.On("CheckMaxOpenPositions", ctx).Return(nil) - mockChecker.On("PreparePools", ctx, msg.BorrowAsset).Return(poolId, ammtypes.Pool{}, types.Pool{}, nil) + mockChecker.On("PreparePools", ctx, msg.Collateral.Denom, msg.TradingAsset).Return(poolId, ammtypes.Pool{}, types.Pool{}, nil) mockChecker.On("CheckPoolHealth", ctx, poolId).Return(nil) mockChecker.On("OpenShort", ctx, poolId, msg, ptypes.BaseCurrency).Return(mtp, nil) mockChecker.On("EmitOpenEvent", ctx, mtp).Return() diff --git a/x/margin/keeper/params.go b/x/margin/keeper/params.go index e80964437..ed1302ff8 100644 --- a/x/margin/keeper/params.go +++ b/x/margin/keeper/params.go @@ -167,3 +167,7 @@ func (k Keeper) GetFundingFeeCollectionAddress(ctx sdk.Context) sdk.AccAddress { return addr } + +func (k Keeper) GetSwapFee(ctx sdk.Context) sdk.Dec { + return k.GetParams(ctx).SwapFee +} diff --git a/x/margin/keeper/prepare_pools.go b/x/margin/keeper/prepare_pools.go index a00b6fb91..7e9b0de9a 100644 --- a/x/margin/keeper/prepare_pools.go +++ b/x/margin/keeper/prepare_pools.go @@ -6,8 +6,8 @@ import ( "github.com/elys-network/elys/x/margin/types" ) -func (k Keeper) PreparePools(ctx sdk.Context, tradingAsset string) (poolId uint64, ammPool ammtypes.Pool, pool types.Pool, err error) { - poolId, err = k.GetFirstValidPool(ctx, tradingAsset) +func (k Keeper) PreparePools(ctx sdk.Context, collateralAsset, tradingAsset string) (poolId uint64, ammPool ammtypes.Pool, pool types.Pool, err error) { + poolId, err = k.GetFirstValidPool(ctx, collateralAsset, tradingAsset) if err != nil { return } diff --git a/x/margin/keeper/query_open_estimation.go b/x/margin/keeper/query_open_estimation.go new file mode 100644 index 000000000..3b90fbc6d --- /dev/null +++ b/x/margin/keeper/query_open_estimation.go @@ -0,0 +1,73 @@ +package keeper + +import ( + "context" + + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + assetprofiletypes "github.com/elys-network/elys/x/assetprofile/types" + "github.com/elys-network/elys/x/margin/types" + ptypes "github.com/elys-network/elys/x/parameter/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func (k Keeper) OpenEstimation(goCtx context.Context, req *types.QueryOpenEstimationRequest) (*types.QueryOpenEstimationResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "invalid request") + } + + ctx := sdk.UnwrapSDKContext(goCtx) + + // calculate min collateral + minCollateral, err := k.CalcMinCollateral(ctx, req.Leverage) + if err != nil { + return nil, sdkerrors.Wrapf(types.ErrCalcMinCollateral, "error calculating min collateral: %s", err.Error()) + } + + // get swap fee param + swapFee := k.GetSwapFee(ctx) + + entry, found := k.apKeeper.GetEntry(ctx, ptypes.BaseCurrency) + if !found { + return nil, sdkerrors.Wrapf(assetprofiletypes.ErrAssetProfileNotFound, "asset %s not found", ptypes.BaseCurrency) + } + baseCurrency := entry.Denom + + leveragedAmount := sdk.NewDecFromBigInt(req.Collateral.Amount.BigInt()).Mul(req.Leverage).TruncateInt() + leveragedCoin := sdk.NewCoin(req.Collateral.Denom, leveragedAmount) + + _, _, positionSize, openPrice, swapFee, discount, availableLiquidity, err := k.amm.CalcSwapEstimationByDenom(ctx, leveragedCoin, req.Collateral.Denom, req.TradingAsset, baseCurrency, req.Discount, swapFee) + if err != nil { + return nil, err + } + + // calculate estimated pnl + // estimated_pnl = leveraged_amount * (open_price - take_profit_price) + estimatedPnL := sdk.NewDecFromBigInt(leveragedAmount.BigInt()).Mul(req.TakeProfitPrice.Sub(openPrice)).TruncateInt() + + if leveragedAmount.IsZero() { + return nil, sdkerrors.Wrapf(types.ErrAmountTooLow, "leveraged amount is zero") + } + + // calculate liquidation price + // liquidation_price = -collateral_amount / leveraged_amount_value + open_price_value + liquidationPrice := sdk.NewDecFromBigInt(req.Collateral.Amount.Neg().BigInt()).Quo(sdk.NewDecFromBigInt(leveragedAmount.BigInt())).Add(openPrice) + + return &types.QueryOpenEstimationResponse{ + Position: req.Position, + Leverage: req.Leverage, + TradingAsset: req.TradingAsset, + Collateral: req.Collateral, + MinCollateral: sdk.NewCoin(req.Collateral.Denom, minCollateral), + ValidCollateral: req.Collateral.Amount.GTE(minCollateral), + PositionSize: positionSize, + SwapFee: swapFee, + Discount: discount, + OpenPrice: openPrice, + TakeProfitPrice: req.TakeProfitPrice, + LiquidationPrice: liquidationPrice, + EstimatedPnl: estimatedPnL, + AvailableLiquidity: availableLiquidity, + }, nil +} diff --git a/x/margin/keeper/query_open_estimation_test.go b/x/margin/keeper/query_open_estimation_test.go new file mode 100644 index 000000000..273d080c8 --- /dev/null +++ b/x/margin/keeper/query_open_estimation_test.go @@ -0,0 +1,107 @@ +package keeper_test + +import ( + "fmt" + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + ammtypes "github.com/elys-network/elys/x/amm/types" + "github.com/elys-network/elys/x/margin/types" + + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + simapp "github.com/elys-network/elys/app" + ptypes "github.com/elys-network/elys/x/parameter/types" + "github.com/stretchr/testify/require" +) + +func TestOpenEstimation_Long5XAtom100Usdc(t *testing.T) { + app := simapp.InitElysTestApp(true) + ctx := app.BaseApp.NewContext(true, tmproto.Header{}) + + mk, amm, oracle := app.MarginKeeper, app.AmmKeeper, app.OracleKeeper + + // Setup coin prices + SetupStableCoinPrices(ctx, oracle) + + // Generate 1 random account with 1000stake balanced + addr := simapp.AddTestAddrs(app, ctx, 1, sdk.NewInt(1000000000000)) + + // Create a pool + // Mint 100000USDC + usdcToken := []sdk.Coin{sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(1000000000000))} + // Mint 100000ATOM + atomToken := []sdk.Coin{sdk.NewCoin(ptypes.ATOM, sdk.NewInt(1000000000000))} + + err := app.BankKeeper.MintCoins(ctx, ammtypes.ModuleName, usdcToken) + require.NoError(t, err) + err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, ammtypes.ModuleName, addr[0], usdcToken) + require.NoError(t, err) + + err = app.BankKeeper.MintCoins(ctx, ammtypes.ModuleName, atomToken) + require.NoError(t, err) + err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, ammtypes.ModuleName, addr[0], atomToken) + require.NoError(t, err) + + poolAssets := []ammtypes.PoolAsset{ + { + Weight: sdk.NewInt(50), + Token: sdk.NewCoin(ptypes.ATOM, sdk.NewInt(100000000000)), + }, + { + Weight: sdk.NewInt(50), + Token: sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(100000000000)), + }, + } + + argSwapFee := sdk.MustNewDecFromStr("0.0") + argExitFee := sdk.MustNewDecFromStr("0.0") + + poolParams := &ammtypes.PoolParams{ + SwapFee: argSwapFee, + ExitFee: argExitFee, + } + + msg := ammtypes.NewMsgCreatePool( + addr[0].String(), + poolParams, + poolAssets, + ) + + // Create a ATOM+USDC pool + poolId, err := amm.CreatePool(ctx, msg) + require.NoError(t, err) + require.Equal(t, poolId, uint64(1)) + + pools := amm.GetAllPool(ctx) + + // check length of pools + require.Equal(t, len(pools), 1) + + // call min collateral query + res, err := mk.OpenEstimation(ctx, &types.QueryOpenEstimationRequest{ + Position: types.Position_LONG, + Leverage: sdk.MustNewDecFromStr("5.0"), + TradingAsset: ptypes.ATOM, + Collateral: sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(100000000)), + Discount: sdk.MustNewDecFromStr("0.0"), + TakeProfitPrice: sdk.MustNewDecFromStr("2.0"), + }) + require.NoError(t, err) + fmt.Println(res) + require.Equal(t, &types.QueryOpenEstimationResponse{ + Position: types.Position_LONG, + Leverage: sdk.MustNewDecFromStr("5.0"), + TradingAsset: ptypes.ATOM, + Collateral: sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(100000000)), + MinCollateral: sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(8333333)), + ValidCollateral: true, + PositionSize: sdk.NewCoin(ptypes.ATOM, sdk.NewInt(497017398)), + SwapFee: sdk.MustNewDecFromStr("0.001000000000000000"), + Discount: sdk.MustNewDecFromStr("0.000000000000000000"), + OpenPrice: sdk.MustNewDecFromStr("0.994034796000000000"), + TakeProfitPrice: sdk.MustNewDecFromStr("2.000000000000000000"), + LiquidationPrice: sdk.MustNewDecFromStr("0.794034796000000000"), + EstimatedPnl: sdk.NewInt(502982602), + AvailableLiquidity: sdk.NewCoin(ptypes.ATOM, sdk.NewInt(100000000000)), + }, res) +} diff --git a/x/margin/keeper/repay.go b/x/margin/keeper/repay.go index 86ecaaf46..1fbf3fb17 100644 --- a/x/margin/keeper/repay.go +++ b/x/margin/keeper/repay.go @@ -2,35 +2,34 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ammtypes "github.com/elys-network/elys/x/amm/types" - assetprofiletypes "github.com/elys-network/elys/x/assetprofile/types" "github.com/elys-network/elys/x/margin/types" - ptypes "github.com/elys-network/elys/x/parameter/types" ) -func (k Keeper) Repay(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool ammtypes.Pool, repayAmount sdk.Int, takeFundPayment bool, collateralAsset string) error { - collateralIndex, _ := types.GetMTPAssetIndex(mtp, collateralAsset, "") +func (k Keeper) Repay(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool ammtypes.Pool, repayAmount sdk.Int, takeFundPayment bool, amount sdk.Int, baseCurrency string) error { // nolint:staticcheck,ineffassign returnAmount := sdk.ZeroInt() Liabilities := mtp.Liabilities - BorrowInterestUnpaidCollateral := mtp.BorrowInterestUnpaidCollaterals[collateralIndex] + BorrowInterestUnpaid := mtp.BorrowInterestUnpaidCollateral - entry, found := k.apKeeper.GetEntry(ctx, ptypes.BaseCurrency) - if !found { - return sdkerrors.Wrapf(assetprofiletypes.ErrAssetProfileNotFound, "asset %s not found", ptypes.BaseCurrency) - } - baseCurrency := entry.Denom + if mtp.Position == types.Position_SHORT { + // swap to trading asset + unpaidCollateralIn := sdk.NewCoin(mtp.CollateralAsset, mtp.BorrowInterestUnpaidCollateral) + C, err := k.EstimateSwapGivenOut(ctx, unpaidCollateralIn, mtp.TradingAsset, ammPool) + if err != nil { + return err + } - if collateralAsset != baseCurrency { + BorrowInterestUnpaid = C + } else if mtp.CollateralAsset != baseCurrency { // swap to base currency - unpaidCollateralIn := sdk.NewCoin(mtp.Collaterals[collateralIndex].Denom, mtp.BorrowInterestUnpaidCollaterals[collateralIndex].Amount) + unpaidCollateralIn := sdk.NewCoin(mtp.CollateralAsset, mtp.BorrowInterestUnpaidCollateral) C, err := k.EstimateSwapGivenOut(ctx, unpaidCollateralIn, baseCurrency, ammPool) if err != nil { return err } - BorrowInterestUnpaidCollateral.Amount = C + BorrowInterestUnpaid = C } var err error @@ -39,29 +38,40 @@ func (k Keeper) Repay(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool return err } + // if long both repay amount and liablities are collateral asset + // if short both repay amount and liablities are trading asset + have := repayAmount - owe := Liabilities.Add(BorrowInterestUnpaidCollateral.Amount) + owe := Liabilities.Add(BorrowInterestUnpaid) if have.LT(Liabilities) { - //can't afford principle liability + // can't afford principle liability returnAmount = sdk.ZeroInt() } else if have.LT(owe) { // v principle liability; x excess liability returnAmount = sdk.ZeroInt() } else { // can afford both - returnAmount = have.Sub(Liabilities).Sub(BorrowInterestUnpaidCollateral.Amount) + returnAmount = have.Sub(Liabilities).Sub(BorrowInterestUnpaid) } - if !returnAmount.IsZero() { + if returnAmount.IsPositive() { actualReturnAmount := returnAmount if takeFundPayment { takePercentage := k.GetForceCloseFundPercentage(ctx) fundAddr := k.GetForceCloseFundAddress(ctx) - takeAmount, err := k.TakeFundPayment(ctx, returnAmount, baseCurrency, takePercentage, fundAddr, &ammPool) - if err != nil { - return err + takeAmount := sdk.ZeroInt() + if mtp.Position == types.Position_LONG { + takeAmount, err = k.TakeFundPayment(ctx, returnAmount, baseCurrency, takePercentage, fundAddr, &ammPool) + if err != nil { + return err + } + } else if mtp.Position == types.Position_SHORT { + takeAmount, err = k.TakeFundPayment(ctx, returnAmount, mtp.TradingAsset, takePercentage, fundAddr, &ammPool) + if err != nil { + return err + } } actualReturnAmount = returnAmount.Sub(takeAmount) if !takeAmount.IsZero() { @@ -69,12 +79,21 @@ func (k Keeper) Repay(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool } } - // actualReturnAmount is so far in base currency, now should convert it to collateralAsset in order to return - if !actualReturnAmount.IsZero() { - if collateralAsset != baseCurrency { - // swap to base currency + // actualReturnAmount is so far in base currency if long or trading asset if short, now should convert it to collateralAsset in order to return + if actualReturnAmount.IsPositive() { + if mtp.Position == types.Position_SHORT { + // swap to collateral asset + amtTokenIn := sdk.NewCoin(mtp.TradingAsset, actualReturnAmount) + C, err := k.EstimateSwapGivenOut(ctx, amtTokenIn, mtp.CollateralAsset, ammPool) + if err != nil { + return err + } + + actualReturnAmount = C + } else if mtp.CollateralAsset != baseCurrency { + // swap to collateral asset amtTokenIn := sdk.NewCoin(baseCurrency, actualReturnAmount) - C, err := k.EstimateSwapGivenOut(ctx, amtTokenIn, collateralAsset, ammPool) + C, err := k.EstimateSwapGivenOut(ctx, amtTokenIn, mtp.CollateralAsset, ammPool) if err != nil { return err } @@ -82,9 +101,8 @@ func (k Keeper) Repay(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool actualReturnAmount = C } - var coins sdk.Coins - returnCoin := sdk.NewCoin(collateralAsset, sdk.NewIntFromBigInt(actualReturnAmount.BigInt())) - returnCoins := coins.Add(returnCoin) + returnCoin := sdk.NewCoin(mtp.CollateralAsset, sdk.NewIntFromBigInt(actualReturnAmount.BigInt())) + returnCoins := sdk.NewCoins(returnCoin) addr, err := sdk.AccAddressFromBech32(mtp.Address) if err != nil { return err @@ -104,10 +122,19 @@ func (k Keeper) Repay(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool // before updating collateral asset balance, we should convert returnAmount to collateralAsset // because so far returnAmount is in base currency. - if collateralAsset != baseCurrency { - // swap to base currency + if mtp.Position == types.Position_SHORT { + // swap to collateral asset + amtTokenIn := sdk.NewCoin(mtp.TradingAsset, returnAmount) + C, err := k.EstimateSwapGivenOut(ctx, amtTokenIn, mtp.CollateralAsset, ammPool) + if err != nil { + return err + } + + returnAmount = C + } else if mtp.CollateralAsset != baseCurrency { + // swap to collateral asset amtTokenIn := sdk.NewCoin(baseCurrency, returnAmount) - C, err := k.EstimateSwapGivenOut(ctx, amtTokenIn, collateralAsset, ammPool) + C, err := k.EstimateSwapGivenOut(ctx, amtTokenIn, mtp.CollateralAsset, ammPool) if err != nil { return err } @@ -115,30 +142,35 @@ func (k Keeper) Repay(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool returnAmount = C } - err = pool.UpdateBalance(ctx, mtp.Collaterals[collateralIndex].Denom, returnAmount, false, mtp.Position) + err = pool.UpdateBalance(ctx, mtp.CollateralAsset, returnAmount, false, mtp.Position) if err != nil { return err } // long position - err = pool.UpdateLiabilities(ctx, baseCurrency, mtp.Liabilities, false, mtp.Position) + err = pool.UpdateLiabilities(ctx, mtp.LiabilitiesAsset, mtp.Liabilities, false, mtp.Position) if err != nil { return err } - err = pool.UpdateTakeProfitLiabilities(ctx, baseCurrency, mtp.TakeProfitLiabilities, false, mtp.Position) + err = pool.UpdateTakeProfitLiabilities(ctx, mtp.LiabilitiesAsset, mtp.TakeProfitLiabilities, false, mtp.Position) if err != nil { return err } - err = pool.UpdateTakeProfitCustody(ctx, baseCurrency, mtp.TakeProfitCustodies[collateralIndex].Amount, false, mtp.Position) + err = pool.UpdateTakeProfitCustody(ctx, mtp.CustodyAsset, mtp.TakeProfitCustody, false, mtp.Position) if err != nil { return err } - err = k.DestroyMTP(ctx, mtp.Address, mtp.Id) - if err != nil { - return err + mtp.Custody = mtp.Custody.Sub(amount) + if mtp.Custody.IsZero() { + err = k.DestroyMTP(ctx, mtp.Address, mtp.Id) + if err != nil { + return err + } + } else { + k.SetMTP(ctx, mtp) } k.SetPool(ctx, *pool) diff --git a/x/margin/keeper/take_out_custody.go b/x/margin/keeper/take_out_custody.go index 29da42f97..d0ed2b35b 100644 --- a/x/margin/keeper/take_out_custody.go +++ b/x/margin/keeper/take_out_custody.go @@ -5,14 +5,13 @@ import ( "github.com/elys-network/elys/x/margin/types" ) -func (k Keeper) TakeOutCustody(ctx sdk.Context, mtp types.MTP, pool *types.Pool, custodyAsset string) error { - _, custodyIndex := types.GetMTPAssetIndex(&mtp, "", custodyAsset) - err := pool.UpdateBalance(ctx, mtp.Custodies[custodyIndex].Denom, mtp.Custodies[custodyIndex].Amount, true, mtp.Position) +func (k Keeper) TakeOutCustody(ctx sdk.Context, mtp types.MTP, pool *types.Pool, amount sdk.Int) error { + err := pool.UpdateBalance(ctx, mtp.CustodyAsset, amount, true, mtp.Position) if err != nil { return err } - err = pool.UpdateCustody(ctx, mtp.Custodies[custodyIndex].Denom, mtp.Custodies[custodyIndex].Amount, false, mtp.Position) + err = pool.UpdateCustody(ctx, mtp.CustodyAsset, amount, false, mtp.Position) if err != nil { return err } diff --git a/x/margin/keeper/update_mtp_health.go b/x/margin/keeper/update_mtp_health.go index f7e5958cb..c9e70e0ef 100644 --- a/x/margin/keeper/update_mtp_health.go +++ b/x/margin/keeper/update_mtp_health.go @@ -13,33 +13,46 @@ func (k Keeper) UpdateMTPHealth(ctx sdk.Context, mtp types.MTP, ammPool ammtypes return sdk.ZeroDec(), nil } + // if short position, convert liabilities to base currency + if mtp.Position == types.Position_SHORT { + liabilities := sdk.NewCoin(mtp.LiabilitiesAsset, xl) + var err error + xl, err = k.EstimateSwapGivenOut(ctx, liabilities, baseCurrency, ammPool) + if err != nil { + return sdk.ZeroDec(), err + } + + if xl.IsZero() { + return sdk.ZeroDec(), nil + } + } + // include unpaid borrow interest in debt (from disabled incremental pay) - for i := range mtp.Collaterals { - if mtp.BorrowInterestUnpaidCollaterals[i].Amount.GT(sdk.ZeroInt()) { - unpaidCollaterals := sdk.NewCoin(mtp.Collaterals[i].Denom, mtp.BorrowInterestUnpaidCollaterals[i].Amount) - - if mtp.Collaterals[i].Denom == baseCurrency { - xl = xl.Add(mtp.BorrowInterestUnpaidCollaterals[i].Amount) - } else { - C, err := k.EstimateSwapGivenOut(ctx, unpaidCollaterals, baseCurrency, ammPool) - if err != nil { - return sdk.ZeroDec(), err - } - - xl = xl.Add(C) + if mtp.BorrowInterestUnpaidCollateral.IsPositive() { + unpaidCollateral := sdk.NewCoin(mtp.CollateralAsset, mtp.BorrowInterestUnpaidCollateral) + + if mtp.CollateralAsset == baseCurrency { + xl = xl.Add(mtp.BorrowInterestUnpaidCollateral) + } else { + C, err := k.EstimateSwapGivenOut(ctx, unpaidCollateral, baseCurrency, ammPool) + if err != nil { + return sdk.ZeroDec(), err } + + xl = xl.Add(C) } } - custodyAmtInBaseCurrency := sdk.ZeroInt() - for i := range mtp.Custodies { - custodyTokenIn := sdk.NewCoin(mtp.Custodies[i].Denom, mtp.Custodies[i].Amount) - // All liabilty is in base currency - C, err := k.EstimateSwapGivenOut(ctx, custodyTokenIn, baseCurrency, ammPool) + // if short position, custody asset is already in base currency + custodyAmtInBaseCurrency := mtp.Custody + + if mtp.Position == types.Position_LONG { + custodyAmt := sdk.NewCoin(mtp.CustodyAsset, mtp.Custody) + var err error + custodyAmtInBaseCurrency, err = k.EstimateSwapGivenOut(ctx, custodyAmt, baseCurrency, ammPool) if err != nil { return sdk.ZeroDec(), err } - custodyAmtInBaseCurrency = custodyAmtInBaseCurrency.Add(C) } lr := sdk.NewDecFromBigInt(custodyAmtInBaseCurrency.BigInt()).Quo(sdk.NewDecFromBigInt(xl.BigInt())) diff --git a/x/margin/migrations/v4_migration.go b/x/margin/migrations/v4_migration.go new file mode 100644 index 000000000..22b9f43ec --- /dev/null +++ b/x/margin/migrations/v4_migration.go @@ -0,0 +1,24 @@ +package migrations + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/elys-network/elys/x/margin/types" +) + +func (m Migrator) V4Migration(ctx sdk.Context) error { + // reset params + params := types.NewParams() + m.keeper.SetParams(ctx, ¶ms) + + // reset mtps + for _, mtp := range m.keeper.GetAllMTPs(ctx) { + m.keeper.DestroyMTP(ctx, mtp.Address, mtp.Id) + } + + // reset pools + for _, pool := range m.keeper.GetAllPools(ctx) { + m.keeper.RemovePool(ctx, pool.AmmPoolId) + } + + return nil +} diff --git a/x/margin/module.go b/x/margin/module.go index 0b7234d28..322bb9976 100644 --- a/x/margin/module.go +++ b/x/margin/module.go @@ -117,7 +117,7 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) types.RegisterQueryServer(cfg.QueryServer(), am.keeper) m := migrations.NewMigrator(am.keeper) - err := cfg.RegisterMigration(types.ModuleName, 2, m.V3Migration) + err := cfg.RegisterMigration(types.ModuleName, 3, m.V4Migration) if err != nil { panic(err) } @@ -144,7 +144,7 @@ func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.Raw } // ConsensusVersion is a sequence number for state-breaking change of the module. It should be incremented on each consensus-breaking change introduced by the module. To avoid wrong/empty versions, the initial version should be set to 1 -func (AppModule) ConsensusVersion() uint64 { return 3 } +func (AppModule) ConsensusVersion() uint64 { return 4 } // BeginBlock contains the logic that is automatically triggered at the beginning of each block func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { diff --git a/x/margin/types/calc_mtp_take_profit_custodies.go b/x/margin/types/calc_mtp_take_profit_custodies.go deleted file mode 100644 index 22ba193a0..000000000 --- a/x/margin/types/calc_mtp_take_profit_custodies.go +++ /dev/null @@ -1,17 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func CalcMTPTakeProfitCustodies(mtp *MTP) sdk.Coins { - takeProfitCustodies := mtp.TakeProfitCustodies - for custodyIndex, custody := range mtp.Custodies { - if IsTakeProfitPriceInifite(mtp) || mtp.TakeProfitPrice.IsZero() { - takeProfitCustodies[custodyIndex].Amount = custody.Amount - continue - } - takeProfitCustodies[custodyIndex].Amount = sdk.NewDecFromInt(mtp.Liabilities).Quo(mtp.TakeProfitPrice).TruncateInt() - } - return takeProfitCustodies -} diff --git a/x/margin/types/calc_mtp_take_profit_custody.go b/x/margin/types/calc_mtp_take_profit_custody.go new file mode 100644 index 000000000..b3ef46bd1 --- /dev/null +++ b/x/margin/types/calc_mtp_take_profit_custody.go @@ -0,0 +1,12 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func CalcMTPTakeProfitCustody(mtp *MTP) sdk.Int { + if IsTakeProfitPriceInifite(mtp) || mtp.TakeProfitPrice.IsZero() { + return mtp.Custody + } + return sdk.NewDecFromInt(mtp.Liabilities).Quo(mtp.TakeProfitPrice).TruncateInt() +} diff --git a/x/margin/types/calc_take_amount.go b/x/margin/types/calc_take_amount.go index 7026dca0c..965779a01 100644 --- a/x/margin/types/calc_take_amount.go +++ b/x/margin/types/calc_take_amount.go @@ -5,14 +5,11 @@ import ( ) // CalcTakeAmount calculates the take amount in the custody asset based on the funding rate -func CalcTakeAmount(custodyAmount sdk.Coin, custodyAsset string, fundingRate sdk.Dec) sdk.Coin { +func CalcTakeAmount(custodyAmount sdk.Int, custodyAsset string, fundingRate sdk.Dec) sdk.Int { absoluteFundingRate := fundingRate.Abs() // Calculate the take amount - takeAmountValue := sdk.NewDecFromInt(custodyAmount.Amount).Mul(absoluteFundingRate).TruncateInt() + takeAmountValue := sdk.NewDecFromInt(custodyAmount).Mul(absoluteFundingRate).TruncateInt() - // Create the take amount coin - takeAmount := sdk.NewCoin(custodyAsset, takeAmountValue) - - return takeAmount + return takeAmountValue } diff --git a/x/margin/types/errors.go b/x/margin/types/errors.go index 366c2cc49..71ec5dcdf 100644 --- a/x/margin/types/errors.go +++ b/x/margin/types/errors.go @@ -26,4 +26,8 @@ var ( ErrBalanceNotAvailable = sdkerrors.Register(ModuleName, 18, "user does not have enough balance of the required coin") ErrAmountTooLow = sdkerrors.Register(ModuleName, 32, "Tx amount is too low") ErrMarginDisabled = sdkerrors.Register(ModuleName, 33, "margin disabled pool") + ErrDenomNotFound = sdkerrors.Register(ModuleName, 34, "denom not found") + ErrInvalidLeverage = sdkerrors.Register(ModuleName, 35, "invalid leverage") + ErrInvalidCloseSize = sdkerrors.Register(ModuleName, 36, "invalid close size") + ErrCalcMinCollateral = sdkerrors.Register(ModuleName, 37, "error calculating min collateral") ) diff --git a/x/margin/types/expected_keepers.go b/x/margin/types/expected_keepers.go index 70c9ae994..38d433118 100644 --- a/x/margin/types/expected_keepers.go +++ b/x/margin/types/expected_keepers.go @@ -32,7 +32,7 @@ type PoolChecker interface { type OpenChecker interface { CheckUserAuthorization(ctx sdk.Context, msg *MsgOpen) error CheckMaxOpenPositions(ctx sdk.Context) error - PreparePools(ctx sdk.Context, tradingAsset string) (poolId uint64, ammPool ammtypes.Pool, pool Pool, err error) + PreparePools(ctx sdk.Context, collateralAsset, tradingAsset string) (poolId uint64, ammPool ammtypes.Pool, pool Pool, err error) CheckPoolHealth(ctx sdk.Context, poolId uint64) error OpenLong(ctx sdk.Context, poolId uint64, msg *MsgOpen, baseCurrency string) (*MTP, error) OpenShort(ctx sdk.Context, poolId uint64, msg *MsgOpen, baseCurrency string) (*MTP, error) @@ -49,10 +49,10 @@ type OpenLongChecker interface { GetPool(ctx sdk.Context, poolId uint64) (Pool, bool) IsPoolEnabled(ctx sdk.Context, poolId uint64) bool GetAmmPool(ctx sdk.Context, poolId uint64, tradingAsset string) (ammtypes.Pool, error) - CheckMinLiabilities(ctx sdk.Context, collateralTokenAmt sdk.Coin, eta sdk.Dec, pool Pool, ammPool ammtypes.Pool, borrowAsset string) error + CheckMinLiabilities(ctx sdk.Context, collateralTokenAmt sdk.Coin, eta sdk.Dec, ammPool ammtypes.Pool, borrowAsset string, baseCurrency string) error EstimateSwap(ctx sdk.Context, leveragedAmtTokenIn sdk.Coin, borrowAsset string, ammPool ammtypes.Pool) (sdk.Int, error) EstimateSwapGivenOut(ctx sdk.Context, tokenOutAmount sdk.Coin, tokenInDenom string, ammPool ammtypes.Pool) (sdk.Int, error) - Borrow(ctx sdk.Context, collateralAsset string, custodyAsset string, collateralAmount sdk.Int, custodyAmount sdk.Int, mtp *MTP, ammPool *ammtypes.Pool, pool *Pool, eta sdk.Dec, baseCurrency string) error + Borrow(ctx sdk.Context, collateralAmount sdk.Int, custodyAmount sdk.Int, mtp *MTP, ammPool *ammtypes.Pool, pool *Pool, eta sdk.Dec, baseCurrency string) error UpdatePoolHealth(ctx sdk.Context, pool *Pool) error TakeInCustody(ctx sdk.Context, mtp MTP, pool *Pool) error UpdateMTPHealth(ctx sdk.Context, mtp MTP, ammPool ammtypes.Pool, baseCurrency string) (sdk.Dec, error) @@ -69,10 +69,10 @@ type OpenShortChecker interface { GetPool(ctx sdk.Context, poolId uint64) (Pool, bool) IsPoolEnabled(ctx sdk.Context, poolId uint64) bool GetAmmPool(ctx sdk.Context, poolId uint64, tradingAsset string) (ammtypes.Pool, error) - CheckMinLiabilities(ctx sdk.Context, collateralTokenAmt sdk.Coin, eta sdk.Dec, pool Pool, ammPool ammtypes.Pool, borrowAsset string) error + CheckMinLiabilities(ctx sdk.Context, collateralTokenAmt sdk.Coin, eta sdk.Dec, ammPool ammtypes.Pool, borrowAsset string, baseCurrency string) error EstimateSwap(ctx sdk.Context, leveragedAmtTokenIn sdk.Coin, borrowAsset string, ammPool ammtypes.Pool) (sdk.Int, error) EstimateSwapGivenOut(ctx sdk.Context, tokenOutAmount sdk.Coin, tokenInDenom string, ammPool ammtypes.Pool) (sdk.Int, error) - Borrow(ctx sdk.Context, collateralAsset string, custodyAsset string, collateralAmount sdk.Int, custodyAmount sdk.Int, mtp *MTP, ammPool *ammtypes.Pool, pool *Pool, eta sdk.Dec, baseCurrency string) error + Borrow(ctx sdk.Context, collateralAmount sdk.Int, custodyAmount sdk.Int, mtp *MTP, ammPool *ammtypes.Pool, pool *Pool, eta sdk.Dec, baseCurrency string) error UpdatePoolHealth(ctx sdk.Context, pool *Pool) error TakeInCustody(ctx sdk.Context, mtp MTP, pool *Pool) error UpdateMTPHealth(ctx sdk.Context, mtp MTP, ammPool ammtypes.Pool, baseCurrency string) (sdk.Dec, error) @@ -92,9 +92,9 @@ type CloseLongChecker interface { ) (val Pool, found bool) GetAmmPool(ctx sdk.Context, poolId uint64, tradingAsset string) (ammtypes.Pool, error) - HandleBorrowInterest(ctx sdk.Context, mtp *MTP, pool *Pool, ammPool ammtypes.Pool, collateralAsset string, custodyAsset string) error - TakeOutCustody(ctx sdk.Context, mtp MTP, pool *Pool, custodyAsset string) error - EstimateAndRepay(ctx sdk.Context, mtp MTP, pool Pool, ammPool ammtypes.Pool, collateralAsset string, custodyAsset string) (sdk.Int, error) + HandleBorrowInterest(ctx sdk.Context, mtp *MTP, pool *Pool, ammPool ammtypes.Pool) error + TakeOutCustody(ctx sdk.Context, mtp MTP, pool *Pool, amount sdk.Int) error + EstimateAndRepay(ctx sdk.Context, mtp MTP, pool Pool, ammPool ammtypes.Pool, amount sdk.Int, baseCurrency string) (sdk.Int, error) } //go:generate mockery --srcpkg . --name CloseShortChecker --structname CloseShortChecker --filename close_short_checker.go --with-expecter @@ -106,9 +106,9 @@ type CloseShortChecker interface { ) (val Pool, found bool) GetAmmPool(ctx sdk.Context, poolId uint64, tradingAsset string) (ammtypes.Pool, error) - HandleBorrowInterest(ctx sdk.Context, mtp *MTP, pool *Pool, ammPool ammtypes.Pool, collateralAsset string, custodyAsset string) error - TakeOutCustody(ctx sdk.Context, mtp MTP, pool *Pool, custodyAsset string) error - EstimateAndRepay(ctx sdk.Context, mtp MTP, pool Pool, ammPool ammtypes.Pool, collateralAsset string, custodyAsset string) (sdk.Int, error) + HandleBorrowInterest(ctx sdk.Context, mtp *MTP, pool *Pool, ammPool ammtypes.Pool) error + TakeOutCustody(ctx sdk.Context, mtp MTP, pool *Pool, amount sdk.Int) error + EstimateAndRepay(ctx sdk.Context, mtp MTP, pool Pool, ammPool ammtypes.Pool, amount sdk.Int, baseCurrency string) (sdk.Int, error) } // AccountKeeper defines the expected account keeper used for simulations (noalias) @@ -125,6 +125,8 @@ type AccountKeeper interface { type AmmKeeper interface { // Get pool Ids that contains the denom in pool assets GetAllPoolIdsWithDenom(sdk.Context, string) []uint64 + // Get first pool id that contains all denoms in pool assets + GetPoolIdWithAllDenoms(ctx sdk.Context, denoms []string) (poolId uint64, found bool) // GetPool returns a pool from its index GetPool(sdk.Context, uint64) (ammtypes.Pool, bool) // Get all pools @@ -135,6 +137,25 @@ type AmmKeeper interface { CalcOutAmtGivenIn(ctx sdk.Context, poolId uint64, oracle ammtypes.OracleKeeper, snapshot *ammtypes.Pool, tokensIn sdk.Coins, tokenOutDenom string, swapFee sdk.Dec) (sdk.Coin, error) CalcInAmtGivenOut(ctx sdk.Context, poolId uint64, oracle ammtypes.OracleKeeper, snapshot *ammtypes.Pool, tokensOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec) (tokenIn sdk.Coin, err error) + + CalcSwapEstimationByDenom( + ctx sdk.Context, + amount sdk.Coin, + denomIn string, + denomOut string, + baseCurrency string, + discount sdk.Dec, + overrideSwapFee sdk.Dec, + ) ( + inRoute []*ammtypes.SwapAmountInRoute, + outRoute []*ammtypes.SwapAmountOutRoute, + outAmount sdk.Coin, + spotPrice sdk.Dec, + swapFee sdk.Dec, + discountOut sdk.Dec, + availableLiquidity sdk.Coin, + err error, + ) } // BankKeeper defines the expected interface needed to retrieve account balances. diff --git a/x/margin/types/generate_open_event.go b/x/margin/types/generate_open_event.go new file mode 100644 index 000000000..f03f607dc --- /dev/null +++ b/x/margin/types/generate_open_event.go @@ -0,0 +1,23 @@ +package types + +import ( + "strconv" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func GenerateOpenEvent(mtp *MTP) sdk.Event { + return sdk.NewEvent(EventOpen, + sdk.NewAttribute("id", strconv.FormatInt(int64(mtp.Id), 10)), + sdk.NewAttribute("position", mtp.Position.String()), + sdk.NewAttribute("address", mtp.Address), + sdk.NewAttribute("collateral", mtp.Collateral.String()), + sdk.NewAttribute("custody", mtp.Custody.String()), + sdk.NewAttribute("leverage", mtp.Leverage.String()), + sdk.NewAttribute("liabilities", mtp.Liabilities.String()), + sdk.NewAttribute("borrow_interest_paid_collateral", mtp.BorrowInterestPaidCollateral.String()), + sdk.NewAttribute("borrow_interest_paid_custody", mtp.BorrowInterestPaidCustody.String()), + sdk.NewAttribute("borrow_interest_unpaid_collateral", mtp.BorrowInterestUnpaidCollateral.String()), + sdk.NewAttribute("health", mtp.MtpHealth.String()), + ) +} diff --git a/x/margin/types/generate_open_event_test.go b/x/margin/types/generate_open_event_test.go new file mode 100644 index 000000000..6e4e0a1be --- /dev/null +++ b/x/margin/types/generate_open_event_test.go @@ -0,0 +1,67 @@ +package types_test + +import ( + "fmt" + "strconv" + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/elys-network/elys/x/margin/types" + "github.com/stretchr/testify/assert" +) + +func TestGenerateOpenEvent(t *testing.T) { + // Mock data for testing + var testMTP = types.MTP{ + Address: "elys1x0jyazg9qzys8x9m2x8q3q3x0jyazg9qzys8x9", + Collateral: sdk.ZeroInt(), + Liabilities: sdk.ZeroInt(), + BorrowInterestPaidCollateral: sdk.ZeroInt(), + BorrowInterestPaidCustody: sdk.ZeroInt(), + BorrowInterestUnpaidCollateral: sdk.ZeroInt(), + Custody: sdk.ZeroInt(), + TakeProfitLiabilities: sdk.ZeroInt(), + TakeProfitCustody: sdk.ZeroInt(), + Leverage: sdk.NewDec(10), + MtpHealth: sdk.ZeroDec(), + Position: types.Position_LONG, + AmmPoolId: 1, + Id: 1, + ConsolidateLeverage: sdk.NewDec(10), + SumCollateral: sdk.ZeroInt(), + TakeProfitPrice: sdk.NewDec(10), + TakeProfitBorrowRate: sdk.OneDec(), + FundingFeePaidCollateral: sdk.ZeroInt(), + FundingFeePaidCustody: sdk.ZeroInt(), + FundingFeeReceivedCollateral: sdk.ZeroInt(), + FundingFeeReceivedCustody: sdk.ZeroInt(), + } + + event := types.GenerateOpenEvent(&testMTP) + + // Assert that the event type is correct + assert.Equal(t, types.EventOpen, event.Type) + + // Assert that all the attributes are correctly set + assert.Equal(t, strconv.FormatInt(int64(testMTP.Id), 10), getAttributeValue(event, "id")) + assert.Equal(t, testMTP.Position.String(), getAttributeValue(event, "position")) + assert.Equal(t, testMTP.Address, getAttributeValue(event, "address")) + assert.Equal(t, testMTP.Collateral.String(), getAttributeValue(event, "collateral")) + assert.Equal(t, testMTP.Custody.String(), getAttributeValue(event, "custody")) + assert.Equal(t, fmt.Sprintf("%s", testMTP.Leverage), getAttributeValue(event, "leverage")) + assert.Equal(t, testMTP.Liabilities.String(), getAttributeValue(event, "liabilities")) + assert.Equal(t, testMTP.BorrowInterestPaidCollateral.String(), getAttributeValue(event, "borrow_interest_paid_collateral")) + assert.Equal(t, testMTP.BorrowInterestPaidCustody.String(), getAttributeValue(event, "borrow_interest_paid_custody")) + assert.Equal(t, testMTP.BorrowInterestUnpaidCollateral.String(), getAttributeValue(event, "borrow_interest_unpaid_collateral")) + assert.Equal(t, testMTP.MtpHealth.String(), getAttributeValue(event, "health")) +} + +// Helper function to get attribute value from an event +func getAttributeValue(event sdk.Event, key string) string { + for _, attr := range event.Attributes { + if attr.Key == key { + return attr.Value + } + } + return "" +} diff --git a/x/margin/types/get_margin_pool_balance.go b/x/margin/types/get_margin_pool_balance.go index 193f0fba4..9c33c1f2b 100644 --- a/x/margin/types/get_margin_pool_balance.go +++ b/x/margin/types/get_margin_pool_balance.go @@ -5,15 +5,8 @@ import ( ) func GetMarginPoolBalancesByPosition(marginPool Pool, denom string, position Position) (sdk.Int, sdk.Int, sdk.Int) { - poolAssets := marginPool.GetPoolAssets(position) - - for _, asset := range *poolAssets { - if asset.AssetDenom == denom { - return asset.AssetBalance, asset.Liabilities, asset.Custody - } - } - - return sdk.ZeroInt(), sdk.ZeroInt(), sdk.ZeroInt() + poolAsset := marginPool.GetPoolAsset(position, denom) + return poolAsset.AssetBalance, poolAsset.Liabilities, poolAsset.Custody } // Get Margin Pool Balance diff --git a/x/margin/types/get_mtp_asset_index.go b/x/margin/types/get_mtp_asset_index.go deleted file mode 100644 index 2c65de212..000000000 --- a/x/margin/types/get_mtp_asset_index.go +++ /dev/null @@ -1,22 +0,0 @@ -package types - -// Get Assets Index -func GetMTPAssetIndex(mtp *MTP, collateralAsset string, borrowAsset string) (int, int) { - collateralIndex := -1 - borrowIndex := -1 - for i, asset := range mtp.Collaterals { - if asset.Denom == collateralAsset { - collateralIndex = i - break - } - } - - for i, asset := range mtp.Custodies { - if asset.Denom == borrowAsset { - borrowIndex = i - break - } - } - - return collateralIndex, borrowIndex -} diff --git a/x/margin/types/get_trading_asset.go b/x/margin/types/get_trading_asset.go deleted file mode 100644 index cbbb74527..000000000 --- a/x/margin/types/get_trading_asset.go +++ /dev/null @@ -1,8 +0,0 @@ -package types - -func GetTradingAsset(collateralAsset string, borrowAsset string, baseCurrency string) string { - if collateralAsset == baseCurrency { - return borrowAsset - } - return collateralAsset -} diff --git a/x/margin/types/get_trading_asset_test.go b/x/margin/types/get_trading_asset_test.go deleted file mode 100644 index ee8db4579..000000000 --- a/x/margin/types/get_trading_asset_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/elys-network/elys/x/margin/types" - ptypes "github.com/elys-network/elys/x/parameter/types" - "github.com/stretchr/testify/assert" -) - -func TestGetTradingAsset_WhenCollateralIsBaseCurrency(t *testing.T) { - // Test case: collateral is base currency and borrow is ATOM - result := types.GetTradingAsset(ptypes.BaseCurrency, ptypes.ATOM, ptypes.BaseCurrency) - assert.Equal(t, ptypes.ATOM, result) - - // Test case: both collateral and borrow are base currency - result = types.GetTradingAsset(ptypes.BaseCurrency, ptypes.BaseCurrency, ptypes.BaseCurrency) - assert.Equal(t, ptypes.BaseCurrency, result) - - // Test case: collateral is base currency and borrow is some other asset (e.g., BTC) - result = types.GetTradingAsset(ptypes.BaseCurrency, "BTC", ptypes.BaseCurrency) - assert.Equal(t, "BTC", result) -} - -func TestGetTradingAsset_WhenCollateralIsNotBaseCurrency(t *testing.T) { - // Test case: collateral is ATOM and borrow is base currency - result := types.GetTradingAsset(ptypes.ATOM, ptypes.BaseCurrency, ptypes.BaseCurrency) - assert.Equal(t, ptypes.ATOM, result) - - // Test case: both collateral and borrow are ATOM - result = types.GetTradingAsset(ptypes.ATOM, ptypes.ATOM, ptypes.BaseCurrency) - assert.Equal(t, ptypes.ATOM, result) - - // Test case: collateral is some other asset (e.g., BTC) and borrow is base currency - result = types.GetTradingAsset("BTC", ptypes.BaseCurrency, ptypes.BaseCurrency) - assert.Equal(t, "BTC", result) -} diff --git a/x/margin/types/mocks/amm_keeper.go b/x/margin/types/mocks/amm_keeper.go index 68d7dc238..de93bb967 100644 --- a/x/margin/types/mocks/amm_keeper.go +++ b/x/margin/types/mocks/amm_keeper.go @@ -141,6 +141,110 @@ func (_c *AmmKeeper_CalcOutAmtGivenIn_Call) RunAndReturn(run func(types.Context, return _c } +// CalcSwapEstimationByDenom provides a mock function with given fields: ctx, amount, denomIn, denomOut, baseCurrency, discount, overrideSwapFee +func (_m *AmmKeeper) CalcSwapEstimationByDenom(ctx types.Context, amount types.Coin, denomIn string, denomOut string, baseCurrency string, discount math.LegacyDec, overrideSwapFee math.LegacyDec) ([]*ammtypes.SwapAmountInRoute, []*ammtypes.SwapAmountOutRoute, types.Coin, math.LegacyDec, math.LegacyDec, math.LegacyDec, types.Coin, error) { + ret := _m.Called(ctx, amount, denomIn, denomOut, baseCurrency, discount, overrideSwapFee) + + var r0 []*ammtypes.SwapAmountInRoute + var r1 []*ammtypes.SwapAmountOutRoute + var r2 types.Coin + var r3 math.LegacyDec + var r4 math.LegacyDec + var r5 math.LegacyDec + var r6 types.Coin + var r7 error + if rf, ok := ret.Get(0).(func(types.Context, types.Coin, string, string, string, math.LegacyDec, math.LegacyDec) ([]*ammtypes.SwapAmountInRoute, []*ammtypes.SwapAmountOutRoute, types.Coin, math.LegacyDec, math.LegacyDec, math.LegacyDec, types.Coin, error)); ok { + return rf(ctx, amount, denomIn, denomOut, baseCurrency, discount, overrideSwapFee) + } + if rf, ok := ret.Get(0).(func(types.Context, types.Coin, string, string, string, math.LegacyDec, math.LegacyDec) []*ammtypes.SwapAmountInRoute); ok { + r0 = rf(ctx, amount, denomIn, denomOut, baseCurrency, discount, overrideSwapFee) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]*ammtypes.SwapAmountInRoute) + } + } + + if rf, ok := ret.Get(1).(func(types.Context, types.Coin, string, string, string, math.LegacyDec, math.LegacyDec) []*ammtypes.SwapAmountOutRoute); ok { + r1 = rf(ctx, amount, denomIn, denomOut, baseCurrency, discount, overrideSwapFee) + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).([]*ammtypes.SwapAmountOutRoute) + } + } + + if rf, ok := ret.Get(2).(func(types.Context, types.Coin, string, string, string, math.LegacyDec, math.LegacyDec) types.Coin); ok { + r2 = rf(ctx, amount, denomIn, denomOut, baseCurrency, discount, overrideSwapFee) + } else { + r2 = ret.Get(2).(types.Coin) + } + + if rf, ok := ret.Get(3).(func(types.Context, types.Coin, string, string, string, math.LegacyDec, math.LegacyDec) math.LegacyDec); ok { + r3 = rf(ctx, amount, denomIn, denomOut, baseCurrency, discount, overrideSwapFee) + } else { + r3 = ret.Get(3).(math.LegacyDec) + } + + if rf, ok := ret.Get(4).(func(types.Context, types.Coin, string, string, string, math.LegacyDec, math.LegacyDec) math.LegacyDec); ok { + r4 = rf(ctx, amount, denomIn, denomOut, baseCurrency, discount, overrideSwapFee) + } else { + r4 = ret.Get(4).(math.LegacyDec) + } + + if rf, ok := ret.Get(5).(func(types.Context, types.Coin, string, string, string, math.LegacyDec, math.LegacyDec) math.LegacyDec); ok { + r5 = rf(ctx, amount, denomIn, denomOut, baseCurrency, discount, overrideSwapFee) + } else { + r5 = ret.Get(5).(math.LegacyDec) + } + + if rf, ok := ret.Get(6).(func(types.Context, types.Coin, string, string, string, math.LegacyDec, math.LegacyDec) types.Coin); ok { + r6 = rf(ctx, amount, denomIn, denomOut, baseCurrency, discount, overrideSwapFee) + } else { + r6 = ret.Get(6).(types.Coin) + } + + if rf, ok := ret.Get(7).(func(types.Context, types.Coin, string, string, string, math.LegacyDec, math.LegacyDec) error); ok { + r7 = rf(ctx, amount, denomIn, denomOut, baseCurrency, discount, overrideSwapFee) + } else { + r7 = ret.Error(7) + } + + return r0, r1, r2, r3, r4, r5, r6, r7 +} + +// AmmKeeper_CalcSwapEstimationByDenom_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CalcSwapEstimationByDenom' +type AmmKeeper_CalcSwapEstimationByDenom_Call struct { + *mock.Call +} + +// CalcSwapEstimationByDenom is a helper method to define mock.On call +// - ctx types.Context +// - amount types.Coin +// - denomIn string +// - denomOut string +// - baseCurrency string +// - discount math.LegacyDec +// - overrideSwapFee math.LegacyDec +func (_e *AmmKeeper_Expecter) CalcSwapEstimationByDenom(ctx interface{}, amount interface{}, denomIn interface{}, denomOut interface{}, baseCurrency interface{}, discount interface{}, overrideSwapFee interface{}) *AmmKeeper_CalcSwapEstimationByDenom_Call { + return &AmmKeeper_CalcSwapEstimationByDenom_Call{Call: _e.mock.On("CalcSwapEstimationByDenom", ctx, amount, denomIn, denomOut, baseCurrency, discount, overrideSwapFee)} +} + +func (_c *AmmKeeper_CalcSwapEstimationByDenom_Call) Run(run func(ctx types.Context, amount types.Coin, denomIn string, denomOut string, baseCurrency string, discount math.LegacyDec, overrideSwapFee math.LegacyDec)) *AmmKeeper_CalcSwapEstimationByDenom_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].(types.Coin), args[2].(string), args[3].(string), args[4].(string), args[5].(math.LegacyDec), args[6].(math.LegacyDec)) + }) + return _c +} + +func (_c *AmmKeeper_CalcSwapEstimationByDenom_Call) Return(inRoute []*ammtypes.SwapAmountInRoute, outRoute []*ammtypes.SwapAmountOutRoute, outAmount types.Coin, spotPrice math.LegacyDec, swapFee math.LegacyDec, discountOut math.LegacyDec, availableLiquidity types.Coin, err error) *AmmKeeper_CalcSwapEstimationByDenom_Call { + _c.Call.Return(inRoute, outRoute, outAmount, spotPrice, swapFee, discountOut, availableLiquidity, err) + return _c +} + +func (_c *AmmKeeper_CalcSwapEstimationByDenom_Call) RunAndReturn(run func(types.Context, types.Coin, string, string, string, math.LegacyDec, math.LegacyDec) ([]*ammtypes.SwapAmountInRoute, []*ammtypes.SwapAmountOutRoute, types.Coin, math.LegacyDec, math.LegacyDec, math.LegacyDec, types.Coin, error)) *AmmKeeper_CalcSwapEstimationByDenom_Call { + _c.Call.Return(run) + return _c +} + // GetAllPool provides a mock function with given fields: _a0 func (_m *AmmKeeper) GetAllPool(_a0 types.Context) []ammtypes.Pool { ret := _m.Called(_a0) @@ -283,6 +387,59 @@ func (_c *AmmKeeper_GetPool_Call) RunAndReturn(run func(types.Context, uint64) ( return _c } +// GetPoolIdWithAllDenoms provides a mock function with given fields: ctx, denoms +func (_m *AmmKeeper) GetPoolIdWithAllDenoms(ctx types.Context, denoms []string) (uint64, bool) { + ret := _m.Called(ctx, denoms) + + var r0 uint64 + var r1 bool + if rf, ok := ret.Get(0).(func(types.Context, []string) (uint64, bool)); ok { + return rf(ctx, denoms) + } + if rf, ok := ret.Get(0).(func(types.Context, []string) uint64); ok { + r0 = rf(ctx, denoms) + } else { + r0 = ret.Get(0).(uint64) + } + + if rf, ok := ret.Get(1).(func(types.Context, []string) bool); ok { + r1 = rf(ctx, denoms) + } else { + r1 = ret.Get(1).(bool) + } + + return r0, r1 +} + +// AmmKeeper_GetPoolIdWithAllDenoms_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPoolIdWithAllDenoms' +type AmmKeeper_GetPoolIdWithAllDenoms_Call struct { + *mock.Call +} + +// GetPoolIdWithAllDenoms is a helper method to define mock.On call +// - ctx types.Context +// - denoms []string +func (_e *AmmKeeper_Expecter) GetPoolIdWithAllDenoms(ctx interface{}, denoms interface{}) *AmmKeeper_GetPoolIdWithAllDenoms_Call { + return &AmmKeeper_GetPoolIdWithAllDenoms_Call{Call: _e.mock.On("GetPoolIdWithAllDenoms", ctx, denoms)} +} + +func (_c *AmmKeeper_GetPoolIdWithAllDenoms_Call) Run(run func(ctx types.Context, denoms []string)) *AmmKeeper_GetPoolIdWithAllDenoms_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(types.Context), args[1].([]string)) + }) + return _c +} + +func (_c *AmmKeeper_GetPoolIdWithAllDenoms_Call) Return(poolId uint64, found bool) *AmmKeeper_GetPoolIdWithAllDenoms_Call { + _c.Call.Return(poolId, found) + return _c +} + +func (_c *AmmKeeper_GetPoolIdWithAllDenoms_Call) RunAndReturn(run func(types.Context, []string) (uint64, bool)) *AmmKeeper_GetPoolIdWithAllDenoms_Call { + _c.Call.Return(run) + return _c +} + // GetPoolSnapshotOrSet provides a mock function with given fields: ctx, pool func (_m *AmmKeeper) GetPoolSnapshotOrSet(ctx types.Context, pool ammtypes.Pool) ammtypes.Pool { ret := _m.Called(ctx, pool) diff --git a/x/margin/types/mocks/close_long_checker.go b/x/margin/types/mocks/close_long_checker.go index 6ee16a691..16e641597 100644 --- a/x/margin/types/mocks/close_long_checker.go +++ b/x/margin/types/mocks/close_long_checker.go @@ -26,23 +26,23 @@ func (_m *CloseLongChecker) EXPECT() *CloseLongChecker_Expecter { return &CloseLongChecker_Expecter{mock: &_m.Mock} } -// EstimateAndRepay provides a mock function with given fields: ctx, mtp, pool, ammPool, collateralAsset, custodyAsset -func (_m *CloseLongChecker) EstimateAndRepay(ctx types.Context, mtp margintypes.MTP, pool margintypes.Pool, ammPool ammtypes.Pool, collateralAsset string, custodyAsset string) (math.Int, error) { - ret := _m.Called(ctx, mtp, pool, ammPool, collateralAsset, custodyAsset) +// EstimateAndRepay provides a mock function with given fields: ctx, mtp, pool, ammPool, amount, baseCurrency +func (_m *CloseLongChecker) EstimateAndRepay(ctx types.Context, mtp margintypes.MTP, pool margintypes.Pool, ammPool ammtypes.Pool, amount math.Int, baseCurrency string) (math.Int, error) { + ret := _m.Called(ctx, mtp, pool, ammPool, amount, baseCurrency) var r0 math.Int var r1 error - if rf, ok := ret.Get(0).(func(types.Context, margintypes.MTP, margintypes.Pool, ammtypes.Pool, string, string) (math.Int, error)); ok { - return rf(ctx, mtp, pool, ammPool, collateralAsset, custodyAsset) + if rf, ok := ret.Get(0).(func(types.Context, margintypes.MTP, margintypes.Pool, ammtypes.Pool, math.Int, string) (math.Int, error)); ok { + return rf(ctx, mtp, pool, ammPool, amount, baseCurrency) } - if rf, ok := ret.Get(0).(func(types.Context, margintypes.MTP, margintypes.Pool, ammtypes.Pool, string, string) math.Int); ok { - r0 = rf(ctx, mtp, pool, ammPool, collateralAsset, custodyAsset) + if rf, ok := ret.Get(0).(func(types.Context, margintypes.MTP, margintypes.Pool, ammtypes.Pool, math.Int, string) math.Int); ok { + r0 = rf(ctx, mtp, pool, ammPool, amount, baseCurrency) } else { r0 = ret.Get(0).(math.Int) } - if rf, ok := ret.Get(1).(func(types.Context, margintypes.MTP, margintypes.Pool, ammtypes.Pool, string, string) error); ok { - r1 = rf(ctx, mtp, pool, ammPool, collateralAsset, custodyAsset) + if rf, ok := ret.Get(1).(func(types.Context, margintypes.MTP, margintypes.Pool, ammtypes.Pool, math.Int, string) error); ok { + r1 = rf(ctx, mtp, pool, ammPool, amount, baseCurrency) } else { r1 = ret.Error(1) } @@ -60,15 +60,15 @@ type CloseLongChecker_EstimateAndRepay_Call struct { // - mtp margintypes.MTP // - pool margintypes.Pool // - ammPool ammtypes.Pool -// - collateralAsset string -// - custodyAsset string -func (_e *CloseLongChecker_Expecter) EstimateAndRepay(ctx interface{}, mtp interface{}, pool interface{}, ammPool interface{}, collateralAsset interface{}, custodyAsset interface{}) *CloseLongChecker_EstimateAndRepay_Call { - return &CloseLongChecker_EstimateAndRepay_Call{Call: _e.mock.On("EstimateAndRepay", ctx, mtp, pool, ammPool, collateralAsset, custodyAsset)} +// - amount math.Int +// - baseCurrency string +func (_e *CloseLongChecker_Expecter) EstimateAndRepay(ctx interface{}, mtp interface{}, pool interface{}, ammPool interface{}, amount interface{}, baseCurrency interface{}) *CloseLongChecker_EstimateAndRepay_Call { + return &CloseLongChecker_EstimateAndRepay_Call{Call: _e.mock.On("EstimateAndRepay", ctx, mtp, pool, ammPool, amount, baseCurrency)} } -func (_c *CloseLongChecker_EstimateAndRepay_Call) Run(run func(ctx types.Context, mtp margintypes.MTP, pool margintypes.Pool, ammPool ammtypes.Pool, collateralAsset string, custodyAsset string)) *CloseLongChecker_EstimateAndRepay_Call { +func (_c *CloseLongChecker_EstimateAndRepay_Call) Run(run func(ctx types.Context, mtp margintypes.MTP, pool margintypes.Pool, ammPool ammtypes.Pool, amount math.Int, baseCurrency string)) *CloseLongChecker_EstimateAndRepay_Call { _c.Call.Run(func(args mock.Arguments) { - run(args[0].(types.Context), args[1].(margintypes.MTP), args[2].(margintypes.Pool), args[3].(ammtypes.Pool), args[4].(string), args[5].(string)) + run(args[0].(types.Context), args[1].(margintypes.MTP), args[2].(margintypes.Pool), args[3].(ammtypes.Pool), args[4].(math.Int), args[5].(string)) }) return _c } @@ -78,7 +78,7 @@ func (_c *CloseLongChecker_EstimateAndRepay_Call) Return(_a0 math.Int, _a1 error return _c } -func (_c *CloseLongChecker_EstimateAndRepay_Call) RunAndReturn(run func(types.Context, margintypes.MTP, margintypes.Pool, ammtypes.Pool, string, string) (math.Int, error)) *CloseLongChecker_EstimateAndRepay_Call { +func (_c *CloseLongChecker_EstimateAndRepay_Call) RunAndReturn(run func(types.Context, margintypes.MTP, margintypes.Pool, ammtypes.Pool, math.Int, string) (math.Int, error)) *CloseLongChecker_EstimateAndRepay_Call { _c.Call.Return(run) return _c } @@ -244,13 +244,13 @@ func (_c *CloseLongChecker_GetPool_Call) RunAndReturn(run func(types.Context, ui return _c } -// HandleBorrowInterest provides a mock function with given fields: ctx, mtp, pool, ammPool, collateralAsset, custodyAsset -func (_m *CloseLongChecker) HandleBorrowInterest(ctx types.Context, mtp *margintypes.MTP, pool *margintypes.Pool, ammPool ammtypes.Pool, collateralAsset string, custodyAsset string) error { - ret := _m.Called(ctx, mtp, pool, ammPool, collateralAsset, custodyAsset) +// HandleBorrowInterest provides a mock function with given fields: ctx, mtp, pool, ammPool +func (_m *CloseLongChecker) HandleBorrowInterest(ctx types.Context, mtp *margintypes.MTP, pool *margintypes.Pool, ammPool ammtypes.Pool) error { + ret := _m.Called(ctx, mtp, pool, ammPool) var r0 error - if rf, ok := ret.Get(0).(func(types.Context, *margintypes.MTP, *margintypes.Pool, ammtypes.Pool, string, string) error); ok { - r0 = rf(ctx, mtp, pool, ammPool, collateralAsset, custodyAsset) + if rf, ok := ret.Get(0).(func(types.Context, *margintypes.MTP, *margintypes.Pool, ammtypes.Pool) error); ok { + r0 = rf(ctx, mtp, pool, ammPool) } else { r0 = ret.Error(0) } @@ -268,15 +268,13 @@ type CloseLongChecker_HandleBorrowInterest_Call struct { // - mtp *margintypes.MTP // - pool *margintypes.Pool // - ammPool ammtypes.Pool -// - collateralAsset string -// - custodyAsset string -func (_e *CloseLongChecker_Expecter) HandleBorrowInterest(ctx interface{}, mtp interface{}, pool interface{}, ammPool interface{}, collateralAsset interface{}, custodyAsset interface{}) *CloseLongChecker_HandleBorrowInterest_Call { - return &CloseLongChecker_HandleBorrowInterest_Call{Call: _e.mock.On("HandleBorrowInterest", ctx, mtp, pool, ammPool, collateralAsset, custodyAsset)} +func (_e *CloseLongChecker_Expecter) HandleBorrowInterest(ctx interface{}, mtp interface{}, pool interface{}, ammPool interface{}) *CloseLongChecker_HandleBorrowInterest_Call { + return &CloseLongChecker_HandleBorrowInterest_Call{Call: _e.mock.On("HandleBorrowInterest", ctx, mtp, pool, ammPool)} } -func (_c *CloseLongChecker_HandleBorrowInterest_Call) Run(run func(ctx types.Context, mtp *margintypes.MTP, pool *margintypes.Pool, ammPool ammtypes.Pool, collateralAsset string, custodyAsset string)) *CloseLongChecker_HandleBorrowInterest_Call { +func (_c *CloseLongChecker_HandleBorrowInterest_Call) Run(run func(ctx types.Context, mtp *margintypes.MTP, pool *margintypes.Pool, ammPool ammtypes.Pool)) *CloseLongChecker_HandleBorrowInterest_Call { _c.Call.Run(func(args mock.Arguments) { - run(args[0].(types.Context), args[1].(*margintypes.MTP), args[2].(*margintypes.Pool), args[3].(ammtypes.Pool), args[4].(string), args[5].(string)) + run(args[0].(types.Context), args[1].(*margintypes.MTP), args[2].(*margintypes.Pool), args[3].(ammtypes.Pool)) }) return _c } @@ -286,18 +284,18 @@ func (_c *CloseLongChecker_HandleBorrowInterest_Call) Return(_a0 error) *CloseLo return _c } -func (_c *CloseLongChecker_HandleBorrowInterest_Call) RunAndReturn(run func(types.Context, *margintypes.MTP, *margintypes.Pool, ammtypes.Pool, string, string) error) *CloseLongChecker_HandleBorrowInterest_Call { +func (_c *CloseLongChecker_HandleBorrowInterest_Call) RunAndReturn(run func(types.Context, *margintypes.MTP, *margintypes.Pool, ammtypes.Pool) error) *CloseLongChecker_HandleBorrowInterest_Call { _c.Call.Return(run) return _c } -// TakeOutCustody provides a mock function with given fields: ctx, mtp, pool, custodyAsset -func (_m *CloseLongChecker) TakeOutCustody(ctx types.Context, mtp margintypes.MTP, pool *margintypes.Pool, custodyAsset string) error { - ret := _m.Called(ctx, mtp, pool, custodyAsset) +// TakeOutCustody provides a mock function with given fields: ctx, mtp, pool, amount +func (_m *CloseLongChecker) TakeOutCustody(ctx types.Context, mtp margintypes.MTP, pool *margintypes.Pool, amount math.Int) error { + ret := _m.Called(ctx, mtp, pool, amount) var r0 error - if rf, ok := ret.Get(0).(func(types.Context, margintypes.MTP, *margintypes.Pool, string) error); ok { - r0 = rf(ctx, mtp, pool, custodyAsset) + if rf, ok := ret.Get(0).(func(types.Context, margintypes.MTP, *margintypes.Pool, math.Int) error); ok { + r0 = rf(ctx, mtp, pool, amount) } else { r0 = ret.Error(0) } @@ -314,14 +312,14 @@ type CloseLongChecker_TakeOutCustody_Call struct { // - ctx types.Context // - mtp margintypes.MTP // - pool *margintypes.Pool -// - custodyAsset string -func (_e *CloseLongChecker_Expecter) TakeOutCustody(ctx interface{}, mtp interface{}, pool interface{}, custodyAsset interface{}) *CloseLongChecker_TakeOutCustody_Call { - return &CloseLongChecker_TakeOutCustody_Call{Call: _e.mock.On("TakeOutCustody", ctx, mtp, pool, custodyAsset)} +// - amount math.Int +func (_e *CloseLongChecker_Expecter) TakeOutCustody(ctx interface{}, mtp interface{}, pool interface{}, amount interface{}) *CloseLongChecker_TakeOutCustody_Call { + return &CloseLongChecker_TakeOutCustody_Call{Call: _e.mock.On("TakeOutCustody", ctx, mtp, pool, amount)} } -func (_c *CloseLongChecker_TakeOutCustody_Call) Run(run func(ctx types.Context, mtp margintypes.MTP, pool *margintypes.Pool, custodyAsset string)) *CloseLongChecker_TakeOutCustody_Call { +func (_c *CloseLongChecker_TakeOutCustody_Call) Run(run func(ctx types.Context, mtp margintypes.MTP, pool *margintypes.Pool, amount math.Int)) *CloseLongChecker_TakeOutCustody_Call { _c.Call.Run(func(args mock.Arguments) { - run(args[0].(types.Context), args[1].(margintypes.MTP), args[2].(*margintypes.Pool), args[3].(string)) + run(args[0].(types.Context), args[1].(margintypes.MTP), args[2].(*margintypes.Pool), args[3].(math.Int)) }) return _c } @@ -331,7 +329,7 @@ func (_c *CloseLongChecker_TakeOutCustody_Call) Return(_a0 error) *CloseLongChec return _c } -func (_c *CloseLongChecker_TakeOutCustody_Call) RunAndReturn(run func(types.Context, margintypes.MTP, *margintypes.Pool, string) error) *CloseLongChecker_TakeOutCustody_Call { +func (_c *CloseLongChecker_TakeOutCustody_Call) RunAndReturn(run func(types.Context, margintypes.MTP, *margintypes.Pool, math.Int) error) *CloseLongChecker_TakeOutCustody_Call { _c.Call.Return(run) return _c } diff --git a/x/margin/types/mocks/close_short_checker.go b/x/margin/types/mocks/close_short_checker.go index fbb63fc2d..244e4d77d 100644 --- a/x/margin/types/mocks/close_short_checker.go +++ b/x/margin/types/mocks/close_short_checker.go @@ -26,23 +26,23 @@ func (_m *CloseShortChecker) EXPECT() *CloseShortChecker_Expecter { return &CloseShortChecker_Expecter{mock: &_m.Mock} } -// EstimateAndRepay provides a mock function with given fields: ctx, mtp, pool, ammPool, collateralAsset, custodyAsset -func (_m *CloseShortChecker) EstimateAndRepay(ctx types.Context, mtp margintypes.MTP, pool margintypes.Pool, ammPool ammtypes.Pool, collateralAsset string, custodyAsset string) (math.Int, error) { - ret := _m.Called(ctx, mtp, pool, ammPool, collateralAsset, custodyAsset) +// EstimateAndRepay provides a mock function with given fields: ctx, mtp, pool, ammPool, amount, baseCurrency +func (_m *CloseShortChecker) EstimateAndRepay(ctx types.Context, mtp margintypes.MTP, pool margintypes.Pool, ammPool ammtypes.Pool, amount math.Int, baseCurrency string) (math.Int, error) { + ret := _m.Called(ctx, mtp, pool, ammPool, amount, baseCurrency) var r0 math.Int var r1 error - if rf, ok := ret.Get(0).(func(types.Context, margintypes.MTP, margintypes.Pool, ammtypes.Pool, string, string) (math.Int, error)); ok { - return rf(ctx, mtp, pool, ammPool, collateralAsset, custodyAsset) + if rf, ok := ret.Get(0).(func(types.Context, margintypes.MTP, margintypes.Pool, ammtypes.Pool, math.Int, string) (math.Int, error)); ok { + return rf(ctx, mtp, pool, ammPool, amount, baseCurrency) } - if rf, ok := ret.Get(0).(func(types.Context, margintypes.MTP, margintypes.Pool, ammtypes.Pool, string, string) math.Int); ok { - r0 = rf(ctx, mtp, pool, ammPool, collateralAsset, custodyAsset) + if rf, ok := ret.Get(0).(func(types.Context, margintypes.MTP, margintypes.Pool, ammtypes.Pool, math.Int, string) math.Int); ok { + r0 = rf(ctx, mtp, pool, ammPool, amount, baseCurrency) } else { r0 = ret.Get(0).(math.Int) } - if rf, ok := ret.Get(1).(func(types.Context, margintypes.MTP, margintypes.Pool, ammtypes.Pool, string, string) error); ok { - r1 = rf(ctx, mtp, pool, ammPool, collateralAsset, custodyAsset) + if rf, ok := ret.Get(1).(func(types.Context, margintypes.MTP, margintypes.Pool, ammtypes.Pool, math.Int, string) error); ok { + r1 = rf(ctx, mtp, pool, ammPool, amount, baseCurrency) } else { r1 = ret.Error(1) } @@ -60,15 +60,15 @@ type CloseShortChecker_EstimateAndRepay_Call struct { // - mtp margintypes.MTP // - pool margintypes.Pool // - ammPool ammtypes.Pool -// - collateralAsset string -// - custodyAsset string -func (_e *CloseShortChecker_Expecter) EstimateAndRepay(ctx interface{}, mtp interface{}, pool interface{}, ammPool interface{}, collateralAsset interface{}, custodyAsset interface{}) *CloseShortChecker_EstimateAndRepay_Call { - return &CloseShortChecker_EstimateAndRepay_Call{Call: _e.mock.On("EstimateAndRepay", ctx, mtp, pool, ammPool, collateralAsset, custodyAsset)} +// - amount math.Int +// - baseCurrency string +func (_e *CloseShortChecker_Expecter) EstimateAndRepay(ctx interface{}, mtp interface{}, pool interface{}, ammPool interface{}, amount interface{}, baseCurrency interface{}) *CloseShortChecker_EstimateAndRepay_Call { + return &CloseShortChecker_EstimateAndRepay_Call{Call: _e.mock.On("EstimateAndRepay", ctx, mtp, pool, ammPool, amount, baseCurrency)} } -func (_c *CloseShortChecker_EstimateAndRepay_Call) Run(run func(ctx types.Context, mtp margintypes.MTP, pool margintypes.Pool, ammPool ammtypes.Pool, collateralAsset string, custodyAsset string)) *CloseShortChecker_EstimateAndRepay_Call { +func (_c *CloseShortChecker_EstimateAndRepay_Call) Run(run func(ctx types.Context, mtp margintypes.MTP, pool margintypes.Pool, ammPool ammtypes.Pool, amount math.Int, baseCurrency string)) *CloseShortChecker_EstimateAndRepay_Call { _c.Call.Run(func(args mock.Arguments) { - run(args[0].(types.Context), args[1].(margintypes.MTP), args[2].(margintypes.Pool), args[3].(ammtypes.Pool), args[4].(string), args[5].(string)) + run(args[0].(types.Context), args[1].(margintypes.MTP), args[2].(margintypes.Pool), args[3].(ammtypes.Pool), args[4].(math.Int), args[5].(string)) }) return _c } @@ -78,7 +78,7 @@ func (_c *CloseShortChecker_EstimateAndRepay_Call) Return(_a0 math.Int, _a1 erro return _c } -func (_c *CloseShortChecker_EstimateAndRepay_Call) RunAndReturn(run func(types.Context, margintypes.MTP, margintypes.Pool, ammtypes.Pool, string, string) (math.Int, error)) *CloseShortChecker_EstimateAndRepay_Call { +func (_c *CloseShortChecker_EstimateAndRepay_Call) RunAndReturn(run func(types.Context, margintypes.MTP, margintypes.Pool, ammtypes.Pool, math.Int, string) (math.Int, error)) *CloseShortChecker_EstimateAndRepay_Call { _c.Call.Return(run) return _c } @@ -244,13 +244,13 @@ func (_c *CloseShortChecker_GetPool_Call) RunAndReturn(run func(types.Context, u return _c } -// HandleBorrowInterest provides a mock function with given fields: ctx, mtp, pool, ammPool, collateralAsset, custodyAsset -func (_m *CloseShortChecker) HandleBorrowInterest(ctx types.Context, mtp *margintypes.MTP, pool *margintypes.Pool, ammPool ammtypes.Pool, collateralAsset string, custodyAsset string) error { - ret := _m.Called(ctx, mtp, pool, ammPool, collateralAsset, custodyAsset) +// HandleBorrowInterest provides a mock function with given fields: ctx, mtp, pool, ammPool +func (_m *CloseShortChecker) HandleBorrowInterest(ctx types.Context, mtp *margintypes.MTP, pool *margintypes.Pool, ammPool ammtypes.Pool) error { + ret := _m.Called(ctx, mtp, pool, ammPool) var r0 error - if rf, ok := ret.Get(0).(func(types.Context, *margintypes.MTP, *margintypes.Pool, ammtypes.Pool, string, string) error); ok { - r0 = rf(ctx, mtp, pool, ammPool, collateralAsset, custodyAsset) + if rf, ok := ret.Get(0).(func(types.Context, *margintypes.MTP, *margintypes.Pool, ammtypes.Pool) error); ok { + r0 = rf(ctx, mtp, pool, ammPool) } else { r0 = ret.Error(0) } @@ -268,15 +268,13 @@ type CloseShortChecker_HandleBorrowInterest_Call struct { // - mtp *margintypes.MTP // - pool *margintypes.Pool // - ammPool ammtypes.Pool -// - collateralAsset string -// - custodyAsset string -func (_e *CloseShortChecker_Expecter) HandleBorrowInterest(ctx interface{}, mtp interface{}, pool interface{}, ammPool interface{}, collateralAsset interface{}, custodyAsset interface{}) *CloseShortChecker_HandleBorrowInterest_Call { - return &CloseShortChecker_HandleBorrowInterest_Call{Call: _e.mock.On("HandleBorrowInterest", ctx, mtp, pool, ammPool, collateralAsset, custodyAsset)} +func (_e *CloseShortChecker_Expecter) HandleBorrowInterest(ctx interface{}, mtp interface{}, pool interface{}, ammPool interface{}) *CloseShortChecker_HandleBorrowInterest_Call { + return &CloseShortChecker_HandleBorrowInterest_Call{Call: _e.mock.On("HandleBorrowInterest", ctx, mtp, pool, ammPool)} } -func (_c *CloseShortChecker_HandleBorrowInterest_Call) Run(run func(ctx types.Context, mtp *margintypes.MTP, pool *margintypes.Pool, ammPool ammtypes.Pool, collateralAsset string, custodyAsset string)) *CloseShortChecker_HandleBorrowInterest_Call { +func (_c *CloseShortChecker_HandleBorrowInterest_Call) Run(run func(ctx types.Context, mtp *margintypes.MTP, pool *margintypes.Pool, ammPool ammtypes.Pool)) *CloseShortChecker_HandleBorrowInterest_Call { _c.Call.Run(func(args mock.Arguments) { - run(args[0].(types.Context), args[1].(*margintypes.MTP), args[2].(*margintypes.Pool), args[3].(ammtypes.Pool), args[4].(string), args[5].(string)) + run(args[0].(types.Context), args[1].(*margintypes.MTP), args[2].(*margintypes.Pool), args[3].(ammtypes.Pool)) }) return _c } @@ -286,18 +284,18 @@ func (_c *CloseShortChecker_HandleBorrowInterest_Call) Return(_a0 error) *CloseS return _c } -func (_c *CloseShortChecker_HandleBorrowInterest_Call) RunAndReturn(run func(types.Context, *margintypes.MTP, *margintypes.Pool, ammtypes.Pool, string, string) error) *CloseShortChecker_HandleBorrowInterest_Call { +func (_c *CloseShortChecker_HandleBorrowInterest_Call) RunAndReturn(run func(types.Context, *margintypes.MTP, *margintypes.Pool, ammtypes.Pool) error) *CloseShortChecker_HandleBorrowInterest_Call { _c.Call.Return(run) return _c } -// TakeOutCustody provides a mock function with given fields: ctx, mtp, pool, custodyAsset -func (_m *CloseShortChecker) TakeOutCustody(ctx types.Context, mtp margintypes.MTP, pool *margintypes.Pool, custodyAsset string) error { - ret := _m.Called(ctx, mtp, pool, custodyAsset) +// TakeOutCustody provides a mock function with given fields: ctx, mtp, pool, amount +func (_m *CloseShortChecker) TakeOutCustody(ctx types.Context, mtp margintypes.MTP, pool *margintypes.Pool, amount math.Int) error { + ret := _m.Called(ctx, mtp, pool, amount) var r0 error - if rf, ok := ret.Get(0).(func(types.Context, margintypes.MTP, *margintypes.Pool, string) error); ok { - r0 = rf(ctx, mtp, pool, custodyAsset) + if rf, ok := ret.Get(0).(func(types.Context, margintypes.MTP, *margintypes.Pool, math.Int) error); ok { + r0 = rf(ctx, mtp, pool, amount) } else { r0 = ret.Error(0) } @@ -314,14 +312,14 @@ type CloseShortChecker_TakeOutCustody_Call struct { // - ctx types.Context // - mtp margintypes.MTP // - pool *margintypes.Pool -// - custodyAsset string -func (_e *CloseShortChecker_Expecter) TakeOutCustody(ctx interface{}, mtp interface{}, pool interface{}, custodyAsset interface{}) *CloseShortChecker_TakeOutCustody_Call { - return &CloseShortChecker_TakeOutCustody_Call{Call: _e.mock.On("TakeOutCustody", ctx, mtp, pool, custodyAsset)} +// - amount math.Int +func (_e *CloseShortChecker_Expecter) TakeOutCustody(ctx interface{}, mtp interface{}, pool interface{}, amount interface{}) *CloseShortChecker_TakeOutCustody_Call { + return &CloseShortChecker_TakeOutCustody_Call{Call: _e.mock.On("TakeOutCustody", ctx, mtp, pool, amount)} } -func (_c *CloseShortChecker_TakeOutCustody_Call) Run(run func(ctx types.Context, mtp margintypes.MTP, pool *margintypes.Pool, custodyAsset string)) *CloseShortChecker_TakeOutCustody_Call { +func (_c *CloseShortChecker_TakeOutCustody_Call) Run(run func(ctx types.Context, mtp margintypes.MTP, pool *margintypes.Pool, amount math.Int)) *CloseShortChecker_TakeOutCustody_Call { _c.Call.Run(func(args mock.Arguments) { - run(args[0].(types.Context), args[1].(margintypes.MTP), args[2].(*margintypes.Pool), args[3].(string)) + run(args[0].(types.Context), args[1].(margintypes.MTP), args[2].(*margintypes.Pool), args[3].(math.Int)) }) return _c } @@ -331,7 +329,7 @@ func (_c *CloseShortChecker_TakeOutCustody_Call) Return(_a0 error) *CloseShortCh return _c } -func (_c *CloseShortChecker_TakeOutCustody_Call) RunAndReturn(run func(types.Context, margintypes.MTP, *margintypes.Pool, string) error) *CloseShortChecker_TakeOutCustody_Call { +func (_c *CloseShortChecker_TakeOutCustody_Call) RunAndReturn(run func(types.Context, margintypes.MTP, *margintypes.Pool, math.Int) error) *CloseShortChecker_TakeOutCustody_Call { _c.Call.Return(run) return _c } diff --git a/x/margin/types/mocks/open_checker.go b/x/margin/types/mocks/open_checker.go index 5bf24eabc..ea800d54d 100644 --- a/x/margin/types/mocks/open_checker.go +++ b/x/margin/types/mocks/open_checker.go @@ -429,37 +429,37 @@ func (_c *OpenChecker_OpenShort_Call) RunAndReturn(run func(types.Context, uint6 return _c } -// PreparePools provides a mock function with given fields: ctx, tradingAsset -func (_m *OpenChecker) PreparePools(ctx types.Context, tradingAsset string) (uint64, ammtypes.Pool, margintypes.Pool, error) { - ret := _m.Called(ctx, tradingAsset) +// PreparePools provides a mock function with given fields: ctx, collateralAsset, tradingAsset +func (_m *OpenChecker) PreparePools(ctx types.Context, collateralAsset string, tradingAsset string) (uint64, ammtypes.Pool, margintypes.Pool, error) { + ret := _m.Called(ctx, collateralAsset, tradingAsset) var r0 uint64 var r1 ammtypes.Pool var r2 margintypes.Pool var r3 error - if rf, ok := ret.Get(0).(func(types.Context, string) (uint64, ammtypes.Pool, margintypes.Pool, error)); ok { - return rf(ctx, tradingAsset) + if rf, ok := ret.Get(0).(func(types.Context, string, string) (uint64, ammtypes.Pool, margintypes.Pool, error)); ok { + return rf(ctx, collateralAsset, tradingAsset) } - if rf, ok := ret.Get(0).(func(types.Context, string) uint64); ok { - r0 = rf(ctx, tradingAsset) + if rf, ok := ret.Get(0).(func(types.Context, string, string) uint64); ok { + r0 = rf(ctx, collateralAsset, tradingAsset) } else { r0 = ret.Get(0).(uint64) } - if rf, ok := ret.Get(1).(func(types.Context, string) ammtypes.Pool); ok { - r1 = rf(ctx, tradingAsset) + if rf, ok := ret.Get(1).(func(types.Context, string, string) ammtypes.Pool); ok { + r1 = rf(ctx, collateralAsset, tradingAsset) } else { r1 = ret.Get(1).(ammtypes.Pool) } - if rf, ok := ret.Get(2).(func(types.Context, string) margintypes.Pool); ok { - r2 = rf(ctx, tradingAsset) + if rf, ok := ret.Get(2).(func(types.Context, string, string) margintypes.Pool); ok { + r2 = rf(ctx, collateralAsset, tradingAsset) } else { r2 = ret.Get(2).(margintypes.Pool) } - if rf, ok := ret.Get(3).(func(types.Context, string) error); ok { - r3 = rf(ctx, tradingAsset) + if rf, ok := ret.Get(3).(func(types.Context, string, string) error); ok { + r3 = rf(ctx, collateralAsset, tradingAsset) } else { r3 = ret.Error(3) } @@ -474,14 +474,15 @@ type OpenChecker_PreparePools_Call struct { // PreparePools is a helper method to define mock.On call // - ctx types.Context +// - collateralAsset string // - tradingAsset string -func (_e *OpenChecker_Expecter) PreparePools(ctx interface{}, tradingAsset interface{}) *OpenChecker_PreparePools_Call { - return &OpenChecker_PreparePools_Call{Call: _e.mock.On("PreparePools", ctx, tradingAsset)} +func (_e *OpenChecker_Expecter) PreparePools(ctx interface{}, collateralAsset interface{}, tradingAsset interface{}) *OpenChecker_PreparePools_Call { + return &OpenChecker_PreparePools_Call{Call: _e.mock.On("PreparePools", ctx, collateralAsset, tradingAsset)} } -func (_c *OpenChecker_PreparePools_Call) Run(run func(ctx types.Context, tradingAsset string)) *OpenChecker_PreparePools_Call { +func (_c *OpenChecker_PreparePools_Call) Run(run func(ctx types.Context, collateralAsset string, tradingAsset string)) *OpenChecker_PreparePools_Call { _c.Call.Run(func(args mock.Arguments) { - run(args[0].(types.Context), args[1].(string)) + run(args[0].(types.Context), args[1].(string), args[2].(string)) }) return _c } @@ -491,7 +492,7 @@ func (_c *OpenChecker_PreparePools_Call) Return(poolId uint64, ammPool ammtypes. return _c } -func (_c *OpenChecker_PreparePools_Call) RunAndReturn(run func(types.Context, string) (uint64, ammtypes.Pool, margintypes.Pool, error)) *OpenChecker_PreparePools_Call { +func (_c *OpenChecker_PreparePools_Call) RunAndReturn(run func(types.Context, string, string) (uint64, ammtypes.Pool, margintypes.Pool, error)) *OpenChecker_PreparePools_Call { _c.Call.Return(run) return _c } diff --git a/x/margin/types/mocks/open_long_checker.go b/x/margin/types/mocks/open_long_checker.go index 607893a04..d0d909344 100644 --- a/x/margin/types/mocks/open_long_checker.go +++ b/x/margin/types/mocks/open_long_checker.go @@ -26,13 +26,13 @@ func (_m *OpenLongChecker) EXPECT() *OpenLongChecker_Expecter { return &OpenLongChecker_Expecter{mock: &_m.Mock} } -// Borrow provides a mock function with given fields: ctx, collateralAsset, custodyAsset, collateralAmount, custodyAmount, mtp, ammPool, pool, eta, baseCurrency -func (_m *OpenLongChecker) Borrow(ctx types.Context, collateralAsset string, custodyAsset string, collateralAmount math.Int, custodyAmount math.Int, mtp *margintypes.MTP, ammPool *ammtypes.Pool, pool *margintypes.Pool, eta math.LegacyDec, baseCurrency string) error { - ret := _m.Called(ctx, collateralAsset, custodyAsset, collateralAmount, custodyAmount, mtp, ammPool, pool, eta, baseCurrency) +// Borrow provides a mock function with given fields: ctx, collateralAmount, custodyAmount, mtp, ammPool, pool, eta, baseCurrency +func (_m *OpenLongChecker) Borrow(ctx types.Context, collateralAmount math.Int, custodyAmount math.Int, mtp *margintypes.MTP, ammPool *ammtypes.Pool, pool *margintypes.Pool, eta math.LegacyDec, baseCurrency string) error { + ret := _m.Called(ctx, collateralAmount, custodyAmount, mtp, ammPool, pool, eta, baseCurrency) var r0 error - if rf, ok := ret.Get(0).(func(types.Context, string, string, math.Int, math.Int, *margintypes.MTP, *ammtypes.Pool, *margintypes.Pool, math.LegacyDec, string) error); ok { - r0 = rf(ctx, collateralAsset, custodyAsset, collateralAmount, custodyAmount, mtp, ammPool, pool, eta, baseCurrency) + if rf, ok := ret.Get(0).(func(types.Context, math.Int, math.Int, *margintypes.MTP, *ammtypes.Pool, *margintypes.Pool, math.LegacyDec, string) error); ok { + r0 = rf(ctx, collateralAmount, custodyAmount, mtp, ammPool, pool, eta, baseCurrency) } else { r0 = ret.Error(0) } @@ -47,8 +47,6 @@ type OpenLongChecker_Borrow_Call struct { // Borrow is a helper method to define mock.On call // - ctx types.Context -// - collateralAsset string -// - custodyAsset string // - collateralAmount math.Int // - custodyAmount math.Int // - mtp *margintypes.MTP @@ -56,13 +54,13 @@ type OpenLongChecker_Borrow_Call struct { // - pool *margintypes.Pool // - eta math.LegacyDec // - baseCurrency string -func (_e *OpenLongChecker_Expecter) Borrow(ctx interface{}, collateralAsset interface{}, custodyAsset interface{}, collateralAmount interface{}, custodyAmount interface{}, mtp interface{}, ammPool interface{}, pool interface{}, eta interface{}, baseCurrency interface{}) *OpenLongChecker_Borrow_Call { - return &OpenLongChecker_Borrow_Call{Call: _e.mock.On("Borrow", ctx, collateralAsset, custodyAsset, collateralAmount, custodyAmount, mtp, ammPool, pool, eta, baseCurrency)} +func (_e *OpenLongChecker_Expecter) Borrow(ctx interface{}, collateralAmount interface{}, custodyAmount interface{}, mtp interface{}, ammPool interface{}, pool interface{}, eta interface{}, baseCurrency interface{}) *OpenLongChecker_Borrow_Call { + return &OpenLongChecker_Borrow_Call{Call: _e.mock.On("Borrow", ctx, collateralAmount, custodyAmount, mtp, ammPool, pool, eta, baseCurrency)} } -func (_c *OpenLongChecker_Borrow_Call) Run(run func(ctx types.Context, collateralAsset string, custodyAsset string, collateralAmount math.Int, custodyAmount math.Int, mtp *margintypes.MTP, ammPool *ammtypes.Pool, pool *margintypes.Pool, eta math.LegacyDec, baseCurrency string)) *OpenLongChecker_Borrow_Call { +func (_c *OpenLongChecker_Borrow_Call) Run(run func(ctx types.Context, collateralAmount math.Int, custodyAmount math.Int, mtp *margintypes.MTP, ammPool *ammtypes.Pool, pool *margintypes.Pool, eta math.LegacyDec, baseCurrency string)) *OpenLongChecker_Borrow_Call { _c.Call.Run(func(args mock.Arguments) { - run(args[0].(types.Context), args[1].(string), args[2].(string), args[3].(math.Int), args[4].(math.Int), args[5].(*margintypes.MTP), args[6].(*ammtypes.Pool), args[7].(*margintypes.Pool), args[8].(math.LegacyDec), args[9].(string)) + run(args[0].(types.Context), args[1].(math.Int), args[2].(math.Int), args[3].(*margintypes.MTP), args[4].(*ammtypes.Pool), args[5].(*margintypes.Pool), args[6].(math.LegacyDec), args[7].(string)) }) return _c } @@ -72,7 +70,7 @@ func (_c *OpenLongChecker_Borrow_Call) Return(_a0 error) *OpenLongChecker_Borrow return _c } -func (_c *OpenLongChecker_Borrow_Call) RunAndReturn(run func(types.Context, string, string, math.Int, math.Int, *margintypes.MTP, *ammtypes.Pool, *margintypes.Pool, math.LegacyDec, string) error) *OpenLongChecker_Borrow_Call { +func (_c *OpenLongChecker_Borrow_Call) RunAndReturn(run func(types.Context, math.Int, math.Int, *margintypes.MTP, *ammtypes.Pool, *margintypes.Pool, math.LegacyDec, string) error) *OpenLongChecker_Borrow_Call { _c.Call.Return(run) return _c } @@ -121,13 +119,13 @@ func (_c *OpenLongChecker_CalcMTPConsolidateCollateral_Call) RunAndReturn(run fu return _c } -// CheckMinLiabilities provides a mock function with given fields: ctx, collateralTokenAmt, eta, pool, ammPool, borrowAsset -func (_m *OpenLongChecker) CheckMinLiabilities(ctx types.Context, collateralTokenAmt types.Coin, eta math.LegacyDec, pool margintypes.Pool, ammPool ammtypes.Pool, borrowAsset string) error { - ret := _m.Called(ctx, collateralTokenAmt, eta, pool, ammPool, borrowAsset) +// CheckMinLiabilities provides a mock function with given fields: ctx, collateralTokenAmt, eta, ammPool, borrowAsset, baseCurrency +func (_m *OpenLongChecker) CheckMinLiabilities(ctx types.Context, collateralTokenAmt types.Coin, eta math.LegacyDec, ammPool ammtypes.Pool, borrowAsset string, baseCurrency string) error { + ret := _m.Called(ctx, collateralTokenAmt, eta, ammPool, borrowAsset, baseCurrency) var r0 error - if rf, ok := ret.Get(0).(func(types.Context, types.Coin, math.LegacyDec, margintypes.Pool, ammtypes.Pool, string) error); ok { - r0 = rf(ctx, collateralTokenAmt, eta, pool, ammPool, borrowAsset) + if rf, ok := ret.Get(0).(func(types.Context, types.Coin, math.LegacyDec, ammtypes.Pool, string, string) error); ok { + r0 = rf(ctx, collateralTokenAmt, eta, ammPool, borrowAsset, baseCurrency) } else { r0 = ret.Error(0) } @@ -144,16 +142,16 @@ type OpenLongChecker_CheckMinLiabilities_Call struct { // - ctx types.Context // - collateralTokenAmt types.Coin // - eta math.LegacyDec -// - pool margintypes.Pool // - ammPool ammtypes.Pool // - borrowAsset string -func (_e *OpenLongChecker_Expecter) CheckMinLiabilities(ctx interface{}, collateralTokenAmt interface{}, eta interface{}, pool interface{}, ammPool interface{}, borrowAsset interface{}) *OpenLongChecker_CheckMinLiabilities_Call { - return &OpenLongChecker_CheckMinLiabilities_Call{Call: _e.mock.On("CheckMinLiabilities", ctx, collateralTokenAmt, eta, pool, ammPool, borrowAsset)} +// - baseCurrency string +func (_e *OpenLongChecker_Expecter) CheckMinLiabilities(ctx interface{}, collateralTokenAmt interface{}, eta interface{}, ammPool interface{}, borrowAsset interface{}, baseCurrency interface{}) *OpenLongChecker_CheckMinLiabilities_Call { + return &OpenLongChecker_CheckMinLiabilities_Call{Call: _e.mock.On("CheckMinLiabilities", ctx, collateralTokenAmt, eta, ammPool, borrowAsset, baseCurrency)} } -func (_c *OpenLongChecker_CheckMinLiabilities_Call) Run(run func(ctx types.Context, collateralTokenAmt types.Coin, eta math.LegacyDec, pool margintypes.Pool, ammPool ammtypes.Pool, borrowAsset string)) *OpenLongChecker_CheckMinLiabilities_Call { +func (_c *OpenLongChecker_CheckMinLiabilities_Call) Run(run func(ctx types.Context, collateralTokenAmt types.Coin, eta math.LegacyDec, ammPool ammtypes.Pool, borrowAsset string, baseCurrency string)) *OpenLongChecker_CheckMinLiabilities_Call { _c.Call.Run(func(args mock.Arguments) { - run(args[0].(types.Context), args[1].(types.Coin), args[2].(math.LegacyDec), args[3].(margintypes.Pool), args[4].(ammtypes.Pool), args[5].(string)) + run(args[0].(types.Context), args[1].(types.Coin), args[2].(math.LegacyDec), args[3].(ammtypes.Pool), args[4].(string), args[5].(string)) }) return _c } @@ -163,7 +161,7 @@ func (_c *OpenLongChecker_CheckMinLiabilities_Call) Return(_a0 error) *OpenLongC return _c } -func (_c *OpenLongChecker_CheckMinLiabilities_Call) RunAndReturn(run func(types.Context, types.Coin, math.LegacyDec, margintypes.Pool, ammtypes.Pool, string) error) *OpenLongChecker_CheckMinLiabilities_Call { +func (_c *OpenLongChecker_CheckMinLiabilities_Call) RunAndReturn(run func(types.Context, types.Coin, math.LegacyDec, ammtypes.Pool, string, string) error) *OpenLongChecker_CheckMinLiabilities_Call { _c.Call.Return(run) return _c } diff --git a/x/margin/types/mocks/open_short_checker.go b/x/margin/types/mocks/open_short_checker.go index 3f63036dd..1aefc0161 100644 --- a/x/margin/types/mocks/open_short_checker.go +++ b/x/margin/types/mocks/open_short_checker.go @@ -26,13 +26,13 @@ func (_m *OpenShortChecker) EXPECT() *OpenShortChecker_Expecter { return &OpenShortChecker_Expecter{mock: &_m.Mock} } -// Borrow provides a mock function with given fields: ctx, collateralAsset, custodyAsset, collateralAmount, custodyAmount, mtp, ammPool, pool, eta, baseCurrency -func (_m *OpenShortChecker) Borrow(ctx types.Context, collateralAsset string, custodyAsset string, collateralAmount math.Int, custodyAmount math.Int, mtp *margintypes.MTP, ammPool *ammtypes.Pool, pool *margintypes.Pool, eta math.LegacyDec, baseCurrency string) error { - ret := _m.Called(ctx, collateralAsset, custodyAsset, collateralAmount, custodyAmount, mtp, ammPool, pool, eta, baseCurrency) +// Borrow provides a mock function with given fields: ctx, collateralAmount, custodyAmount, mtp, ammPool, pool, eta, baseCurrency +func (_m *OpenShortChecker) Borrow(ctx types.Context, collateralAmount math.Int, custodyAmount math.Int, mtp *margintypes.MTP, ammPool *ammtypes.Pool, pool *margintypes.Pool, eta math.LegacyDec, baseCurrency string) error { + ret := _m.Called(ctx, collateralAmount, custodyAmount, mtp, ammPool, pool, eta, baseCurrency) var r0 error - if rf, ok := ret.Get(0).(func(types.Context, string, string, math.Int, math.Int, *margintypes.MTP, *ammtypes.Pool, *margintypes.Pool, math.LegacyDec, string) error); ok { - r0 = rf(ctx, collateralAsset, custodyAsset, collateralAmount, custodyAmount, mtp, ammPool, pool, eta, baseCurrency) + if rf, ok := ret.Get(0).(func(types.Context, math.Int, math.Int, *margintypes.MTP, *ammtypes.Pool, *margintypes.Pool, math.LegacyDec, string) error); ok { + r0 = rf(ctx, collateralAmount, custodyAmount, mtp, ammPool, pool, eta, baseCurrency) } else { r0 = ret.Error(0) } @@ -47,8 +47,6 @@ type OpenShortChecker_Borrow_Call struct { // Borrow is a helper method to define mock.On call // - ctx types.Context -// - collateralAsset string -// - custodyAsset string // - collateralAmount math.Int // - custodyAmount math.Int // - mtp *margintypes.MTP @@ -56,13 +54,13 @@ type OpenShortChecker_Borrow_Call struct { // - pool *margintypes.Pool // - eta math.LegacyDec // - baseCurrency string -func (_e *OpenShortChecker_Expecter) Borrow(ctx interface{}, collateralAsset interface{}, custodyAsset interface{}, collateralAmount interface{}, custodyAmount interface{}, mtp interface{}, ammPool interface{}, pool interface{}, eta interface{}, baseCurrency interface{}) *OpenShortChecker_Borrow_Call { - return &OpenShortChecker_Borrow_Call{Call: _e.mock.On("Borrow", ctx, collateralAsset, custodyAsset, collateralAmount, custodyAmount, mtp, ammPool, pool, eta, baseCurrency)} +func (_e *OpenShortChecker_Expecter) Borrow(ctx interface{}, collateralAmount interface{}, custodyAmount interface{}, mtp interface{}, ammPool interface{}, pool interface{}, eta interface{}, baseCurrency interface{}) *OpenShortChecker_Borrow_Call { + return &OpenShortChecker_Borrow_Call{Call: _e.mock.On("Borrow", ctx, collateralAmount, custodyAmount, mtp, ammPool, pool, eta, baseCurrency)} } -func (_c *OpenShortChecker_Borrow_Call) Run(run func(ctx types.Context, collateralAsset string, custodyAsset string, collateralAmount math.Int, custodyAmount math.Int, mtp *margintypes.MTP, ammPool *ammtypes.Pool, pool *margintypes.Pool, eta math.LegacyDec, baseCurrency string)) *OpenShortChecker_Borrow_Call { +func (_c *OpenShortChecker_Borrow_Call) Run(run func(ctx types.Context, collateralAmount math.Int, custodyAmount math.Int, mtp *margintypes.MTP, ammPool *ammtypes.Pool, pool *margintypes.Pool, eta math.LegacyDec, baseCurrency string)) *OpenShortChecker_Borrow_Call { _c.Call.Run(func(args mock.Arguments) { - run(args[0].(types.Context), args[1].(string), args[2].(string), args[3].(math.Int), args[4].(math.Int), args[5].(*margintypes.MTP), args[6].(*ammtypes.Pool), args[7].(*margintypes.Pool), args[8].(math.LegacyDec), args[9].(string)) + run(args[0].(types.Context), args[1].(math.Int), args[2].(math.Int), args[3].(*margintypes.MTP), args[4].(*ammtypes.Pool), args[5].(*margintypes.Pool), args[6].(math.LegacyDec), args[7].(string)) }) return _c } @@ -72,7 +70,7 @@ func (_c *OpenShortChecker_Borrow_Call) Return(_a0 error) *OpenShortChecker_Borr return _c } -func (_c *OpenShortChecker_Borrow_Call) RunAndReturn(run func(types.Context, string, string, math.Int, math.Int, *margintypes.MTP, *ammtypes.Pool, *margintypes.Pool, math.LegacyDec, string) error) *OpenShortChecker_Borrow_Call { +func (_c *OpenShortChecker_Borrow_Call) RunAndReturn(run func(types.Context, math.Int, math.Int, *margintypes.MTP, *ammtypes.Pool, *margintypes.Pool, math.LegacyDec, string) error) *OpenShortChecker_Borrow_Call { _c.Call.Return(run) return _c } @@ -121,13 +119,13 @@ func (_c *OpenShortChecker_CalcMTPConsolidateCollateral_Call) RunAndReturn(run f return _c } -// CheckMinLiabilities provides a mock function with given fields: ctx, collateralTokenAmt, eta, pool, ammPool, borrowAsset -func (_m *OpenShortChecker) CheckMinLiabilities(ctx types.Context, collateralTokenAmt types.Coin, eta math.LegacyDec, pool margintypes.Pool, ammPool ammtypes.Pool, borrowAsset string) error { - ret := _m.Called(ctx, collateralTokenAmt, eta, pool, ammPool, borrowAsset) +// CheckMinLiabilities provides a mock function with given fields: ctx, collateralTokenAmt, eta, ammPool, borrowAsset, baseCurrency +func (_m *OpenShortChecker) CheckMinLiabilities(ctx types.Context, collateralTokenAmt types.Coin, eta math.LegacyDec, ammPool ammtypes.Pool, borrowAsset string, baseCurrency string) error { + ret := _m.Called(ctx, collateralTokenAmt, eta, ammPool, borrowAsset, baseCurrency) var r0 error - if rf, ok := ret.Get(0).(func(types.Context, types.Coin, math.LegacyDec, margintypes.Pool, ammtypes.Pool, string) error); ok { - r0 = rf(ctx, collateralTokenAmt, eta, pool, ammPool, borrowAsset) + if rf, ok := ret.Get(0).(func(types.Context, types.Coin, math.LegacyDec, ammtypes.Pool, string, string) error); ok { + r0 = rf(ctx, collateralTokenAmt, eta, ammPool, borrowAsset, baseCurrency) } else { r0 = ret.Error(0) } @@ -144,16 +142,16 @@ type OpenShortChecker_CheckMinLiabilities_Call struct { // - ctx types.Context // - collateralTokenAmt types.Coin // - eta math.LegacyDec -// - pool margintypes.Pool // - ammPool ammtypes.Pool // - borrowAsset string -func (_e *OpenShortChecker_Expecter) CheckMinLiabilities(ctx interface{}, collateralTokenAmt interface{}, eta interface{}, pool interface{}, ammPool interface{}, borrowAsset interface{}) *OpenShortChecker_CheckMinLiabilities_Call { - return &OpenShortChecker_CheckMinLiabilities_Call{Call: _e.mock.On("CheckMinLiabilities", ctx, collateralTokenAmt, eta, pool, ammPool, borrowAsset)} +// - baseCurrency string +func (_e *OpenShortChecker_Expecter) CheckMinLiabilities(ctx interface{}, collateralTokenAmt interface{}, eta interface{}, ammPool interface{}, borrowAsset interface{}, baseCurrency interface{}) *OpenShortChecker_CheckMinLiabilities_Call { + return &OpenShortChecker_CheckMinLiabilities_Call{Call: _e.mock.On("CheckMinLiabilities", ctx, collateralTokenAmt, eta, ammPool, borrowAsset, baseCurrency)} } -func (_c *OpenShortChecker_CheckMinLiabilities_Call) Run(run func(ctx types.Context, collateralTokenAmt types.Coin, eta math.LegacyDec, pool margintypes.Pool, ammPool ammtypes.Pool, borrowAsset string)) *OpenShortChecker_CheckMinLiabilities_Call { +func (_c *OpenShortChecker_CheckMinLiabilities_Call) Run(run func(ctx types.Context, collateralTokenAmt types.Coin, eta math.LegacyDec, ammPool ammtypes.Pool, borrowAsset string, baseCurrency string)) *OpenShortChecker_CheckMinLiabilities_Call { _c.Call.Run(func(args mock.Arguments) { - run(args[0].(types.Context), args[1].(types.Coin), args[2].(math.LegacyDec), args[3].(margintypes.Pool), args[4].(ammtypes.Pool), args[5].(string)) + run(args[0].(types.Context), args[1].(types.Coin), args[2].(math.LegacyDec), args[3].(ammtypes.Pool), args[4].(string), args[5].(string)) }) return _c } @@ -163,7 +161,7 @@ func (_c *OpenShortChecker_CheckMinLiabilities_Call) Return(_a0 error) *OpenShor return _c } -func (_c *OpenShortChecker_CheckMinLiabilities_Call) RunAndReturn(run func(types.Context, types.Coin, math.LegacyDec, margintypes.Pool, ammtypes.Pool, string) error) *OpenShortChecker_CheckMinLiabilities_Call { +func (_c *OpenShortChecker_CheckMinLiabilities_Call) RunAndReturn(run func(types.Context, types.Coin, math.LegacyDec, ammtypes.Pool, string, string) error) *OpenShortChecker_CheckMinLiabilities_Call { _c.Call.Return(run) return _c } diff --git a/x/margin/types/msgs.go b/x/margin/types/msgs.go index eb1c0641a..e797bda8e 100644 --- a/x/margin/types/msgs.go +++ b/x/margin/types/msgs.go @@ -23,7 +23,7 @@ var ( _ sdk.Msg = &MsgDewhitelist{} ) -func NewMsgClose(creator string, id uint64, amount sdk.Coin) *MsgClose { +func NewMsgClose(creator string, id uint64, amount sdk.Int) *MsgClose { return &MsgClose{ Creator: creator, Id: id, @@ -60,15 +60,14 @@ func (msg *MsgClose) ValidateBasic() error { return nil } -func NewMsgOpen(creator string, collateralAsset string, collateralAmount sdk.Int, borrowAsset string, position Position, leverage sdk.Dec, takeProfitPrice sdk.Dec) *MsgOpen { +func NewMsgOpen(creator string, position Position, leverage sdk.Dec, tradingAsset string, collateral sdk.Coin, takeProfitPrice sdk.Dec) *MsgOpen { return &MsgOpen{ - Creator: creator, - CollateralAsset: collateralAsset, - CollateralAmount: collateralAmount, - BorrowAsset: borrowAsset, - Position: position, - Leverage: leverage, - TakeProfitPrice: takeProfitPrice, + Creator: creator, + Position: position, + Leverage: leverage, + TradingAsset: tradingAsset, + Collateral: collateral, + TakeProfitPrice: takeProfitPrice, } } diff --git a/x/margin/types/params.go b/x/margin/types/params.go index f03532676..e5a7ff4ac 100644 --- a/x/margin/types/params.go +++ b/x/margin/types/params.go @@ -41,6 +41,7 @@ var ( KeyFundingFeeMinRate = []byte("FundingFeeMinRate") KeyFundingFeeMaxRate = []byte("FundingFeeMaxRate") KeyFundingFeeCollectionAddress = []byte("FundingFeeCollectionAddress") + KeySwapFee = []byte("SwapFee") ) // ParamKeyTable the param key table for launch module @@ -51,6 +52,7 @@ func ParamKeyTable() paramtypes.KeyTable { // NewParams creates a new Params instance func NewParams() Params { return Params{ + SwapFee: sdk.NewDecWithPrec(1, 3), // 0.1% FundingFeeCollectionAddress: ZeroAddress, FundingFeeMinRate: sdk.NewDecWithPrec(-1, 3), // -0.1% FundingFeeMaxRate: sdk.NewDecWithPrec(1, 3), // 0.1% @@ -110,6 +112,7 @@ func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { paramtypes.NewParamSetPair(KeyFundingFeeMinRate, &p.FundingFeeMinRate, validateBorrowInterestRateMax), paramtypes.NewParamSetPair(KeyFundingFeeMaxRate, &p.FundingFeeMaxRate, validateBorrowInterestRateMax), paramtypes.NewParamSetPair(KeyFundingFeeCollectionAddress, &p.FundingFeeCollectionAddress, validateFundingFeeCollectionAddress), + paramtypes.NewParamSetPair(KeySwapFee, &p.SwapFee, validateSwapFee), } } @@ -187,6 +190,9 @@ func (p Params) Validate() error { if err := validateFundingFeeCollectionAddress(p.FundingFeeCollectionAddress); err != nil { return err } + if err := validateSwapFee(p.SwapFee); err != nil { + return err + } return nil } @@ -526,3 +532,18 @@ func validateFundingFeeCollectionAddress(i interface{}) error { return nil } + +func validateSwapFee(i interface{}) error { + v, ok := i.(sdk.Dec) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + if v.IsNil() { + return fmt.Errorf("swap fee must be not nil") + } + if v.IsNegative() { + return fmt.Errorf("swap fee must be positive: %s", v) + } + + return nil +} diff --git a/x/margin/types/params.pb.go b/x/margin/types/params.pb.go index ab9bbc71a..33745e4a0 100644 --- a/x/margin/types/params.pb.go +++ b/x/margin/types/params.pb.go @@ -50,6 +50,7 @@ type Params struct { FundingFeeMaxRate github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,22,opt,name=funding_fee_max_rate,json=fundingFeeMaxRate,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"funding_fee_max_rate"` FundingFeeMinRate github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,23,opt,name=funding_fee_min_rate,json=fundingFeeMinRate,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"funding_fee_min_rate"` FundingFeeCollectionAddress string `protobuf:"bytes,24,opt,name=funding_fee_collection_address,json=fundingFeeCollectionAddress,proto3" json:"funding_fee_collection_address,omitempty"` + SwapFee github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,25,opt,name=swap_fee,json=swapFee,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"swap_fee"` } func (m *Params) Reset() { *m = Params{} } @@ -147,56 +148,57 @@ func init() { func init() { proto.RegisterFile("elys/margin/params.proto", fileDescriptor_f427d3667a99d828) } var fileDescriptor_f427d3667a99d828 = []byte{ - // 776 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x96, 0x4f, 0x8f, 0x1b, 0x35, - 0x14, 0xc0, 0x33, 0xb4, 0x2c, 0xad, 0x93, 0xc2, 0xae, 0x93, 0x50, 0xab, 0x15, 0xc9, 0x82, 0x10, - 0xac, 0xb4, 0x34, 0x01, 0x7a, 0x40, 0xe2, 0x46, 0xd2, 0x5d, 0x54, 0x89, 0x55, 0xd3, 0xc0, 0x09, - 0x55, 0x58, 0xce, 0xcc, 0x9b, 0x19, 0x2b, 0x33, 0xf6, 0xc4, 0x76, 0x76, 0x93, 0x03, 0xdf, 0x01, - 0x6e, 0x48, 0x5c, 0xf8, 0x38, 0x3d, 0xf6, 0x88, 0x38, 0x54, 0x68, 0xf7, 0x8b, 0x20, 0x7b, 0x66, - 0x92, 0x74, 0xff, 0xc0, 0x6a, 0xd8, 0x53, 0x32, 0x7e, 0xf6, 0xef, 0xf7, 0x9e, 0xff, 0xc9, 0x88, - 0x40, 0xb2, 0xd4, 0xfd, 0x94, 0xa9, 0x88, 0x8b, 0x7e, 0xc6, 0x14, 0x4b, 0x75, 0x2f, 0x53, 0xd2, - 0x48, 0x5c, 0xb7, 0x91, 0x5e, 0x1e, 0x79, 0xd0, 0x8a, 0x64, 0x24, 0x5d, 0x7b, 0xdf, 0xfe, 0xcb, - 0xbb, 0x7c, 0xf4, 0xeb, 0x0e, 0xda, 0x1a, 0xb9, 0x31, 0xf8, 0x39, 0x6a, 0x24, 0x70, 0x0c, 0x8a, - 0x45, 0x40, 0x53, 0xb6, 0x20, 0xde, 0xae, 0xb7, 0x77, 0x77, 0xd0, 0x7b, 0xf9, 0xba, 0x5b, 0xfb, - 0xeb, 0x75, 0xf7, 0x93, 0x88, 0x9b, 0x78, 0x3e, 0xe9, 0xf9, 0x32, 0xed, 0xfb, 0x52, 0xa7, 0x52, - 0x17, 0x3f, 0x8f, 0x74, 0x30, 0xed, 0x9b, 0x65, 0x06, 0xba, 0xf7, 0x04, 0xfc, 0x71, 0xbd, 0x64, - 0x1c, 0xb1, 0x05, 0x8e, 0x10, 0x99, 0x48, 0xa5, 0xe4, 0x09, 0xe5, 0xc2, 0x80, 0x02, 0x6d, 0xa8, - 0x62, 0x26, 0xc7, 0xbf, 0x55, 0x09, 0xdf, 0xce, 0x79, 0x4f, 0x0b, 0xdc, 0x98, 0x99, 0x7f, 0x17, - 0x71, 0x41, 0x6e, 0xdd, 0x98, 0x88, 0x0b, 0x3c, 0x43, 0x1f, 0x5c, 0x2a, 0xe2, 0xc2, 0x57, 0xc0, - 0x34, 0x90, 0xdb, 0x95, 0x6c, 0x0f, 0x2e, 0xda, 0x9e, 0x16, 0xc4, 0x2b, 0x95, 0x01, 0x14, 0xca, - 0xb7, 0x6f, 0x4a, 0xf9, 0xa4, 0x20, 0xe2, 0x17, 0x08, 0xc7, 0xc0, 0x12, 0x13, 0xd3, 0x88, 0x71, - 0x41, 0x43, 0xe6, 0x1b, 0xa9, 0xc8, 0x56, 0x25, 0xcf, 0x76, 0x4e, 0xfa, 0x96, 0x71, 0x71, 0xe8, - 0x38, 0xf8, 0x43, 0xd4, 0x80, 0x4c, 0xfa, 0x31, 0x4d, 0x40, 0x44, 0x26, 0x26, 0xef, 0xec, 0x7a, - 0x7b, 0xb7, 0xc6, 0x75, 0xd7, 0xf6, 0x9d, 0x6b, 0xc2, 0x21, 0xba, 0xaf, 0x20, 0x95, 0xc7, 0x2c, - 0xa1, 0xb3, 0x39, 0xcc, 0x81, 0x9a, 0x58, 0x81, 0x8e, 0x65, 0x12, 0x90, 0x3b, 0xd5, 0x96, 0xb3, - 0xc0, 0x3d, 0xb7, 0xb4, 0x1f, 0x4a, 0x18, 0xfe, 0x0c, 0xe1, 0x94, 0x2d, 0xa8, 0xcc, 0x40, 0xd0, - 0x4c, 0x6a, 0x6e, 0xb8, 0x14, 0x9a, 0xdc, 0x75, 0x09, 0x6d, 0xa7, 0x6c, 0xf1, 0x2c, 0x03, 0x31, - 0x2a, 0xdb, 0xf1, 0x4f, 0xa8, 0x99, 0x49, 0x99, 0xe4, 0xdd, 0xd7, 0x19, 0xa1, 0x4a, 0x19, 0xed, - 0x58, 0x94, 0xe5, 0xaf, 0xb3, 0x49, 0xd1, 0xc3, 0x50, 0x2a, 0x1f, 0xa8, 0x9f, 0x48, 0x0d, 0x34, - 0x9c, 0x8b, 0x80, 0x66, 0xa0, 0x7c, 0x10, 0x86, 0x45, 0x40, 0xea, 0x95, 0x3c, 0xc4, 0x21, 0x87, - 0x96, 0x78, 0x38, 0x17, 0xc1, 0x68, 0xc5, 0xc3, 0x5f, 0x21, 0x72, 0x41, 0xc7, 0x82, 0x40, 0x81, - 0xd6, 0xa4, 0x61, 0x5d, 0xe3, 0xf6, 0x9b, 0x63, 0xbf, 0xc9, 0x83, 0xf8, 0x77, 0x0f, 0x3d, 0x76, - 0x1b, 0x3e, 0xb5, 0xa4, 0x84, 0x9e, 0xdf, 0x9e, 0x19, 0x5b, 0xda, 0xc8, 0x85, 0x02, 0xee, 0x55, - 0x2a, 0xa0, 0xb7, 0xa1, 0x1a, 0xbc, 0xb1, 0x67, 0x47, 0xb9, 0xe7, 0x5c, 0x59, 0x80, 0x3e, 0xbf, - 0x76, 0x72, 0x65, 0xb9, 0xef, 0xba, 0x72, 0xf7, 0xaf, 0x63, 0x2a, 0x27, 0xe1, 0x19, 0xaa, 0xeb, - 0x19, 0x4d, 0x65, 0xc0, 0x43, 0x0e, 0x8a, 0xbc, 0x57, 0xa9, 0x36, 0xa4, 0x67, 0x47, 0x05, 0x01, - 0x7f, 0x8f, 0xee, 0x69, 0x16, 0x82, 0x59, 0x96, 0xe7, 0x6d, 0xbb, 0x12, 0xb2, 0x91, 0x43, 0x8a, - 0xb3, 0xf6, 0x02, 0xed, 0x5f, 0x67, 0x32, 0x40, 0xb0, 0x49, 0x02, 0x01, 0xd9, 0xd9, 0xf5, 0xf6, - 0xee, 0x8c, 0x3f, 0xfd, 0xaf, 0x79, 0x38, 0xc8, 0xbb, 0xe3, 0x2f, 0x50, 0xeb, 0x24, 0xe6, 0x06, - 0x12, 0xae, 0x0d, 0x17, 0xd1, 0x0a, 0x83, 0x1d, 0xa6, 0xb9, 0x19, 0x2b, 0x87, 0x7c, 0x89, 0xda, - 0x5c, 0x1c, 0x33, 0xc5, 0x99, 0x30, 0xd4, 0x8f, 0xc1, 0x9f, 0x52, 0x77, 0xf0, 0x49, 0xd3, 0x2d, - 0x41, 0x73, 0x15, 0x1c, 0xda, 0xd8, 0x81, 0x0d, 0xe1, 0x9f, 0xd1, 0xc7, 0x86, 0x4d, 0x81, 0x66, - 0x4a, 0x86, 0xdc, 0xd0, 0x2b, 0x6f, 0xfa, 0x56, 0xa5, 0x09, 0xeb, 0x5a, 0xf6, 0xc8, 0xa1, 0x07, - 0x97, 0xde, 0xf9, 0x0c, 0xb5, 0xed, 0x66, 0xb1, 0x05, 0x86, 0x00, 0x74, 0xc2, 0x34, 0x38, 0x27, - 0x69, 0x57, 0xf2, 0xe1, 0x02, 0x76, 0x08, 0x30, 0x60, 0x1a, 0xac, 0x05, 0x53, 0xd4, 0xda, 0x54, - 0xd8, 0x3b, 0xc9, 0x19, 0xde, 0xaf, 0x76, 0xb5, 0xac, 0x0d, 0x47, 0x6c, 0x71, 0xa9, 0x80, 0x8b, - 0x5c, 0x70, 0xff, 0x7f, 0x0b, 0xb8, 0x70, 0x82, 0x21, 0xea, 0x6c, 0x0a, 0x7c, 0x99, 0x24, 0xe0, - 0xdb, 0x6b, 0x73, 0x75, 0xc6, 0x88, 0x5b, 0xe0, 0x87, 0xeb, 0xa1, 0xc3, 0x55, 0x9f, 0xe2, 0x4c, - 0x7d, 0x7d, 0xfb, 0xb7, 0x3f, 0xba, 0xb5, 0xc1, 0xc1, 0xcb, 0xd3, 0x8e, 0xf7, 0xea, 0xb4, 0xe3, - 0xfd, 0x7d, 0xda, 0xf1, 0x7e, 0x39, 0xeb, 0xd4, 0x5e, 0x9d, 0x75, 0x6a, 0x7f, 0x9e, 0x75, 0x6a, - 0x3f, 0xee, 0x6f, 0xe4, 0x67, 0xdf, 0x36, 0x8f, 0x04, 0x98, 0x13, 0xa9, 0xa6, 0xee, 0xa3, 0xbf, - 0x28, 0x1f, 0x41, 0x2e, 0xd1, 0xc9, 0x96, 0x7b, 0xe1, 0x3c, 0xfe, 0x27, 0x00, 0x00, 0xff, 0xff, - 0xd0, 0xf4, 0xd8, 0x3d, 0x20, 0x09, 0x00, 0x00, + // 792 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x96, 0x4f, 0x6f, 0x1b, 0x45, + 0x14, 0xc0, 0xbd, 0xb4, 0xa4, 0xe9, 0x38, 0x85, 0x64, 0x62, 0xd3, 0xa1, 0x15, 0x76, 0x40, 0x08, + 0x22, 0x85, 0xda, 0x40, 0x0f, 0x48, 0xdc, 0xb0, 0x1b, 0xa3, 0x48, 0x44, 0x75, 0x0d, 0x27, 0x54, + 0x31, 0x1a, 0xef, 0xbe, 0xdd, 0x1d, 0x79, 0x77, 0x66, 0x3d, 0x33, 0x8e, 0xed, 0x03, 0xdf, 0x81, + 0x23, 0x12, 0x17, 0x3e, 0x4e, 0x8f, 0x3d, 0x22, 0x84, 0x2a, 0x94, 0x7c, 0x11, 0x34, 0xb3, 0xbb, + 0xb6, 0xdb, 0xa4, 0x10, 0x2d, 0x3d, 0xd9, 0x3b, 0x6f, 0xe6, 0xf7, 0x7b, 0x6f, 0xfe, 0x69, 0x10, + 0x81, 0x64, 0xa9, 0xbb, 0x29, 0x53, 0x11, 0x17, 0xdd, 0x8c, 0x29, 0x96, 0xea, 0x4e, 0xa6, 0xa4, + 0x91, 0xb8, 0x6e, 0x23, 0x9d, 0x3c, 0x72, 0xaf, 0x11, 0xc9, 0x48, 0xba, 0xf6, 0xae, 0xfd, 0x97, + 0x77, 0xf9, 0xe8, 0xaf, 0x3d, 0xb4, 0x35, 0x74, 0x63, 0xf0, 0x13, 0xb4, 0x93, 0xc0, 0x19, 0x28, + 0x16, 0x01, 0x4d, 0xd9, 0x82, 0x78, 0x07, 0xde, 0xe1, 0xed, 0x5e, 0xe7, 0xd9, 0x8b, 0x76, 0xed, + 0xcf, 0x17, 0xed, 0x4f, 0x22, 0x6e, 0xe2, 0xd9, 0xb8, 0xe3, 0xcb, 0xb4, 0xeb, 0x4b, 0x9d, 0x4a, + 0x5d, 0xfc, 0x3c, 0xd0, 0xc1, 0xa4, 0x6b, 0x96, 0x19, 0xe8, 0xce, 0x23, 0xf0, 0x47, 0xf5, 0x92, + 0x71, 0xca, 0x16, 0x38, 0x42, 0x64, 0x2c, 0x95, 0x92, 0x73, 0xca, 0x85, 0x01, 0x05, 0xda, 0x50, + 0xc5, 0x4c, 0x8e, 0x7f, 0xab, 0x12, 0xbe, 0x99, 0xf3, 0x4e, 0x0a, 0xdc, 0x88, 0x99, 0x7f, 0x17, + 0x71, 0x41, 0x6e, 0xbc, 0x31, 0x11, 0x17, 0x78, 0x8a, 0x3e, 0xb8, 0x52, 0xc4, 0x85, 0xaf, 0x80, + 0x69, 0x20, 0x37, 0x2b, 0xd9, 0xee, 0x5d, 0xb6, 0x9d, 0x14, 0xc4, 0xd7, 0x2a, 0x03, 0x28, 0x94, + 0x6f, 0xbf, 0x29, 0xe5, 0xa3, 0x82, 0x88, 0x9f, 0x22, 0x1c, 0x03, 0x4b, 0x4c, 0x4c, 0x23, 0xc6, + 0x05, 0x0d, 0x99, 0x6f, 0xa4, 0x22, 0x5b, 0x95, 0x3c, 0xbb, 0x39, 0xe9, 0x5b, 0xc6, 0xc5, 0xc0, + 0x71, 0xf0, 0x87, 0x68, 0x07, 0x32, 0xe9, 0xc7, 0x34, 0x01, 0x11, 0x99, 0x98, 0xdc, 0x3a, 0xf0, + 0x0e, 0x6f, 0x8c, 0xea, 0xae, 0xed, 0x3b, 0xd7, 0x84, 0x43, 0x74, 0x57, 0x41, 0x2a, 0xcf, 0x58, + 0x42, 0xa7, 0x33, 0x98, 0x01, 0x35, 0xb1, 0x02, 0x1d, 0xcb, 0x24, 0x20, 0xdb, 0xd5, 0x96, 0xb3, + 0xc0, 0x3d, 0xb1, 0xb4, 0x1f, 0x4a, 0x18, 0xfe, 0x0c, 0xe1, 0x94, 0x2d, 0xa8, 0xcc, 0x40, 0xd0, + 0x4c, 0x6a, 0x6e, 0xb8, 0x14, 0x9a, 0xdc, 0x76, 0x09, 0xed, 0xa6, 0x6c, 0xf1, 0x38, 0x03, 0x31, + 0x2c, 0xdb, 0xf1, 0x4f, 0x68, 0x3f, 0x93, 0x32, 0xc9, 0xbb, 0xaf, 0x33, 0x42, 0x95, 0x32, 0xda, + 0xb3, 0x28, 0xcb, 0x5f, 0x67, 0x93, 0xa2, 0xfb, 0xa1, 0x54, 0x3e, 0x50, 0x3f, 0x91, 0x1a, 0x68, + 0x38, 0x13, 0x01, 0xcd, 0x40, 0xf9, 0x20, 0x0c, 0x8b, 0x80, 0xd4, 0x2b, 0x79, 0x88, 0x43, 0xf6, + 0x2d, 0x71, 0x30, 0x13, 0xc1, 0x70, 0xc5, 0xc3, 0x5f, 0x21, 0x72, 0x49, 0xc7, 0x82, 0x40, 0x81, + 0xd6, 0x64, 0xc7, 0xba, 0x46, 0xcd, 0x97, 0xc7, 0x7e, 0x93, 0x07, 0xf1, 0x6f, 0x1e, 0x7a, 0xe8, + 0x36, 0x7c, 0x6a, 0x49, 0x09, 0x7d, 0x75, 0x7b, 0x66, 0x6c, 0x69, 0x23, 0x97, 0x0a, 0xb8, 0x53, + 0xa9, 0x80, 0xce, 0x86, 0xaa, 0xf7, 0xd2, 0x9e, 0x1d, 0xe6, 0x9e, 0x57, 0xca, 0x02, 0xf4, 0xf9, + 0xb5, 0x93, 0x2b, 0xcb, 0x7d, 0xc7, 0x95, 0x7b, 0x74, 0x1d, 0x53, 0x39, 0x09, 0x8f, 0x51, 0x5d, + 0x4f, 0x69, 0x2a, 0x03, 0x1e, 0x72, 0x50, 0xe4, 0xdd, 0x4a, 0xb5, 0x21, 0x3d, 0x3d, 0x2d, 0x08, + 0xf8, 0x7b, 0x74, 0x47, 0xb3, 0x10, 0xcc, 0xb2, 0x3c, 0x6f, 0xbb, 0x95, 0x90, 0x3b, 0x39, 0xa4, + 0x38, 0x6b, 0x4f, 0xd1, 0xd1, 0x75, 0x26, 0x03, 0x04, 0x1b, 0x27, 0x10, 0x90, 0xbd, 0x03, 0xef, + 0x70, 0x7b, 0xf4, 0xe9, 0x7f, 0xcd, 0xc3, 0x71, 0xde, 0x1d, 0x7f, 0x81, 0x1a, 0xf3, 0x98, 0x1b, + 0x48, 0xb8, 0x36, 0x5c, 0x44, 0x2b, 0x0c, 0x76, 0x98, 0xfd, 0xcd, 0x58, 0x39, 0xe4, 0x4b, 0xd4, + 0xe4, 0xe2, 0x8c, 0x29, 0xce, 0x84, 0xa1, 0x7e, 0x0c, 0xfe, 0x84, 0xba, 0x83, 0x4f, 0xf6, 0xdd, + 0x12, 0xec, 0xaf, 0x82, 0x7d, 0x1b, 0x3b, 0xb6, 0x21, 0xfc, 0x33, 0xfa, 0xd8, 0xb0, 0x09, 0xd0, + 0x4c, 0xc9, 0x90, 0x1b, 0xfa, 0xda, 0x9b, 0xbe, 0x51, 0x69, 0xc2, 0xda, 0x96, 0x3d, 0x74, 0xe8, + 0xde, 0x95, 0x77, 0x3e, 0x43, 0x4d, 0xbb, 0x59, 0x6c, 0x81, 0x21, 0x00, 0x1d, 0x33, 0x0d, 0xce, + 0x49, 0x9a, 0x95, 0x7c, 0xb8, 0x80, 0x0d, 0x00, 0x7a, 0x4c, 0x83, 0xb5, 0x60, 0x8a, 0x1a, 0x9b, + 0x0a, 0x7b, 0x27, 0x39, 0xc3, 0x7b, 0xd5, 0xae, 0x96, 0xb5, 0xe1, 0x94, 0x2d, 0xae, 0x14, 0x70, + 0x91, 0x0b, 0xee, 0xfe, 0x6f, 0x01, 0x17, 0x4e, 0xd0, 0x47, 0xad, 0x4d, 0x81, 0x2f, 0x93, 0x04, + 0x7c, 0x7b, 0x6d, 0xae, 0xce, 0x18, 0x71, 0x0b, 0x7c, 0x7f, 0x3d, 0xb4, 0xbf, 0xea, 0x53, 0x9e, + 0xa9, 0x13, 0xb4, 0xad, 0xe7, 0x2c, 0xb3, 0x04, 0xf2, 0x7e, 0xa5, 0xcc, 0x6e, 0xd9, 0xf1, 0x03, + 0x80, 0xaf, 0x6f, 0xfe, 0xfa, 0x7b, 0xbb, 0xd6, 0x3b, 0x7e, 0x76, 0xde, 0xf2, 0x9e, 0x9f, 0xb7, + 0xbc, 0xbf, 0xcf, 0x5b, 0xde, 0x2f, 0x17, 0xad, 0xda, 0xf3, 0x8b, 0x56, 0xed, 0x8f, 0x8b, 0x56, + 0xed, 0xc7, 0xa3, 0x0d, 0xa0, 0x7d, 0x26, 0x3d, 0x10, 0x60, 0xe6, 0x52, 0x4d, 0xdc, 0x47, 0x77, + 0x51, 0xbe, 0xa7, 0x1c, 0x79, 0xbc, 0xe5, 0x1e, 0x4b, 0x0f, 0xff, 0x09, 0x00, 0x00, 0xff, 0xff, + 0x8c, 0xdf, 0x43, 0xf2, 0x6b, 0x09, 0x00, 0x00, } func (m *Params) Marshal() (dAtA []byte, err error) { @@ -219,6 +221,18 @@ func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + { + size := m.SwapFee.Size() + i -= size + if _, err := m.SwapFee.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintParams(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0xca if len(m.FundingFeeCollectionAddress) > 0 { i -= len(m.FundingFeeCollectionAddress) copy(dAtA[i:], m.FundingFeeCollectionAddress) @@ -535,6 +549,8 @@ func (m *Params) Size() (n int) { if l > 0 { n += 2 + l + sovParams(uint64(l)) } + l = m.SwapFee.Size() + n += 2 + l + sovParams(uint64(l)) return n } @@ -1323,6 +1339,40 @@ func (m *Params) Unmarshal(dAtA []byte) error { } m.FundingFeeCollectionAddress = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex + case 25: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SwapFee", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + 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 ErrInvalidLengthParams + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthParams + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.SwapFee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipParams(dAtA[iNdEx:]) diff --git a/x/margin/types/pool.go b/x/margin/types/pool.go index 458f8551c..55457ee5e 100644 --- a/x/margin/types/pool.go +++ b/x/margin/types/pool.go @@ -29,111 +29,111 @@ func (p *Pool) GetPoolAssets(position Position) *[]PoolAsset { } } -// Update the asset balance -func (p *Pool) UpdateBalance(ctx sdk.Context, assetDenom string, amount sdk.Int, isIncrease bool, position Position) error { +// Get relevant pool asset based on position direction and asset denom +func (p *Pool) GetPoolAsset(position Position, assetDenom string) *PoolAsset { poolAssets := p.GetPoolAssets(position) for i, asset := range *poolAssets { if asset.AssetDenom == assetDenom { - if isIncrease { - (*poolAssets)[i].AssetBalance = asset.AssetBalance.Add(amount) - } else { - (*poolAssets)[i].AssetBalance = asset.AssetBalance.Sub(amount) - } - - return nil + return &(*poolAssets)[i] } } + return nil +} - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "invalid asset denom") +// Update the asset balance +func (p *Pool) UpdateBalance(ctx sdk.Context, assetDenom string, amount sdk.Int, isIncrease bool, position Position) error { + poolAsset := p.GetPoolAsset(position, assetDenom) + if poolAsset == nil { + return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "invalid asset denom") + } + + if isIncrease { + poolAsset.AssetBalance = poolAsset.AssetBalance.Add(amount) + } else { + poolAsset.AssetBalance = poolAsset.AssetBalance.Sub(amount) + } + + return nil } // Update the asset liabilities func (p *Pool) UpdateLiabilities(ctx sdk.Context, assetDenom string, amount sdk.Int, isIncrease bool, position Position) error { - poolAssets := p.GetPoolAssets(position) - for i, asset := range *poolAssets { - if asset.AssetDenom == assetDenom { - if isIncrease { - (*poolAssets)[i].Liabilities = asset.Liabilities.Add(amount) - } else { - (*poolAssets)[i].Liabilities = asset.Liabilities.Sub(amount) - } + poolAsset := p.GetPoolAsset(position, assetDenom) + if poolAsset == nil { + return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "invalid asset denom") + } - return nil - } + if isIncrease { + poolAsset.Liabilities = poolAsset.Liabilities.Add(amount) + } else { + poolAsset.Liabilities = poolAsset.Liabilities.Sub(amount) } - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "invalid asset denom") + return nil } // Update the asset take profit liabilities func (p *Pool) UpdateTakeProfitLiabilities(ctx sdk.Context, assetDenom string, amount sdk.Int, isIncrease bool, position Position) error { - poolAssets := p.GetPoolAssets(position) - for i, asset := range *poolAssets { - if asset.AssetDenom == assetDenom { - if isIncrease { - (*poolAssets)[i].TakeProfitLiabilities = asset.TakeProfitLiabilities.Add(amount) - } else { - (*poolAssets)[i].TakeProfitLiabilities = asset.TakeProfitLiabilities.Sub(amount) - } + poolAsset := p.GetPoolAsset(position, assetDenom) + if poolAsset == nil { + return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "invalid asset denom") + } - return nil - } + if isIncrease { + poolAsset.TakeProfitLiabilities = poolAsset.TakeProfitLiabilities.Add(amount) + } else { + poolAsset.TakeProfitLiabilities = poolAsset.TakeProfitLiabilities.Sub(amount) } - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "invalid asset denom") + return nil } // Update the asset take profit custody func (p *Pool) UpdateTakeProfitCustody(ctx sdk.Context, assetDenom string, amount sdk.Int, isIncrease bool, position Position) error { - poolAssets := p.GetPoolAssets(position) - for i, asset := range *poolAssets { - if asset.AssetDenom == assetDenom { - if isIncrease { - (*poolAssets)[i].TakeProfitCustody = asset.TakeProfitCustody.Add(amount) - } else { - (*poolAssets)[i].TakeProfitCustody = asset.TakeProfitCustody.Sub(amount) - } + poolAsset := p.GetPoolAsset(position, assetDenom) + if poolAsset == nil { + return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "invalid asset denom") + } - return nil - } + if isIncrease { + poolAsset.TakeProfitCustody = poolAsset.TakeProfitCustody.Add(amount) + } else { + poolAsset.TakeProfitCustody = poolAsset.TakeProfitCustody.Sub(amount) } - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "invalid asset denom") + return nil } // Update the asset custody func (p *Pool) UpdateCustody(ctx sdk.Context, assetDenom string, amount sdk.Int, isIncrease bool, position Position) error { - poolAssets := p.GetPoolAssets(position) - for i, asset := range *poolAssets { - if asset.AssetDenom == assetDenom { - if isIncrease { - (*poolAssets)[i].Custody = asset.Custody.Add(amount) - } else { - (*poolAssets)[i].Custody = asset.Custody.Sub(amount) - } - return nil - } + poolAsset := p.GetPoolAsset(position, assetDenom) + if poolAsset == nil { + return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "invalid asset denom") + } + + if isIncrease { + poolAsset.Custody = poolAsset.Custody.Add(amount) + } else { + poolAsset.Custody = poolAsset.Custody.Sub(amount) } - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "invalid asset denom") + return nil } // Update the unsettled liabilities balance func (p *Pool) UpdateBlockBorrowInterest(ctx sdk.Context, assetDenom string, amount sdk.Int, isIncrease bool, position Position) error { - poolAssets := p.GetPoolAssets(position) - for i, asset := range *poolAssets { - if asset.AssetDenom == assetDenom { - if isIncrease { - (*poolAssets)[i].BlockBorrowInterest = asset.BlockBorrowInterest.Add(amount) - } else { - (*poolAssets)[i].BlockBorrowInterest = asset.BlockBorrowInterest.Sub(amount) - } + poolAsset := p.GetPoolAsset(position, assetDenom) + if poolAsset == nil { + return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "invalid asset denom") + } - return nil - } + if isIncrease { + poolAsset.BlockBorrowInterest = poolAsset.BlockBorrowInterest.Add(amount) + } else { + poolAsset.BlockBorrowInterest = poolAsset.BlockBorrowInterest.Sub(amount) } - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "invalid asset denom") + return nil } // Initialite pool asset according to its corresponding amm pool assets. diff --git a/x/margin/types/query.pb.go b/x/margin/types/query.pb.go index b4b525905..b33f7f579 100644 --- a/x/margin/types/query.pb.go +++ b/x/margin/types/query.pb.go @@ -6,6 +6,8 @@ package types import ( context "context" fmt "fmt" + github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" + types "github.com/cosmos/cosmos-sdk/types" query "github.com/cosmos/cosmos-sdk/types/query" _ "github.com/cosmos/gogoproto/gogoproto" grpc1 "github.com/cosmos/gogoproto/grpc" @@ -977,6 +979,168 @@ func (m *MTPResponse) GetMtp() *MTP { return nil } +type QueryOpenEstimationRequest struct { + Position Position `protobuf:"varint,1,opt,name=position,proto3,enum=elys.margin.Position" json:"position,omitempty"` + Leverage github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=leverage,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"leverage"` + TradingAsset string `protobuf:"bytes,3,opt,name=trading_asset,json=tradingAsset,proto3" json:"trading_asset,omitempty"` + Collateral types.Coin `protobuf:"bytes,4,opt,name=collateral,proto3" json:"collateral"` + Discount github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=discount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"discount"` + TakeProfitPrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,6,opt,name=take_profit_price,json=takeProfitPrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"take_profit_price"` +} + +func (m *QueryOpenEstimationRequest) Reset() { *m = QueryOpenEstimationRequest{} } +func (m *QueryOpenEstimationRequest) String() string { return proto.CompactTextString(m) } +func (*QueryOpenEstimationRequest) ProtoMessage() {} +func (*QueryOpenEstimationRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_1668b4919d9577d0, []int{20} +} +func (m *QueryOpenEstimationRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryOpenEstimationRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryOpenEstimationRequest.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 *QueryOpenEstimationRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryOpenEstimationRequest.Merge(m, src) +} +func (m *QueryOpenEstimationRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryOpenEstimationRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryOpenEstimationRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryOpenEstimationRequest proto.InternalMessageInfo + +func (m *QueryOpenEstimationRequest) GetPosition() Position { + if m != nil { + return m.Position + } + return Position_UNSPECIFIED +} + +func (m *QueryOpenEstimationRequest) GetTradingAsset() string { + if m != nil { + return m.TradingAsset + } + return "" +} + +func (m *QueryOpenEstimationRequest) GetCollateral() types.Coin { + if m != nil { + return m.Collateral + } + return types.Coin{} +} + +type QueryOpenEstimationResponse struct { + Position Position `protobuf:"varint,1,opt,name=position,proto3,enum=elys.margin.Position" json:"position,omitempty"` + Leverage github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=leverage,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"leverage"` + TradingAsset string `protobuf:"bytes,3,opt,name=trading_asset,json=tradingAsset,proto3" json:"trading_asset,omitempty"` + Collateral types.Coin `protobuf:"bytes,4,opt,name=collateral,proto3" json:"collateral"` + MinCollateral types.Coin `protobuf:"bytes,5,opt,name=min_collateral,json=minCollateral,proto3" json:"min_collateral"` + ValidCollateral bool `protobuf:"varint,6,opt,name=valid_collateral,json=validCollateral,proto3" json:"valid_collateral,omitempty"` + PositionSize types.Coin `protobuf:"bytes,7,opt,name=position_size,json=positionSize,proto3" json:"position_size"` + SwapFee github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,8,opt,name=swap_fee,json=swapFee,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"swap_fee"` + Discount github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,9,opt,name=discount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"discount"` + OpenPrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,10,opt,name=open_price,json=openPrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"open_price"` + TakeProfitPrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,11,opt,name=take_profit_price,json=takeProfitPrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"take_profit_price"` + LiquidationPrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,12,opt,name=liquidation_price,json=liquidationPrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"liquidation_price"` + EstimatedPnl github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,13,opt,name=estimated_pnl,json=estimatedPnl,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"estimated_pnl"` + AvailableLiquidity types.Coin `protobuf:"bytes,14,opt,name=available_liquidity,json=availableLiquidity,proto3" json:"available_liquidity"` +} + +func (m *QueryOpenEstimationResponse) Reset() { *m = QueryOpenEstimationResponse{} } +func (m *QueryOpenEstimationResponse) String() string { return proto.CompactTextString(m) } +func (*QueryOpenEstimationResponse) ProtoMessage() {} +func (*QueryOpenEstimationResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_1668b4919d9577d0, []int{21} +} +func (m *QueryOpenEstimationResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryOpenEstimationResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryOpenEstimationResponse.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 *QueryOpenEstimationResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryOpenEstimationResponse.Merge(m, src) +} +func (m *QueryOpenEstimationResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryOpenEstimationResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryOpenEstimationResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryOpenEstimationResponse proto.InternalMessageInfo + +func (m *QueryOpenEstimationResponse) GetPosition() Position { + if m != nil { + return m.Position + } + return Position_UNSPECIFIED +} + +func (m *QueryOpenEstimationResponse) GetTradingAsset() string { + if m != nil { + return m.TradingAsset + } + return "" +} + +func (m *QueryOpenEstimationResponse) GetCollateral() types.Coin { + if m != nil { + return m.Collateral + } + return types.Coin{} +} + +func (m *QueryOpenEstimationResponse) GetMinCollateral() types.Coin { + if m != nil { + return m.MinCollateral + } + return types.Coin{} +} + +func (m *QueryOpenEstimationResponse) GetValidCollateral() bool { + if m != nil { + return m.ValidCollateral + } + return false +} + +func (m *QueryOpenEstimationResponse) GetPositionSize() types.Coin { + if m != nil { + return m.PositionSize + } + return types.Coin{} +} + +func (m *QueryOpenEstimationResponse) GetAvailableLiquidity() types.Coin { + if m != nil { + return m.AvailableLiquidity + } + return types.Coin{} +} + func init() { proto.RegisterType((*ParamsRequest)(nil), "elys.margin.ParamsRequest") proto.RegisterType((*ParamsResponse)(nil), "elys.margin.ParamsResponse") @@ -998,76 +1162,102 @@ func init() { proto.RegisterType((*QueryAllPoolResponse)(nil), "elys.margin.QueryAllPoolResponse") proto.RegisterType((*MTPRequest)(nil), "elys.margin.MTPRequest") proto.RegisterType((*MTPResponse)(nil), "elys.margin.MTPResponse") + proto.RegisterType((*QueryOpenEstimationRequest)(nil), "elys.margin.QueryOpenEstimationRequest") + proto.RegisterType((*QueryOpenEstimationResponse)(nil), "elys.margin.QueryOpenEstimationResponse") } func init() { proto.RegisterFile("elys/margin/query.proto", fileDescriptor_1668b4919d9577d0) } var fileDescriptor_1668b4919d9577d0 = []byte{ - // 1011 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x57, 0x4f, 0x6f, 0x1b, 0x45, - 0x14, 0xcf, 0x3a, 0x4e, 0xc0, 0xcf, 0x8d, 0x9b, 0x4c, 0x43, 0x12, 0x6d, 0x8b, 0x49, 0x97, 0xd2, - 0x5a, 0x4d, 0xbd, 0x5b, 0x87, 0xaa, 0x5c, 0xb8, 0x34, 0x51, 0x1b, 0xf5, 0x10, 0xc9, 0x98, 0x4a, - 0xa0, 0x48, 0xc8, 0x5a, 0x67, 0xa7, 0xee, 0x28, 0xbb, 0x3b, 0x5b, 0xef, 0x98, 0xd4, 0x44, 0x41, - 0xa8, 0x12, 0x52, 0x25, 0x7a, 0x40, 0xe2, 0x7b, 0xf0, 0x01, 0xf8, 0x04, 0x3d, 0x56, 0xe2, 0xc2, - 0x09, 0xa1, 0x84, 0x33, 0x9f, 0x01, 0xcd, 0xec, 0xec, 0x66, 0x67, 0x77, 0x63, 0x17, 0x64, 0x29, - 0x37, 0x7b, 0xde, 0x9b, 0xf7, 0xfb, 0xbd, 0x3f, 0xf3, 0x7b, 0x36, 0xac, 0x62, 0x77, 0x14, 0x5a, - 0x9e, 0x3d, 0xe8, 0x13, 0xdf, 0x7a, 0x3e, 0xc4, 0x83, 0x91, 0x19, 0x0c, 0x28, 0xa3, 0xa8, 0xca, - 0x0d, 0x66, 0x64, 0xd0, 0x97, 0xfb, 0xb4, 0x4f, 0xc5, 0xb9, 0xc5, 0x3f, 0x45, 0x2e, 0xfa, 0xb5, - 0x3e, 0xa5, 0x7d, 0x17, 0x5b, 0x76, 0x40, 0x2c, 0xdb, 0xf7, 0x29, 0xb3, 0x19, 0xa1, 0x7e, 0x28, - 0xad, 0xb7, 0xf7, 0x69, 0xe8, 0xd1, 0xd0, 0xea, 0xd9, 0x21, 0x8e, 0x22, 0x5b, 0xdf, 0xb6, 0x7a, - 0x98, 0xd9, 0x2d, 0x2b, 0xb0, 0xfb, 0xc4, 0x17, 0xce, 0xd2, 0x77, 0x2d, 0xcd, 0x22, 0xb0, 0x07, - 0xb6, 0x17, 0x47, 0x51, 0xf8, 0xb1, 0x51, 0x80, 0x63, 0xc3, 0x8a, 0x72, 0x85, 0x52, 0x37, 0x3a, - 0x37, 0x2e, 0xc3, 0x42, 0x5b, 0x04, 0xe8, 0xe0, 0xe7, 0x43, 0x1c, 0x32, 0x63, 0x1b, 0x6a, 0xf1, - 0x41, 0x18, 0x50, 0x3f, 0xc4, 0xa8, 0x05, 0xf3, 0x11, 0xc6, 0x9a, 0xb6, 0xae, 0x35, 0xaa, 0x9b, - 0x57, 0xcc, 0x54, 0xae, 0x66, 0xe4, 0xbc, 0x55, 0x7e, 0xf3, 0xe7, 0x47, 0x33, 0x1d, 0xe9, 0x68, - 0xec, 0xc1, 0x62, 0x9b, 0x86, 0x44, 0xe4, 0x27, 0x03, 0xa3, 0x47, 0x00, 0x67, 0x89, 0xc8, 0x50, - 0x37, 0xcd, 0x28, 0x6b, 0x93, 0x67, 0x6d, 0x46, 0xf5, 0x94, 0x59, 0x9b, 0x6d, 0xbb, 0x8f, 0xe5, - 0xdd, 0x4e, 0xea, 0xa6, 0xf1, 0x52, 0x83, 0xa5, 0x54, 0x70, 0x49, 0xf2, 0x06, 0x94, 0x3d, 0x16, - 0x70, 0x8a, 0xb3, 0x8d, 0xea, 0xe6, 0xa2, 0x42, 0x71, 0xf7, 0x49, 0xbb, 0x23, 0xac, 0x68, 0x47, - 0xe1, 0x50, 0x12, 0x1c, 0x6e, 0x4d, 0xe4, 0x10, 0x41, 0x28, 0x24, 0x7e, 0xd0, 0x60, 0x25, 0x21, - 0xb1, 0x35, 0x6a, 0x53, 0xea, 0xc6, 0x79, 0xd6, 0xa1, 0x6a, 0x7b, 0x5e, 0x97, 0xd7, 0xb8, 0x4b, - 0x1c, 0x91, 0x68, 0xb9, 0x53, 0xb1, 0x3d, 0x8f, 0x3b, 0x3d, 0x76, 0x32, 0x75, 0x28, 0xfd, 0xef, - 0x3a, 0xbc, 0xd2, 0x60, 0x35, 0x47, 0xe1, 0x62, 0xaa, 0x71, 0x19, 0x16, 0xbe, 0x64, 0x36, 0x1b, - 0x26, 0x43, 0xe4, 0x40, 0x2d, 0x3e, 0x48, 0x18, 0xd5, 0x68, 0x80, 0xfd, 0xae, 0xc7, 0x82, 0xee, - 0x3e, 0x1d, 0xfa, 0x4c, 0x16, 0xe6, 0x12, 0x3f, 0xdd, 0x65, 0xc1, 0x36, 0x3f, 0x43, 0x77, 0x00, - 0xb9, 0xe4, 0x29, 0x66, 0xc4, 0xc3, 0x29, 0xcf, 0x92, 0xf0, 0x5c, 0x8c, 0x2d, 0xb1, 0xb7, 0xf1, - 0x3d, 0xe8, 0x49, 0x01, 0x1e, 0xd1, 0xc1, 0x03, 0xc7, 0x19, 0xe0, 0x30, 0x99, 0xb7, 0x35, 0x78, - 0xcf, 0x8e, 0x4e, 0x04, 0x54, 0xa5, 0x13, 0x7f, 0x9d, 0x5a, 0x07, 0x5e, 0x6b, 0x70, 0xb5, 0x90, - 0xc0, 0xc5, 0x74, 0x61, 0x0f, 0x16, 0xbf, 0x7a, 0x46, 0x18, 0x76, 0x49, 0xc8, 0xa6, 0xfd, 0xe8, - 0xbe, 0x83, 0xa5, 0x54, 0x6c, 0x99, 0xdf, 0x35, 0xa8, 0x1c, 0xc6, 0x87, 0x22, 0xc9, 0x4a, 0xe7, - 0xec, 0x60, 0x7a, 0x79, 0xdd, 0x85, 0xe5, 0xc7, 0x61, 0x82, 0x8e, 0x9d, 0x89, 0x0d, 0x36, 0xbe, - 0x86, 0x0f, 0x32, 0x37, 0x24, 0xe3, 0xf3, 0x67, 0xe2, 0x13, 0xa8, 0x91, 0xb0, 0x7b, 0x78, 0x76, - 0x47, 0x30, 0x7e, 0xbf, 0xb3, 0x40, 0xd2, 0x81, 0x8c, 0x0d, 0xb8, 0xf2, 0x05, 0x67, 0xbd, 0x83, - 0x59, 0xfa, 0xcd, 0x2f, 0xc3, 0x1c, 0xf1, 0x1d, 0xfc, 0x42, 0x0e, 0x75, 0xf4, 0xc5, 0xd8, 0x86, - 0x65, 0xd5, 0x59, 0xb2, 0xd8, 0x80, 0x32, 0x57, 0x07, 0xd9, 0x8e, 0x25, 0x55, 0x4e, 0x29, 0x75, - 0xa5, 0x98, 0x0a, 0x27, 0xe3, 0x1b, 0x89, 0xf8, 0xc0, 0x75, 0xd3, 0x88, 0xd3, 0x6a, 0xec, 0x6b, - 0x4d, 0x92, 0x4c, 0xe2, 0xe7, 0x48, 0xce, 0x4e, 0x24, 0x39, 0xbd, 0x5e, 0xdf, 0x07, 0xe0, 0x2f, - 0x63, 0xe2, 0x13, 0xae, 0x41, 0x89, 0x38, 0x52, 0x18, 0x4a, 0xc4, 0x31, 0x5a, 0x50, 0x15, 0xf7, - 0x24, 0x79, 0x03, 0x66, 0x3d, 0x16, 0xc8, 0xb2, 0xe4, 0x1f, 0x1e, 0x37, 0x6e, 0xfe, 0x03, 0x30, - 0x27, 0x32, 0x47, 0x07, 0x30, 0x1f, 0x6d, 0x31, 0xa4, 0x17, 0xac, 0x36, 0x49, 0x46, 0xbf, 0x5a, - 0x68, 0x8b, 0x00, 0x8d, 0xc6, 0xcb, 0xdf, 0xff, 0xfe, 0xa5, 0x64, 0xa0, 0x75, 0x8b, 0x3b, 0x35, - 0x7d, 0xcc, 0x0e, 0xe9, 0xe0, 0xc0, 0xca, 0xef, 0x69, 0xf4, 0x93, 0x06, 0x97, 0xc4, 0x40, 0x48, - 0xdd, 0x40, 0x1f, 0x66, 0x4a, 0xab, 0xae, 0x4d, 0xbd, 0x7e, 0x9e, 0x59, 0x22, 0x7f, 0x2e, 0x90, - 0xef, 0xa3, 0x7b, 0x63, 0x90, 0xe3, 0x4b, 0xd6, 0x51, 0xea, 0xa7, 0xc4, 0x01, 0x1e, 0x1d, 0xa3, - 0x5f, 0x35, 0x40, 0x69, 0x36, 0xd1, 0x1e, 0x41, 0x1f, 0x17, 0x83, 0x2a, 0x8b, 0x4e, 0xbf, 0x31, - 0xde, 0x49, 0xf2, 0xdb, 0x15, 0xfc, 0x76, 0xd0, 0xc3, 0xf3, 0xf9, 0x71, 0x19, 0x6c, 0xf6, 0x46, - 0x4d, 0x3e, 0x4a, 0xd6, 0x51, 0x6a, 0x79, 0x1e, 0xe7, 0x09, 0xfb, 0x50, 0xd9, 0xc1, 0x2c, 0x5a, - 0x2e, 0x99, 0x76, 0x29, 0x2b, 0x28, 0xd3, 0x2e, 0x75, 0x1b, 0xbd, 0x4b, 0xbb, 0xc2, 0x08, 0xe2, - 0x37, 0x0d, 0x56, 0xd2, 0x05, 0x3a, 0x93, 0x79, 0x74, 0xab, 0x38, 0xff, 0xdc, 0x26, 0xd2, 0x1b, - 0x93, 0x1d, 0xff, 0x63, 0xb1, 0x9e, 0xd2, 0x41, 0x53, 0x3e, 0x05, 0xeb, 0x48, 0x7e, 0x28, 0x28, - 0x96, 0x9c, 0xb5, 0x44, 0xc0, 0x32, 0xb3, 0x96, 0xdd, 0x16, 0x99, 0x59, 0xcb, 0x09, 0xfe, 0xbb, - 0xcc, 0x5a, 0xa2, 0xa0, 0x79, 0x36, 0xaf, 0x34, 0x58, 0x50, 0x64, 0x19, 0x5d, 0x57, 0xf0, 0x8a, - 0x44, 0x5e, 0x37, 0xc6, 0xb9, 0x48, 0x5a, 0x77, 0x05, 0xad, 0xdb, 0xa8, 0x71, 0x3e, 0x2d, 0x12, - 0x36, 0x53, 0xda, 0x8e, 0x8e, 0xa0, 0x2c, 0xe6, 0x7c, 0x5d, 0x89, 0x5e, 0xa0, 0xec, 0xfa, 0xf5, - 0x31, 0x1e, 0x12, 0xde, 0x14, 0xf0, 0x0d, 0x74, 0x73, 0xdc, 0x0b, 0xe4, 0x93, 0x2d, 0xb6, 0xc2, - 0x31, 0xfa, 0x51, 0x83, 0x39, 0x1e, 0x20, 0x2c, 0x82, 0x57, 0x65, 0xbe, 0x08, 0x3e, 0x23, 0xd4, - 0xc6, 0x67, 0x02, 0xbe, 0x85, 0xac, 0x49, 0xf0, 0xf9, 0xa7, 0x34, 0xbb, 0xfb, 0xa4, 0x8d, 0x56, - 0x73, 0xf2, 0x28, 0xb1, 0xd7, 0xf2, 0x06, 0x09, 0x79, 0x4f, 0x40, 0x9a, 0xe8, 0xce, 0xd8, 0x31, - 0x4d, 0x4f, 0x26, 0x71, 0x8e, 0xb7, 0x1e, 0xbe, 0x39, 0xa9, 0x6b, 0x6f, 0x4f, 0xea, 0xda, 0x5f, - 0x27, 0x75, 0xed, 0xe7, 0xd3, 0xfa, 0xcc, 0xdb, 0xd3, 0xfa, 0xcc, 0x1f, 0xa7, 0xf5, 0x99, 0xbd, - 0x8d, 0x3e, 0x61, 0xcf, 0x86, 0x3d, 0x73, 0x9f, 0x7a, 0x05, 0x11, 0x5f, 0x28, 0xff, 0x67, 0x7a, - 0xf3, 0xe2, 0x8f, 0xcb, 0xa7, 0xff, 0x06, 0x00, 0x00, 0xff, 0xff, 0x18, 0x6f, 0x92, 0x21, 0x8b, - 0x0d, 0x00, 0x00, + // 1408 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe4, 0x58, 0xdf, 0x6e, 0x13, 0xc7, + 0x17, 0xce, 0xe6, 0x1f, 0xf1, 0x89, 0xed, 0x24, 0x43, 0x00, 0xff, 0x0c, 0x3f, 0x03, 0x0b, 0x85, + 0x40, 0xb0, 0x17, 0xa7, 0x88, 0xde, 0x54, 0xaa, 0x48, 0x20, 0x51, 0xaa, 0x46, 0x75, 0x0d, 0x52, + 0xab, 0x54, 0xd5, 0x6a, 0xe2, 0x9d, 0x98, 0x51, 0x76, 0x77, 0x96, 0xdd, 0x49, 0x82, 0x89, 0x52, + 0xb5, 0x48, 0x55, 0x91, 0xca, 0x45, 0xa5, 0x4a, 0x7d, 0x87, 0xde, 0xf4, 0x01, 0xfa, 0x04, 0x5c, + 0x22, 0xf5, 0xa6, 0xea, 0x05, 0xaa, 0xa0, 0x0f, 0x52, 0xcd, 0xec, 0xec, 0x66, 0xd7, 0xde, 0x38, + 0x21, 0x8d, 0xc4, 0x45, 0xaf, 0x6c, 0xcf, 0x9c, 0xf3, 0x7d, 0xdf, 0x9c, 0x73, 0x66, 0xe6, 0x8c, + 0xe1, 0x0c, 0xb1, 0x3b, 0x81, 0xe1, 0x60, 0xbf, 0x4d, 0x5d, 0xe3, 0xd1, 0x26, 0xf1, 0x3b, 0x35, + 0xcf, 0x67, 0x9c, 0xa1, 0x71, 0x31, 0x51, 0x0b, 0x27, 0xca, 0xd3, 0x6d, 0xd6, 0x66, 0x72, 0xdc, + 0x10, 0xdf, 0x42, 0x93, 0xf2, 0xb9, 0x36, 0x63, 0x6d, 0x9b, 0x18, 0xd8, 0xa3, 0x06, 0x76, 0x5d, + 0xc6, 0x31, 0xa7, 0xcc, 0x0d, 0xd4, 0xec, 0xf5, 0x16, 0x0b, 0x1c, 0x16, 0x18, 0x6b, 0x38, 0x20, + 0x21, 0xb2, 0xb1, 0x55, 0x5f, 0x23, 0x1c, 0xd7, 0x0d, 0x0f, 0xb7, 0xa9, 0x2b, 0x8d, 0x95, 0x6d, + 0x29, 0xa9, 0xc2, 0xc3, 0x3e, 0x76, 0x22, 0x94, 0x94, 0x3e, 0xde, 0xf1, 0x48, 0x34, 0x71, 0x3a, + 0xe5, 0xc2, 0x98, 0xad, 0xc6, 0x2b, 0x49, 0xda, 0x88, 0xb0, 0xc5, 0xa8, 0xa2, 0xd2, 0x27, 0xa0, + 0xd0, 0x90, 0x04, 0x4d, 0xf2, 0x68, 0x93, 0x04, 0x5c, 0x5f, 0x80, 0x62, 0x34, 0x10, 0x78, 0xcc, + 0x0d, 0x08, 0xaa, 0xc3, 0x68, 0xa8, 0xa1, 0xa4, 0x5d, 0xd0, 0x66, 0xc6, 0xe7, 0x4e, 0xd6, 0x12, + 0xb1, 0xa8, 0x85, 0xc6, 0xf3, 0xc3, 0x2f, 0x5e, 0x9d, 0x1f, 0x68, 0x2a, 0x43, 0x7d, 0x15, 0x26, + 0x1b, 0x2c, 0xa0, 0x72, 0xfd, 0x0a, 0x18, 0x2d, 0x02, 0xec, 0x2d, 0x54, 0x41, 0x5d, 0xa9, 0x85, + 0xf2, 0x6a, 0x42, 0x5e, 0x2d, 0x8c, 0xb7, 0x12, 0x59, 0x6b, 0xe0, 0x36, 0x51, 0xbe, 0xcd, 0x84, + 0xa7, 0xfe, 0x54, 0x83, 0xa9, 0x04, 0xb8, 0x12, 0x79, 0x19, 0x86, 0x1d, 0xee, 0x09, 0x89, 0x43, + 0x33, 0xe3, 0x73, 0x93, 0x29, 0x89, 0x2b, 0x0f, 0x1a, 0x4d, 0x39, 0x8b, 0x96, 0x52, 0x1a, 0x06, + 0xa5, 0x86, 0xab, 0x07, 0x6a, 0x08, 0x29, 0x52, 0x22, 0xbe, 0xd1, 0xe0, 0x74, 0x2c, 0x62, 0xbe, + 0xd3, 0x60, 0xcc, 0x8e, 0xd6, 0x59, 0x81, 0x71, 0xec, 0x38, 0xa6, 0xc8, 0x81, 0x49, 0x2d, 0xb9, + 0xd0, 0xe1, 0x66, 0x0e, 0x3b, 0x8e, 0x30, 0x5a, 0xb6, 0xba, 0xe2, 0x30, 0x78, 0xe4, 0x38, 0x3c, + 0xd3, 0xe0, 0x4c, 0x8f, 0x84, 0x77, 0x13, 0x8d, 0x09, 0x28, 0xdc, 0xe7, 0x98, 0x6f, 0xc6, 0x45, + 0x64, 0x41, 0x31, 0x1a, 0x88, 0x15, 0x15, 0x99, 0x47, 0x5c, 0xd3, 0xe1, 0x9e, 0xd9, 0x62, 0x9b, + 0x2e, 0x57, 0x81, 0xc9, 0x8b, 0xd1, 0x15, 0xee, 0x2d, 0x88, 0x31, 0x74, 0x03, 0x90, 0x4d, 0xd7, + 0x09, 0xa7, 0x0e, 0x49, 0x58, 0x0e, 0x4a, 0xcb, 0xc9, 0x68, 0x26, 0xb2, 0xd6, 0xbf, 0x86, 0x72, + 0x1c, 0x80, 0x45, 0xe6, 0xdf, 0xb1, 0x2c, 0x9f, 0x04, 0x71, 0xbd, 0x95, 0xe0, 0x04, 0x0e, 0x47, + 0x24, 0x55, 0xae, 0x19, 0xfd, 0x3c, 0xb6, 0x0c, 0x3c, 0xd7, 0xe0, 0x6c, 0xa6, 0x80, 0x77, 0x93, + 0x85, 0x55, 0x98, 0xfc, 0xfc, 0x21, 0xe5, 0xc4, 0xa6, 0x01, 0x3f, 0xee, 0x4d, 0xf7, 0x04, 0xa6, + 0x12, 0xd8, 0x6a, 0x7d, 0xe7, 0x20, 0xb7, 0x1d, 0x0d, 0xca, 0x45, 0xe6, 0x9a, 0x7b, 0x03, 0xc7, + 0xb7, 0xae, 0x9b, 0x30, 0xbd, 0x1c, 0xc4, 0xec, 0xc4, 0x3a, 0x30, 0xc1, 0xfa, 0x17, 0x70, 0xaa, + 0xcb, 0x43, 0x29, 0xde, 0xbf, 0x26, 0xde, 0x83, 0x22, 0x0d, 0xcc, 0xed, 0x3d, 0x1f, 0xa9, 0x78, + 0xac, 0x59, 0xa0, 0x49, 0x20, 0x7d, 0x16, 0x4e, 0x7e, 0x26, 0x54, 0x2f, 0x11, 0x9e, 0xdc, 0xf3, + 0xd3, 0x30, 0x42, 0x5d, 0x8b, 0x3c, 0x56, 0x45, 0x1d, 0xfe, 0xd0, 0x17, 0x60, 0x3a, 0x6d, 0xac, + 0x54, 0xcc, 0xc2, 0xb0, 0x38, 0x1d, 0x54, 0x3a, 0xa6, 0xd2, 0xc7, 0x29, 0x63, 0xb6, 0x3a, 0x4c, + 0xa5, 0x91, 0xfe, 0x95, 0x62, 0xbc, 0x63, 0xdb, 0x49, 0xc6, 0xe3, 0x4a, 0xec, 0x73, 0x4d, 0x89, + 0x8c, 0xf1, 0x7b, 0x44, 0x0e, 0x1d, 0x28, 0xf2, 0xf8, 0x72, 0x7d, 0x1b, 0x40, 0xec, 0x8c, 0x03, + 0xb7, 0x70, 0x11, 0x06, 0xa9, 0xa5, 0x0e, 0x86, 0x41, 0x6a, 0xe9, 0x75, 0x18, 0x97, 0x7e, 0x4a, + 0xbc, 0x0e, 0x43, 0x0e, 0xf7, 0x54, 0x58, 0x7a, 0x37, 0x9e, 0x98, 0xd4, 0x7f, 0x19, 0x82, 0xb2, + 0x5c, 0xf9, 0xa7, 0x1e, 0x71, 0xef, 0x05, 0x9c, 0x3a, 0x52, 0x42, 0xc4, 0x5d, 0x87, 0x31, 0x4f, + 0xed, 0x6d, 0x89, 0x53, 0x9c, 0x3b, 0xd5, 0x15, 0x83, 0x70, 0xb2, 0x19, 0x9b, 0xa1, 0x8f, 0x61, + 0xcc, 0x26, 0x5b, 0xc4, 0xc7, 0x6d, 0x22, 0xa5, 0xe5, 0xe6, 0x6b, 0x22, 0x46, 0x7f, 0xbe, 0x3a, + 0x7f, 0xa5, 0x4d, 0xf9, 0xc3, 0xcd, 0xb5, 0x5a, 0x8b, 0x39, 0x86, 0xba, 0x90, 0xc3, 0x8f, 0x6a, + 0x60, 0x6d, 0xa8, 0x7b, 0xfc, 0x2e, 0x69, 0x35, 0x63, 0x7f, 0x74, 0x09, 0x0a, 0xdc, 0xc7, 0x16, + 0x75, 0xdb, 0x26, 0x0e, 0x02, 0xc2, 0x4b, 0x43, 0x32, 0x00, 0x79, 0x35, 0x78, 0x47, 0x8c, 0xa1, + 0x8f, 0x00, 0x5a, 0xcc, 0xb6, 0x31, 0x27, 0x3e, 0xb6, 0x4b, 0xc3, 0x72, 0xb5, 0xff, 0x4b, 0x85, + 0x3d, 0x0a, 0xf8, 0x02, 0xa3, 0xae, 0xca, 0x58, 0xc2, 0x45, 0x28, 0xb6, 0x68, 0x10, 0x9e, 0xb2, + 0x23, 0x47, 0x53, 0x1c, 0xf9, 0xa3, 0x55, 0x98, 0xe2, 0x78, 0x83, 0x98, 0x9e, 0xcf, 0xd6, 0x29, + 0x37, 0x3d, 0x9f, 0xb6, 0x48, 0x69, 0xf4, 0x48, 0xa0, 0x13, 0x02, 0xa8, 0x21, 0x71, 0x1a, 0x02, + 0x46, 0xff, 0x76, 0x0c, 0xce, 0x66, 0xe6, 0x2a, 0x6e, 0x51, 0xfe, 0x03, 0xc9, 0x5a, 0x84, 0xa2, + 0x43, 0x5d, 0x33, 0x01, 0x32, 0x72, 0x38, 0x90, 0x82, 0x43, 0xdd, 0x85, 0x3d, 0x9c, 0x6b, 0x30, + 0xb9, 0x85, 0x6d, 0x6a, 0x25, 0x91, 0x46, 0xe5, 0x61, 0x37, 0x21, 0xc7, 0x13, 0xa6, 0x77, 0xa1, + 0x10, 0x05, 0xcc, 0x0c, 0xe8, 0x13, 0x52, 0x3a, 0x71, 0x38, 0xc6, 0x7c, 0xe4, 0x75, 0x9f, 0x3e, + 0x21, 0x68, 0x19, 0xc6, 0x82, 0x6d, 0xec, 0x99, 0xeb, 0x84, 0x94, 0xc6, 0x8e, 0x14, 0xea, 0x13, + 0xc2, 0x7f, 0x91, 0x90, 0x54, 0xc1, 0xe6, 0xfe, 0x65, 0xc1, 0xae, 0x00, 0xc8, 0x96, 0x24, 0xac, + 0x54, 0x38, 0x12, 0x5a, 0x4e, 0x20, 0xc8, 0x1a, 0xcd, 0xae, 0xff, 0xf1, 0x63, 0xa9, 0x7f, 0xf4, + 0x25, 0x4c, 0xd9, 0xf4, 0xd1, 0x26, 0xb5, 0x64, 0xd9, 0x2b, 0xec, 0xfc, 0x91, 0xb0, 0x27, 0x13, + 0x40, 0x21, 0xf8, 0x7d, 0x28, 0x90, 0x70, 0x4b, 0x11, 0xcb, 0xf4, 0x5c, 0xbb, 0x54, 0x78, 0x6b, + 0xe0, 0x65, 0x97, 0x37, 0xf3, 0x31, 0x48, 0xc3, 0xb5, 0x51, 0x03, 0x4e, 0xe2, 0x2d, 0x4c, 0x6d, + 0xbc, 0x66, 0x13, 0x33, 0xa4, 0xa4, 0xbc, 0x53, 0x2a, 0x1e, 0xae, 0x7e, 0x50, 0xec, 0xfb, 0x49, + 0xe4, 0x3a, 0xf7, 0x7d, 0x1e, 0x46, 0xe4, 0x19, 0x80, 0x36, 0x60, 0x34, 0x7c, 0x75, 0xa0, 0x72, + 0xc6, 0x53, 0x44, 0x1d, 0xe0, 0xe5, 0xb3, 0x99, 0x73, 0xe1, 0x81, 0xa1, 0xcf, 0x3c, 0xfd, 0xfd, + 0xef, 0x9f, 0x06, 0x75, 0x74, 0xc1, 0x10, 0x46, 0x55, 0x97, 0xf0, 0x6d, 0xe6, 0x6f, 0x18, 0xbd, + 0xef, 0x2e, 0xf4, 0x83, 0x06, 0x79, 0x79, 0x81, 0xab, 0x3e, 0x0f, 0xfd, 0x3f, 0xf3, 0x64, 0x89, + 0x69, 0x2b, 0xfb, 0x4d, 0x2b, 0xe6, 0x0f, 0x25, 0xf3, 0x6d, 0x74, 0xab, 0x0f, 0x73, 0xe4, 0x64, + 0xec, 0x24, 0x9e, 0x86, 0x1b, 0xa4, 0xb3, 0x8b, 0x7e, 0xd5, 0x00, 0x25, 0xd5, 0x84, 0x7d, 0x3f, + 0xba, 0x94, 0x4d, 0x9a, 0x7a, 0x98, 0x94, 0x2f, 0xf7, 0x37, 0x52, 0xfa, 0x56, 0xa4, 0xbe, 0x25, + 0x74, 0x6f, 0x7f, 0x7d, 0xa2, 0x6d, 0xad, 0xae, 0x75, 0xaa, 0xe2, 0xea, 0x37, 0x76, 0x12, 0x8f, + 0x9d, 0xdd, 0x5e, 0xc1, 0x2e, 0xe4, 0x96, 0x08, 0x0f, 0x1f, 0x03, 0x5d, 0xe9, 0x4a, 0x3d, 0x19, + 0xba, 0xd2, 0x95, 0x7e, 0x3d, 0x1c, 0x26, 0x5d, 0x41, 0x48, 0xf1, 0x9b, 0x06, 0xa7, 0x93, 0x01, + 0xda, 0x6b, 0xcb, 0xd1, 0xd5, 0xec, 0xf5, 0xf7, 0xbc, 0x1c, 0xca, 0x33, 0x07, 0x1b, 0xbe, 0x65, + 0xb0, 0xd6, 0x99, 0x5f, 0x55, 0xad, 0x8b, 0xb1, 0xa3, 0xbe, 0x64, 0x04, 0x4b, 0xd5, 0x5a, 0xdc, + 0x70, 0x76, 0xd5, 0x5a, 0x77, 0x77, 0xdf, 0x55, 0x6b, 0x3d, 0x0d, 0xfa, 0x61, 0x6a, 0x2d, 0xee, + 0x78, 0x7b, 0xd5, 0x3c, 0xd3, 0xa0, 0x90, 0x6a, 0xa3, 0xd1, 0xc5, 0x14, 0x5f, 0x56, 0x53, 0x5e, + 0xd6, 0xfb, 0x99, 0x28, 0x59, 0x37, 0xa5, 0xac, 0xeb, 0x68, 0x66, 0x7f, 0x59, 0x34, 0xa8, 0x26, + 0x7a, 0x71, 0xb4, 0x03, 0xc3, 0xb2, 0xce, 0x2f, 0xa4, 0xd0, 0x33, 0x3a, 0xf1, 0xf2, 0xc5, 0x3e, + 0x16, 0x8a, 0xbe, 0x26, 0xe9, 0x67, 0xd0, 0x95, 0x7e, 0x3b, 0x50, 0x54, 0xb6, 0xec, 0xe2, 0x77, + 0xd1, 0x77, 0x1a, 0x8c, 0x08, 0x80, 0x20, 0x8b, 0x3e, 0xdd, 0x96, 0x67, 0xd1, 0x77, 0x35, 0xd6, + 0xfa, 0x07, 0x92, 0xbe, 0x8e, 0x8c, 0x83, 0xe8, 0x7b, 0xb7, 0xd2, 0xd0, 0xca, 0x83, 0x06, 0x3a, + 0xd3, 0xd3, 0xce, 0x2a, 0xee, 0x52, 0xef, 0x84, 0xa2, 0xbc, 0x25, 0x29, 0x6b, 0xe8, 0x46, 0xdf, + 0x32, 0x4d, 0x56, 0x26, 0xb5, 0x76, 0xd1, 0xcf, 0x1a, 0x14, 0xd3, 0xfd, 0x56, 0xd7, 0x16, 0xda, + 0xbf, 0x7b, 0xee, 0xda, 0x42, 0x7d, 0x5a, 0x37, 0xbd, 0x2e, 0xb5, 0xcd, 0xa2, 0x6b, 0xfb, 0x6b, + 0x13, 0x77, 0x6c, 0x95, 0xc4, 0xae, 0xf3, 0xf7, 0x5e, 0xbc, 0xae, 0x68, 0x2f, 0x5f, 0x57, 0xb4, + 0xbf, 0x5e, 0x57, 0xb4, 0x1f, 0xdf, 0x54, 0x06, 0x5e, 0xbe, 0xa9, 0x0c, 0xfc, 0xf1, 0xa6, 0x32, + 0xb0, 0x3a, 0x9b, 0xb8, 0xab, 0x7a, 0xe1, 0x1e, 0xa7, 0xfe, 0x38, 0x5b, 0x1b, 0x95, 0xff, 0x80, + 0xbd, 0xff, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xfe, 0x3b, 0x0f, 0x93, 0xf4, 0x13, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -1084,23 +1274,26 @@ const _ = grpc.SupportPackageIsVersion4 type QueryClient interface { // Parameters queries the parameters of the module. Params(ctx context.Context, in *ParamsRequest, opts ...grpc.CallOption) (*ParamsResponse, error) - // Queries a list of GetPositions items. + // Queries a list of positions. GetPositions(ctx context.Context, in *PositionsRequest, opts ...grpc.CallOption) (*PositionsResponse, error) - // Queries a list of GetPositionsByPool items. + // Queries a list of mtp positions by pool. GetPositionsByPool(ctx context.Context, in *PositionsByPoolRequest, opts ...grpc.CallOption) (*PositionsByPoolResponse, error) - // Queries a list of GetStatus items. + // Retuns the total number of open and lifetime mtps. GetStatus(ctx context.Context, in *StatusRequest, opts ...grpc.CallOption) (*StatusResponse, error) - // Queries a list of GetPositionsForAddress items. + // Queries a list of mtp positions for a given address. GetPositionsForAddress(ctx context.Context, in *PositionsForAddressRequest, opts ...grpc.CallOption) (*PositionsForAddressResponse, error) - // Queries a list of GetWhitelist items. + // Queries a list of whitelisted addresses. GetWhitelist(ctx context.Context, in *WhitelistRequest, opts ...grpc.CallOption) (*WhitelistResponse, error) - // Queries a list of IsWhitelisted items. + // Is an address whitelisted? IsWhitelisted(ctx context.Context, in *IsWhitelistedRequest, opts ...grpc.CallOption) (*IsWhitelistedResponse, error) - // Queries a list of Pool items. + // Queries a single pool given its index. Pool(ctx context.Context, in *QueryGetPoolRequest, opts ...grpc.CallOption) (*QueryGetPoolResponse, error) + // Queries a list of all pools. Pools(ctx context.Context, in *QueryAllPoolRequest, opts ...grpc.CallOption) (*QueryAllPoolResponse, error) - // Queries a list of MTP items. + // Queries a single mtp position given its address and id. MTP(ctx context.Context, in *MTPRequest, opts ...grpc.CallOption) (*MTPResponse, error) + // Queries an estimation of a new open position details. + OpenEstimation(ctx context.Context, in *QueryOpenEstimationRequest, opts ...grpc.CallOption) (*QueryOpenEstimationResponse, error) } type queryClient struct { @@ -1201,27 +1394,39 @@ func (c *queryClient) MTP(ctx context.Context, in *MTPRequest, opts ...grpc.Call return out, nil } +func (c *queryClient) OpenEstimation(ctx context.Context, in *QueryOpenEstimationRequest, opts ...grpc.CallOption) (*QueryOpenEstimationResponse, error) { + out := new(QueryOpenEstimationResponse) + err := c.cc.Invoke(ctx, "/elys.margin.Query/OpenEstimation", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + // QueryServer is the server API for Query service. type QueryServer interface { // Parameters queries the parameters of the module. Params(context.Context, *ParamsRequest) (*ParamsResponse, error) - // Queries a list of GetPositions items. + // Queries a list of positions. GetPositions(context.Context, *PositionsRequest) (*PositionsResponse, error) - // Queries a list of GetPositionsByPool items. + // Queries a list of mtp positions by pool. GetPositionsByPool(context.Context, *PositionsByPoolRequest) (*PositionsByPoolResponse, error) - // Queries a list of GetStatus items. + // Retuns the total number of open and lifetime mtps. GetStatus(context.Context, *StatusRequest) (*StatusResponse, error) - // Queries a list of GetPositionsForAddress items. + // Queries a list of mtp positions for a given address. GetPositionsForAddress(context.Context, *PositionsForAddressRequest) (*PositionsForAddressResponse, error) - // Queries a list of GetWhitelist items. + // Queries a list of whitelisted addresses. GetWhitelist(context.Context, *WhitelistRequest) (*WhitelistResponse, error) - // Queries a list of IsWhitelisted items. + // Is an address whitelisted? IsWhitelisted(context.Context, *IsWhitelistedRequest) (*IsWhitelistedResponse, error) - // Queries a list of Pool items. + // Queries a single pool given its index. Pool(context.Context, *QueryGetPoolRequest) (*QueryGetPoolResponse, error) + // Queries a list of all pools. Pools(context.Context, *QueryAllPoolRequest) (*QueryAllPoolResponse, error) - // Queries a list of MTP items. + // Queries a single mtp position given its address and id. MTP(context.Context, *MTPRequest) (*MTPResponse, error) + // Queries an estimation of a new open position details. + OpenEstimation(context.Context, *QueryOpenEstimationRequest) (*QueryOpenEstimationResponse, error) } // UnimplementedQueryServer can be embedded to have forward compatible implementations. @@ -1258,6 +1463,9 @@ func (*UnimplementedQueryServer) Pools(ctx context.Context, req *QueryAllPoolReq func (*UnimplementedQueryServer) MTP(ctx context.Context, req *MTPRequest) (*MTPResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method MTP not implemented") } +func (*UnimplementedQueryServer) OpenEstimation(ctx context.Context, req *QueryOpenEstimationRequest) (*QueryOpenEstimationResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method OpenEstimation not implemented") +} func RegisterQueryServer(s grpc1.Server, srv QueryServer) { s.RegisterService(&_Query_serviceDesc, srv) @@ -1443,6 +1651,24 @@ func _Query_MTP_Handler(srv interface{}, ctx context.Context, dec func(interface return interceptor(ctx, in, info, handler) } +func _Query_OpenEstimation_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryOpenEstimationRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).OpenEstimation(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/elys.margin.Query/OpenEstimation", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).OpenEstimation(ctx, req.(*QueryOpenEstimationRequest)) + } + return interceptor(ctx, in, info, handler) +} + var _Query_serviceDesc = grpc.ServiceDesc{ ServiceName: "elys.margin.Query", HandlerType: (*QueryServer)(nil), @@ -1487,6 +1713,10 @@ var _Query_serviceDesc = grpc.ServiceDesc{ MethodName: "MTP", Handler: _Query_MTP_Handler, }, + { + MethodName: "OpenEstimation", + Handler: _Query_OpenEstimation_Handler, + }, }, Streams: []grpc.StreamDesc{}, Metadata: "elys/margin/query.proto", @@ -2232,126 +2462,356 @@ func (m *MTPResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { 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 *ParamsRequest) Size() (n int) { - if m == nil { - return 0 +func (m *QueryOpenEstimationRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } - var l int - _ = l - return n + return dAtA[:n], nil } -func (m *ParamsResponse) 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 *QueryOpenEstimationRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *PositionsRequest) Size() (n int) { - if m == nil { - return 0 - } +func (m *QueryOpenEstimationRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i var l int _ = l - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *PositionsResponse) Size() (n int) { - if m == nil { - return 0 + { + size := m.TakeProfitPrice.Size() + i -= size + if _, err := m.TakeProfitPrice.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintQuery(dAtA, i, uint64(size)) } - var l int - _ = l - if len(m.Mtps) > 0 { - for _, e := range m.Mtps { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) + i-- + dAtA[i] = 0x32 + { + size := m.Discount.Size() + i -= size + if _, err := m.Discount.MarshalTo(dAtA[i:]); err != nil { + return 0, err } + i = encodeVarintQuery(dAtA, i, uint64(size)) } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) + i-- + dAtA[i] = 0x2a + { + size, err := m.Collateral.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) } - return n -} - -func (m *PositionsByPoolRequest) Size() (n int) { - if m == nil { - return 0 + i-- + dAtA[i] = 0x22 + if len(m.TradingAsset) > 0 { + i -= len(m.TradingAsset) + copy(dAtA[i:], m.TradingAsset) + i = encodeVarintQuery(dAtA, i, uint64(len(m.TradingAsset))) + i-- + dAtA[i] = 0x1a } - var l int - _ = l - if m.AmmPoolId != 0 { - n += 1 + sovQuery(uint64(m.AmmPoolId)) + { + size := m.Leverage.Size() + i -= size + if _, err := m.Leverage.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintQuery(dAtA, i, uint64(size)) } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) + i-- + dAtA[i] = 0x12 + if m.Position != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.Position)) + i-- + dAtA[i] = 0x8 } - return n + return len(dAtA) - i, nil } -func (m *PositionsByPoolResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Mtps) > 0 { - for _, e := range m.Mtps { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) +func (m *QueryOpenEstimationResponse) 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 n + return dAtA[:n], nil } -func (m *StatusRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n +func (m *QueryOpenEstimationResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *StatusResponse) Size() (n int) { - if m == nil { - return 0 - } +func (m *QueryOpenEstimationResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i var l int _ = l - if m.OpenMtpCount != 0 { - n += 1 + sovQuery(uint64(m.OpenMtpCount)) + { + size, err := m.AvailableLiquidity.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) } - if m.LifetimeMtpCount != 0 { - n += 1 + sovQuery(uint64(m.LifetimeMtpCount)) + i-- + dAtA[i] = 0x72 + { + size := m.EstimatedPnl.Size() + i -= size + if _, err := m.EstimatedPnl.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintQuery(dAtA, i, uint64(size)) } - return n + i-- + dAtA[i] = 0x6a + { + size := m.LiquidationPrice.Size() + i -= size + if _, err := m.LiquidationPrice.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x62 + { + size := m.TakeProfitPrice.Size() + i -= size + if _, err := m.TakeProfitPrice.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x5a + { + size := m.OpenPrice.Size() + i -= size + if _, err := m.OpenPrice.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x52 + { + size := m.Discount.Size() + i -= size + if _, err := m.Discount.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x4a + { + size := m.SwapFee.Size() + i -= size + if _, err := m.SwapFee.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x42 + { + size, err := m.PositionSize.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x3a + if m.ValidCollateral { + i-- + if m.ValidCollateral { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x30 + } + { + size, err := m.MinCollateral.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + { + size, err := m.Collateral.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + if len(m.TradingAsset) > 0 { + i -= len(m.TradingAsset) + copy(dAtA[i:], m.TradingAsset) + i = encodeVarintQuery(dAtA, i, uint64(len(m.TradingAsset))) + i-- + dAtA[i] = 0x1a + } + { + size := m.Leverage.Size() + i -= size + if _, err := m.Leverage.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if m.Position != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.Position)) + i-- + dAtA[i] = 0x8 + } + 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 *ParamsRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *ParamsResponse) 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 *PositionsRequest) 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 *PositionsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Mtps) > 0 { + for _, e := range m.Mtps { + 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 *PositionsByPoolRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.AmmPoolId != 0 { + n += 1 + sovQuery(uint64(m.AmmPoolId)) + } + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *PositionsByPoolResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Mtps) > 0 { + for _, e := range m.Mtps { + 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 *StatusRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *StatusResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.OpenMtpCount != 0 { + n += 1 + sovQuery(uint64(m.OpenMtpCount)) + } + if m.LifetimeMtpCount != 0 { + n += 1 + sovQuery(uint64(m.LifetimeMtpCount)) + } + return n } func (m *PositionsForAddressRequest) Size() (n int) { @@ -2535,6 +2995,71 @@ func (m *MTPResponse) Size() (n int) { return n } +func (m *QueryOpenEstimationRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Position != 0 { + n += 1 + sovQuery(uint64(m.Position)) + } + l = m.Leverage.Size() + n += 1 + l + sovQuery(uint64(l)) + l = len(m.TradingAsset) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + l = m.Collateral.Size() + n += 1 + l + sovQuery(uint64(l)) + l = m.Discount.Size() + n += 1 + l + sovQuery(uint64(l)) + l = m.TakeProfitPrice.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + +func (m *QueryOpenEstimationResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Position != 0 { + n += 1 + sovQuery(uint64(m.Position)) + } + l = m.Leverage.Size() + n += 1 + l + sovQuery(uint64(l)) + l = len(m.TradingAsset) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + l = m.Collateral.Size() + n += 1 + l + sovQuery(uint64(l)) + l = m.MinCollateral.Size() + n += 1 + l + sovQuery(uint64(l)) + if m.ValidCollateral { + n += 2 + } + l = m.PositionSize.Size() + n += 1 + l + sovQuery(uint64(l)) + l = m.SwapFee.Size() + n += 1 + l + sovQuery(uint64(l)) + l = m.Discount.Size() + n += 1 + l + sovQuery(uint64(l)) + l = m.OpenPrice.Size() + n += 1 + l + sovQuery(uint64(l)) + l = m.TakeProfitPrice.Size() + n += 1 + l + sovQuery(uint64(l)) + l = m.LiquidationPrice.Size() + n += 1 + l + sovQuery(uint64(l)) + l = m.EstimatedPnl.Size() + n += 1 + l + sovQuery(uint64(l)) + l = m.AvailableLiquidity.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + func sovQuery(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } @@ -4414,6 +4939,733 @@ func (m *MTPResponse) Unmarshal(dAtA []byte) error { } return nil } +func (m *QueryOpenEstimationRequest) 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: QueryOpenEstimationRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryOpenEstimationRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Position", wireType) + } + m.Position = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Position |= Position(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Leverage", 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 + } + if err := m.Leverage.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TradingAsset", 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.TradingAsset = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Collateral", 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.Collateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Discount", 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 + } + if err := m.Discount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TakeProfitPrice", 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 + } + if err := m.TakeProfitPrice.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 *QueryOpenEstimationResponse) 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: QueryOpenEstimationResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryOpenEstimationResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Position", wireType) + } + m.Position = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Position |= Position(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Leverage", 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 + } + if err := m.Leverage.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TradingAsset", 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.TradingAsset = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Collateral", 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.Collateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field MinCollateral", 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.MinCollateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidCollateral", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.ValidCollateral = bool(v != 0) + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PositionSize", 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.PositionSize.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SwapFee", 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 + } + if err := m.SwapFee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Discount", 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 + } + if err := m.Discount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 10: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field OpenPrice", 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 + } + if err := m.OpenPrice.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 11: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TakeProfitPrice", 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 + } + if err := m.TakeProfitPrice.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 12: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LiquidationPrice", 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 + } + if err := m.LiquidationPrice.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 13: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field EstimatedPnl", 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 + } + if err := m.EstimatedPnl.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 14: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AvailableLiquidity", 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.AvailableLiquidity.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 diff --git a/x/margin/types/query.pb.gw.go b/x/margin/types/query.pb.gw.go index 4df04ec91..2b5757147 100644 --- a/x/margin/types/query.pb.gw.go +++ b/x/margin/types/query.pb.gw.go @@ -20,6 +20,7 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) @@ -30,6 +31,7 @@ var _ status.Status var _ = runtime.String var _ = utilities.NewDoubleArray var _ = descriptor.ForMessage +var _ = metadata.Join func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq ParamsRequest @@ -637,15 +639,53 @@ func local_request_Query_MTP_0(ctx context.Context, marshaler runtime.Marshaler, } +var ( + filter_Query_OpenEstimation_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} +) + +func request_Query_OpenEstimation_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryOpenEstimationRequest + 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_OpenEstimation_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.OpenEstimation(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_OpenEstimation_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryOpenEstimationRequest + 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_OpenEstimation_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.OpenEstimation(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 (such as grpc.SendHeader, etc) to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. +// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { @@ -653,6 +693,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv 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) @@ -666,6 +707,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_GetPositions_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 { @@ -673,6 +716,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_GetPositions_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) @@ -686,6 +730,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_GetPositionsByPool_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 { @@ -693,6 +739,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_GetPositionsByPool_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) @@ -706,6 +753,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_GetStatus_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 { @@ -713,6 +762,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_GetStatus_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) @@ -726,6 +776,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_GetPositionsForAddress_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 { @@ -733,6 +785,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_GetPositionsForAddress_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) @@ -746,6 +799,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_GetWhitelist_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 { @@ -753,6 +808,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_GetWhitelist_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) @@ -766,6 +822,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_IsWhitelisted_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 { @@ -773,6 +831,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_IsWhitelisted_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) @@ -786,6 +845,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_Pool_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 { @@ -793,6 +854,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_Pool_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) @@ -806,6 +868,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_Pools_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 { @@ -813,6 +877,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_Pools_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) @@ -826,6 +891,8 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv mux.Handle("GET", pattern_Query_MTP_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 { @@ -833,6 +900,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } resp, md, err := local_request_Query_MTP_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) @@ -843,6 +911,29 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv }) + mux.Handle("GET", pattern_Query_OpenEstimation_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_OpenEstimation_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_OpenEstimation_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + return nil } @@ -1084,6 +1175,26 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie }) + mux.Handle("GET", pattern_Query_OpenEstimation_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_OpenEstimation_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_OpenEstimation_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + return nil } @@ -1107,6 +1218,8 @@ var ( pattern_Query_Pools_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"elys-network", "elys", "margin", "pool", "pagination.key"}, "", runtime.AssumeColonVerbOpt(true))) pattern_Query_MTP_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 1, 0, 4, 1, 5, 5}, []string{"elys-network", "elys", "margin", "mtp", "address", "id"}, "", runtime.AssumeColonVerbOpt(true))) + + pattern_Query_OpenEstimation_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"elys-network", "elys", "margin", "open-estimation"}, "", runtime.AssumeColonVerbOpt(true))) ) var ( @@ -1129,4 +1242,6 @@ var ( forward_Query_Pools_0 = runtime.ForwardResponseMessage forward_Query_MTP_0 = runtime.ForwardResponseMessage + + forward_Query_OpenEstimation_0 = runtime.ForwardResponseMessage ) diff --git a/x/margin/types/reached_take_profit_price.go b/x/margin/types/reached_take_profit_price.go new file mode 100644 index 000000000..0e4819b42 --- /dev/null +++ b/x/margin/types/reached_take_profit_price.go @@ -0,0 +1,15 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// ReachedTakeProfitPrice tells if the take profit price is reached +func ReachedTakeProfitPrice(mtp *MTP, assetPrice sdk.Int) bool { + if mtp.Position == Position_LONG { + return mtp.TakeProfitPrice.GTE(sdk.NewDecFromInt(assetPrice)) + } else if mtp.Position == Position_SHORT { + return mtp.TakeProfitPrice.LTE(sdk.NewDecFromInt(assetPrice)) + } + return false +} diff --git a/x/margin/types/tx.pb.go b/x/margin/types/tx.pb.go index e8e492b24..c860639f6 100644 --- a/x/margin/types/tx.pb.go +++ b/x/margin/types/tx.pb.go @@ -31,13 +31,12 @@ var _ = math.Inf const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package type MsgOpen struct { - Creator string `protobuf:"bytes,1,opt,name=creator,proto3" json:"creator,omitempty"` - CollateralAsset string `protobuf:"bytes,2,opt,name=collateral_asset,json=collateralAsset,proto3" json:"collateral_asset,omitempty"` - CollateralAmount github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,3,opt,name=collateral_amount,json=collateralAmount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"collateral_amount"` - BorrowAsset string `protobuf:"bytes,4,opt,name=borrow_asset,json=borrowAsset,proto3" json:"borrow_asset,omitempty"` - Position Position `protobuf:"varint,5,opt,name=position,proto3,enum=elys.margin.Position" json:"position,omitempty"` - Leverage github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,6,opt,name=leverage,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"leverage"` - TakeProfitPrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,7,opt,name=take_profit_price,json=takeProfitPrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"take_profit_price"` + Creator string `protobuf:"bytes,1,opt,name=creator,proto3" json:"creator,omitempty"` + Position Position `protobuf:"varint,2,opt,name=position,proto3,enum=elys.margin.Position" json:"position,omitempty"` + Leverage github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=leverage,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"leverage"` + TradingAsset string `protobuf:"bytes,4,opt,name=trading_asset,json=tradingAsset,proto3" json:"trading_asset,omitempty"` + Collateral types.Coin `protobuf:"bytes,5,opt,name=collateral,proto3" json:"collateral"` + TakeProfitPrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,6,opt,name=take_profit_price,json=takeProfitPrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"take_profit_price"` } func (m *MsgOpen) Reset() { *m = MsgOpen{} } @@ -80,25 +79,25 @@ func (m *MsgOpen) GetCreator() string { return "" } -func (m *MsgOpen) GetCollateralAsset() string { +func (m *MsgOpen) GetPosition() Position { if m != nil { - return m.CollateralAsset + return m.Position } - return "" + return Position_UNSPECIFIED } -func (m *MsgOpen) GetBorrowAsset() string { +func (m *MsgOpen) GetTradingAsset() string { if m != nil { - return m.BorrowAsset + return m.TradingAsset } return "" } -func (m *MsgOpen) GetPosition() Position { +func (m *MsgOpen) GetCollateral() types.Coin { if m != nil { - return m.Position + return m.Collateral } - return Position_UNSPECIFIED + return types.Coin{} } type MsgOpenResponse struct { @@ -146,9 +145,9 @@ func (m *MsgOpenResponse) GetId() uint64 { } type MsgClose struct { - Creator string `protobuf:"bytes,1,opt,name=creator,proto3" json:"creator,omitempty"` - Id uint64 `protobuf:"varint,2,opt,name=id,proto3" json:"id,omitempty"` - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` + Creator string `protobuf:"bytes,1,opt,name=creator,proto3" json:"creator,omitempty"` + Id uint64 `protobuf:"varint,2,opt,name=id,proto3" json:"id,omitempty"` + Amount github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,3,opt,name=amount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"amount"` } func (m *MsgClose) Reset() { *m = MsgClose{} } @@ -198,16 +197,9 @@ func (m *MsgClose) GetId() uint64 { return 0 } -func (m *MsgClose) GetAmount() types.Coin { - if m != nil { - return m.Amount - } - return types.Coin{} -} - type MsgCloseResponse struct { - Id uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` - Amount types.Coin `protobuf:"bytes,2,opt,name=amount,proto3" json:"amount"` + Id uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Amount github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,2,opt,name=amount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"amount"` } func (m *MsgCloseResponse) Reset() { *m = MsgCloseResponse{} } @@ -250,13 +242,6 @@ func (m *MsgCloseResponse) GetId() uint64 { return 0 } -func (m *MsgCloseResponse) GetAmount() types.Coin { - if m != nil { - return m.Amount - } - return types.Coin{} -} - type MsgUpdateParams struct { // authority is the address that controls the module (defaults to x/gov unless overwritten). Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` @@ -637,52 +622,51 @@ func init() { func init() { proto.RegisterFile("elys/margin/tx.proto", fileDescriptor_01b9dbed35cc5a15) } var fileDescriptor_01b9dbed35cc5a15 = []byte{ - // 714 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x55, 0xcb, 0x4e, 0xdb, 0x40, - 0x14, 0xcd, 0x8b, 0x40, 0x6e, 0x10, 0x0f, 0x13, 0xc0, 0xa4, 0xd4, 0x80, 0x5b, 0x55, 0x54, 0x08, - 0x5b, 0xd0, 0x45, 0xa5, 0x4a, 0x5d, 0xf0, 0xe8, 0x82, 0x4a, 0x11, 0x91, 0xa5, 0xaa, 0x12, 0xb4, - 0x8a, 0x1c, 0x7b, 0x6a, 0x2c, 0x1c, 0x8f, 0x35, 0x33, 0x10, 0xf8, 0x8b, 0xfe, 0x46, 0x3f, 0xa3, - 0x3b, 0x96, 0x2c, 0xab, 0x2e, 0x50, 0x05, 0x3f, 0x52, 0x79, 0x66, 0xe2, 0x4c, 0xc2, 0x4b, 0x54, - 0xea, 0x0a, 0xe6, 0x9e, 0x3b, 0xe7, 0x9c, 0xeb, 0x7b, 0x62, 0x43, 0x0d, 0x45, 0xe7, 0xd4, 0xee, - 0xb8, 0x24, 0x08, 0x63, 0x9b, 0x9d, 0x59, 0x09, 0xc1, 0x0c, 0x6b, 0xd5, 0xb4, 0x6a, 0x89, 0x6a, - 0xbd, 0x16, 0xe0, 0x00, 0xf3, 0xba, 0x9d, 0xfe, 0x27, 0x5a, 0xea, 0x86, 0x87, 0x69, 0x07, 0x53, - 0xbb, 0xed, 0x52, 0x64, 0x9f, 0x6e, 0xb4, 0x11, 0x73, 0x37, 0x6c, 0x0f, 0x87, 0xb1, 0xc4, 0x75, - 0x95, 0x38, 0x71, 0x89, 0xdb, 0xa1, 0x12, 0x99, 0x1f, 0x90, 0x3c, 0x4f, 0x90, 0x04, 0xcc, 0x1f, - 0x45, 0x18, 0x6d, 0xd0, 0x60, 0x3f, 0x41, 0xb1, 0xa6, 0xc3, 0xa8, 0x47, 0x90, 0xcb, 0x30, 0xd1, - 0xf3, 0xcb, 0xf9, 0xd5, 0x8a, 0xd3, 0x3b, 0x6a, 0xaf, 0x61, 0xca, 0xc3, 0x51, 0xe4, 0x32, 0x44, - 0xdc, 0xa8, 0xe5, 0x52, 0x8a, 0x98, 0x5e, 0xe0, 0x2d, 0x93, 0xfd, 0xfa, 0x56, 0x5a, 0xd6, 0x0e, - 0x61, 0x5a, 0x6d, 0xed, 0xe0, 0x93, 0x98, 0xe9, 0xc5, 0xb4, 0x77, 0xdb, 0xba, 0xb8, 0x5a, 0xca, - 0xfd, 0xbe, 0x5a, 0x7a, 0x15, 0x84, 0xec, 0xe8, 0xa4, 0x6d, 0x79, 0xb8, 0x63, 0xcb, 0x89, 0xc4, - 0x9f, 0x75, 0xea, 0x1f, 0x4b, 0x77, 0x7b, 0x31, 0x73, 0x14, 0xcd, 0x2d, 0xce, 0xa3, 0xad, 0xc0, - 0x78, 0x1b, 0x13, 0x82, 0xbb, 0xd2, 0x43, 0x89, 0x7b, 0xa8, 0x8a, 0x9a, 0xd0, 0xdf, 0x80, 0xb1, - 0x04, 0xd3, 0x90, 0x85, 0x38, 0xd6, 0x47, 0x96, 0xf3, 0xab, 0x13, 0x9b, 0xb3, 0x96, 0xf2, 0x64, - 0xad, 0xa6, 0x04, 0x9d, 0xac, 0x4d, 0xfb, 0x08, 0x63, 0x11, 0x3a, 0x45, 0xc4, 0x0d, 0x90, 0x5e, - 0x7e, 0xb2, 0xd3, 0x5d, 0xe4, 0x39, 0xd9, 0x7d, 0xed, 0x00, 0xa6, 0x99, 0x7b, 0x8c, 0x5a, 0x09, - 0xc1, 0xdf, 0x42, 0xd6, 0x4a, 0x48, 0xe8, 0x21, 0x7d, 0xf4, 0x9f, 0x48, 0x27, 0x53, 0xa2, 0x26, - 0xe7, 0x69, 0xa6, 0x34, 0xe6, 0x0a, 0x4c, 0xca, 0x55, 0x39, 0x88, 0x26, 0x38, 0xa6, 0x48, 0x9b, - 0x80, 0x42, 0xe8, 0xf3, 0x6d, 0x95, 0x9c, 0x42, 0xe8, 0x9b, 0x1d, 0x18, 0x6b, 0xd0, 0x60, 0x27, - 0xc2, 0x14, 0x3d, 0xb0, 0x4e, 0x71, 0xab, 0xd0, 0xbb, 0xa5, 0xbd, 0x85, 0xb2, 0xb2, 0xa8, 0xea, - 0xe6, 0x82, 0x25, 0x0c, 0x59, 0x69, 0xd0, 0x2c, 0x19, 0x34, 0x6b, 0x07, 0x87, 0xf1, 0x76, 0x29, - 0x1d, 0xc2, 0x91, 0xed, 0xe6, 0x21, 0x4c, 0xf5, 0xe4, 0xee, 0xb3, 0xa4, 0x90, 0x17, 0x9e, 0x46, - 0xfe, 0x85, 0x8f, 0xfb, 0x29, 0xf1, 0x5d, 0x86, 0x9a, 0x3c, 0xcc, 0xda, 0x22, 0x54, 0xdc, 0x13, - 0x76, 0x84, 0x49, 0xc8, 0xce, 0xe5, 0x50, 0xfd, 0x82, 0xb6, 0x06, 0x65, 0x11, 0x7a, 0xa9, 0x34, - 0x33, 0xb8, 0x78, 0x0e, 0x39, 0xb2, 0xc5, 0x5c, 0x80, 0xf9, 0x21, 0xf6, 0xde, 0x04, 0x66, 0x00, - 0x13, 0x7d, 0x08, 0xe3, 0xe8, 0x31, 0xdd, 0x1a, 0x8c, 0x24, 0x69, 0x9b, 0x5e, 0x58, 0x2e, 0xae, - 0x56, 0x1c, 0x71, 0x48, 0xb3, 0xea, 0xa5, 0x0f, 0xc6, 0x6f, 0x09, 0xb0, 0xc8, 0xc1, 0xaa, 0xa8, - 0x71, 0x5a, 0x53, 0x87, 0xb9, 0x41, 0xa1, 0xcc, 0xc2, 0x57, 0x18, 0x6f, 0xd0, 0xe0, 0xf3, 0x51, - 0xc8, 0x50, 0x14, 0x52, 0xf6, 0x88, 0x01, 0x1b, 0x66, 0xba, 0xbd, 0x56, 0xe4, 0xb7, 0x5c, 0xdf, - 0x27, 0x88, 0x52, 0xf9, 0x0b, 0xd5, 0x14, 0x68, 0x4b, 0x20, 0xe6, 0x1c, 0xd4, 0x54, 0xfa, 0x4c, - 0xb6, 0xc5, 0x27, 0xdf, 0x45, 0xdd, 0xff, 0x25, 0x2c, 0x26, 0x56, 0x04, 0x7a, 0xd2, 0x9b, 0x3f, - 0x8b, 0x50, 0x6c, 0xd0, 0x40, 0x7b, 0x07, 0x25, 0xfe, 0x32, 0xaa, 0x0d, 0x2c, 0x4f, 0xe6, 0xbe, - 0xbe, 0x78, 0x57, 0x35, 0x8b, 0xde, 0x7b, 0x18, 0x11, 0xd1, 0x9f, 0x1d, 0x6e, 0xe3, 0xe5, 0xfa, - 0xf3, 0x3b, 0xcb, 0xd9, 0x75, 0x07, 0xc6, 0x07, 0xd3, 0x36, 0xdc, 0xae, 0xa2, 0xf5, 0x97, 0x0f, - 0xa1, 0x19, 0xe7, 0x3e, 0x54, 0xd5, 0x20, 0x3d, 0xbb, 0xe7, 0x52, 0x0a, 0xd6, 0x5f, 0x3c, 0x00, - 0x66, 0x84, 0x7b, 0x50, 0xe9, 0xc7, 0x62, 0x61, 0xf8, 0x46, 0x06, 0xd5, 0x57, 0xee, 0x85, 0x54, - 0x6f, 0xea, 0xaa, 0x6f, 0x79, 0x53, 0xc0, 0xdb, 0xde, 0xee, 0xd8, 0xe1, 0xf6, 0x87, 0x8b, 0x6b, - 0x23, 0x7f, 0x79, 0x6d, 0xe4, 0xff, 0x5c, 0x1b, 0xf9, 0xef, 0x37, 0x46, 0xee, 0xf2, 0xc6, 0xc8, - 0xfd, 0xba, 0x31, 0x72, 0x07, 0x6b, 0xca, 0x3b, 0x2f, 0x25, 0x5a, 0x8f, 0x11, 0xeb, 0x62, 0x72, - 0xcc, 0x0f, 0xf6, 0xd9, 0xc0, 0x97, 0xa9, 0x5d, 0xe6, 0x9f, 0xa6, 0x37, 0x7f, 0x03, 0x00, 0x00, - 0xff, 0xff, 0x30, 0xe2, 0xd8, 0x6c, 0x28, 0x07, 0x00, 0x00, + // 703 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x55, 0x5b, 0x4b, 0xdc, 0x40, + 0x14, 0xde, 0x9b, 0xab, 0x7b, 0x76, 0xab, 0xed, 0xb8, 0x6a, 0x4c, 0x6d, 0x5c, 0x63, 0x29, 0x0b, + 0x62, 0x82, 0xdb, 0xb7, 0x42, 0x29, 0x5e, 0x5a, 0xb0, 0xb0, 0xb8, 0x04, 0x4a, 0x41, 0x5a, 0x96, + 0xd9, 0x64, 0x1a, 0xa7, 0x66, 0x33, 0x21, 0x33, 0xde, 0xa0, 0x3f, 0xa2, 0x7f, 0xa9, 0x6f, 0x3e, + 0xfa, 0x58, 0xfa, 0x20, 0x45, 0xfb, 0x43, 0x4a, 0x26, 0xd9, 0x98, 0x5d, 0x6f, 0x60, 0xe9, 0x93, + 0xce, 0xf9, 0xce, 0xf9, 0xbe, 0xef, 0x9c, 0x39, 0xb3, 0x81, 0x3a, 0xf1, 0x4e, 0xb8, 0xd9, 0xc7, + 0xa1, 0x4b, 0x7d, 0x53, 0x1c, 0x1b, 0x41, 0xc8, 0x04, 0x43, 0xd5, 0x28, 0x6a, 0xc4, 0x51, 0xb5, + 0xee, 0x32, 0x97, 0xc9, 0xb8, 0x19, 0xfd, 0x17, 0xa7, 0xa8, 0x9a, 0xcd, 0x78, 0x9f, 0x71, 0xb3, + 0x87, 0x39, 0x31, 0x0f, 0xd7, 0x7a, 0x44, 0xe0, 0x35, 0xd3, 0x66, 0xd4, 0x4f, 0x70, 0x25, 0x4b, + 0x1c, 0xe0, 0x10, 0xf7, 0x79, 0x82, 0xcc, 0x0d, 0x49, 0x9e, 0x04, 0x24, 0x01, 0xf4, 0x3f, 0x05, + 0x18, 0x6f, 0x73, 0x77, 0x27, 0x20, 0x3e, 0x52, 0x60, 0xdc, 0x0e, 0x09, 0x16, 0x2c, 0x54, 0xf2, + 0x8d, 0x7c, 0xb3, 0x62, 0x0d, 0x8e, 0x68, 0x0d, 0x26, 0x02, 0xc6, 0xa9, 0xa0, 0xcc, 0x57, 0x0a, + 0x8d, 0x7c, 0x73, 0xb2, 0x35, 0x63, 0x64, 0xec, 0x1a, 0x9d, 0x04, 0xb4, 0xd2, 0x34, 0xf4, 0x1e, + 0x26, 0x3c, 0x72, 0x48, 0x42, 0xec, 0x12, 0xa5, 0x18, 0xb1, 0x6d, 0x18, 0xa7, 0xe7, 0x8b, 0xb9, + 0x5f, 0xe7, 0x8b, 0x2f, 0x5c, 0x2a, 0xf6, 0x0e, 0x7a, 0x86, 0xcd, 0xfa, 0x66, 0xd2, 0x50, 0xfc, + 0x67, 0x95, 0x3b, 0xfb, 0x89, 0xb9, 0x2d, 0x62, 0x5b, 0x69, 0x3d, 0x5a, 0x86, 0x47, 0x22, 0xc4, + 0x0e, 0xf5, 0xdd, 0x2e, 0xe6, 0x9c, 0x08, 0xa5, 0x24, 0xed, 0xd5, 0x92, 0xe0, 0x7a, 0x14, 0x43, + 0x6f, 0x00, 0x6c, 0xe6, 0x79, 0x58, 0x90, 0x10, 0x7b, 0xca, 0x58, 0x23, 0xdf, 0xac, 0xb6, 0xe6, + 0x8d, 0x98, 0xd9, 0x88, 0x26, 0x66, 0x24, 0x13, 0x33, 0x36, 0x19, 0xf5, 0x37, 0x4a, 0x91, 0x1b, + 0x2b, 0x53, 0x82, 0x76, 0xe1, 0x89, 0xc0, 0xfb, 0xa4, 0x1b, 0x84, 0xec, 0x0b, 0x15, 0xdd, 0x20, + 0xa4, 0x36, 0x51, 0xca, 0x0f, 0xb2, 0x3e, 0x15, 0x11, 0x75, 0x24, 0x4f, 0x27, 0xa2, 0xd1, 0x97, + 0x60, 0x2a, 0x99, 0xb2, 0x45, 0x78, 0xc0, 0x7c, 0x4e, 0xd0, 0x24, 0x14, 0xa8, 0x23, 0x07, 0x5d, + 0xb2, 0x0a, 0xd4, 0xd1, 0xbf, 0xc1, 0x44, 0x9b, 0xbb, 0x9b, 0x1e, 0xe3, 0xe4, 0x8e, 0x9b, 0x88, + 0xab, 0x0a, 0x83, 0x2a, 0xf4, 0x0e, 0xca, 0xb8, 0xcf, 0x0e, 0x7c, 0xf1, 0x80, 0x21, 0x6f, 0xfb, + 0xc2, 0x4a, 0xaa, 0xf5, 0xaf, 0xf0, 0x78, 0xa0, 0x7e, 0x9b, 0xc3, 0x8c, 0x56, 0xe1, 0x9f, 0xb4, + 0x3e, 0xc9, 0x61, 0x7c, 0x08, 0x1c, 0x2c, 0x48, 0x47, 0x6e, 0x29, 0x5a, 0x80, 0x0a, 0x3e, 0x10, + 0x7b, 0x2c, 0xa4, 0xe2, 0x24, 0x69, 0xf9, 0x2a, 0x80, 0x56, 0xa0, 0x1c, 0x6f, 0xb3, 0x14, 0xae, + 0xb6, 0xa6, 0x87, 0x97, 0x4f, 0x42, 0x56, 0x92, 0xa2, 0xcf, 0xc3, 0xdc, 0x08, 0xfb, 0xa0, 0x21, + 0xdd, 0x85, 0xc9, 0x2b, 0x88, 0x31, 0xef, 0x3e, 0xdd, 0x3a, 0x8c, 0x05, 0x51, 0x9a, 0x52, 0x68, + 0x14, 0x9b, 0x15, 0x2b, 0x3e, 0xa0, 0x25, 0xa8, 0xd9, 0xd1, 0x9c, 0x9c, 0x6e, 0x0c, 0x16, 0x25, + 0x58, 0x8d, 0x63, 0x92, 0x56, 0x57, 0x60, 0x76, 0x58, 0x28, 0xb5, 0xf0, 0x19, 0x6a, 0x6d, 0xee, + 0x7e, 0xdc, 0xa3, 0x82, 0x78, 0x94, 0x8b, 0x7b, 0x0c, 0x98, 0x30, 0x7d, 0x34, 0x48, 0x25, 0x4e, + 0x17, 0x3b, 0x4e, 0x48, 0x78, 0x3c, 0x85, 0x8a, 0x85, 0x32, 0xd0, 0x7a, 0x8c, 0xe8, 0xb3, 0x50, + 0xcf, 0xd2, 0xa7, 0xb2, 0x5d, 0xd9, 0xf9, 0x16, 0x39, 0xfa, 0x5f, 0xc2, 0x71, 0xc7, 0x19, 0x81, + 0x81, 0x74, 0xeb, 0x47, 0x11, 0x8a, 0x6d, 0xee, 0xa2, 0x57, 0x50, 0x92, 0xbf, 0x32, 0xf5, 0xa1, + 0xcb, 0x4b, 0x5e, 0x85, 0xba, 0x70, 0x53, 0x34, 0xdd, 0xc4, 0xd7, 0x30, 0x16, 0x3f, 0x8c, 0x99, + 0xd1, 0x34, 0x19, 0x56, 0x9f, 0xdd, 0x18, 0x4e, 0xcb, 0x2d, 0xa8, 0x0d, 0x6f, 0xdb, 0x68, 0x7a, + 0x16, 0x55, 0x9f, 0xdf, 0x85, 0xa6, 0x9c, 0x3b, 0x50, 0xcd, 0x2e, 0xd2, 0xd3, 0x5b, 0x8a, 0x22, + 0x50, 0x5d, 0xbe, 0x03, 0x4c, 0x09, 0xb7, 0xa1, 0x72, 0xb5, 0x16, 0xf3, 0xa3, 0x15, 0x29, 0xa4, + 0x2e, 0xdd, 0x0a, 0x65, 0xbd, 0x65, 0xaf, 0xfa, 0x9a, 0xb7, 0x0c, 0x78, 0xdd, 0xdb, 0x0d, 0x77, + 0xb8, 0xf1, 0xf6, 0xf4, 0x42, 0xcb, 0x9f, 0x5d, 0x68, 0xf9, 0xdf, 0x17, 0x5a, 0xfe, 0xfb, 0xa5, + 0x96, 0x3b, 0xbb, 0xd4, 0x72, 0x3f, 0x2f, 0xb5, 0xdc, 0xee, 0x4a, 0xe6, 0xed, 0x47, 0x44, 0xab, + 0x3e, 0x11, 0x47, 0x2c, 0xdc, 0x97, 0x07, 0xf3, 0x78, 0xe8, 0x93, 0xd3, 0x2b, 0xcb, 0x6f, 0xce, + 0xcb, 0xbf, 0x01, 0x00, 0x00, 0xff, 0xff, 0x49, 0x89, 0x09, 0x31, 0x01, 0x07, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -974,45 +958,38 @@ func (m *MsgOpen) MarshalToSizedBuffer(dAtA []byte) (int, error) { i = encodeVarintTx(dAtA, i, uint64(size)) } i-- - dAtA[i] = 0x3a + dAtA[i] = 0x32 { - size := m.Leverage.Size() - i -= size - if _, err := m.Leverage.MarshalTo(dAtA[i:]); err != nil { + size, err := m.Collateral.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { return 0, err } + i -= size i = encodeVarintTx(dAtA, i, uint64(size)) } i-- - dAtA[i] = 0x32 - if m.Position != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Position)) - i-- - dAtA[i] = 0x28 - } - if len(m.BorrowAsset) > 0 { - i -= len(m.BorrowAsset) - copy(dAtA[i:], m.BorrowAsset) - i = encodeVarintTx(dAtA, i, uint64(len(m.BorrowAsset))) + dAtA[i] = 0x2a + if len(m.TradingAsset) > 0 { + i -= len(m.TradingAsset) + copy(dAtA[i:], m.TradingAsset) + i = encodeVarintTx(dAtA, i, uint64(len(m.TradingAsset))) i-- dAtA[i] = 0x22 } { - size := m.CollateralAmount.Size() + size := m.Leverage.Size() i -= size - if _, err := m.CollateralAmount.MarshalTo(dAtA[i:]); err != nil { + if _, err := m.Leverage.MarshalTo(dAtA[i:]); err != nil { return 0, err } i = encodeVarintTx(dAtA, i, uint64(size)) } i-- dAtA[i] = 0x1a - if len(m.CollateralAsset) > 0 { - i -= len(m.CollateralAsset) - copy(dAtA[i:], m.CollateralAsset) - i = encodeVarintTx(dAtA, i, uint64(len(m.CollateralAsset))) + if m.Position != 0 { + i = encodeVarintTx(dAtA, i, uint64(m.Position)) i-- - dAtA[i] = 0x12 + dAtA[i] = 0x10 } if len(m.Creator) > 0 { i -= len(m.Creator) @@ -1073,11 +1050,11 @@ func (m *MsgClose) MarshalToSizedBuffer(dAtA []byte) (int, error) { var l int _ = l { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { + size := m.Amount.Size() + i -= size + if _, err := m.Amount.MarshalTo(dAtA[i:]); err != nil { return 0, err } - i -= size i = encodeVarintTx(dAtA, i, uint64(size)) } i-- @@ -1118,11 +1095,11 @@ func (m *MsgCloseResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { var l int _ = l { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { + size := m.Amount.Size() + i -= size + if _, err := m.Amount.MarshalTo(dAtA[i:]); err != nil { return 0, err } - i -= size i = encodeVarintTx(dAtA, i, uint64(size)) } i-- @@ -1412,20 +1389,16 @@ func (m *MsgOpen) Size() (n int) { if l > 0 { n += 1 + l + sovTx(uint64(l)) } - l = len(m.CollateralAsset) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + if m.Position != 0 { + n += 1 + sovTx(uint64(m.Position)) } - l = m.CollateralAmount.Size() + l = m.Leverage.Size() n += 1 + l + sovTx(uint64(l)) - l = len(m.BorrowAsset) + l = len(m.TradingAsset) if l > 0 { n += 1 + l + sovTx(uint64(l)) } - if m.Position != 0 { - n += 1 + sovTx(uint64(m.Position)) - } - l = m.Leverage.Size() + l = m.Collateral.Size() n += 1 + l + sovTx(uint64(l)) l = m.TakeProfitPrice.Size() n += 1 + l + sovTx(uint64(l)) @@ -1656,10 +1629,10 @@ func (m *MsgOpen) Unmarshal(dAtA []byte) error { m.Creator = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralAsset", wireType) + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Position", wireType) } - var stringLen uint64 + m.Position = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx @@ -1669,27 +1642,14 @@ func (m *MsgOpen) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + m.Position |= Position(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.CollateralAsset = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralAmount", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Leverage", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -1717,13 +1677,13 @@ func (m *MsgOpen) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.CollateralAmount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.Leverage.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 4: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BorrowAsset", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field TradingAsset", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -1751,32 +1711,13 @@ func (m *MsgOpen) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.BorrowAsset = string(dAtA[iNdEx:postIndex]) + m.TradingAsset = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Position", wireType) - } - m.Position = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Position |= Position(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 6: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Leverage", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Collateral", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx @@ -1786,27 +1727,26 @@ func (m *MsgOpen) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + msglen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthTx } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.Leverage.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.Collateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 7: + case 6: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field TakeProfitPrice", wireType) } @@ -2014,7 +1954,7 @@ func (m *MsgClose) Unmarshal(dAtA []byte) error { if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx @@ -2024,15 +1964,16 @@ func (m *MsgClose) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthTx } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTx } @@ -2116,7 +2057,7 @@ func (m *MsgCloseResponse) Unmarshal(dAtA []byte) error { if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx @@ -2126,15 +2067,16 @@ func (m *MsgCloseResponse) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthTx } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTx } diff --git a/x/margin/types/types.go b/x/margin/types/types.go index 205f6669b..bedcee0e4 100644 --- a/x/margin/types/types.go +++ b/x/margin/types/types.go @@ -17,41 +17,42 @@ func GetPositionFromString(s string) Position { } } -func NewMTP(signer string, collateralAsset string, borrowAsset string, position Position, leverage sdk.Dec, takeProfitPrice sdk.Dec, poolId uint64) *MTP { +func NewMTP(signer, collateralAsset, tradingAsset, liabilitiesAsset, custodyAsset string, position Position, leverage, takeProfitPrice sdk.Dec, poolId uint64) *MTP { return &MTP{ - Address: signer, - Collaterals: []sdk.Coin{sdk.NewCoin(collateralAsset, sdk.ZeroInt())}, - Liabilities: sdk.ZeroInt(), - BorrowInterestPaidCollaterals: []sdk.Coin{sdk.NewCoin(collateralAsset, sdk.ZeroInt())}, - BorrowInterestPaidCustodies: []sdk.Coin{sdk.NewCoin(borrowAsset, sdk.ZeroInt())}, - BorrowInterestUnpaidCollaterals: []sdk.Coin{sdk.NewCoin(collateralAsset, sdk.ZeroInt())}, - Custodies: []sdk.Coin{sdk.NewCoin(borrowAsset, sdk.ZeroInt())}, - TakeProfitLiabilities: sdk.ZeroInt(), - TakeProfitCustodies: []sdk.Coin{sdk.NewCoin(borrowAsset, sdk.ZeroInt())}, - Leverages: []sdk.Dec{leverage}, - MtpHealth: sdk.ZeroDec(), - Position: position, - AmmPoolId: poolId, - ConsolidateLeverage: leverage, - SumCollateral: sdk.ZeroInt(), - TakeProfitPrice: takeProfitPrice, - TakeProfitBorrowRate: sdk.OneDec(), - FundingFeePaidCollaterals: []sdk.Coin{sdk.NewCoin(collateralAsset, sdk.ZeroInt())}, - FundingFeePaidCustodies: []sdk.Coin{sdk.NewCoin(borrowAsset, sdk.ZeroInt())}, - FundingFeeReceivedCollaterals: []sdk.Coin{sdk.NewCoin(collateralAsset, sdk.ZeroInt())}, - FundingFeeReceivedCustodies: []sdk.Coin{sdk.NewCoin(borrowAsset, sdk.ZeroInt())}, + Address: signer, + CollateralAsset: collateralAsset, + TradingAsset: tradingAsset, + LiabilitiesAsset: liabilitiesAsset, + CustodyAsset: custodyAsset, + Collateral: sdk.ZeroInt(), + Liabilities: sdk.ZeroInt(), + BorrowInterestPaidCollateral: sdk.ZeroInt(), + BorrowInterestPaidCustody: sdk.ZeroInt(), + BorrowInterestUnpaidCollateral: sdk.ZeroInt(), + Custody: sdk.ZeroInt(), + TakeProfitLiabilities: sdk.ZeroInt(), + TakeProfitCustody: sdk.ZeroInt(), + Leverage: leverage, + MtpHealth: sdk.ZeroDec(), + Position: position, + AmmPoolId: poolId, + ConsolidateLeverage: leverage, + SumCollateral: sdk.ZeroInt(), + TakeProfitPrice: takeProfitPrice, + TakeProfitBorrowRate: sdk.OneDec(), + FundingFeePaidCollateral: sdk.ZeroInt(), + FundingFeePaidCustody: sdk.ZeroInt(), + FundingFeeReceivedCollateral: sdk.ZeroInt(), + FundingFeeReceivedCustody: sdk.ZeroInt(), } } func (mtp MTP) Validate() error { - if len(mtp.Collaterals) < 1 { - return sdkerrors.Wrap(ErrMTPInvalid, "no asset specified") + if mtp.CollateralAsset == "" { + return sdkerrors.Wrap(ErrMTPInvalid, "no collateral asset specified") } - for _, collateral := range mtp.Collaterals { - asset := collateral.Denom - if asset == "" { - return sdkerrors.Wrap(ErrMTPInvalid, "no asset specified") - } + if mtp.CustodyAsset == "" { + return sdkerrors.Wrap(ErrMTPInvalid, "no custody asset specified") } if mtp.Address == "" { return sdkerrors.Wrap(ErrMTPInvalid, "no address specified") @@ -74,6 +75,6 @@ func NewMarginCollateralAddress(positionId uint64) sdk.AccAddress { // Generate a new margin custody wallet per position func NewMarginCustodyAddress(positionId uint64) sdk.AccAddress { - key := append([]byte("margin_collateral"), sdk.Uint64ToBigEndian(positionId)...) + key := append([]byte("margin_custody"), sdk.Uint64ToBigEndian(positionId)...) return address.Module(ModuleName, key) } diff --git a/x/margin/types/types.pb.go b/x/margin/types/types.pb.go index 3e3404b11..1c9cc6b15 100644 --- a/x/margin/types/types.pb.go +++ b/x/margin/types/types.pb.go @@ -6,7 +6,6 @@ package types import ( fmt "fmt" 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" io "io" @@ -54,30 +53,35 @@ func (Position) EnumDescriptor() ([]byte, []int) { } type MTP struct { - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - Collaterals []types.Coin `protobuf:"bytes,2,rep,name=collaterals,proto3" json:"collaterals"` - Liabilities github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,3,opt,name=liabilities,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"liabilities"` - BorrowInterestPaidCollaterals []types.Coin `protobuf:"bytes,4,rep,name=borrow_interest_paid_collaterals,json=borrowInterestPaidCollaterals,proto3" json:"borrow_interest_paid_collaterals"` - BorrowInterestPaidCustodies []types.Coin `protobuf:"bytes,5,rep,name=borrow_interest_paid_custodies,json=borrowInterestPaidCustodies,proto3" json:"borrow_interest_paid_custodies"` - BorrowInterestUnpaidCollaterals []types.Coin `protobuf:"bytes,6,rep,name=borrow_interest_unpaid_collaterals,json=borrowInterestUnpaidCollaterals,proto3" json:"borrow_interest_unpaid_collaterals"` - Custodies []types.Coin `protobuf:"bytes,7,rep,name=custodies,proto3" json:"custodies"` - TakeProfitLiabilities github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,8,opt,name=take_profit_liabilities,json=takeProfitLiabilities,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"take_profit_liabilities"` - TakeProfitCustodies []types.Coin `protobuf:"bytes,9,rep,name=take_profit_custodies,json=takeProfitCustodies,proto3" json:"take_profit_custodies"` - Leverages []github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,10,rep,name=leverages,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"leverages"` - MtpHealth github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,11,opt,name=mtp_health,json=mtpHealth,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"mtp_health"` - Position Position `protobuf:"varint,12,opt,name=position,proto3,enum=elys.margin.Position" json:"position,omitempty"` - Id uint64 `protobuf:"varint,13,opt,name=id,proto3" json:"id,omitempty"` - AmmPoolId uint64 `protobuf:"varint,14,opt,name=amm_pool_id,json=ammPoolId,proto3" json:"amm_pool_id,omitempty"` - ConsolidateLeverage github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,15,opt,name=consolidate_leverage,json=consolidateLeverage,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"consolidate_leverage"` - SumCollateral github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,16,opt,name=sum_collateral,json=sumCollateral,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"sum_collateral"` - TakeProfitPrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,17,opt,name=take_profit_price,json=takeProfitPrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"take_profit_price"` - TakeProfitBorrowRate github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,18,opt,name=take_profit_borrow_rate,json=takeProfitBorrowRate,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"take_profit_borrow_rate"` + Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` + CollateralAsset string `protobuf:"bytes,2,opt,name=collateral_asset,json=collateralAsset,proto3" json:"collateral_asset,omitempty"` + TradingAsset string `protobuf:"bytes,3,opt,name=trading_asset,json=tradingAsset,proto3" json:"trading_asset,omitempty"` + LiabilitiesAsset string `protobuf:"bytes,4,opt,name=liabilities_asset,json=liabilitiesAsset,proto3" json:"liabilities_asset,omitempty"` + CustodyAsset string `protobuf:"bytes,5,opt,name=custody_asset,json=custodyAsset,proto3" json:"custody_asset,omitempty"` + Collateral github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,6,opt,name=collateral,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"collateral"` + Liabilities github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,7,opt,name=liabilities,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"liabilities"` + BorrowInterestPaidCollateral github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,8,opt,name=borrow_interest_paid_collateral,json=borrowInterestPaidCollateral,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"borrow_interest_paid_collateral"` + BorrowInterestPaidCustody github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,9,opt,name=borrow_interest_paid_custody,json=borrowInterestPaidCustody,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"borrow_interest_paid_custody"` + BorrowInterestUnpaidCollateral github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,10,opt,name=borrow_interest_unpaid_collateral,json=borrowInterestUnpaidCollateral,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"borrow_interest_unpaid_collateral"` + Custody github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,11,opt,name=custody,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"custody"` + TakeProfitLiabilities github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,12,opt,name=take_profit_liabilities,json=takeProfitLiabilities,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"take_profit_liabilities"` + TakeProfitCustody github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,13,opt,name=take_profit_custody,json=takeProfitCustody,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"take_profit_custody"` + Leverage github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,14,opt,name=leverage,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"leverage"` + MtpHealth github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,15,opt,name=mtp_health,json=mtpHealth,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"mtp_health"` + Position Position `protobuf:"varint,16,opt,name=position,proto3,enum=elys.margin.Position" json:"position,omitempty"` + Id uint64 `protobuf:"varint,17,opt,name=id,proto3" json:"id,omitempty"` + AmmPoolId uint64 `protobuf:"varint,18,opt,name=amm_pool_id,json=ammPoolId,proto3" json:"amm_pool_id,omitempty"` + ConsolidateLeverage github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,19,opt,name=consolidate_leverage,json=consolidateLeverage,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"consolidate_leverage"` + SumCollateral github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,20,opt,name=sum_collateral,json=sumCollateral,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"sum_collateral"` + TakeProfitPrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,21,opt,name=take_profit_price,json=takeProfitPrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"take_profit_price"` + TakeProfitBorrowRate github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,22,opt,name=take_profit_borrow_rate,json=takeProfitBorrowRate,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"take_profit_borrow_rate"` // funding fee paid - FundingFeePaidCollaterals []types.Coin `protobuf:"bytes,19,rep,name=funding_fee_paid_collaterals,json=fundingFeePaidCollaterals,proto3" json:"funding_fee_paid_collaterals"` - FundingFeePaidCustodies []types.Coin `protobuf:"bytes,20,rep,name=funding_fee_paid_custodies,json=fundingFeePaidCustodies,proto3" json:"funding_fee_paid_custodies"` + FundingFeePaidCollateral github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,23,opt,name=funding_fee_paid_collateral,json=fundingFeePaidCollateral,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"funding_fee_paid_collateral"` + FundingFeePaidCustody github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,24,opt,name=funding_fee_paid_custody,json=fundingFeePaidCustody,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"funding_fee_paid_custody"` // funding fee received - FundingFeeReceivedCollaterals []types.Coin `protobuf:"bytes,21,rep,name=funding_fee_received_collaterals,json=fundingFeeReceivedCollaterals,proto3" json:"funding_fee_received_collaterals"` - FundingFeeReceivedCustodies []types.Coin `protobuf:"bytes,22,rep,name=funding_fee_received_custodies,json=fundingFeeReceivedCustodies,proto3" json:"funding_fee_received_custodies"` + FundingFeeReceivedCollateral github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,25,opt,name=funding_fee_received_collateral,json=fundingFeeReceivedCollateral,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"funding_fee_received_collateral"` + FundingFeeReceivedCustody github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,26,opt,name=funding_fee_received_custody,json=fundingFeeReceivedCustody,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"funding_fee_received_custody"` + OpenPrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,27,opt,name=open_price,json=openPrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"open_price"` } func (m *MTP) Reset() { *m = MTP{} } @@ -120,46 +124,32 @@ func (m *MTP) GetAddress() string { return "" } -func (m *MTP) GetCollaterals() []types.Coin { +func (m *MTP) GetCollateralAsset() string { if m != nil { - return m.Collaterals + return m.CollateralAsset } - return nil -} - -func (m *MTP) GetBorrowInterestPaidCollaterals() []types.Coin { - if m != nil { - return m.BorrowInterestPaidCollaterals - } - return nil -} - -func (m *MTP) GetBorrowInterestPaidCustodies() []types.Coin { - if m != nil { - return m.BorrowInterestPaidCustodies - } - return nil + return "" } -func (m *MTP) GetBorrowInterestUnpaidCollaterals() []types.Coin { +func (m *MTP) GetTradingAsset() string { if m != nil { - return m.BorrowInterestUnpaidCollaterals + return m.TradingAsset } - return nil + return "" } -func (m *MTP) GetCustodies() []types.Coin { +func (m *MTP) GetLiabilitiesAsset() string { if m != nil { - return m.Custodies + return m.LiabilitiesAsset } - return nil + return "" } -func (m *MTP) GetTakeProfitCustodies() []types.Coin { +func (m *MTP) GetCustodyAsset() string { if m != nil { - return m.TakeProfitCustodies + return m.CustodyAsset } - return nil + return "" } func (m *MTP) GetPosition() Position { @@ -183,34 +173,6 @@ func (m *MTP) GetAmmPoolId() uint64 { return 0 } -func (m *MTP) GetFundingFeePaidCollaterals() []types.Coin { - if m != nil { - return m.FundingFeePaidCollaterals - } - return nil -} - -func (m *MTP) GetFundingFeePaidCustodies() []types.Coin { - if m != nil { - return m.FundingFeePaidCustodies - } - return nil -} - -func (m *MTP) GetFundingFeeReceivedCollaterals() []types.Coin { - if m != nil { - return m.FundingFeeReceivedCollaterals - } - return nil -} - -func (m *MTP) GetFundingFeeReceivedCustodies() []types.Coin { - if m != nil { - return m.FundingFeeReceivedCustodies - } - return nil -} - type WhiteList struct { ValidatorList []string `protobuf:"bytes,1,rep,name=validator_list,json=validatorList,proto3" json:"validator_list,omitempty"` } @@ -264,55 +226,56 @@ func init() { func init() { proto.RegisterFile("elys/margin/types.proto", fileDescriptor_cd1c09c977f732f9) } var fileDescriptor_cd1c09c977f732f9 = []byte{ - // 753 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x95, 0x5f, 0x4f, 0xda, 0x50, - 0x18, 0xc6, 0x29, 0xa0, 0xc2, 0x61, 0x20, 0x1e, 0x61, 0x56, 0xb7, 0x55, 0x62, 0xb2, 0x85, 0x6c, - 0xb1, 0x9d, 0xee, 0x7a, 0x17, 0xc3, 0x3f, 0x93, 0x04, 0xb5, 0xa9, 0x9a, 0x25, 0x66, 0x49, 0x77, - 0x68, 0x0f, 0x70, 0x62, 0xdb, 0xd3, 0xf4, 0x1c, 0x70, 0x7e, 0x8b, 0x7d, 0x2c, 0x2f, 0xbd, 0x5c, - 0x76, 0x61, 0x16, 0xfd, 0x18, 0xbb, 0x59, 0x5a, 0x0a, 0x2d, 0xc8, 0x45, 0xe5, 0x0a, 0xda, 0x73, - 0xfa, 0x7b, 0x9e, 0xb7, 0xe7, 0x79, 0xdf, 0x82, 0x35, 0x6c, 0xdd, 0x30, 0xc5, 0x46, 0x5e, 0x97, - 0x38, 0x0a, 0xbf, 0x71, 0x31, 0x93, 0x5d, 0x8f, 0x72, 0x0a, 0x0b, 0xfe, 0x82, 0x3c, 0x5c, 0xd8, - 0xa8, 0x74, 0x69, 0x97, 0x06, 0xf7, 0x15, 0xff, 0xdf, 0x70, 0xcb, 0x86, 0x64, 0x50, 0x66, 0x53, - 0xa6, 0xb4, 0x11, 0xc3, 0xca, 0x60, 0xa7, 0x8d, 0x39, 0xda, 0x51, 0x0c, 0x4a, 0x9c, 0xe1, 0xfa, - 0xd6, 0xbf, 0x22, 0xc8, 0x1c, 0x9f, 0xab, 0x50, 0x04, 0x4b, 0xc8, 0x34, 0x3d, 0xcc, 0x98, 0x28, - 0xd4, 0x84, 0x7a, 0x5e, 0x1b, 0x5d, 0xc2, 0x2f, 0xa0, 0x60, 0x50, 0xcb, 0x42, 0x1c, 0x7b, 0xc8, - 0x62, 0x62, 0xba, 0x96, 0xa9, 0x17, 0x76, 0xd7, 0xe5, 0x21, 0x57, 0xf6, 0xb9, 0x72, 0xc8, 0x95, - 0xf7, 0x28, 0x71, 0x1a, 0xd9, 0xdb, 0xfb, 0xcd, 0x94, 0x16, 0x7f, 0x06, 0xaa, 0xa0, 0x60, 0x11, - 0xd4, 0x26, 0x16, 0xe1, 0x04, 0x33, 0x31, 0xe3, 0x0b, 0x34, 0x64, 0x7f, 0xdf, 0x9f, 0xfb, 0xcd, - 0x77, 0x5d, 0xc2, 0x7b, 0xfd, 0xb6, 0x6c, 0x50, 0x5b, 0x09, 0xcd, 0x0e, 0x7f, 0xb6, 0x99, 0x79, - 0x15, 0x96, 0xdb, 0x74, 0xb8, 0x16, 0x47, 0xc0, 0x1e, 0xa8, 0xb5, 0xa9, 0xe7, 0xd1, 0x6b, 0x9d, - 0x38, 0x1c, 0x7b, 0x98, 0x71, 0xdd, 0x45, 0xc4, 0xd4, 0xe3, 0x4e, 0xb3, 0xc9, 0x9c, 0xbe, 0x19, - 0x82, 0x9a, 0x21, 0x47, 0x45, 0xc4, 0xdc, 0x8b, 0x79, 0x37, 0x81, 0x34, 0x5b, 0xa9, 0xcf, 0x38, - 0x35, 0xfd, 0x72, 0x16, 0x92, 0xe9, 0xbc, 0x9a, 0xa1, 0x33, 0x62, 0x40, 0x0b, 0x6c, 0x4d, 0xab, - 0xf4, 0x9d, 0x27, 0x15, 0x2d, 0x26, 0x53, 0xda, 0x9c, 0x54, 0xba, 0x08, 0x40, 0xf1, 0x9a, 0x3e, - 0x83, 0x7c, 0x64, 0x7f, 0x29, 0x19, 0x34, 0x7a, 0x02, 0x76, 0xc0, 0x1a, 0x47, 0x57, 0x58, 0x77, - 0x3d, 0xda, 0x21, 0x5c, 0x8f, 0x1f, 0x6d, 0x6e, 0xae, 0xa3, 0xad, 0xfa, 0x38, 0x35, 0xa0, 0xb5, - 0x62, 0x87, 0x7c, 0x06, 0xaa, 0x71, 0x9d, 0xc8, 0x72, 0x3e, 0x99, 0xe5, 0xd5, 0x08, 0x1b, 0xbd, - 0xe9, 0x16, 0xc8, 0x5b, 0x78, 0x80, 0x3d, 0xd4, 0xc5, 0x4c, 0x04, 0xb5, 0xcc, 0x33, 0xed, 0xee, - 0x63, 0x43, 0x8b, 0x00, 0xf0, 0x18, 0x00, 0x9b, 0xbb, 0x7a, 0x0f, 0x23, 0x8b, 0xf7, 0xc4, 0xc2, - 0xb3, 0xab, 0x0f, 0x70, 0x36, 0x77, 0x8f, 0x02, 0x00, 0xdc, 0x01, 0x39, 0x97, 0x32, 0xc2, 0x09, - 0x75, 0xc4, 0x17, 0x35, 0xa1, 0x5e, 0xda, 0xad, 0xca, 0xb1, 0x1e, 0x97, 0xd5, 0x70, 0x51, 0x1b, - 0x6f, 0x83, 0x25, 0x90, 0x26, 0xa6, 0x58, 0xac, 0x09, 0xf5, 0xac, 0x96, 0x26, 0x26, 0x94, 0x40, - 0x01, 0xd9, 0xb6, 0xee, 0x52, 0x6a, 0xe9, 0xc4, 0x14, 0x4b, 0xc1, 0x42, 0x1e, 0xd9, 0xb6, 0x4a, - 0xa9, 0xd5, 0x34, 0x21, 0x02, 0x15, 0x83, 0x3a, 0x8c, 0x5a, 0xc4, 0x44, 0x1c, 0xeb, 0xa3, 0x52, - 0xc4, 0xe5, 0xb9, 0xbc, 0xaf, 0xc6, 0x58, 0xad, 0x10, 0x05, 0x2f, 0x40, 0x89, 0xf5, 0xed, 0x58, - 0x72, 0xc5, 0xf2, 0x5c, 0xb1, 0x28, 0xb2, 0xbe, 0x1d, 0xc5, 0x16, 0x5e, 0x82, 0x95, 0x78, 0x1c, - 0x5c, 0x8f, 0x18, 0x58, 0x5c, 0x99, 0xcb, 0xf6, 0x72, 0x94, 0x0c, 0xd5, 0xc7, 0x40, 0x3c, 0x19, - 0xe9, 0xb0, 0x17, 0x3d, 0xc4, 0xb1, 0x08, 0xe7, 0x52, 0xa8, 0x44, 0x0a, 0x8d, 0x00, 0xa6, 0x21, - 0x8e, 0xe1, 0x0f, 0xf0, 0xba, 0xd3, 0x77, 0x4c, 0xe2, 0x74, 0xf5, 0x0e, 0xc6, 0x4f, 0x47, 0xd6, - 0x6a, 0xb2, 0x60, 0xaf, 0x87, 0x90, 0x43, 0x8c, 0xa7, 0xc7, 0xd5, 0x77, 0xb0, 0xf1, 0x54, 0x61, - 0xdc, 0x38, 0x95, 0x64, 0xfc, 0xb5, 0x29, 0xfe, 0xb8, 0x79, 0x7a, 0xa0, 0x16, 0xa7, 0x7b, 0xd8, - 0xc0, 0x64, 0x80, 0x27, 0x6b, 0xa8, 0x26, 0x1c, 0xbb, 0x91, 0x86, 0x16, 0x62, 0xa6, 0xc6, 0xee, - 0x6c, 0xa5, 0x71, 0x2d, 0x2f, 0x13, 0x8e, 0xdd, 0x19, 0x3a, 0x23, 0xc6, 0xd6, 0x2e, 0xc8, 0x7f, - 0xeb, 0x11, 0x8e, 0x5b, 0x84, 0x71, 0xf8, 0x16, 0x94, 0x06, 0x28, 0x88, 0x32, 0xf5, 0x74, 0x8b, - 0x30, 0x2e, 0x0a, 0xfe, 0x78, 0xd0, 0x8a, 0xe3, 0xbb, 0xfe, 0xb6, 0xf7, 0x1f, 0x41, 0x6e, 0xd4, - 0x86, 0x70, 0x19, 0x14, 0x2e, 0x4e, 0xce, 0xd4, 0x83, 0xbd, 0xe6, 0x61, 0xf3, 0x60, 0xbf, 0x9c, - 0x82, 0x39, 0x90, 0x6d, 0x9d, 0x9e, 0x7c, 0x2d, 0x0b, 0x30, 0x0f, 0x16, 0xce, 0x8e, 0x4e, 0xb5, - 0xf3, 0x72, 0xba, 0x71, 0x70, 0xfb, 0x20, 0x09, 0x77, 0x0f, 0x92, 0xf0, 0xf7, 0x41, 0x12, 0x7e, - 0x3d, 0x4a, 0xa9, 0xbb, 0x47, 0x29, 0xf5, 0xfb, 0x51, 0x4a, 0x5d, 0x7e, 0x88, 0xa5, 0xc9, 0xef, - 0xf3, 0x6d, 0x07, 0xf3, 0x6b, 0xea, 0x5d, 0x05, 0x17, 0xca, 0xcf, 0x89, 0x6f, 0x7e, 0x7b, 0x31, - 0xf8, 0x62, 0x7f, 0xfa, 0x1f, 0x00, 0x00, 0xff, 0xff, 0x17, 0xea, 0x43, 0xef, 0x0f, 0x08, 0x00, - 0x00, + // 782 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x96, 0xdf, 0x6e, 0xdb, 0x36, + 0x14, 0xc6, 0xad, 0x24, 0x6d, 0xec, 0xe3, 0xc6, 0x71, 0x18, 0x67, 0x61, 0xff, 0x40, 0xf6, 0x3a, + 0x6c, 0xf0, 0x56, 0xd4, 0xde, 0xba, 0x27, 0x58, 0xda, 0x74, 0xf1, 0xe0, 0xa4, 0x82, 0xda, 0x60, + 0x40, 0x2f, 0x26, 0xd0, 0x12, 0x6d, 0x13, 0x91, 0x44, 0x41, 0xa4, 0xd2, 0xf9, 0x2d, 0xf6, 0x58, + 0xbd, 0xec, 0xe5, 0xb0, 0x8b, 0x62, 0x70, 0x5e, 0x64, 0x90, 0x44, 0xdb, 0xb4, 0xeb, 0x9b, 0xf1, + 0xca, 0x16, 0xf9, 0xe9, 0xf7, 0x9d, 0x43, 0x9d, 0x73, 0x24, 0x38, 0xa5, 0xe1, 0x4c, 0xf4, 0x23, + 0x92, 0x4e, 0x58, 0xdc, 0x97, 0xb3, 0x84, 0x8a, 0x5e, 0x92, 0x72, 0xc9, 0x51, 0x3d, 0xdf, 0xe8, + 0x95, 0x1b, 0x8f, 0x5a, 0x13, 0x3e, 0xe1, 0xc5, 0x7a, 0x3f, 0xff, 0x57, 0x4a, 0x9e, 0xce, 0x9b, + 0xb0, 0x7b, 0xf9, 0xce, 0x41, 0x18, 0xf6, 0x49, 0x10, 0xa4, 0x54, 0x08, 0x6c, 0x75, 0xac, 0x6e, + 0xcd, 0x5d, 0x5c, 0xa2, 0xef, 0xa1, 0xe9, 0xf3, 0x30, 0x24, 0x92, 0xa6, 0x24, 0xf4, 0x88, 0x10, + 0x54, 0xe2, 0x9d, 0x42, 0x72, 0xb8, 0x5a, 0xff, 0x25, 0x5f, 0x46, 0xdf, 0xc0, 0x81, 0x4c, 0x49, + 0xc0, 0xe2, 0x89, 0xd2, 0xed, 0x16, 0xba, 0x07, 0x6a, 0xb1, 0x14, 0x3d, 0x83, 0xa3, 0x90, 0x91, + 0x11, 0x0b, 0x99, 0x64, 0x54, 0x28, 0xe1, 0x5e, 0x21, 0x6c, 0x6a, 0x1b, 0x4b, 0xa2, 0x9f, 0x09, + 0xc9, 0x83, 0x99, 0x12, 0xde, 0x2b, 0x89, 0x6a, 0xb1, 0x14, 0x5d, 0x01, 0xac, 0x22, 0xc1, 0xf7, + 0x73, 0xc5, 0x59, 0xef, 0xe3, 0xe7, 0x76, 0xe5, 0x9f, 0xcf, 0xed, 0xef, 0x26, 0x4c, 0x4e, 0xb3, + 0x51, 0xcf, 0xe7, 0x51, 0xdf, 0xe7, 0x22, 0xe2, 0x42, 0xfd, 0x3c, 0x17, 0xc1, 0x8d, 0x3a, 0xac, + 0x41, 0x2c, 0x5d, 0x8d, 0x80, 0x1c, 0xa8, 0x6b, 0x81, 0xe0, 0x7d, 0x23, 0xa0, 0x8e, 0x40, 0x19, + 0xb4, 0x47, 0x3c, 0x4d, 0xf9, 0x07, 0x8f, 0xc5, 0x92, 0xa6, 0x54, 0x48, 0x2f, 0x21, 0x2c, 0xf0, + 0xb4, 0xb0, 0xab, 0x46, 0x2e, 0x4f, 0x4a, 0xec, 0x40, 0x51, 0x1d, 0xc2, 0x82, 0x97, 0xab, 0x44, + 0x38, 0x3c, 0xd9, 0x6e, 0x5b, 0x9e, 0x1e, 0xae, 0x19, 0x79, 0x3e, 0xdc, 0xe2, 0x59, 0x02, 0xd1, + 0x0c, 0xbe, 0xde, 0x34, 0xcc, 0xe2, 0xcd, 0x4c, 0xc1, 0xc8, 0xd5, 0x5e, 0x77, 0xbd, 0x2e, 0xb0, + 0x5a, 0xae, 0x17, 0xb0, 0xbf, 0x48, 0xab, 0x6e, 0x64, 0xb0, 0xb8, 0x1d, 0x8d, 0xe1, 0x54, 0x92, + 0x1b, 0xea, 0x25, 0x29, 0x1f, 0x33, 0xe9, 0xe9, 0xa5, 0xf0, 0xc0, 0x88, 0x7c, 0x92, 0xe3, 0x9c, + 0x82, 0x36, 0xd4, 0x8a, 0xe2, 0x0f, 0x38, 0xd6, 0x7d, 0x16, 0xd1, 0x1f, 0x18, 0x79, 0x1c, 0xad, + 0x3c, 0x16, 0x0f, 0xe3, 0x37, 0xa8, 0x86, 0xf4, 0x96, 0xa6, 0x64, 0x42, 0x71, 0xe3, 0x7f, 0x43, + 0x5f, 0x51, 0xdf, 0x5d, 0xde, 0x8f, 0x2e, 0x01, 0x22, 0x99, 0x78, 0x53, 0x4a, 0x42, 0x39, 0xc5, + 0x87, 0x46, 0xb4, 0x5a, 0x24, 0x93, 0x8b, 0x02, 0x80, 0x7e, 0x82, 0x6a, 0xc2, 0x05, 0x93, 0x8c, + 0xc7, 0xb8, 0xd9, 0xb1, 0xba, 0x8d, 0x17, 0x27, 0x3d, 0x6d, 0x56, 0xf5, 0x1c, 0xb5, 0xe9, 0x2e, + 0x65, 0xa8, 0x01, 0x3b, 0x2c, 0xc0, 0x47, 0x1d, 0xab, 0xbb, 0xe7, 0xee, 0xb0, 0x00, 0xd9, 0x50, + 0x27, 0x51, 0xe4, 0x25, 0x9c, 0x87, 0x1e, 0x0b, 0x30, 0x2a, 0x36, 0x6a, 0x24, 0x8a, 0x1c, 0xce, + 0xc3, 0x41, 0x80, 0x08, 0xb4, 0x7c, 0x1e, 0x0b, 0x1e, 0xb2, 0x80, 0x48, 0xea, 0x2d, 0x4f, 0xe2, + 0xd8, 0x28, 0xf6, 0x63, 0x8d, 0x35, 0x5c, 0x1c, 0xca, 0x35, 0x34, 0x44, 0x16, 0xe9, 0xa5, 0xdd, + 0x32, 0x7a, 0x76, 0x07, 0x22, 0x8b, 0xb4, 0x4a, 0x7e, 0x0f, 0x47, 0x7a, 0x5d, 0x24, 0x29, 0xf3, + 0x29, 0x3e, 0x31, 0x0a, 0xfb, 0x70, 0x55, 0x15, 0x4e, 0x8e, 0x41, 0x74, 0xbd, 0xb6, 0x55, 0xb3, + 0xa6, 0x44, 0x52, 0xfc, 0x95, 0x91, 0x43, 0x6b, 0xe5, 0x70, 0x56, 0xc0, 0x5c, 0x22, 0x29, 0x8a, + 0xe0, 0xf1, 0x38, 0x8b, 0x8b, 0x17, 0xc1, 0x98, 0xd2, 0x2f, 0x66, 0xdd, 0xa9, 0xd1, 0x31, 0x61, + 0x85, 0x7c, 0x4d, 0xe9, 0xc6, 0x9c, 0x9b, 0x00, 0xfe, 0xd2, 0x4e, 0xb5, 0x13, 0x36, 0x6b, 0xd9, + 0x0d, 0x2f, 0xd5, 0x52, 0x19, 0xb4, 0x75, 0xa3, 0x94, 0xfa, 0x94, 0xdd, 0xd2, 0xb5, 0xdc, 0x1e, + 0x9a, 0xcd, 0xf1, 0x95, 0x9f, 0xab, 0xa0, 0xeb, 0x73, 0x7c, 0xbb, 0xad, 0xca, 0xf1, 0x91, 0xd9, + 0x1c, 0xdf, 0xe2, 0xa9, 0xf2, 0xbc, 0x04, 0xe0, 0x09, 0x8d, 0x55, 0xed, 0x3d, 0x36, 0x6b, 0xf7, + 0x9c, 0x50, 0x54, 0xdd, 0xd3, 0x17, 0x50, 0xfb, 0x7d, 0xca, 0x24, 0x1d, 0x32, 0x21, 0xd1, 0xb7, + 0xd0, 0xb8, 0x25, 0x45, 0x27, 0xf1, 0xd4, 0x0b, 0x99, 0x90, 0xd8, 0xea, 0xec, 0x76, 0x6b, 0xee, + 0xc1, 0x72, 0x35, 0x97, 0xfd, 0xf0, 0x23, 0x54, 0x17, 0x53, 0x00, 0x1d, 0x42, 0xfd, 0xfa, 0xea, + 0xad, 0x73, 0xfe, 0x72, 0xf0, 0x7a, 0x70, 0xfe, 0xaa, 0x59, 0x41, 0x55, 0xd8, 0x1b, 0xbe, 0xb9, + 0xfa, 0xb5, 0x69, 0xa1, 0x1a, 0xdc, 0x7b, 0x7b, 0xf1, 0xc6, 0x7d, 0xd7, 0xdc, 0x39, 0x3b, 0xff, + 0x38, 0xb7, 0xad, 0x4f, 0x73, 0xdb, 0xfa, 0x77, 0x6e, 0x5b, 0x7f, 0xdd, 0xd9, 0x95, 0x4f, 0x77, + 0x76, 0xe5, 0xef, 0x3b, 0xbb, 0xf2, 0xfe, 0x99, 0x16, 0x72, 0x3e, 0x66, 0x9e, 0xc7, 0x54, 0x7e, + 0xe0, 0xe9, 0x4d, 0x71, 0xd1, 0xff, 0x73, 0xed, 0xd3, 0x69, 0x74, 0xbf, 0xf8, 0x30, 0xfa, 0xf9, + 0xbf, 0x00, 0x00, 0x00, 0xff, 0xff, 0xe4, 0xec, 0x4e, 0x08, 0x56, 0x09, 0x00, 0x00, } func (m *MTP) Marshal() (dAtA []byte, err error) { @@ -335,70 +298,66 @@ func (m *MTP) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - if len(m.FundingFeeReceivedCustodies) > 0 { - for iNdEx := len(m.FundingFeeReceivedCustodies) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.FundingFeeReceivedCustodies[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1 - i-- - dAtA[i] = 0xb2 + { + size := m.OpenPrice.Size() + i -= size + if _, err := m.OpenPrice.MarshalTo(dAtA[i:]); err != nil { + return 0, err } + i = encodeVarintTypes(dAtA, i, uint64(size)) } - if len(m.FundingFeeReceivedCollaterals) > 0 { - for iNdEx := len(m.FundingFeeReceivedCollaterals) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.FundingFeeReceivedCollaterals[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1 - i-- - dAtA[i] = 0xaa + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0xda + { + size := m.FundingFeeReceivedCustody.Size() + i -= size + if _, err := m.FundingFeeReceivedCustody.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0xd2 + { + size := m.FundingFeeReceivedCollateral.Size() + i -= size + if _, err := m.FundingFeeReceivedCollateral.MarshalTo(dAtA[i:]); err != nil { + return 0, err } + i = encodeVarintTypes(dAtA, i, uint64(size)) } - if len(m.FundingFeePaidCustodies) > 0 { - for iNdEx := len(m.FundingFeePaidCustodies) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.FundingFeePaidCustodies[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1 - i-- - dAtA[i] = 0xa2 + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0xca + { + size := m.FundingFeePaidCustody.Size() + i -= size + if _, err := m.FundingFeePaidCustody.MarshalTo(dAtA[i:]); err != nil { + return 0, err } + i = encodeVarintTypes(dAtA, i, uint64(size)) } - if len(m.FundingFeePaidCollaterals) > 0 { - for iNdEx := len(m.FundingFeePaidCollaterals) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.FundingFeePaidCollaterals[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1 - i-- - dAtA[i] = 0x9a + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0xc2 + { + size := m.FundingFeePaidCollateral.Size() + i -= size + if _, err := m.FundingFeePaidCollateral.MarshalTo(dAtA[i:]); err != nil { + return 0, err } + i = encodeVarintTypes(dAtA, i, uint64(size)) } + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0xba { size := m.TakeProfitBorrowRate.Size() i -= size @@ -410,7 +369,7 @@ func (m *MTP) MarshalToSizedBuffer(dAtA []byte) (int, error) { i-- dAtA[i] = 0x1 i-- - dAtA[i] = 0x92 + dAtA[i] = 0xb2 { size := m.TakeProfitPrice.Size() i -= size @@ -422,7 +381,7 @@ func (m *MTP) MarshalToSizedBuffer(dAtA []byte) (int, error) { i-- dAtA[i] = 0x1 i-- - dAtA[i] = 0x8a + dAtA[i] = 0xaa { size := m.SumCollateral.Size() i -= size @@ -434,7 +393,7 @@ func (m *MTP) MarshalToSizedBuffer(dAtA []byte) (int, error) { i-- dAtA[i] = 0x1 i-- - dAtA[i] = 0x82 + dAtA[i] = 0xa2 { size := m.ConsolidateLeverage.Size() i -= size @@ -444,21 +403,29 @@ func (m *MTP) MarshalToSizedBuffer(dAtA []byte) (int, error) { i = encodeVarintTypes(dAtA, i, uint64(size)) } i-- - dAtA[i] = 0x7a + dAtA[i] = 0x1 + i-- + dAtA[i] = 0x9a if m.AmmPoolId != 0 { i = encodeVarintTypes(dAtA, i, uint64(m.AmmPoolId)) i-- - dAtA[i] = 0x70 + dAtA[i] = 0x1 + i-- + dAtA[i] = 0x90 } if m.Id != 0 { i = encodeVarintTypes(dAtA, i, uint64(m.Id)) i-- - dAtA[i] = 0x68 + dAtA[i] = 0x1 + i-- + dAtA[i] = 0x88 } if m.Position != 0 { i = encodeVarintTypes(dAtA, i, uint64(m.Position)) i-- - dAtA[i] = 0x60 + dAtA[i] = 0x1 + i-- + dAtA[i] = 0x80 } { size := m.MtpHealth.Size() @@ -469,35 +436,27 @@ func (m *MTP) MarshalToSizedBuffer(dAtA []byte) (int, error) { i = encodeVarintTypes(dAtA, i, uint64(size)) } i-- - dAtA[i] = 0x5a - if len(m.Leverages) > 0 { - for iNdEx := len(m.Leverages) - 1; iNdEx >= 0; iNdEx-- { - { - size := m.Leverages[iNdEx].Size() - i -= size - if _, err := m.Leverages[iNdEx].MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x52 + dAtA[i] = 0x7a + { + size := m.Leverage.Size() + i -= size + if _, err := m.Leverage.MarshalTo(dAtA[i:]); err != nil { + return 0, err } + i = encodeVarintTypes(dAtA, i, uint64(size)) } - if len(m.TakeProfitCustodies) > 0 { - for iNdEx := len(m.TakeProfitCustodies) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TakeProfitCustodies[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x4a + i-- + dAtA[i] = 0x72 + { + size := m.TakeProfitCustody.Size() + i -= size + if _, err := m.TakeProfitCustody.MarshalTo(dAtA[i:]); err != nil { + return 0, err } + i = encodeVarintTypes(dAtA, i, uint64(size)) } + i-- + dAtA[i] = 0x6a { size := m.TakeProfitLiabilities.Size() i -= size @@ -507,63 +466,47 @@ func (m *MTP) MarshalToSizedBuffer(dAtA []byte) (int, error) { i = encodeVarintTypes(dAtA, i, uint64(size)) } i-- - dAtA[i] = 0x42 - if len(m.Custodies) > 0 { - for iNdEx := len(m.Custodies) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Custodies[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a + dAtA[i] = 0x62 + { + size := m.Custody.Size() + i -= size + if _, err := m.Custody.MarshalTo(dAtA[i:]); err != nil { + return 0, err } + i = encodeVarintTypes(dAtA, i, uint64(size)) } - if len(m.BorrowInterestUnpaidCollaterals) > 0 { - for iNdEx := len(m.BorrowInterestUnpaidCollaterals) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.BorrowInterestUnpaidCollaterals[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 + i-- + dAtA[i] = 0x5a + { + size := m.BorrowInterestUnpaidCollateral.Size() + i -= size + if _, err := m.BorrowInterestUnpaidCollateral.MarshalTo(dAtA[i:]); err != nil { + return 0, err } + i = encodeVarintTypes(dAtA, i, uint64(size)) } - if len(m.BorrowInterestPaidCustodies) > 0 { - for iNdEx := len(m.BorrowInterestPaidCustodies) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.BorrowInterestPaidCustodies[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a + i-- + dAtA[i] = 0x52 + { + size := m.BorrowInterestPaidCustody.Size() + i -= size + if _, err := m.BorrowInterestPaidCustody.MarshalTo(dAtA[i:]); err != nil { + return 0, err } + i = encodeVarintTypes(dAtA, i, uint64(size)) } - if len(m.BorrowInterestPaidCollaterals) > 0 { - for iNdEx := len(m.BorrowInterestPaidCollaterals) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.BorrowInterestPaidCollaterals[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 + i-- + dAtA[i] = 0x4a + { + size := m.BorrowInterestPaidCollateral.Size() + i -= size + if _, err := m.BorrowInterestPaidCollateral.MarshalTo(dAtA[i:]); err != nil { + return 0, err } + i = encodeVarintTypes(dAtA, i, uint64(size)) } + i-- + dAtA[i] = 0x42 { size := m.Liabilities.Size() i -= size @@ -573,20 +516,44 @@ func (m *MTP) MarshalToSizedBuffer(dAtA []byte) (int, error) { i = encodeVarintTypes(dAtA, i, uint64(size)) } i-- - dAtA[i] = 0x1a - if len(m.Collaterals) > 0 { - for iNdEx := len(m.Collaterals) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Collaterals[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 + dAtA[i] = 0x3a + { + size := m.Collateral.Size() + i -= size + if _, err := m.Collateral.MarshalTo(dAtA[i:]); err != nil { + return 0, err } + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + if len(m.CustodyAsset) > 0 { + i -= len(m.CustodyAsset) + copy(dAtA[i:], m.CustodyAsset) + i = encodeVarintTypes(dAtA, i, uint64(len(m.CustodyAsset))) + i-- + dAtA[i] = 0x2a + } + if len(m.LiabilitiesAsset) > 0 { + i -= len(m.LiabilitiesAsset) + copy(dAtA[i:], m.LiabilitiesAsset) + i = encodeVarintTypes(dAtA, i, uint64(len(m.LiabilitiesAsset))) + i-- + dAtA[i] = 0x22 + } + if len(m.TradingAsset) > 0 { + i -= len(m.TradingAsset) + copy(dAtA[i:], m.TradingAsset) + i = encodeVarintTypes(dAtA, i, uint64(len(m.TradingAsset))) + i-- + dAtA[i] = 0x1a + } + if len(m.CollateralAsset) > 0 { + i -= len(m.CollateralAsset) + copy(dAtA[i:], m.CollateralAsset) + i = encodeVarintTypes(dAtA, i, uint64(len(m.CollateralAsset))) + i-- + dAtA[i] = 0x12 } if len(m.Address) > 0 { i -= len(m.Address) @@ -651,95 +618,69 @@ func (m *MTP) Size() (n int) { if l > 0 { n += 1 + l + sovTypes(uint64(l)) } - if len(m.Collaterals) > 0 { - for _, e := range m.Collaterals { - l = e.Size() - n += 1 + l + sovTypes(uint64(l)) - } - } - l = m.Liabilities.Size() - n += 1 + l + sovTypes(uint64(l)) - if len(m.BorrowInterestPaidCollaterals) > 0 { - for _, e := range m.BorrowInterestPaidCollaterals { - l = e.Size() - n += 1 + l + sovTypes(uint64(l)) - } + l = len(m.CollateralAsset) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) } - if len(m.BorrowInterestPaidCustodies) > 0 { - for _, e := range m.BorrowInterestPaidCustodies { - l = e.Size() - n += 1 + l + sovTypes(uint64(l)) - } + l = len(m.TradingAsset) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) } - if len(m.BorrowInterestUnpaidCollaterals) > 0 { - for _, e := range m.BorrowInterestUnpaidCollaterals { - l = e.Size() - n += 1 + l + sovTypes(uint64(l)) - } + l = len(m.LiabilitiesAsset) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) } - if len(m.Custodies) > 0 { - for _, e := range m.Custodies { - l = e.Size() - n += 1 + l + sovTypes(uint64(l)) - } + l = len(m.CustodyAsset) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) } + l = m.Collateral.Size() + n += 1 + l + sovTypes(uint64(l)) + l = m.Liabilities.Size() + n += 1 + l + sovTypes(uint64(l)) + l = m.BorrowInterestPaidCollateral.Size() + n += 1 + l + sovTypes(uint64(l)) + l = m.BorrowInterestPaidCustody.Size() + n += 1 + l + sovTypes(uint64(l)) + l = m.BorrowInterestUnpaidCollateral.Size() + n += 1 + l + sovTypes(uint64(l)) + l = m.Custody.Size() + n += 1 + l + sovTypes(uint64(l)) l = m.TakeProfitLiabilities.Size() n += 1 + l + sovTypes(uint64(l)) - if len(m.TakeProfitCustodies) > 0 { - for _, e := range m.TakeProfitCustodies { - l = e.Size() - n += 1 + l + sovTypes(uint64(l)) - } - } - if len(m.Leverages) > 0 { - for _, e := range m.Leverages { - l = e.Size() - n += 1 + l + sovTypes(uint64(l)) - } - } + l = m.TakeProfitCustody.Size() + n += 1 + l + sovTypes(uint64(l)) + l = m.Leverage.Size() + n += 1 + l + sovTypes(uint64(l)) l = m.MtpHealth.Size() n += 1 + l + sovTypes(uint64(l)) if m.Position != 0 { - n += 1 + sovTypes(uint64(m.Position)) + n += 2 + sovTypes(uint64(m.Position)) } if m.Id != 0 { - n += 1 + sovTypes(uint64(m.Id)) + n += 2 + sovTypes(uint64(m.Id)) } if m.AmmPoolId != 0 { - n += 1 + sovTypes(uint64(m.AmmPoolId)) + n += 2 + sovTypes(uint64(m.AmmPoolId)) } l = m.ConsolidateLeverage.Size() - n += 1 + l + sovTypes(uint64(l)) + n += 2 + l + sovTypes(uint64(l)) l = m.SumCollateral.Size() n += 2 + l + sovTypes(uint64(l)) l = m.TakeProfitPrice.Size() n += 2 + l + sovTypes(uint64(l)) l = m.TakeProfitBorrowRate.Size() n += 2 + l + sovTypes(uint64(l)) - if len(m.FundingFeePaidCollaterals) > 0 { - for _, e := range m.FundingFeePaidCollaterals { - l = e.Size() - n += 2 + l + sovTypes(uint64(l)) - } - } - if len(m.FundingFeePaidCustodies) > 0 { - for _, e := range m.FundingFeePaidCustodies { - l = e.Size() - n += 2 + l + sovTypes(uint64(l)) - } - } - if len(m.FundingFeeReceivedCollaterals) > 0 { - for _, e := range m.FundingFeeReceivedCollaterals { - l = e.Size() - n += 2 + l + sovTypes(uint64(l)) - } - } - if len(m.FundingFeeReceivedCustodies) > 0 { - for _, e := range m.FundingFeeReceivedCustodies { - l = e.Size() - n += 2 + l + sovTypes(uint64(l)) - } - } + l = m.FundingFeePaidCollateral.Size() + n += 2 + l + sovTypes(uint64(l)) + l = m.FundingFeePaidCustody.Size() + n += 2 + l + sovTypes(uint64(l)) + l = m.FundingFeeReceivedCollateral.Size() + n += 2 + l + sovTypes(uint64(l)) + l = m.FundingFeeReceivedCustody.Size() + n += 2 + l + sovTypes(uint64(l)) + l = m.OpenPrice.Size() + n += 2 + l + sovTypes(uint64(l)) return n } @@ -827,9 +768,105 @@ func (m *MTP) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Collaterals", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field CollateralAsset", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + 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 ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CollateralAsset = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TradingAsset", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + 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 ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.TradingAsset = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LiabilitiesAsset", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + 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 ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.LiabilitiesAsset = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CustodyAsset", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTypes @@ -839,27 +876,59 @@ func (m *MTP) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthTypes } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTypes } if postIndex > l { return io.ErrUnexpectedEOF } - m.Collaterals = append(m.Collaterals, types.Coin{}) - if err := m.Collaterals[len(m.Collaterals)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.CustodyAsset = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Collateral", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + 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 ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Collateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 3: + case 7: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Liabilities", wireType) } @@ -893,11 +962,11 @@ func (m *MTP) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex - case 4: + case 8: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BorrowInterestPaidCollaterals", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field BorrowInterestPaidCollateral", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTypes @@ -907,31 +976,31 @@ func (m *MTP) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthTypes } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTypes } if postIndex > l { return io.ErrUnexpectedEOF } - m.BorrowInterestPaidCollaterals = append(m.BorrowInterestPaidCollaterals, types.Coin{}) - if err := m.BorrowInterestPaidCollaterals[len(m.BorrowInterestPaidCollaterals)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.BorrowInterestPaidCollateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 5: + case 9: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BorrowInterestPaidCustodies", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field BorrowInterestPaidCustody", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTypes @@ -941,31 +1010,31 @@ func (m *MTP) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthTypes } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTypes } if postIndex > l { return io.ErrUnexpectedEOF } - m.BorrowInterestPaidCustodies = append(m.BorrowInterestPaidCustodies, types.Coin{}) - if err := m.BorrowInterestPaidCustodies[len(m.BorrowInterestPaidCustodies)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.BorrowInterestPaidCustody.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 6: + case 10: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BorrowInterestUnpaidCollaterals", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field BorrowInterestUnpaidCollateral", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTypes @@ -975,31 +1044,31 @@ func (m *MTP) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthTypes } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTypes } if postIndex > l { return io.ErrUnexpectedEOF } - m.BorrowInterestUnpaidCollaterals = append(m.BorrowInterestUnpaidCollaterals, types.Coin{}) - if err := m.BorrowInterestUnpaidCollaterals[len(m.BorrowInterestUnpaidCollaterals)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.BorrowInterestUnpaidCollateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 7: + case 11: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Custodies", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Custody", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTypes @@ -1009,27 +1078,27 @@ func (m *MTP) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthTypes } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTypes } if postIndex > l { return io.ErrUnexpectedEOF } - m.Custodies = append(m.Custodies, types.Coin{}) - if err := m.Custodies[len(m.Custodies)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.Custody.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 8: + case 12: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field TakeProfitLiabilities", wireType) } @@ -1063,11 +1132,11 @@ func (m *MTP) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex - case 9: + case 13: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TakeProfitCustodies", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field TakeProfitCustody", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTypes @@ -1077,29 +1146,29 @@ func (m *MTP) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthTypes } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTypes } if postIndex > l { return io.ErrUnexpectedEOF } - m.TakeProfitCustodies = append(m.TakeProfitCustodies, types.Coin{}) - if err := m.TakeProfitCustodies[len(m.TakeProfitCustodies)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.TakeProfitCustody.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 10: + case 14: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Leverages", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Leverage", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -1127,13 +1196,11 @@ func (m *MTP) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - var v github_com_cosmos_cosmos_sdk_types.Dec - m.Leverages = append(m.Leverages, v) - if err := m.Leverages[len(m.Leverages)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.Leverage.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 11: + case 15: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field MtpHealth", wireType) } @@ -1167,7 +1234,7 @@ func (m *MTP) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex - case 12: + case 16: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Position", wireType) } @@ -1186,7 +1253,7 @@ func (m *MTP) Unmarshal(dAtA []byte) error { break } } - case 13: + case 17: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) } @@ -1205,7 +1272,7 @@ func (m *MTP) Unmarshal(dAtA []byte) error { break } } - case 14: + case 18: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field AmmPoolId", wireType) } @@ -1224,7 +1291,7 @@ func (m *MTP) Unmarshal(dAtA []byte) error { break } } - case 15: + case 19: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ConsolidateLeverage", wireType) } @@ -1258,7 +1325,7 @@ func (m *MTP) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex - case 16: + case 20: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field SumCollateral", wireType) } @@ -1292,7 +1359,7 @@ func (m *MTP) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex - case 17: + case 21: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field TakeProfitPrice", wireType) } @@ -1326,7 +1393,7 @@ func (m *MTP) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex - case 18: + case 22: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field TakeProfitBorrowRate", wireType) } @@ -1360,11 +1427,11 @@ func (m *MTP) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex - case 19: + case 23: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FundingFeePaidCollaterals", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field FundingFeePaidCollateral", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTypes @@ -1374,31 +1441,31 @@ func (m *MTP) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthTypes } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTypes } if postIndex > l { return io.ErrUnexpectedEOF } - m.FundingFeePaidCollaterals = append(m.FundingFeePaidCollaterals, types.Coin{}) - if err := m.FundingFeePaidCollaterals[len(m.FundingFeePaidCollaterals)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.FundingFeePaidCollateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 20: + case 24: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FundingFeePaidCustodies", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field FundingFeePaidCustody", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTypes @@ -1408,31 +1475,31 @@ func (m *MTP) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthTypes } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTypes } if postIndex > l { return io.ErrUnexpectedEOF } - m.FundingFeePaidCustodies = append(m.FundingFeePaidCustodies, types.Coin{}) - if err := m.FundingFeePaidCustodies[len(m.FundingFeePaidCustodies)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.FundingFeePaidCustody.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 21: + case 25: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FundingFeeReceivedCollaterals", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field FundingFeeReceivedCollateral", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTypes @@ -1442,31 +1509,65 @@ func (m *MTP) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthTypes } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTypes } if postIndex > l { return io.ErrUnexpectedEOF } - m.FundingFeeReceivedCollaterals = append(m.FundingFeeReceivedCollaterals, types.Coin{}) - if err := m.FundingFeeReceivedCollaterals[len(m.FundingFeeReceivedCollaterals)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.FundingFeeReceivedCollateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex - case 22: + case 26: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field FundingFeeReceivedCustody", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + 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 ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.FundingFeeReceivedCustody.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 27: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FundingFeeReceivedCustodies", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field OpenPrice", wireType) } - var msglen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTypes @@ -1476,23 +1577,23 @@ func (m *MTP) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - msglen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if msglen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthTypes } - postIndex := iNdEx + msglen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthTypes } if postIndex > l { return io.ErrUnexpectedEOF } - m.FundingFeeReceivedCustodies = append(m.FundingFeeReceivedCustodies, types.Coin{}) - if err := m.FundingFeeReceivedCustodies[len(m.FundingFeeReceivedCustodies)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.OpenPrice.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex diff --git a/x/parameter/types/query.pb.gw.go b/x/parameter/types/query.pb.gw.go index d8ea85070..b076ffb76 100644 --- a/x/parameter/types/query.pb.gw.go +++ b/x/parameter/types/query.pb.gw.go @@ -20,6 +20,7 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) @@ -30,6 +31,7 @@ var _ status.Status var _ = runtime.String var _ = utilities.NewDoubleArray var _ = descriptor.ForMessage +var _ = metadata.Join func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq QueryParamsRequest @@ -52,12 +54,14 @@ func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshal // 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 (such as grpc.SendHeader, etc) to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. +// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { @@ -65,6 +69,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv 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)