@gmx-io/sdk 1.6.3 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +49 -1
- package/build/cjs/scripts/generate-synthetics-abis.js +181 -0
- package/build/cjs/scripts/subsquid-codegen.js +1 -1
- package/build/cjs/src/abis/AbstractSubaccountApprovalNonceable.js +23 -0
- package/build/cjs/src/abis/CustomErrors.js +198 -88
- package/build/cjs/src/abis/ExchangeRouter.js +155 -272
- package/build/cjs/src/abis/GelatoRelayRouter.js +331 -0
- package/build/cjs/src/abis/SimulationRouter.js +583 -0
- package/build/cjs/src/abis/SubaccountGelatoRelayRouter.js +393 -0
- package/build/cjs/src/abis/SyntheticsReader.js +40 -0
- package/build/cjs/src/abis/index.js +4 -24
- package/build/cjs/src/clients/v1/modules/markets/index.js +10 -6
- package/build/cjs/src/clients/v1/modules/orders/utils.js +1 -0
- package/build/cjs/src/clients/v1/modules/orders/utils.spec.js +66 -0
- package/build/cjs/src/clients/v1/modules/positions/positions.js +2 -10
- package/build/cjs/src/clients/v1/modules/positions/positions.spec.js +1 -1
- package/build/cjs/src/clients/v1/modules/trades/trades.js +5 -1
- package/build/cjs/src/clients/v1/simulateExecuteOrder.js +33 -54
- package/build/cjs/src/clients/v1/testUtil.js +1 -1
- package/build/cjs/src/clients/v2/__tests__/data.spec.js +5 -5
- package/build/cjs/src/clients/v2/__tests__/decrease.spec.js +6 -6
- package/build/cjs/src/clients/v2/__tests__/editCancel.spec.js +15 -13
- package/build/cjs/src/clients/v2/__tests__/errors.spec.js +1 -47
- package/build/cjs/src/clients/v2/__tests__/errorsLifecycle.spec.js +53 -0
- package/build/cjs/src/clients/v2/__tests__/globalCleanup.js +80 -0
- package/build/cjs/src/clients/v2/__tests__/increase.spec.js +22 -20
- package/build/cjs/src/clients/v2/__tests__/multichain.spec.js +5 -6
- package/build/cjs/src/clients/v2/__tests__/prepareErrors.spec.js +167 -0
- package/build/cjs/src/clients/v2/__tests__/setupAllowance.js +32 -0
- package/build/cjs/src/clients/v2/__tests__/subaccount.spec.js +16 -123
- package/build/cjs/src/clients/v2/__tests__/subaccountLifecycle.spec.js +108 -0
- package/build/cjs/src/clients/v2/__tests__/testUtil.js +38 -5
- package/build/cjs/src/clients/v2/__tests__/tradingCapacity.spec.js +371 -0
- package/build/cjs/src/clients/v2/index.js +12 -1
- package/build/cjs/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +0 -26
- package/build/cjs/src/codegen/prebuilt/hashedMarketConfigKeys.json +1692 -561
- package/build/cjs/src/codegen/prebuilt/hashedMarketValuesKeys.json +0 -47
- package/build/cjs/src/codegen/subsquid.js +377 -14
- package/build/cjs/src/configs/__tests__/markets.spec.js +8 -0
- package/build/cjs/src/configs/__tests__/tokens.spec.js +0 -1
- package/build/cjs/src/configs/api.js +0 -4
- package/build/cjs/src/configs/batch.js +0 -1
- package/build/cjs/src/configs/chainIds.js +1 -2
- package/build/cjs/src/configs/chains.js +2 -57
- package/build/cjs/src/configs/contracts.js +77 -133
- package/build/cjs/src/configs/dataStore.js +23 -8
- package/build/cjs/src/configs/express.js +0 -2
- package/build/cjs/src/configs/gasLimits.js +0 -7
- package/build/cjs/src/configs/markets.js +0 -23
- package/build/cjs/src/configs/multichainTokens.js +1 -1
- package/build/cjs/src/configs/oracleKeeper.js +0 -2
- package/build/cjs/src/configs/tokens.js +2 -104
- package/build/cjs/src/test/fixtures/arbitrumMarkets.json +1210 -0
- package/build/cjs/src/test/fixtures/arbitrumTickers.json +1002 -0
- package/build/cjs/src/test/fixtures/arbitrumTokens.json +136 -0
- package/build/cjs/src/test/mockCrossFetch.js +28 -0
- package/build/cjs/src/utils/__tests__/fees.spec.js +264 -0
- package/build/cjs/src/utils/__tests__/markets.spec.js +60 -0
- package/build/cjs/src/utils/__tests__/marketsRisk.spec.js +80 -0
- package/build/cjs/src/utils/__tests__/numbers.spec.js +88 -0
- package/build/cjs/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +6 -25
- package/build/cjs/src/utils/__tests__/orderTransactions/increaseOrders.spec.js +6 -25
- package/build/cjs/src/utils/__tests__/orderTransactions/swapOrders.spec.js +3 -13
- package/build/cjs/src/utils/__tests__/parseError.spec.js +23 -0
- package/build/cjs/src/utils/__tests__/positionPnlCap.spec.js +78 -0
- package/build/cjs/src/utils/__tests__/positions.spec.js +16 -4
- package/build/cjs/src/utils/__tests__/uiFeeReceiver.spec.js +159 -58
- package/build/cjs/src/utils/errors/parseError.js +13 -1
- package/build/cjs/src/utils/errors/transactionsErrors.js +2 -0
- package/build/cjs/src/utils/express/utils/batchOrderUtils.js +1 -2
- package/build/cjs/src/utils/express/utils/estimateExpressParams.js +2 -0
- package/build/cjs/src/utils/express/utils/estimateExpressParams.spec.js +81 -0
- package/build/cjs/src/utils/express/utils/expressParamsUtils.js +5 -1
- package/build/cjs/src/utils/express/utils/expressParamsUtils.spec.js +27 -0
- package/build/cjs/src/utils/fees/executionFee.js +0 -1
- package/build/cjs/src/utils/fees/priceImpact.js +61 -20
- package/build/cjs/src/utils/http/validation.js +33 -0
- package/build/cjs/src/utils/markets/__tests__/api.spec.js +168 -0
- package/build/cjs/src/utils/markets/__tests__/mockMarkets.js +14 -5
- package/build/cjs/src/utils/markets/api.js +134 -4
- package/build/cjs/src/utils/markets/hashKeys.js +34 -6
- package/build/cjs/src/utils/markets/multicall.js +114 -17
- package/build/cjs/src/utils/markets/types.js +31 -0
- package/build/cjs/src/utils/markets/utils.js +81 -9
- package/build/cjs/src/utils/numbers/utils.js +52 -12
- package/build/cjs/src/utils/orderTransactions/api.js +160 -2
- package/build/cjs/src/utils/orderTransactions/simulation.js +13 -0
- package/build/cjs/src/utils/orderTransactions/utils.js +21 -8
- package/build/cjs/src/utils/positions/__tests__/api.spec.js +50 -0
- package/build/cjs/src/utils/positions/api.js +7 -1
- package/build/cjs/src/utils/positions/utils.js +8 -2
- package/build/cjs/src/utils/prices/utils.js +2 -0
- package/build/cjs/src/utils/subaccount/sdkClient.js +0 -1
- package/build/cjs/src/utils/swap/buildSwapStrategy.js +6 -123
- package/build/cjs/src/utils/swap/index.js +0 -3
- package/build/cjs/src/utils/swap/swapValues.js +0 -67
- package/build/cjs/src/utils/tokens/utils.js +9 -10
- package/build/cjs/src/utils/trade/__tests__/getMaxWithdrawAmount.spec.js +44 -0
- package/build/cjs/src/utils/trade/decrease.js +47 -23
- package/build/cjs/src/utils/trade/increase.js +22 -6
- package/build/cjs/src/utils/trade/types.js +0 -1
- package/build/cjs/src/utils/tradeHistory/__tests__/utils.spec.js +64 -0
- package/build/cjs/src/utils/tradeHistory/types.js +3 -1
- package/build/cjs/src/utils/tradeHistory/utils.js +9 -0
- package/build/cjs/src/utils/twap/uiFeeReceiver.js +134 -47
- package/build/esm/scripts/generate-synthetics-abis.js +153 -0
- package/build/esm/scripts/subsquid-codegen.js +1 -1
- package/build/esm/src/abis/AbstractSubaccountApprovalNonceable.js +21 -0
- package/build/esm/src/abis/CustomErrors.js +198 -88
- package/build/esm/src/abis/ExchangeRouter.js +155 -272
- package/build/esm/src/abis/GelatoRelayRouter.js +331 -0
- package/build/esm/src/abis/SimulationRouter.js +581 -0
- package/build/esm/src/abis/SubaccountGelatoRelayRouter.js +393 -0
- package/build/esm/src/abis/SyntheticsReader.js +40 -0
- package/build/esm/src/abis/index.js +3 -23
- package/build/esm/src/clients/v1/modules/markets/index.js +10 -6
- package/build/esm/src/clients/v1/modules/orders/utils.js +1 -0
- package/build/esm/src/clients/v1/modules/orders/utils.spec.js +64 -0
- package/build/esm/src/clients/v1/modules/positions/positions.js +2 -10
- package/build/esm/src/clients/v1/modules/positions/positions.spec.js +1 -1
- package/build/esm/src/clients/v1/modules/trades/trades.js +5 -1
- package/build/esm/src/clients/v1/simulateExecuteOrder.js +35 -55
- package/build/esm/src/clients/v1/testUtil.js +1 -1
- package/build/esm/src/clients/v2/__tests__/data.spec.js +6 -6
- package/build/esm/src/clients/v2/__tests__/decrease.spec.js +7 -7
- package/build/esm/src/clients/v2/__tests__/editCancel.spec.js +16 -14
- package/build/esm/src/clients/v2/__tests__/errors.spec.js +2 -48
- package/build/esm/src/clients/v2/__tests__/errorsLifecycle.spec.js +51 -0
- package/build/esm/src/clients/v2/__tests__/globalCleanup.js +77 -0
- package/build/esm/src/clients/v2/__tests__/increase.spec.js +23 -21
- package/build/esm/src/clients/v2/__tests__/multichain.spec.js +6 -7
- package/build/esm/src/clients/v2/__tests__/prepareErrors.spec.js +165 -0
- package/build/esm/src/clients/v2/__tests__/setupAllowance.js +30 -0
- package/build/esm/src/clients/v2/__tests__/subaccount.spec.js +17 -124
- package/build/esm/src/clients/v2/__tests__/subaccountLifecycle.spec.js +106 -0
- package/build/esm/src/clients/v2/__tests__/swap.spec.js +1 -1
- package/build/esm/src/clients/v2/__tests__/testUtil.js +33 -4
- package/build/esm/src/clients/v2/__tests__/tradingCapacity.spec.js +369 -0
- package/build/esm/src/clients/v2/index.js +12 -2
- package/build/esm/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +0 -26
- package/build/esm/src/codegen/prebuilt/hashedMarketConfigKeys.json +1692 -561
- package/build/esm/src/codegen/prebuilt/hashedMarketValuesKeys.json +0 -47
- package/build/esm/src/codegen/subsquid.js +375 -12
- package/build/esm/src/configs/__tests__/markets.spec.js +9 -1
- package/build/esm/src/configs/__tests__/multichainTokens.spec.js +1 -1
- package/build/esm/src/configs/__tests__/tokens.spec.js +1 -2
- package/build/esm/src/configs/api.js +1 -5
- package/build/esm/src/configs/batch.js +1 -2
- package/build/esm/src/configs/chainIds.js +0 -1
- package/build/esm/src/configs/chains.js +3 -57
- package/build/esm/src/configs/contracts.js +76 -133
- package/build/esm/src/configs/dataStore.js +16 -4
- package/build/esm/src/configs/express.js +1 -3
- package/build/esm/src/configs/gasLimits.js +1 -8
- package/build/esm/src/configs/markets.js +1 -24
- package/build/esm/src/configs/multichainTokens.js +1 -1
- package/build/esm/src/configs/oracleKeeper.js +1 -3
- package/build/esm/src/configs/tokens.js +3 -105
- package/build/esm/src/test/fixtures/arbitrumMarkets.json +1210 -0
- package/build/esm/src/test/fixtures/arbitrumTickers.json +1002 -0
- package/build/esm/src/test/fixtures/arbitrumTokens.json +136 -0
- package/build/esm/src/test/mockCrossFetch.js +23 -0
- package/build/esm/src/utils/__tests__/fees.spec.js +266 -2
- package/build/esm/src/utils/__tests__/markets.spec.js +61 -1
- package/build/esm/src/utils/__tests__/marketsRisk.spec.js +78 -0
- package/build/esm/src/utils/__tests__/numbers.spec.js +89 -1
- package/build/esm/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +6 -25
- package/build/esm/src/utils/__tests__/orderTransactions/increaseOrders.spec.js +6 -25
- package/build/esm/src/utils/__tests__/orderTransactions/swapOrders.spec.js +3 -13
- package/build/esm/src/utils/__tests__/parseError.spec.js +25 -2
- package/build/esm/src/utils/__tests__/positionPnlCap.spec.js +76 -0
- package/build/esm/src/utils/__tests__/positions.spec.js +17 -5
- package/build/esm/src/utils/__tests__/uiFeeReceiver.spec.js +161 -60
- package/build/esm/src/utils/errors/parseError.js +12 -1
- package/build/esm/src/utils/errors/transactionsErrors.js +2 -0
- package/build/esm/src/utils/express/utils/batchOrderUtils.js +2 -3
- package/build/esm/src/utils/express/utils/estimateExpressParams.js +2 -0
- package/build/esm/src/utils/express/utils/estimateExpressParams.spec.js +79 -0
- package/build/esm/src/utils/express/utils/expressParamsUtils.js +3 -0
- package/build/esm/src/utils/express/utils/expressParamsUtils.spec.js +25 -0
- package/build/esm/src/utils/fees/executionFee.js +0 -1
- package/build/esm/src/utils/fees/priceImpact.js +54 -13
- package/build/esm/src/utils/http/validation.js +28 -0
- package/build/esm/src/utils/markets/__tests__/api.spec.js +166 -0
- package/build/esm/src/utils/markets/__tests__/mockMarkets.js +15 -6
- package/build/esm/src/utils/markets/api.js +130 -4
- package/build/esm/src/utils/markets/hashKeys.js +35 -7
- package/build/esm/src/utils/markets/multicall.js +112 -17
- package/build/esm/src/utils/markets/types.js +30 -1
- package/build/esm/src/utils/markets/utils.js +78 -8
- package/build/esm/src/utils/numbers/utils.js +45 -10
- package/build/esm/src/utils/orderTransactions/api.js +157 -1
- package/build/esm/src/utils/orderTransactions/simulation.js +9 -0
- package/build/esm/src/utils/orderTransactions/utils.js +22 -9
- package/build/esm/src/utils/positions/__tests__/api.spec.js +48 -0
- package/build/esm/src/utils/positions/api.js +7 -1
- package/build/esm/src/utils/positions/utils.js +9 -3
- package/build/esm/src/utils/prices/utils.js +2 -0
- package/build/esm/src/utils/subaccount/sdkClient.js +0 -1
- package/build/esm/src/utils/swap/buildSwapStrategy.js +7 -124
- package/build/esm/src/utils/swap/index.js +0 -3
- package/build/esm/src/utils/swap/swapValues.js +1 -68
- package/build/esm/src/utils/tokens/utils.js +8 -8
- package/build/esm/src/utils/trade/__tests__/getMaxWithdrawAmount.spec.js +45 -1
- package/build/esm/src/utils/trade/decrease.js +44 -22
- package/build/esm/src/utils/trade/increase.js +23 -7
- package/build/esm/src/utils/trade/types.js +0 -1
- package/build/esm/src/utils/tradeHistory/__tests__/utils.spec.js +62 -0
- package/build/esm/src/utils/tradeHistory/types.js +2 -0
- package/build/esm/src/utils/tradeHistory/utils.js +9 -0
- package/build/esm/src/utils/twap/uiFeeReceiver.js +127 -42
- package/build/tsconfig.tsbuildinfo +1 -1
- package/build/types/scripts/generate-synthetics-abis.d.ts +17 -0
- package/build/types/src/abis/AbstractSubaccountApprovalNonceable.d.ts +16 -0
- package/build/types/src/abis/CustomErrors.d.ts +331 -139
- package/build/types/src/abis/ExchangeRouter.d.ts +121 -209
- package/build/types/src/abis/GelatoRelayRouter.d.ts +258 -0
- package/build/types/src/abis/SimulationRouter.d.ts +448 -0
- package/build/types/src/abis/SubaccountGelatoRelayRouter.d.ts +307 -0
- package/build/types/src/abis/SyntheticsReader.d.ts +32 -0
- package/build/types/src/abis/index.d.ts +8108 -7891
- package/build/types/src/clients/v1/index.d.ts +1 -1
- package/build/types/src/clients/v1/modules/base.d.ts +1 -1
- package/build/types/src/clients/v1/modules/orders/utils.spec.d.ts +1 -0
- package/build/types/src/clients/v1/multicall.d.ts +1 -1
- package/build/types/src/clients/v1/simulateExecuteOrder.d.ts +0 -1
- package/build/types/src/clients/v2/__tests__/errorsLifecycle.spec.d.ts +1 -0
- package/build/types/src/clients/v2/__tests__/globalCleanup.d.ts +1 -0
- package/build/types/src/clients/v2/__tests__/prepareErrors.spec.d.ts +1 -0
- package/build/types/src/clients/v2/__tests__/setupAllowance.d.ts +1 -0
- package/build/types/src/clients/v2/__tests__/subaccountLifecycle.spec.d.ts +1 -0
- package/build/types/src/clients/v2/__tests__/testUtil.d.ts +7 -1
- package/build/types/src/clients/v2/__tests__/tradingCapacity.spec.d.ts +1 -0
- package/build/types/src/clients/v2/index.d.ts +10 -5
- package/build/types/src/codegen/prebuilt/index.d.ts +1692 -634
- package/build/types/src/codegen/subsquid.d.ts +1490 -32
- package/build/types/src/configs/chainIds.d.ts +0 -1
- package/build/types/src/configs/chains.d.ts +9 -34
- package/build/types/src/configs/contracts.d.ts +5 -66
- package/build/types/src/configs/dataStore.d.ts +8 -2
- package/build/types/src/configs/multichainTokens.d.ts +1 -1
- package/build/types/src/test/mockCrossFetch.d.ts +2 -0
- package/build/types/src/utils/__tests__/marketsRisk.spec.d.ts +1 -0
- package/build/types/src/utils/__tests__/positionPnlCap.spec.d.ts +1 -0
- package/build/types/src/utils/errors/parseError.d.ts +1 -0
- package/build/types/src/utils/errors/transactionsErrors.d.ts +2 -0
- package/build/types/src/utils/express/types.d.ts +2 -1
- package/build/types/src/utils/express/utils/batchOrderUtils.d.ts +1 -1
- package/build/types/src/utils/express/utils/estimateExpressParams.spec.d.ts +1 -0
- package/build/types/src/utils/express/utils/expressParamsUtils.d.ts +1 -0
- package/build/types/src/utils/express/utils/expressParamsUtils.spec.d.ts +1 -0
- package/build/types/src/utils/express/utils/globalExpressParams.d.ts +1 -1
- package/build/types/src/utils/fees/priceImpact.d.ts +2 -0
- package/build/types/src/utils/http/validation.d.ts +7 -0
- package/build/types/src/utils/markets/__tests__/api.spec.d.ts +1 -0
- package/build/types/src/utils/markets/api.d.ts +12 -2
- package/build/types/src/utils/markets/hashKeys.d.ts +1 -1
- package/build/types/src/utils/markets/multicall.d.ts +13 -2
- package/build/types/src/utils/markets/types.d.ts +45 -4
- package/build/types/src/utils/markets/utils.d.ts +9 -9
- package/build/types/src/utils/numbers/utils.d.ts +7 -1
- package/build/types/src/utils/orderTransactions/api.d.ts +50 -0
- package/build/types/src/utils/orderTransactions/simulation.d.ts +1 -0
- package/build/types/src/utils/orders/types.d.ts +2 -0
- package/build/types/src/utils/positions/__tests__/api.spec.d.ts +1 -0
- package/build/types/src/utils/positions/types.d.ts +1 -0
- package/build/types/src/utils/positions/utils.d.ts +1 -0
- package/build/types/src/utils/prices/utils.d.ts +1 -0
- package/build/types/src/utils/swap/buildSwapStrategy.d.ts +3 -5
- package/build/types/src/utils/swap/index.d.ts +0 -3
- package/build/types/src/utils/swap/swapValues.d.ts +1 -1
- package/build/types/src/utils/swap/types.d.ts +2 -7
- package/build/types/src/utils/tokens/types.d.ts +0 -1
- package/build/types/src/utils/tokens/utils.d.ts +1 -2
- package/build/types/src/utils/trade/decrease.d.ts +11 -0
- package/build/types/src/utils/trade/types.d.ts +2 -8
- package/build/types/src/utils/tradeHistory/__tests__/utils.spec.d.ts +1 -0
- package/build/types/src/utils/tradeHistory/types.d.ts +9 -0
- package/build/types/src/utils/twap/types.d.ts +1 -1
- package/build/types/src/utils/twap/uiFeeReceiver.d.ts +23 -22
- package/package.json +11 -7
- package/build/cjs/src/abis/StBTC.js +0 -513
- package/build/cjs/src/utils/swap/botanixStaking.js +0 -90
- package/build/cjs/src/utils/swap/externalSwapPath.js +0 -41
- package/build/cjs/src/utils/swap/externalSwapQuoteByPath.js +0 -27
- package/build/esm/src/abis/StBTC.js +0 -511
- package/build/esm/src/utils/swap/botanixStaking.js +0 -83
- package/build/esm/src/utils/swap/externalSwapPath.js +0 -37
- package/build/esm/src/utils/swap/externalSwapQuoteByPath.js +0 -23
- package/build/types/src/abis/StBTC.d.ts +0 -932
- package/build/types/src/utils/swap/botanixStaking.d.ts +0 -11
- package/build/types/src/utils/swap/externalSwapPath.d.ts +0 -13
- package/build/types/src/utils/swap/externalSwapQuoteByPath.d.ts +0 -6
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { encodeFunctionData } from "viem";
|
|
2
|
+
import { abis } from "../../abis";
|
|
3
|
+
export function encodeSimulationRouterExternalCall(simulationRouterAddress, simulateExecuteData) {
|
|
4
|
+
return encodeFunctionData({
|
|
5
|
+
abi: abis.ExchangeRouter,
|
|
6
|
+
functionName: "makeExternalCalls",
|
|
7
|
+
args: [[simulationRouterAddress], [simulateExecuteData], [], []],
|
|
8
|
+
});
|
|
9
|
+
}
|
|
@@ -13,7 +13,7 @@ import { DecreasePositionSwapType, OrderType } from "../orders/types";
|
|
|
13
13
|
import { convertToContractPrice, convertToUsd } from "../tokens";
|
|
14
14
|
import { applySlippageToMinOut, applySlippageToPrice } from "../trade";
|
|
15
15
|
import { getTwapValidFromTime } from "../twap";
|
|
16
|
-
import {
|
|
16
|
+
import { encodeOrderDataListMetadata, generateTwapId } from "../twap/uiFeeReceiver";
|
|
17
17
|
export function buildSwapOrderPayload(p) {
|
|
18
18
|
const tokenTransfersParams = buildTokenTransfersParamsForIncreaseOrSwap(p);
|
|
19
19
|
const orderPayload = {
|
|
@@ -161,7 +161,19 @@ export function buildTwapOrdersPayloads(p, twapParams) {
|
|
|
161
161
|
if (!twapParams.numberOfParts || twapParams.numberOfParts <= 0) {
|
|
162
162
|
throw new Error(`TWAP numberOfParts must be > 0, got ${twapParams.numberOfParts}`);
|
|
163
163
|
}
|
|
164
|
-
const
|
|
164
|
+
const twapId = generateTwapId();
|
|
165
|
+
const twapDataListEntry = encodeOrderDataListMetadata({
|
|
166
|
+
numberOfParts: twapParams.numberOfParts,
|
|
167
|
+
twapId,
|
|
168
|
+
source: twapParams.source,
|
|
169
|
+
});
|
|
170
|
+
const withTwapMetadata = (part) => ({
|
|
171
|
+
...part,
|
|
172
|
+
orderPayload: {
|
|
173
|
+
...part.orderPayload,
|
|
174
|
+
dataList: [...part.orderPayload.dataList, twapDataListEntry],
|
|
175
|
+
},
|
|
176
|
+
});
|
|
165
177
|
if (isSwapOrderType(p.orderType)) {
|
|
166
178
|
return Array.from({ length: twapParams.numberOfParts }, (_, i) => {
|
|
167
179
|
const params = p;
|
|
@@ -185,9 +197,9 @@ export function buildTwapOrdersPayloads(p, twapParams) {
|
|
|
185
197
|
executionFeeAmount: params.executionFeeAmount / BigInt(twapParams.numberOfParts),
|
|
186
198
|
validFromTime: getTwapValidFromTime(twapParams.duration, twapParams.numberOfParts, i),
|
|
187
199
|
orderType: OrderType.LimitSwap,
|
|
188
|
-
uiFeeReceiver,
|
|
200
|
+
uiFeeReceiver: params.uiFeeReceiver,
|
|
189
201
|
});
|
|
190
|
-
});
|
|
202
|
+
}).map(withTwapMetadata);
|
|
191
203
|
}
|
|
192
204
|
if (isIncreaseOrderType(p.orderType)) {
|
|
193
205
|
return Array.from({ length: twapParams.numberOfParts }, (_, i) => {
|
|
@@ -217,9 +229,9 @@ export function buildTwapOrdersPayloads(p, twapParams) {
|
|
|
217
229
|
orderType: OrderType.LimitIncrease,
|
|
218
230
|
acceptablePrice,
|
|
219
231
|
triggerPrice,
|
|
220
|
-
uiFeeReceiver,
|
|
232
|
+
uiFeeReceiver: params.uiFeeReceiver,
|
|
221
233
|
});
|
|
222
|
-
});
|
|
234
|
+
}).map(withTwapMetadata);
|
|
223
235
|
}
|
|
224
236
|
return Array.from({ length: twapParams.numberOfParts }, (_, i) => {
|
|
225
237
|
const params = p;
|
|
@@ -246,12 +258,12 @@ export function buildTwapOrdersPayloads(p, twapParams) {
|
|
|
246
258
|
acceptablePrice,
|
|
247
259
|
triggerPrice,
|
|
248
260
|
allowedSlippage: 0,
|
|
249
|
-
uiFeeReceiver,
|
|
261
|
+
uiFeeReceiver: params.uiFeeReceiver,
|
|
250
262
|
minOutputUsd: params.minOutputUsd / BigInt(twapParams.numberOfParts),
|
|
251
263
|
receiveTokenAddress: params.receiveTokenAddress,
|
|
252
264
|
decreasePositionSwapType: params.decreasePositionSwapType,
|
|
253
265
|
});
|
|
254
|
-
});
|
|
266
|
+
}).map(withTwapMetadata);
|
|
255
267
|
}
|
|
256
268
|
export function getIsTwapOrderPayload(p) {
|
|
257
269
|
return p.numbers.validFromTime !== 0n;
|
|
@@ -597,9 +609,10 @@ export function getBatchSwapsCount(orderParams) {
|
|
|
597
609
|
if (!orderParams) {
|
|
598
610
|
return 0;
|
|
599
611
|
}
|
|
600
|
-
|
|
612
|
+
const count = orderParams.createOrderParams.reduce((acc, co) => {
|
|
601
613
|
return acc + co.orderPayload.addresses.swapPath.length;
|
|
602
614
|
}, 0);
|
|
615
|
+
return count;
|
|
603
616
|
}
|
|
604
617
|
export function getIsEmptyBatch(orderParams) {
|
|
605
618
|
if (!orderParams) {
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { fetchApiPositionsInfo } from "../api";
|
|
3
|
+
const ACCOUNT = "0x1111111111111111111111111111111111111111";
|
|
4
|
+
function createApi(response) {
|
|
5
|
+
return {
|
|
6
|
+
url: "https://example.test",
|
|
7
|
+
fetchJson: async () => response,
|
|
8
|
+
postJson: async () => {
|
|
9
|
+
throw new Error("Unexpected POST request");
|
|
10
|
+
},
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
function fetchPositions(response) {
|
|
14
|
+
return fetchApiPositionsInfo({ api: createApi(response) }, {
|
|
15
|
+
address: ACCOUNT,
|
|
16
|
+
includeRelatedOrders: true,
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
describe("position API validation", () => {
|
|
20
|
+
it.each([
|
|
21
|
+
["negative", "-123", -123n],
|
|
22
|
+
["zero", "0", 0n],
|
|
23
|
+
["positive", "123", 123n],
|
|
24
|
+
])("deserializes a %s positionValueInUsd", async (_label, serialized, expected) => {
|
|
25
|
+
const result = await fetchPositions([
|
|
26
|
+
{
|
|
27
|
+
key: "position-key",
|
|
28
|
+
positionValueInUsd: serialized,
|
|
29
|
+
},
|
|
30
|
+
]);
|
|
31
|
+
expect(result[0].positionValueInUsd).toBe(expected);
|
|
32
|
+
});
|
|
33
|
+
it("rejects a missing positionValueInUsd", async () => {
|
|
34
|
+
await expect(fetchPositions([{ key: "position-key" }])).rejects.toThrow("Invalid /v1/positions response for position-key: missing positionValueInUsd");
|
|
35
|
+
});
|
|
36
|
+
it.each(["invalid", 0, null, {}])("rejects malformed positionValueInUsd: %s", async (positionValueInUsd) => {
|
|
37
|
+
await expect(fetchPositions([{ key: "position-key", positionValueInUsd }])).rejects.toThrow("positionValueInUsd must be bigint");
|
|
38
|
+
});
|
|
39
|
+
it.each([null, {}])("rejects a non-array response: %s", async (response) => {
|
|
40
|
+
await expect(fetchPositions(response)).rejects.toThrow("Invalid /v1/positions response: expected an array");
|
|
41
|
+
});
|
|
42
|
+
it.each([null, "position"])("rejects a malformed array record: %s", async (record) => {
|
|
43
|
+
await expect(fetchPositions([record])).rejects.toThrow("Invalid /v1/positions response at index 0: expected an object");
|
|
44
|
+
});
|
|
45
|
+
it("rejects an array as an array record", async () => {
|
|
46
|
+
await expect(fetchPositions([[]])).rejects.toThrow("Invalid /v1/positions response at index 0: expected an object");
|
|
47
|
+
});
|
|
48
|
+
});
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { assertApiFields, assertApiRecords } from "../http/validation";
|
|
1
2
|
import { deserializeBigIntsInObject } from "../numbers";
|
|
2
3
|
export async function fetchApiPositionsInfo(ctx, params) {
|
|
3
4
|
const positions = await ctx.api.fetchJson("/v1/positions", {
|
|
@@ -6,5 +7,10 @@ export async function fetchApiPositionsInfo(ctx, params) {
|
|
|
6
7
|
includeRelatedOrders: params.includeRelatedOrders || undefined,
|
|
7
8
|
},
|
|
8
9
|
});
|
|
9
|
-
|
|
10
|
+
assertApiRecords(positions, "/v1/positions");
|
|
11
|
+
return positions.map((position, index) => {
|
|
12
|
+
const parsed = deserializeBigIntsInObject(position, { handleInts: true });
|
|
13
|
+
assertApiFields(parsed, [{ name: "positionValueInUsd", type: "bigint" }], "/v1/positions", index);
|
|
14
|
+
return parsed;
|
|
15
|
+
});
|
|
10
16
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { BASIS_POINTS_DIVISOR_BIGINT } from "../../configs/factors";
|
|
2
2
|
import { bigMath } from "../bigmath";
|
|
3
3
|
import { capPositionImpactUsdByMaxImpactPool, capPositionImpactUsdByMaxPriceImpactFactor, getMaxPositionImpactFactors, getPositionFee, getPriceImpactForPosition, getProportionalPendingImpactValues, } from "../fees";
|
|
4
|
-
import { getCappedPoolPnl, getMarketIndexName,
|
|
4
|
+
import { getCappedPoolPnl, getMarketIndexName, getMarketPoolName, getMaxAllowedLeverage, getOpenInterestUsd, getPoolUsdWithoutPnl, getPositiveMarketPnl, } from "../markets";
|
|
5
5
|
import { applyFactor, expandDecimals, FLOAT_PRECISION_SQRT, getBasisPoints, PRECISION } from "../numbers";
|
|
6
6
|
import { getAcceptablePriceInfo, getMarkPrice } from "../prices";
|
|
7
7
|
import { convertToTokenAmount, convertToUsd, getIsEquivalentTokens } from "../tokens";
|
|
@@ -26,7 +26,7 @@ export function getPositionPnlUsd(p) {
|
|
|
26
26
|
if (totalPnl <= 0) {
|
|
27
27
|
return totalPnl;
|
|
28
28
|
}
|
|
29
|
-
const poolPnl =
|
|
29
|
+
const poolPnl = getPositiveMarketPnl(marketInfo, isLong, true);
|
|
30
30
|
const poolUsd = getPoolUsdWithoutPnl(marketInfo, isLong, "minPrice");
|
|
31
31
|
const cappedPnl = getCappedPoolPnl({
|
|
32
32
|
marketInfo,
|
|
@@ -88,7 +88,10 @@ export function getLiquidationPrice(p) {
|
|
|
88
88
|
priceImpactDeltaUsd = maxNegativePriceImpactUsd;
|
|
89
89
|
}
|
|
90
90
|
else {
|
|
91
|
-
const priceImpactForPosition = getPriceImpactForPosition(marketInfo, -sizeInUsd, isLong, {
|
|
91
|
+
const priceImpactForPosition = getPriceImpactForPosition(marketInfo, -sizeInUsd, isLong, {
|
|
92
|
+
fallbackToZero: true,
|
|
93
|
+
sizeDeltaInTokens: sizeInTokens,
|
|
94
|
+
});
|
|
92
95
|
priceImpactDeltaUsd = priceImpactForPosition.priceImpactDeltaUsd;
|
|
93
96
|
if (priceImpactDeltaUsd > 0) {
|
|
94
97
|
priceImpactDeltaUsd = capPositionImpactUsdByMaxPriceImpactFactor(marketInfo, sizeInUsd, priceImpactDeltaUsd);
|
|
@@ -157,6 +160,7 @@ export function getMinCollateralUsdForLiquidationPrice(p) {
|
|
|
157
160
|
const maxNegativePriceImpactUsd = -1n * applyFactor(sizeInUsd, marketInfo.maxPositionImpactFactorForLiquidations);
|
|
158
161
|
let priceImpactDeltaUsd = getPriceImpactForPosition(marketInfo, -sizeInUsd, isLong, {
|
|
159
162
|
fallbackToZero: true,
|
|
163
|
+
sizeDeltaInTokens: sizeInTokens,
|
|
160
164
|
}).priceImpactDeltaUsd;
|
|
161
165
|
if (priceImpactDeltaUsd > 0) {
|
|
162
166
|
priceImpactDeltaUsd = capPositionImpactUsdByMaxPriceImpactFactor(marketInfo, sizeInUsd, priceImpactDeltaUsd);
|
|
@@ -265,6 +269,7 @@ export function getContractPositionDynamicFees({ position, marketInfo, marketFee
|
|
|
265
269
|
const claimableShortTokenAmount = getFundingAmount(latestShortTokenClaimableFundingAmountPerSize, position.shortTokenClaimableFundingAmountPerSize, sizeInUsd);
|
|
266
270
|
const { balanceWasImproved } = getPriceImpactForPosition(marketInfo, -sizeInUsd, isLong, {
|
|
267
271
|
fallbackToZero: true,
|
|
272
|
+
sizeDeltaInTokens: position.sizeInTokens,
|
|
268
273
|
});
|
|
269
274
|
const { positionFeeUsd, discountUsd, uiFeeUsd } = getPositionFee(marketInfo, sizeInUsd, balanceWasImproved, referralInfo);
|
|
270
275
|
const positionFeeAmount = convertToTokenAmount(positionFeeUsd, collateralToken.decimals, collateralMinPrice) ?? 0n;
|
|
@@ -319,6 +324,7 @@ export function getPositionInfo(p) {
|
|
|
319
324
|
isLong: position.isLong,
|
|
320
325
|
indexPrice: markPrice,
|
|
321
326
|
sizeDeltaUsd: position.sizeInUsd,
|
|
327
|
+
sizeDeltaInTokens: position.sizeInTokens,
|
|
322
328
|
});
|
|
323
329
|
const positionFeeInfo = getPositionFee(marketInfo, position.sizeInUsd, closeAcceptablePriceInfo.balanceWasImproved, userReferralInfo, uiFeeFactor);
|
|
324
330
|
const closingFeeUsd = positionFeeInfo.positionFeeUsd;
|
|
@@ -67,6 +67,7 @@ export function getAcceptablePriceInfo(p) {
|
|
|
67
67
|
const { priceImpactDeltaUsd, balanceWasImproved } = getCappedPositionImpactUsd(marketInfo, sizeDeltaUsd, isLong, isIncrease, {
|
|
68
68
|
fallbackToZero: !isIncrease,
|
|
69
69
|
shouldCapNegativeImpact: false,
|
|
70
|
+
sizeDeltaInTokens: p.sizeDeltaInTokens,
|
|
70
71
|
});
|
|
71
72
|
/**
|
|
72
73
|
* We display this value as price impact on action (increase or decrease)
|
|
@@ -85,6 +86,7 @@ export function getAcceptablePriceInfo(p) {
|
|
|
85
86
|
const { priceImpactDeltaUsd: priceImpactDeltaUsdForAcceptablePrice } = getCappedPositionImpactUsd(marketInfo, sizeDeltaUsd, isLong, isIncrease, {
|
|
86
87
|
fallbackToZero: !isIncrease,
|
|
87
88
|
shouldCapNegativeImpact: false,
|
|
89
|
+
sizeDeltaInTokens: p.sizeDeltaInTokens,
|
|
88
90
|
});
|
|
89
91
|
const acceptablePriceValues = getAcceptablePriceByPriceImpact({
|
|
90
92
|
isIncrease,
|
|
@@ -224,7 +224,6 @@ export async function getSdkSubaccountApprovalForOrder(client, account, mainSign
|
|
|
224
224
|
let status = await getSdkSubaccountStatus(client, account, {
|
|
225
225
|
force: forceStatusRefresh,
|
|
226
226
|
});
|
|
227
|
-
// After forced refresh due to submittedRequestId, clear the flag if approval still exists (relay failed but approval is still valid)
|
|
228
227
|
if (subaccount.approval?.submittedRequestId !== undefined) {
|
|
229
228
|
subaccount.approval.submittedRequestId = undefined;
|
|
230
229
|
}
|
|
@@ -1,17 +1,14 @@
|
|
|
1
1
|
import { bigMath } from "../bigmath";
|
|
2
2
|
import { SwapPricingType } from "../orders/types";
|
|
3
|
-
import { convertToTokenAmount, convertToUsd, getIsEquivalentTokens,
|
|
4
|
-
import { getAvailableExternalSwapPaths } from "./externalSwapPath";
|
|
5
|
-
import { getExternalSwapQuoteByPath } from "./externalSwapQuoteByPath";
|
|
3
|
+
import { convertToTokenAmount, convertToUsd, getIsEquivalentTokens, getIsUnwrap, getIsWrap, getMidPrice, } from "../tokens";
|
|
6
4
|
import { createFindSwapPath } from "./swapPath";
|
|
7
5
|
/*
|
|
8
6
|
Order/Priority of getting swap strategy:
|
|
9
|
-
1. Check if it needs a swap and return noSwap if tokens are equivalent
|
|
7
|
+
1. Check if it needs a swap and return noSwap if tokens are equivalent [noSwap]
|
|
10
8
|
2. Check if there is a swap path stats for the internal swap quote and return internalSwap if there is [internalSwap]
|
|
11
|
-
3.
|
|
12
|
-
4. Return defaultSwapStrategy (noSwap) if there is no other swap strategy [noSwap]
|
|
9
|
+
3. Return defaultSwapStrategy (noSwap) if there is no other swap strategy [noSwap]
|
|
13
10
|
*/
|
|
14
|
-
export function buildSwapStrategy({ amountIn, tokenIn, tokenOut, marketsInfoData, chainId, swapOptimizationOrder,
|
|
11
|
+
export function buildSwapStrategy({ amountIn, tokenIn, tokenOut, marketsInfoData, chainId, swapOptimizationOrder, swapPricingType = SwapPricingType.Swap, allowSameTokenSwap, disabledMarkets, manualPath, }) {
|
|
15
12
|
const priceIn = tokenIn.prices.minPrice;
|
|
16
13
|
const usdIn = convertToUsd(amountIn, tokenIn.decimals, priceIn);
|
|
17
14
|
if (amountIn < 0n) {
|
|
@@ -31,9 +28,7 @@ export function buildSwapStrategy({ amountIn, tokenIn, tokenOut, marketsInfoData
|
|
|
31
28
|
};
|
|
32
29
|
if ((!allowSameTokenSwap && getIsEquivalentTokens(tokenIn, tokenOut)) ||
|
|
33
30
|
getIsWrap(tokenIn, tokenOut) ||
|
|
34
|
-
getIsUnwrap(tokenIn, tokenOut)
|
|
35
|
-
getIsStake(tokenIn, tokenOut) ||
|
|
36
|
-
getIsUnstake(tokenIn, tokenOut)) {
|
|
31
|
+
getIsUnwrap(tokenIn, tokenOut)) {
|
|
37
32
|
return defaultSwapStrategy;
|
|
38
33
|
}
|
|
39
34
|
const findSwapPath = createFindSwapPath({
|
|
@@ -60,55 +55,10 @@ export function buildSwapStrategy({ amountIn, tokenIn, tokenOut, marketsInfoData
|
|
|
60
55
|
feesUsd: usdIn - swapPathStats.usdOut,
|
|
61
56
|
};
|
|
62
57
|
}
|
|
63
|
-
const availableExternalSwapPaths = getAvailableExternalSwapPaths({ chainId, fromTokenAddress: tokenIn.address });
|
|
64
|
-
const suitableSwapPath = availableExternalSwapPaths.find((path) => {
|
|
65
|
-
const findSwapPath = createFindSwapPath({
|
|
66
|
-
chainId,
|
|
67
|
-
fromTokenAddress: path.outTokenAddress,
|
|
68
|
-
toTokenAddress: tokenOut.address,
|
|
69
|
-
marketsInfoData,
|
|
70
|
-
swapPricingType,
|
|
71
|
-
disabledMarkets,
|
|
72
|
-
});
|
|
73
|
-
const swapPathStats = findSwapPath(usdIn);
|
|
74
|
-
return Boolean(swapPathStats);
|
|
75
|
-
});
|
|
76
|
-
if (suitableSwapPath && suitableSwapPath.outTokenAddress !== tokenOut.address) {
|
|
77
|
-
const externalSwapQuoteForCombinedSwap = getExternalSwapQuoteByPath({
|
|
78
|
-
amountIn,
|
|
79
|
-
externalSwapPath: suitableSwapPath,
|
|
80
|
-
externalSwapQuoteParams,
|
|
81
|
-
});
|
|
82
|
-
const findSwapPathForSuitableSwapPath = createFindSwapPath({
|
|
83
|
-
chainId,
|
|
84
|
-
fromTokenAddress: suitableSwapPath.outTokenAddress,
|
|
85
|
-
toTokenAddress: tokenOut.address,
|
|
86
|
-
marketsInfoData,
|
|
87
|
-
swapPricingType,
|
|
88
|
-
disabledMarkets,
|
|
89
|
-
});
|
|
90
|
-
const swapPathStatsForCombinedSwap = externalSwapQuoteForCombinedSwap
|
|
91
|
-
? findSwapPathForSuitableSwapPath(externalSwapQuoteForCombinedSwap.usdOut)
|
|
92
|
-
: undefined;
|
|
93
|
-
return externalSwapQuoteForCombinedSwap && swapPathStatsForCombinedSwap
|
|
94
|
-
? {
|
|
95
|
-
type: "combinedSwap",
|
|
96
|
-
externalSwapQuote: externalSwapQuoteForCombinedSwap,
|
|
97
|
-
swapPathStats: swapPathStatsForCombinedSwap,
|
|
98
|
-
amountIn,
|
|
99
|
-
amountOut: swapPathStatsForCombinedSwap.amountOut,
|
|
100
|
-
usdIn: externalSwapQuoteForCombinedSwap.usdIn,
|
|
101
|
-
usdOut: swapPathStatsForCombinedSwap.usdOut,
|
|
102
|
-
priceIn: externalSwapQuoteForCombinedSwap.priceIn,
|
|
103
|
-
priceOut: tokenOut.prices.maxPrice,
|
|
104
|
-
feesUsd: externalSwapQuoteForCombinedSwap.usdIn - swapPathStatsForCombinedSwap.usdOut,
|
|
105
|
-
}
|
|
106
|
-
: defaultSwapStrategy;
|
|
107
|
-
}
|
|
108
58
|
return defaultSwapStrategy;
|
|
109
59
|
}
|
|
110
60
|
// Used for getting swap amounts by to value
|
|
111
|
-
export function buildReverseSwapStrategy({ amountOut, tokenIn, tokenOut, marketsInfoData, chainId,
|
|
61
|
+
export function buildReverseSwapStrategy({ amountOut, tokenIn, tokenOut, marketsInfoData, chainId, swapOptimizationOrder, swapPricingType, allowSameTokenSwap, disabledMarkets, manualPath, }) {
|
|
112
62
|
const priceIn = getMidPrice(tokenIn.prices);
|
|
113
63
|
const priceOut = getMidPrice(tokenOut.prices);
|
|
114
64
|
const preferredUsdOut = convertToUsd(amountOut, tokenOut.decimals, getMidPrice(tokenOut.prices));
|
|
@@ -128,9 +78,7 @@ export function buildReverseSwapStrategy({ amountOut, tokenIn, tokenOut, markets
|
|
|
128
78
|
};
|
|
129
79
|
if ((!allowSameTokenSwap && getIsEquivalentTokens(tokenIn, tokenOut)) ||
|
|
130
80
|
getIsWrap(tokenIn, tokenOut) ||
|
|
131
|
-
getIsUnwrap(tokenIn, tokenOut)
|
|
132
|
-
getIsStake(tokenIn, tokenOut) ||
|
|
133
|
-
getIsUnstake(tokenIn, tokenOut)) {
|
|
81
|
+
getIsUnwrap(tokenIn, tokenOut)) {
|
|
134
82
|
return defaultSwapStrategy;
|
|
135
83
|
}
|
|
136
84
|
const findSwapPath = createFindSwapPath({
|
|
@@ -167,70 +115,5 @@ export function buildReverseSwapStrategy({ amountOut, tokenIn, tokenOut, markets
|
|
|
167
115
|
};
|
|
168
116
|
}
|
|
169
117
|
}
|
|
170
|
-
const availableExternalSwapPaths = getAvailableExternalSwapPaths({ chainId, fromTokenAddress: tokenIn.address });
|
|
171
|
-
const suitableSwapPath = availableExternalSwapPaths.find((path) => {
|
|
172
|
-
if (path.outTokenAddress !== tokenOut.address)
|
|
173
|
-
return false;
|
|
174
|
-
const findSwapPath = createFindSwapPath({
|
|
175
|
-
chainId,
|
|
176
|
-
fromTokenAddress: tokenIn.address,
|
|
177
|
-
toTokenAddress: path.inTokenAddress,
|
|
178
|
-
marketsInfoData,
|
|
179
|
-
swapPricingType,
|
|
180
|
-
disabledMarkets,
|
|
181
|
-
});
|
|
182
|
-
const swapPathStats = findSwapPath(approximateUsdIn);
|
|
183
|
-
return Boolean(swapPathStats);
|
|
184
|
-
});
|
|
185
|
-
if (suitableSwapPath && externalSwapQuoteParams) {
|
|
186
|
-
const approximateExternalSwapQuoteForCombinedSwap = getExternalSwapQuoteByPath({
|
|
187
|
-
amountIn: approximateAmountIn,
|
|
188
|
-
externalSwapPath: suitableSwapPath,
|
|
189
|
-
externalSwapQuoteParams,
|
|
190
|
-
});
|
|
191
|
-
if (!approximateExternalSwapQuoteForCombinedSwap) {
|
|
192
|
-
return defaultSwapStrategy;
|
|
193
|
-
}
|
|
194
|
-
const findSwapPathForSuitableSwapPath = createFindSwapPath({
|
|
195
|
-
chainId,
|
|
196
|
-
fromTokenAddress: tokenIn.address,
|
|
197
|
-
toTokenAddress: suitableSwapPath.inTokenAddress,
|
|
198
|
-
marketsInfoData,
|
|
199
|
-
swapPricingType,
|
|
200
|
-
disabledMarkets,
|
|
201
|
-
});
|
|
202
|
-
const approximateSwapPathStatsForCombinedSwap = findSwapPathForSuitableSwapPath(approximateExternalSwapQuoteForCombinedSwap.usdOut);
|
|
203
|
-
if (!approximateSwapPathStatsForCombinedSwap) {
|
|
204
|
-
return defaultSwapStrategy;
|
|
205
|
-
}
|
|
206
|
-
const adjustedUsdIn = approximateSwapPathStatsForCombinedSwap.usdOut > 0
|
|
207
|
-
? bigMath.mulDiv(approximateUsdIn, preferredUsdOut, approximateSwapPathStatsForCombinedSwap.usdOut)
|
|
208
|
-
: 0n;
|
|
209
|
-
const adjustedAmountIn = convertToTokenAmount(adjustedUsdIn, tokenIn.decimals, getMidPrice(tokenIn.prices));
|
|
210
|
-
const adjustedExternalSwapQuoteForCombinedSwap = getExternalSwapQuoteByPath({
|
|
211
|
-
amountIn: adjustedAmountIn,
|
|
212
|
-
externalSwapPath: suitableSwapPath,
|
|
213
|
-
externalSwapQuoteParams,
|
|
214
|
-
});
|
|
215
|
-
if (!adjustedExternalSwapQuoteForCombinedSwap) {
|
|
216
|
-
return defaultSwapStrategy;
|
|
217
|
-
}
|
|
218
|
-
const adjustedSwapPathStatsForCombinedSwap = findSwapPathForSuitableSwapPath(adjustedExternalSwapQuoteForCombinedSwap.usdOut);
|
|
219
|
-
if (!adjustedSwapPathStatsForCombinedSwap) {
|
|
220
|
-
return defaultSwapStrategy;
|
|
221
|
-
}
|
|
222
|
-
return {
|
|
223
|
-
type: "combinedSwap",
|
|
224
|
-
externalSwapQuote: adjustedExternalSwapQuoteForCombinedSwap,
|
|
225
|
-
swapPathStats: adjustedSwapPathStatsForCombinedSwap,
|
|
226
|
-
amountIn: adjustedAmountIn,
|
|
227
|
-
amountOut: adjustedSwapPathStatsForCombinedSwap.amountOut,
|
|
228
|
-
usdIn: adjustedExternalSwapQuoteForCombinedSwap.usdIn,
|
|
229
|
-
usdOut: adjustedSwapPathStatsForCombinedSwap.usdOut,
|
|
230
|
-
priceIn: adjustedExternalSwapQuoteForCombinedSwap.priceIn,
|
|
231
|
-
priceOut: priceOut,
|
|
232
|
-
feesUsd: adjustedExternalSwapQuoteForCombinedSwap.usdIn - adjustedSwapPathStatsForCombinedSwap.usdOut,
|
|
233
|
-
};
|
|
234
|
-
}
|
|
235
118
|
return defaultSwapStrategy;
|
|
236
119
|
}
|
|
@@ -8,7 +8,4 @@ export * from "./findReachableTokens";
|
|
|
8
8
|
export * from "./buildMarketsAdjacencyGraph";
|
|
9
9
|
export * from "./swapValues";
|
|
10
10
|
export * from "./preparedSwapData";
|
|
11
|
-
export * from "./externalSwapPath";
|
|
12
|
-
export * from "./externalSwapQuoteByPath";
|
|
13
|
-
export * from "./botanixStaking";
|
|
14
11
|
export * from "./constants";
|
|
@@ -3,7 +3,7 @@ import { bigMath } from "../bigmath";
|
|
|
3
3
|
import { getTotalSwapVolumeFromSwapStats } from "../fees";
|
|
4
4
|
import { applyFactor } from "../numbers";
|
|
5
5
|
import { SwapPricingType } from "../orders/types";
|
|
6
|
-
import { convertToTokenAmount, convertToUsd, getAmountByRatio, getIsEquivalentTokens,
|
|
6
|
+
import { convertToTokenAmount, convertToUsd, getAmountByRatio, getIsEquivalentTokens, getIsUnwrap, getIsWrap, } from "../tokens";
|
|
7
7
|
import { buildReverseSwapStrategy, buildSwapStrategy } from "./buildSwapStrategy";
|
|
8
8
|
export function getSwapAmountsByFromValue(p) {
|
|
9
9
|
const { tokenIn, tokenOut, amountIn, triggerRatio, isLimit, swapOptimizationOrder, uiFeeFactor, allowedSwapSlippageBps, marketsInfoData, chainId, externalSwapQuoteParams, allowSameTokenSwap, disabledMarkets, manualPath, } = p;
|
|
@@ -17,7 +17,6 @@ export function getSwapAmountsByFromValue(p) {
|
|
|
17
17
|
marketsInfoData,
|
|
18
18
|
chainId,
|
|
19
19
|
swapOptimizationOrder,
|
|
20
|
-
externalSwapQuoteParams,
|
|
21
20
|
swapPricingType: SwapPricingType.Swap,
|
|
22
21
|
allowSameTokenSwap,
|
|
23
22
|
disabledMarkets,
|
|
@@ -88,7 +87,6 @@ export function getSwapAmountsByToValue(p) {
|
|
|
88
87
|
tokenOut,
|
|
89
88
|
marketsInfoData,
|
|
90
89
|
chainId,
|
|
91
|
-
externalSwapQuoteParams,
|
|
92
90
|
swapOptimizationOrder,
|
|
93
91
|
swapPricingType,
|
|
94
92
|
allowSameTokenSwap,
|
|
@@ -102,7 +100,6 @@ export function getSwapAmountsByToValue(p) {
|
|
|
102
100
|
marketsInfoData,
|
|
103
101
|
chainId,
|
|
104
102
|
swapOptimizationOrder,
|
|
105
|
-
externalSwapQuoteParams,
|
|
106
103
|
swapPricingType,
|
|
107
104
|
allowSameTokenSwap,
|
|
108
105
|
disabledMarkets,
|
|
@@ -224,9 +221,6 @@ function getSwapAmountsByFromValueDefault(p) {
|
|
|
224
221
|
swapStrategy,
|
|
225
222
|
};
|
|
226
223
|
}
|
|
227
|
-
if (getIsStake(tokenIn, tokenOut) || getIsUnstake(tokenIn, tokenOut)) {
|
|
228
|
-
return getPlainSwapAmountsByFromToken(tokenIn, tokenOut, amountIn);
|
|
229
|
-
}
|
|
230
224
|
const swapPathStats = findSwapPath(defaultAmounts.usdIn, { order: swapOptimizationOrder });
|
|
231
225
|
const totalSwapVolume = getTotalSwapVolumeFromSwapStats(swapPathStats?.swapSteps);
|
|
232
226
|
const swapUiFeeUsd = applyFactor(totalSwapVolume, uiFeeFactor);
|
|
@@ -345,9 +339,6 @@ function getSwapAmountsByToValueDefault(p) {
|
|
|
345
339
|
swapStrategy,
|
|
346
340
|
};
|
|
347
341
|
}
|
|
348
|
-
if (getIsStake(tokenIn, tokenOut) || getIsUnstake(tokenIn, tokenOut)) {
|
|
349
|
-
return getPlainSwapAmountsByToToken(tokenIn, tokenOut, amountOut);
|
|
350
|
-
}
|
|
351
342
|
const baseUsdIn = usdOut;
|
|
352
343
|
const swapPathStats = findSwapPath(baseUsdIn, { order: swapOptimizationOrder });
|
|
353
344
|
if (!swapPathStats) {
|
|
@@ -420,61 +411,3 @@ export function getSwapPathComparator(order) {
|
|
|
420
411
|
return 0;
|
|
421
412
|
};
|
|
422
413
|
}
|
|
423
|
-
function getPlainSwapAmountsByFromToken(tokenIn, tokenOut, amountIn) {
|
|
424
|
-
const usdIn = convertToUsd(amountIn, tokenIn.decimals, tokenIn.prices.minPrice);
|
|
425
|
-
const usdOut = usdIn;
|
|
426
|
-
const amountOut = convertToTokenAmount(usdOut, tokenOut.decimals, tokenOut.prices.maxPrice);
|
|
427
|
-
const priceIn = tokenIn.prices.minPrice;
|
|
428
|
-
const priceOut = tokenOut.prices.maxPrice;
|
|
429
|
-
const swapStrategy = {
|
|
430
|
-
type: "noSwap",
|
|
431
|
-
externalSwapQuote: undefined,
|
|
432
|
-
swapPathStats: undefined,
|
|
433
|
-
amountIn,
|
|
434
|
-
amountOut,
|
|
435
|
-
usdIn,
|
|
436
|
-
usdOut,
|
|
437
|
-
priceIn,
|
|
438
|
-
priceOut,
|
|
439
|
-
feesUsd: 0n,
|
|
440
|
-
};
|
|
441
|
-
return {
|
|
442
|
-
amountIn,
|
|
443
|
-
usdIn,
|
|
444
|
-
amountOut,
|
|
445
|
-
usdOut,
|
|
446
|
-
minOutputAmount: amountOut,
|
|
447
|
-
priceIn,
|
|
448
|
-
priceOut,
|
|
449
|
-
swapStrategy,
|
|
450
|
-
};
|
|
451
|
-
}
|
|
452
|
-
function getPlainSwapAmountsByToToken(tokenIn, tokenOut, amountOut) {
|
|
453
|
-
const priceIn = tokenIn.prices.minPrice;
|
|
454
|
-
const priceOut = tokenOut.prices.maxPrice;
|
|
455
|
-
const usdOut = convertToUsd(amountOut, tokenOut.decimals, priceOut);
|
|
456
|
-
const usdIn = usdOut;
|
|
457
|
-
const amountIn = convertToTokenAmount(usdIn, tokenIn.decimals, priceIn);
|
|
458
|
-
const swapStrategy = {
|
|
459
|
-
type: "noSwap",
|
|
460
|
-
externalSwapQuote: undefined,
|
|
461
|
-
swapPathStats: undefined,
|
|
462
|
-
amountIn,
|
|
463
|
-
amountOut,
|
|
464
|
-
usdIn,
|
|
465
|
-
usdOut,
|
|
466
|
-
priceIn,
|
|
467
|
-
priceOut,
|
|
468
|
-
feesUsd: 0n,
|
|
469
|
-
};
|
|
470
|
-
return {
|
|
471
|
-
amountIn,
|
|
472
|
-
usdIn,
|
|
473
|
-
amountOut,
|
|
474
|
-
usdOut,
|
|
475
|
-
minOutputAmount: amountOut,
|
|
476
|
-
priceIn,
|
|
477
|
-
priceOut,
|
|
478
|
-
swapStrategy,
|
|
479
|
-
};
|
|
480
|
-
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { BASIS_POINTS_DIVISOR_BIGINT, DEFAULT_ALLOWED_SWAP_SLIPPAGE_BPS } from "../../configs/factors";
|
|
2
2
|
import { GLV_STUB_ADDRESS, getToken, NATIVE_TOKEN_ADDRESS, GM_STUB_ADDRESS } from "../../configs/tokens";
|
|
3
3
|
import { bigMath } from "../bigmath";
|
|
4
|
-
import { adjustForDecimals, expandDecimals, PRECISION } from "../numbers";
|
|
4
|
+
import { adjustForDecimals, expandDecimals, PRECISION, roundUpMagnitudeDivision } from "../numbers";
|
|
5
5
|
export function parseContractPrice(price, tokenDecimals) {
|
|
6
6
|
return price * expandDecimals(1, tokenDecimals);
|
|
7
7
|
}
|
|
@@ -20,6 +20,13 @@ export function convertToTokenAmount(usd, tokenDecimals, price) {
|
|
|
20
20
|
}
|
|
21
21
|
return (usd * expandDecimals(1, tokenDecimals)) / price;
|
|
22
22
|
}
|
|
23
|
+
export function convertToTokenAmountForIncrease(usd, tokenDecimals, price, isLong) {
|
|
24
|
+
if (usd === undefined || typeof tokenDecimals !== "number" || price === undefined || price <= 0) {
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
const numerator = usd * expandDecimals(1, tokenDecimals);
|
|
28
|
+
return isLong ? numerator / price : roundUpMagnitudeDivision(numerator, price);
|
|
29
|
+
}
|
|
23
30
|
export function convertToUsd(tokenAmount, tokenDecimals, price) {
|
|
24
31
|
if (tokenAmount == undefined || typeof tokenDecimals !== "number" || price === undefined) {
|
|
25
32
|
return undefined;
|
|
@@ -147,13 +154,6 @@ export function getIsWrap(token1, token2) {
|
|
|
147
154
|
export function getIsUnwrap(token1, token2) {
|
|
148
155
|
return token1.isWrapped && token2.isNative;
|
|
149
156
|
}
|
|
150
|
-
export function getIsStake(token1, token2) {
|
|
151
|
-
return (token1.isWrapped || token1.isNative) && token2.isStaking;
|
|
152
|
-
}
|
|
153
|
-
export function getIsUnstake(token1, token2) {
|
|
154
|
-
// can't unstake straight to native token
|
|
155
|
-
return token1.isStaking && token2.isWrapped;
|
|
156
|
-
}
|
|
157
157
|
export function getTokensRatioByPrice(p) {
|
|
158
158
|
const { fromToken, toToken, fromPrice, toPrice } = p;
|
|
159
159
|
const areBothStablecoins = fromToken.isStable && toToken.isStable;
|
|
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
|
|
|
2
2
|
import { mockMarketsInfoData, mockTokensData, usdToToken } from "../../../test/mock";
|
|
3
3
|
import { applyFactor, expandDecimals, USD_DECIMALS } from "../../numbers";
|
|
4
4
|
import { getLiquidationPrice } from "../../positions";
|
|
5
|
-
import { getMaxWithdrawAmount } from "../decrease";
|
|
5
|
+
import { getMaxWithdrawAmount, getMinRequiredCollateralUsdForPosition } from "../decrease";
|
|
6
6
|
describe("getMaxWithdrawAmount", () => {
|
|
7
7
|
const ETH_PRICE = expandDecimals(11952, 29); // $1195.20
|
|
8
8
|
const USDC_PRICE = expandDecimals(1, 30);
|
|
@@ -116,4 +116,48 @@ describe("getMaxWithdrawAmount", () => {
|
|
|
116
116
|
expect(applyFactor(position.sizeInUsd, position.marketInfo.minCollateralFactorForLiquidation)).toBeGreaterThan(0n);
|
|
117
117
|
expect(applyFactor(position.sizeInUsd, position.marketInfo.minCollateralFactor)).toBeGreaterThan(0n);
|
|
118
118
|
});
|
|
119
|
+
it("max withdraw equals the collateral above the min required collateral", () => {
|
|
120
|
+
const { position, usdcToken } = buildScenario();
|
|
121
|
+
const minCollateralUsd = expandDecimals(1, USD_DECIMALS);
|
|
122
|
+
const collateralPrice = usdcToken.prices.minPrice;
|
|
123
|
+
const minRequiredCollateralUsd = getMinRequiredCollateralUsdForPosition({
|
|
124
|
+
position,
|
|
125
|
+
minCollateralUsd,
|
|
126
|
+
userReferralInfo: undefined,
|
|
127
|
+
});
|
|
128
|
+
const maxWithdraw = getMaxWithdrawAmount({
|
|
129
|
+
position,
|
|
130
|
+
minCollateralUsd,
|
|
131
|
+
collateralPrice,
|
|
132
|
+
collateralDecimals: usdcToken.decimals,
|
|
133
|
+
userReferralInfo: undefined,
|
|
134
|
+
});
|
|
135
|
+
const maxWithdrawUsd = (maxWithdraw * collateralPrice) / expandDecimals(1, usdcToken.decimals);
|
|
136
|
+
const conversionLossUsd = position.collateralUsd - minRequiredCollateralUsd - maxWithdrawUsd;
|
|
137
|
+
expect(minRequiredCollateralUsd).toBeGreaterThan(0n);
|
|
138
|
+
expect(conversionLossUsd).toBeGreaterThanOrEqual(0n);
|
|
139
|
+
expect(conversionLossUsd).toBeLessThan(expandDecimals(1, USD_DECIMALS - usdcToken.decimals));
|
|
140
|
+
});
|
|
141
|
+
it("min required collateral exceeds current collateral when pending fees turn the remaining margin negative", () => {
|
|
142
|
+
const { position, usdcToken } = buildScenario();
|
|
143
|
+
const minCollateralUsd = expandDecimals(1, USD_DECIMALS);
|
|
144
|
+
const feeShortfallUsd = expandDecimals(100, USD_DECIMALS);
|
|
145
|
+
const underwaterPosition = {
|
|
146
|
+
...position,
|
|
147
|
+
pendingBorrowingFeesUsd: position.collateralUsd + feeShortfallUsd,
|
|
148
|
+
};
|
|
149
|
+
const minRequiredCollateralUsd = getMinRequiredCollateralUsdForPosition({
|
|
150
|
+
position: underwaterPosition,
|
|
151
|
+
minCollateralUsd,
|
|
152
|
+
userReferralInfo: undefined,
|
|
153
|
+
});
|
|
154
|
+
expect(minRequiredCollateralUsd - underwaterPosition.collateralUsd).toBeGreaterThan(feeShortfallUsd);
|
|
155
|
+
expect(getMaxWithdrawAmount({
|
|
156
|
+
position: underwaterPosition,
|
|
157
|
+
minCollateralUsd,
|
|
158
|
+
collateralPrice: usdcToken.prices.minPrice,
|
|
159
|
+
collateralDecimals: usdcToken.decimals,
|
|
160
|
+
userReferralInfo: undefined,
|
|
161
|
+
})).toBe(0n);
|
|
162
|
+
});
|
|
119
163
|
});
|