@gmx-io/sdk 1.6.3 → 1.6.4

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.
Files changed (247) hide show
  1. package/README.md +1 -1
  2. package/build/cjs/scripts/generate-synthetics-abis.js +181 -0
  3. package/build/cjs/scripts/subsquid-codegen.js +1 -1
  4. package/build/cjs/src/abis/AbstractSubaccountApprovalNonceable.js +23 -0
  5. package/build/cjs/src/abis/CustomErrors.js +198 -88
  6. package/build/cjs/src/abis/ExchangeRouter.js +155 -272
  7. package/build/cjs/src/abis/GelatoRelayRouter.js +331 -0
  8. package/build/cjs/src/abis/SimulationRouter.js +583 -0
  9. package/build/cjs/src/abis/SubaccountGelatoRelayRouter.js +393 -0
  10. package/build/cjs/src/abis/SyntheticsReader.js +40 -0
  11. package/build/cjs/src/abis/index.js +4 -24
  12. package/build/cjs/src/clients/v1/modules/markets/index.js +10 -6
  13. package/build/cjs/src/clients/v1/modules/orders/utils.js +1 -0
  14. package/build/cjs/src/clients/v1/modules/orders/utils.spec.js +66 -0
  15. package/build/cjs/src/clients/v1/modules/positions/positions.js +2 -10
  16. package/build/cjs/src/clients/v1/modules/positions/positions.spec.js +1 -1
  17. package/build/cjs/src/clients/v1/modules/trades/trades.js +5 -1
  18. package/build/cjs/src/clients/v1/simulateExecuteOrder.js +33 -54
  19. package/build/cjs/src/clients/v1/testUtil.js +1 -1
  20. package/build/cjs/src/clients/v2/__tests__/editCancel.spec.js +3 -1
  21. package/build/cjs/src/clients/v2/__tests__/increase.spec.js +8 -6
  22. package/build/cjs/src/clients/v2/index.js +6 -0
  23. package/build/cjs/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +0 -26
  24. package/build/cjs/src/codegen/prebuilt/hashedMarketConfigKeys.json +1692 -561
  25. package/build/cjs/src/codegen/prebuilt/hashedMarketValuesKeys.json +0 -47
  26. package/build/cjs/src/codegen/subsquid.js +101 -2
  27. package/build/cjs/src/configs/__tests__/tokens.spec.js +0 -1
  28. package/build/cjs/src/configs/api.js +0 -4
  29. package/build/cjs/src/configs/batch.js +0 -1
  30. package/build/cjs/src/configs/chainIds.js +1 -2
  31. package/build/cjs/src/configs/chains.js +2 -57
  32. package/build/cjs/src/configs/contracts.js +77 -133
  33. package/build/cjs/src/configs/dataStore.js +23 -8
  34. package/build/cjs/src/configs/express.js +0 -2
  35. package/build/cjs/src/configs/gasLimits.js +0 -7
  36. package/build/cjs/src/configs/markets.js +0 -23
  37. package/build/cjs/src/configs/multichainTokens.js +1 -1
  38. package/build/cjs/src/configs/oracleKeeper.js +0 -2
  39. package/build/cjs/src/configs/tokens.js +2 -104
  40. package/build/cjs/src/test/fixtures/arbitrumMarkets.json +1210 -0
  41. package/build/cjs/src/test/fixtures/arbitrumTickers.json +1002 -0
  42. package/build/cjs/src/test/fixtures/arbitrumTokens.json +136 -0
  43. package/build/cjs/src/test/mockCrossFetch.js +28 -0
  44. package/build/cjs/src/utils/__tests__/fees.spec.js +264 -0
  45. package/build/cjs/src/utils/__tests__/marketsRisk.spec.js +80 -0
  46. package/build/cjs/src/utils/__tests__/numbers.spec.js +49 -0
  47. package/build/cjs/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +6 -25
  48. package/build/cjs/src/utils/__tests__/orderTransactions/increaseOrders.spec.js +6 -25
  49. package/build/cjs/src/utils/__tests__/orderTransactions/swapOrders.spec.js +3 -13
  50. package/build/cjs/src/utils/__tests__/parseError.spec.js +23 -0
  51. package/build/cjs/src/utils/__tests__/uiFeeReceiver.spec.js +159 -58
  52. package/build/cjs/src/utils/errors/parseError.js +13 -1
  53. package/build/cjs/src/utils/errors/transactionsErrors.js +2 -0
  54. package/build/cjs/src/utils/express/utils/batchOrderUtils.js +1 -2
  55. package/build/cjs/src/utils/express/utils/estimateExpressParams.js +2 -0
  56. package/build/cjs/src/utils/express/utils/estimateExpressParams.spec.js +81 -0
  57. package/build/cjs/src/utils/express/utils/expressParamsUtils.js +5 -1
  58. package/build/cjs/src/utils/express/utils/expressParamsUtils.spec.js +27 -0
  59. package/build/cjs/src/utils/fees/executionFee.js +0 -1
  60. package/build/cjs/src/utils/fees/priceImpact.js +61 -20
  61. package/build/cjs/src/utils/http/validation.js +33 -0
  62. package/build/cjs/src/utils/markets/__tests__/api.spec.js +168 -0
  63. package/build/cjs/src/utils/markets/__tests__/mockMarkets.js +14 -5
  64. package/build/cjs/src/utils/markets/api.js +45 -3
  65. package/build/cjs/src/utils/markets/hashKeys.js +34 -6
  66. package/build/cjs/src/utils/markets/multicall.js +110 -11
  67. package/build/cjs/src/utils/markets/types.js +23 -0
  68. package/build/cjs/src/utils/markets/utils.js +15 -1
  69. package/build/cjs/src/utils/numbers/utils.js +26 -5
  70. package/build/cjs/src/utils/orderTransactions/simulation.js +13 -0
  71. package/build/cjs/src/utils/orderTransactions/utils.js +21 -8
  72. package/build/cjs/src/utils/positions/__tests__/api.spec.js +50 -0
  73. package/build/cjs/src/utils/positions/api.js +7 -1
  74. package/build/cjs/src/utils/positions/utils.js +7 -1
  75. package/build/cjs/src/utils/prices/utils.js +2 -0
  76. package/build/cjs/src/utils/subaccount/sdkClient.js +0 -1
  77. package/build/cjs/src/utils/swap/buildSwapStrategy.js +6 -123
  78. package/build/cjs/src/utils/swap/index.js +0 -3
  79. package/build/cjs/src/utils/swap/swapValues.js +0 -67
  80. package/build/cjs/src/utils/tokens/utils.js +9 -10
  81. package/build/cjs/src/utils/trade/__tests__/getMaxWithdrawAmount.spec.js +44 -0
  82. package/build/cjs/src/utils/trade/decrease.js +47 -23
  83. package/build/cjs/src/utils/trade/increase.js +22 -6
  84. package/build/cjs/src/utils/trade/types.js +0 -1
  85. package/build/cjs/src/utils/tradeHistory/types.js +3 -1
  86. package/build/cjs/src/utils/tradeHistory/utils.js +7 -0
  87. package/build/cjs/src/utils/twap/uiFeeReceiver.js +134 -47
  88. package/build/esm/scripts/generate-synthetics-abis.js +153 -0
  89. package/build/esm/scripts/subsquid-codegen.js +1 -1
  90. package/build/esm/src/abis/AbstractSubaccountApprovalNonceable.js +21 -0
  91. package/build/esm/src/abis/CustomErrors.js +198 -88
  92. package/build/esm/src/abis/ExchangeRouter.js +155 -272
  93. package/build/esm/src/abis/GelatoRelayRouter.js +331 -0
  94. package/build/esm/src/abis/SimulationRouter.js +581 -0
  95. package/build/esm/src/abis/SubaccountGelatoRelayRouter.js +393 -0
  96. package/build/esm/src/abis/SyntheticsReader.js +40 -0
  97. package/build/esm/src/abis/index.js +3 -23
  98. package/build/esm/src/clients/v1/modules/markets/index.js +10 -6
  99. package/build/esm/src/clients/v1/modules/orders/utils.js +1 -0
  100. package/build/esm/src/clients/v1/modules/orders/utils.spec.js +64 -0
  101. package/build/esm/src/clients/v1/modules/positions/positions.js +2 -10
  102. package/build/esm/src/clients/v1/modules/positions/positions.spec.js +1 -1
  103. package/build/esm/src/clients/v1/modules/trades/trades.js +5 -1
  104. package/build/esm/src/clients/v1/simulateExecuteOrder.js +35 -55
  105. package/build/esm/src/clients/v1/testUtil.js +1 -1
  106. package/build/esm/src/clients/v2/__tests__/editCancel.spec.js +3 -1
  107. package/build/esm/src/clients/v2/__tests__/increase.spec.js +8 -6
  108. package/build/esm/src/clients/v2/__tests__/swap.spec.js +1 -1
  109. package/build/esm/src/clients/v2/index.js +7 -1
  110. package/build/esm/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +0 -26
  111. package/build/esm/src/codegen/prebuilt/hashedMarketConfigKeys.json +1692 -561
  112. package/build/esm/src/codegen/prebuilt/hashedMarketValuesKeys.json +0 -47
  113. package/build/esm/src/codegen/subsquid.js +99 -0
  114. package/build/esm/src/configs/__tests__/multichainTokens.spec.js +1 -1
  115. package/build/esm/src/configs/__tests__/tokens.spec.js +1 -2
  116. package/build/esm/src/configs/api.js +1 -5
  117. package/build/esm/src/configs/batch.js +1 -2
  118. package/build/esm/src/configs/chainIds.js +0 -1
  119. package/build/esm/src/configs/chains.js +3 -57
  120. package/build/esm/src/configs/contracts.js +76 -133
  121. package/build/esm/src/configs/dataStore.js +16 -4
  122. package/build/esm/src/configs/express.js +1 -3
  123. package/build/esm/src/configs/gasLimits.js +1 -8
  124. package/build/esm/src/configs/markets.js +1 -24
  125. package/build/esm/src/configs/multichainTokens.js +1 -1
  126. package/build/esm/src/configs/oracleKeeper.js +1 -3
  127. package/build/esm/src/configs/tokens.js +3 -105
  128. package/build/esm/src/test/fixtures/arbitrumMarkets.json +1210 -0
  129. package/build/esm/src/test/fixtures/arbitrumTickers.json +1002 -0
  130. package/build/esm/src/test/fixtures/arbitrumTokens.json +136 -0
  131. package/build/esm/src/test/mockCrossFetch.js +23 -0
  132. package/build/esm/src/utils/__tests__/fees.spec.js +266 -2
  133. package/build/esm/src/utils/__tests__/marketsRisk.spec.js +78 -0
  134. package/build/esm/src/utils/__tests__/numbers.spec.js +50 -1
  135. package/build/esm/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +6 -25
  136. package/build/esm/src/utils/__tests__/orderTransactions/increaseOrders.spec.js +6 -25
  137. package/build/esm/src/utils/__tests__/orderTransactions/swapOrders.spec.js +3 -13
  138. package/build/esm/src/utils/__tests__/parseError.spec.js +25 -2
  139. package/build/esm/src/utils/__tests__/uiFeeReceiver.spec.js +161 -60
  140. package/build/esm/src/utils/errors/parseError.js +12 -1
  141. package/build/esm/src/utils/errors/transactionsErrors.js +2 -0
  142. package/build/esm/src/utils/express/utils/batchOrderUtils.js +2 -3
  143. package/build/esm/src/utils/express/utils/estimateExpressParams.js +2 -0
  144. package/build/esm/src/utils/express/utils/estimateExpressParams.spec.js +79 -0
  145. package/build/esm/src/utils/express/utils/expressParamsUtils.js +3 -0
  146. package/build/esm/src/utils/express/utils/expressParamsUtils.spec.js +25 -0
  147. package/build/esm/src/utils/fees/executionFee.js +0 -1
  148. package/build/esm/src/utils/fees/priceImpact.js +54 -13
  149. package/build/esm/src/utils/http/validation.js +28 -0
  150. package/build/esm/src/utils/markets/__tests__/api.spec.js +166 -0
  151. package/build/esm/src/utils/markets/__tests__/mockMarkets.js +15 -6
  152. package/build/esm/src/utils/markets/api.js +42 -2
  153. package/build/esm/src/utils/markets/hashKeys.js +35 -7
  154. package/build/esm/src/utils/markets/multicall.js +108 -11
  155. package/build/esm/src/utils/markets/types.js +22 -1
  156. package/build/esm/src/utils/markets/utils.js +13 -0
  157. package/build/esm/src/utils/numbers/utils.js +21 -3
  158. package/build/esm/src/utils/orderTransactions/simulation.js +9 -0
  159. package/build/esm/src/utils/orderTransactions/utils.js +22 -9
  160. package/build/esm/src/utils/positions/__tests__/api.spec.js +48 -0
  161. package/build/esm/src/utils/positions/api.js +7 -1
  162. package/build/esm/src/utils/positions/utils.js +7 -1
  163. package/build/esm/src/utils/prices/utils.js +2 -0
  164. package/build/esm/src/utils/subaccount/sdkClient.js +0 -1
  165. package/build/esm/src/utils/swap/buildSwapStrategy.js +7 -124
  166. package/build/esm/src/utils/swap/index.js +0 -3
  167. package/build/esm/src/utils/swap/swapValues.js +1 -68
  168. package/build/esm/src/utils/tokens/utils.js +8 -8
  169. package/build/esm/src/utils/trade/__tests__/getMaxWithdrawAmount.spec.js +45 -1
  170. package/build/esm/src/utils/trade/decrease.js +44 -22
  171. package/build/esm/src/utils/trade/increase.js +23 -7
  172. package/build/esm/src/utils/trade/types.js +0 -1
  173. package/build/esm/src/utils/tradeHistory/types.js +2 -0
  174. package/build/esm/src/utils/tradeHistory/utils.js +7 -0
  175. package/build/esm/src/utils/twap/uiFeeReceiver.js +127 -42
  176. package/build/tsconfig.tsbuildinfo +1 -1
  177. package/build/types/scripts/generate-synthetics-abis.d.ts +17 -0
  178. package/build/types/src/abis/AbstractSubaccountApprovalNonceable.d.ts +16 -0
  179. package/build/types/src/abis/CustomErrors.d.ts +331 -139
  180. package/build/types/src/abis/ExchangeRouter.d.ts +121 -209
  181. package/build/types/src/abis/GelatoRelayRouter.d.ts +258 -0
  182. package/build/types/src/abis/SimulationRouter.d.ts +448 -0
  183. package/build/types/src/abis/SubaccountGelatoRelayRouter.d.ts +307 -0
  184. package/build/types/src/abis/SyntheticsReader.d.ts +32 -0
  185. package/build/types/src/abis/index.d.ts +8108 -7891
  186. package/build/types/src/clients/v1/index.d.ts +1 -1
  187. package/build/types/src/clients/v1/modules/base.d.ts +1 -1
  188. package/build/types/src/clients/v1/modules/orders/utils.spec.d.ts +1 -0
  189. package/build/types/src/clients/v1/multicall.d.ts +1 -1
  190. package/build/types/src/clients/v1/simulateExecuteOrder.d.ts +0 -1
  191. package/build/types/src/clients/v2/index.d.ts +2 -0
  192. package/build/types/src/codegen/prebuilt/index.d.ts +1692 -634
  193. package/build/types/src/codegen/subsquid.d.ts +368 -0
  194. package/build/types/src/configs/chainIds.d.ts +0 -1
  195. package/build/types/src/configs/chains.d.ts +9 -34
  196. package/build/types/src/configs/contracts.d.ts +5 -66
  197. package/build/types/src/configs/dataStore.d.ts +8 -2
  198. package/build/types/src/configs/multichainTokens.d.ts +1 -1
  199. package/build/types/src/test/mockCrossFetch.d.ts +2 -0
  200. package/build/types/src/utils/__tests__/marketsRisk.spec.d.ts +1 -0
  201. package/build/types/src/utils/errors/parseError.d.ts +1 -0
  202. package/build/types/src/utils/errors/transactionsErrors.d.ts +2 -0
  203. package/build/types/src/utils/express/types.d.ts +2 -1
  204. package/build/types/src/utils/express/utils/batchOrderUtils.d.ts +1 -1
  205. package/build/types/src/utils/express/utils/estimateExpressParams.spec.d.ts +1 -0
  206. package/build/types/src/utils/express/utils/expressParamsUtils.d.ts +1 -0
  207. package/build/types/src/utils/express/utils/expressParamsUtils.spec.d.ts +1 -0
  208. package/build/types/src/utils/express/utils/globalExpressParams.d.ts +1 -1
  209. package/build/types/src/utils/fees/priceImpact.d.ts +2 -0
  210. package/build/types/src/utils/http/validation.d.ts +7 -0
  211. package/build/types/src/utils/markets/__tests__/api.spec.d.ts +1 -0
  212. package/build/types/src/utils/markets/api.d.ts +7 -1
  213. package/build/types/src/utils/markets/hashKeys.d.ts +1 -1
  214. package/build/types/src/utils/markets/multicall.d.ts +13 -2
  215. package/build/types/src/utils/markets/types.d.ts +18 -4
  216. package/build/types/src/utils/markets/utils.d.ts +2 -1
  217. package/build/types/src/utils/numbers/utils.d.ts +5 -1
  218. package/build/types/src/utils/orderTransactions/simulation.d.ts +1 -0
  219. package/build/types/src/utils/orders/types.d.ts +2 -0
  220. package/build/types/src/utils/positions/__tests__/api.spec.d.ts +1 -0
  221. package/build/types/src/utils/positions/types.d.ts +1 -0
  222. package/build/types/src/utils/positions/utils.d.ts +1 -0
  223. package/build/types/src/utils/prices/utils.d.ts +1 -0
  224. package/build/types/src/utils/swap/buildSwapStrategy.d.ts +3 -5
  225. package/build/types/src/utils/swap/index.d.ts +0 -3
  226. package/build/types/src/utils/swap/swapValues.d.ts +1 -1
  227. package/build/types/src/utils/swap/types.d.ts +2 -7
  228. package/build/types/src/utils/tokens/types.d.ts +0 -1
  229. package/build/types/src/utils/tokens/utils.d.ts +1 -2
  230. package/build/types/src/utils/trade/decrease.d.ts +11 -0
  231. package/build/types/src/utils/trade/types.d.ts +2 -8
  232. package/build/types/src/utils/tradeHistory/types.d.ts +7 -0
  233. package/build/types/src/utils/twap/types.d.ts +1 -1
  234. package/build/types/src/utils/twap/uiFeeReceiver.d.ts +23 -22
  235. package/package.json +10 -7
  236. package/build/cjs/src/abis/StBTC.js +0 -513
  237. package/build/cjs/src/utils/swap/botanixStaking.js +0 -90
  238. package/build/cjs/src/utils/swap/externalSwapPath.js +0 -41
  239. package/build/cjs/src/utils/swap/externalSwapQuoteByPath.js +0 -27
  240. package/build/esm/src/abis/StBTC.js +0 -511
  241. package/build/esm/src/utils/swap/botanixStaking.js +0 -83
  242. package/build/esm/src/utils/swap/externalSwapPath.js +0 -37
  243. package/build/esm/src/utils/swap/externalSwapQuoteByPath.js +0 -23
  244. package/build/types/src/abis/StBTC.d.ts +0 -932
  245. package/build/types/src/utils/swap/botanixStaking.d.ts +0 -11
  246. package/build/types/src/utils/swap/externalSwapPath.d.ts +0 -13
  247. package/build/types/src/utils/swap/externalSwapQuoteByPath.d.ts +0 -6
@@ -1,17 +1,14 @@
1
1
  import { bigMath } from "../bigmath";
2
2
  import { SwapPricingType } from "../orders/types";
3
- import { convertToTokenAmount, convertToUsd, getIsEquivalentTokens, getIsStake, getIsUnstake, getIsUnwrap, getIsWrap, getMidPrice, } from "../tokens";
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, stake or unstake [noSwap]
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. Check if there is a combined swap strategy and return combinedSwap if there is [combinedSwap]
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, externalSwapQuoteParams, swapPricingType = SwapPricingType.Swap, allowSameTokenSwap, disabledMarkets, manualPath, }) {
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, externalSwapQuoteParams, swapOptimizationOrder, swapPricingType, allowSameTokenSwap, disabledMarkets, manualPath, }) {
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, getIsStake, getIsUnstake, getIsUnwrap, getIsWrap, } from "../tokens";
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
  });
@@ -7,6 +7,18 @@ import { getLeverage, getLiquidationPrice, getMinCollateralFactorForPosition, ge
7
7
  import { getAcceptablePriceInfo, getDefaultAcceptablePriceImpactBps, getMarkPrice, getOrderThresholdType, } from "../prices";
8
8
  import { getSwapAmountsByFromValue, getSwapStats } from "../swap";
9
9
  import { convertToTokenAmount, convertToUsd, getIsEquivalentTokens } from "../tokens";
10
+ export function getDecreasePositionSizeDeltaInTokens(p) {
11
+ const { sizeInUsd, sizeInTokens, sizeDeltaUsd, isLong } = p;
12
+ if (sizeInUsd <= 0n || sizeInTokens <= 0n || sizeDeltaUsd <= 0n) {
13
+ return 0n;
14
+ }
15
+ if (sizeDeltaUsd >= sizeInUsd) {
16
+ return sizeInTokens;
17
+ }
18
+ return isLong
19
+ ? roundUpDivision(sizeInTokens * sizeDeltaUsd, sizeInUsd)
20
+ : bigMath.mulDiv(sizeInTokens, sizeDeltaUsd, sizeInUsd);
21
+ }
10
22
  export function getDecreasePositionAmounts(p) {
11
23
  const { marketInfo, collateralToken, isLong, position, closeSizeUsd, keepLeverage, triggerPrice, fixedAcceptablePriceImpactBps, acceptablePriceImpactBuffer, userReferralInfo, minCollateralUsd, minPositionSizeUsd, uiFeeFactor, triggerOrderType: orderType, receiveToken: receiveTokenArg, isSetAcceptablePriceImpactEnabled, forceDecreaseSwapType, } = p;
12
24
  const { indexToken } = marketInfo;
@@ -72,16 +84,18 @@ export function getDecreasePositionAmounts(p) {
72
84
  }
73
85
  values.sizeDeltaUsd = closeSizeUsd;
74
86
  if (!position || position.sizeInUsd <= 0 || position.sizeInTokens <= 0) {
75
- applyAcceptablePrice({
76
- position,
77
- marketInfo,
78
- isLong,
79
- isTrigger,
80
- fixedAcceptablePriceImpactBps,
81
- acceptablePriceImpactBuffer,
82
- values,
83
- isSetAcceptablePriceImpactEnabled,
84
- });
87
+ if (!marketInfo.useOpenInterestInTokensForBalance) {
88
+ applyAcceptablePrice({
89
+ position,
90
+ marketInfo,
91
+ isLong,
92
+ isTrigger,
93
+ fixedAcceptablePriceImpactBps,
94
+ acceptablePriceImpactBuffer,
95
+ values,
96
+ isSetAcceptablePriceImpactEnabled,
97
+ });
98
+ }
85
99
  const positionFeeInfo = getPositionFee(marketInfo, values.sizeDeltaUsd, values.balanceWasImproved, userReferralInfo);
86
100
  values.positionFeeUsd = positionFeeInfo.positionFeeUsd;
87
101
  values.feeDiscountUsd = positionFeeInfo.discountUsd;
@@ -114,16 +128,13 @@ export function getDecreasePositionAmounts(p) {
114
128
  });
115
129
  if (values.isFullClose) {
116
130
  values.sizeDeltaUsd = position.sizeInUsd;
117
- values.sizeDeltaInTokens = position.sizeInTokens;
118
- }
119
- else {
120
- if (position.isLong) {
121
- values.sizeDeltaInTokens = roundUpDivision(position.sizeInTokens * values.sizeDeltaUsd, position.sizeInUsd);
122
- }
123
- else {
124
- values.sizeDeltaInTokens = bigMath.mulDiv(position.sizeInTokens, values.sizeDeltaUsd, position.sizeInUsd);
125
- }
126
131
  }
132
+ values.sizeDeltaInTokens = getDecreasePositionSizeDeltaInTokens({
133
+ sizeInUsd: position.sizeInUsd,
134
+ sizeInTokens: position.sizeInTokens,
135
+ sizeDeltaUsd: values.sizeDeltaUsd,
136
+ isLong: position.isLong,
137
+ });
127
138
  // PNL
128
139
  values.estimatedPnl = getPositionPnlUsd({
129
140
  marketInfo,
@@ -322,8 +333,8 @@ export function getMinCollateralUsdForLeverage(position, openInterestDelta) {
322
333
  const minCollateralFactor = getMinCollateralFactorForPosition(position, openInterestDelta);
323
334
  return applyFactor(position.sizeInUsd, minCollateralFactor);
324
335
  }
325
- export function getMaxWithdrawAmount(p) {
326
- const { position, minCollateralUsd, collateralPrice, collateralDecimals, userReferralInfo } = p;
336
+ export function getMinRequiredCollateralUsdForPosition(p) {
337
+ const { position, minCollateralUsd, userReferralInfo } = p;
327
338
  const minCollateralUsdForLeverage = getMinCollateralUsdForLeverage(position, 0n);
328
339
  let minRequiredNextCollateralUsd = minCollateralUsdForLeverage;
329
340
  if (minCollateralUsd !== undefined && minCollateralUsd > minRequiredNextCollateralUsd) {
@@ -342,7 +353,15 @@ export function getMaxWithdrawAmount(p) {
342
353
  if (minCollateralUsdForLiquidationPrice > minRequiredNextCollateralUsd) {
343
354
  minRequiredNextCollateralUsd = minCollateralUsdForLiquidationPrice;
344
355
  }
345
- const minRequiredCollateralUsd = minRequiredNextCollateralUsd + (position.pendingBorrowingFeesUsd ?? 0n) + (position.pendingFundingFeesUsd ?? 0n);
356
+ return (minRequiredNextCollateralUsd + (position.pendingBorrowingFeesUsd ?? 0n) + (position.pendingFundingFeesUsd ?? 0n));
357
+ }
358
+ export function getMaxWithdrawAmount(p) {
359
+ const { position, minCollateralUsd, collateralPrice, collateralDecimals, userReferralInfo } = p;
360
+ const minRequiredCollateralUsd = getMinRequiredCollateralUsdForPosition({
361
+ position,
362
+ minCollateralUsd,
363
+ userReferralInfo,
364
+ });
346
365
  if (position.collateralUsd < minRequiredCollateralUsd) {
347
366
  return 0n;
348
367
  }
@@ -397,6 +416,7 @@ function applyAcceptablePrice(p) {
397
416
  isLong,
398
417
  indexPrice: values.indexPrice,
399
418
  sizeDeltaUsd: values.sizeDeltaUsd,
419
+ sizeDeltaInTokens: values.sizeDeltaInTokens,
400
420
  });
401
421
  values.acceptablePrice = acceptablePriceInfo.acceptablePrice;
402
422
  values.acceptablePriceDeltaBps = acceptablePriceInfo.acceptablePriceDeltaBps;
@@ -437,6 +457,7 @@ function applyAcceptablePrice(p) {
437
457
  indexPrice: values.indexPrice,
438
458
  sizeDeltaUsd: values.sizeDeltaUsd,
439
459
  maxNegativePriceImpactBps,
460
+ sizeDeltaInTokens: values.sizeDeltaInTokens,
440
461
  });
441
462
  values.acceptablePrice = triggerAcceptablePriceInfo.acceptablePrice;
442
463
  values.acceptablePriceDeltaBps = triggerAcceptablePriceInfo.acceptablePriceDeltaBps;
@@ -509,6 +530,7 @@ export function getNextPositionValuesForDecreaseTrade(p) {
509
530
  : 0n;
510
531
  return {
511
532
  nextSizeUsd,
533
+ nextSizeInTokens,
512
534
  nextCollateralUsd,
513
535
  nextLiqPrice,
514
536
  nextPnl,
@@ -7,7 +7,7 @@ import { OrderType } from "../orders/types";
7
7
  import { getEntryPrice, getLeverage, getLiquidationPrice, getPositionPnlUsd, getPriceImpactDiffUsd, } from "../positions";
8
8
  import { getAcceptablePriceInfo, getDefaultAcceptablePriceImpactBps, getMarkPrice, getOrderThresholdType, } from "../prices";
9
9
  import { getSwapAmountsByFromValue, getSwapAmountsByToValue } from "../swap";
10
- import { convertToTokenAmount, convertToUsd, getTokensRatioByPrice } from "../tokens";
10
+ import { convertToTokenAmount, convertToTokenAmountForIncrease, convertToUsd, getTokensRatioByPrice, } from "../tokens";
11
11
  export function getIncreasePositionAmounts(p) {
12
12
  const { marketInfo, indexToken, initialCollateralToken, collateralToken, initialCollateralAmount, indexTokenAmount, isLong, leverage, triggerPrice, limitOrderType, position, fixedAcceptablePriceImpactBps, acceptablePriceImpactBuffer, externalSwapQuote, findSwapPath, userReferralInfo, uiFeeFactor, strategy, marketsInfoData, chainId, externalSwapQuoteParams, isSetAcceptablePriceImpactEnabled, disabledMarkets, manualPath, } = p;
13
13
  const swapStrategy = {
@@ -108,13 +108,20 @@ export function getIncreasePositionAmounts(p) {
108
108
  const swapAmountOut = values.swapStrategy.amountOut;
109
109
  const baseCollateralUsd = convertToUsd(swapAmountOut, collateralToken.decimals, values.collateralPrice);
110
110
  const baseSizeDeltaUsd = bigMath.mulDiv(baseCollateralUsd, leverage, BASIS_POINTS_DIVISOR_BIGINT);
111
- const { balanceWasImproved } = getPriceImpactForPosition(marketInfo, baseSizeDeltaUsd, isLong);
112
- const basePositionFeeInfo = getPositionFee(marketInfo, baseSizeDeltaUsd, balanceWasImproved, userReferralInfo);
111
+ const baseSizeDeltaInTokens = convertToTokenAmountForIncrease(baseSizeDeltaUsd, indexToken.decimals, values.indexPrice, isLong);
112
+ const { balanceWasImproved: baseBalanceWasImproved } = getPriceImpactForPosition(marketInfo, baseSizeDeltaUsd, isLong, { sizeDeltaInTokens: baseSizeDeltaInTokens });
113
+ const basePositionFeeInfo = getPositionFee(marketInfo, baseSizeDeltaUsd, baseBalanceWasImproved, userReferralInfo);
113
114
  const baseUiFeeUsd = applyFactor(baseSizeDeltaUsd, uiFeeFactor);
114
115
  const totalSwapVolumeUsd = getTotalSwapVolumeFromSwapStats(values.swapStrategy.swapPathStats?.swapSteps);
115
116
  values.swapUiFeeUsd = applyFactor(totalSwapVolumeUsd, uiFeeFactor);
116
117
  values.sizeDeltaUsd = bigMath.mulDiv(baseCollateralUsd - basePositionFeeInfo.positionFeeUsd - baseUiFeeUsd - values.swapUiFeeUsd, leverage, BASIS_POINTS_DIVISOR_BIGINT);
117
- values.indexTokenAmount = convertToTokenAmount(values.sizeDeltaUsd, indexToken.decimals, values.indexPrice);
118
+ if (values.sizeDeltaUsd <= 0n) {
119
+ return values;
120
+ }
121
+ values.indexTokenAmount = convertToTokenAmountForIncrease(values.sizeDeltaUsd, indexToken.decimals, values.indexPrice, isLong);
122
+ const { balanceWasImproved } = getPriceImpactForPosition(marketInfo, values.sizeDeltaUsd, isLong, {
123
+ sizeDeltaInTokens: values.indexTokenAmount,
124
+ });
118
125
  const positionFeeInfo = getPositionFee(marketInfo, values.sizeDeltaUsd, balanceWasImproved, userReferralInfo);
119
126
  values.positionFeeUsd = positionFeeInfo.positionFeeUsd;
120
127
  values.feeDiscountUsd = positionFeeInfo.discountUsd;
@@ -135,7 +142,10 @@ export function getIncreasePositionAmounts(p) {
135
142
  values.estimatedLeverage = leverage;
136
143
  values.indexTokenAmount = indexTokenAmount;
137
144
  values.sizeDeltaUsd = convertToUsd(indexTokenAmount, indexToken.decimals, values.indexPrice);
138
- const { balanceWasImproved } = getPriceImpactForPosition(marketInfo, values.sizeDeltaUsd, isLong);
145
+ const sizeDeltaInTokensForPriceImpact = convertToTokenAmountForIncrease(values.sizeDeltaUsd, indexToken.decimals, values.indexPrice, isLong);
146
+ const { balanceWasImproved } = getPriceImpactForPosition(marketInfo, values.sizeDeltaUsd, isLong, {
147
+ sizeDeltaInTokens: sizeDeltaInTokensForPriceImpact,
148
+ });
139
149
  const positionFeeInfo = getPositionFee(marketInfo, values.sizeDeltaUsd, balanceWasImproved, userReferralInfo);
140
150
  values.positionFeeUsd = positionFeeInfo.positionFeeUsd;
141
151
  values.feeDiscountUsd = positionFeeInfo.discountUsd;
@@ -188,7 +198,10 @@ export function getIncreasePositionAmounts(p) {
188
198
  if (indexTokenAmount !== undefined && indexTokenAmount > 0) {
189
199
  values.indexTokenAmount = indexTokenAmount;
190
200
  values.sizeDeltaUsd = convertToUsd(indexTokenAmount, indexToken.decimals, values.indexPrice);
191
- const { balanceWasImproved } = getPriceImpactForPosition(marketInfo, values.sizeDeltaUsd, isLong);
201
+ const sizeDeltaInTokensForPriceImpact = convertToTokenAmountForIncrease(values.sizeDeltaUsd, indexToken.decimals, values.indexPrice, isLong);
202
+ const { balanceWasImproved } = getPriceImpactForPosition(marketInfo, values.sizeDeltaUsd, isLong, {
203
+ sizeDeltaInTokens: sizeDeltaInTokensForPriceImpact,
204
+ });
192
205
  const positionFeeInfo = getPositionFee(marketInfo, values.sizeDeltaUsd, balanceWasImproved, userReferralInfo);
193
206
  values.positionFeeUsd = positionFeeInfo.positionFeeUsd;
194
207
  values.feeDiscountUsd = positionFeeInfo.discountUsd;
@@ -243,6 +256,7 @@ export function getIncreasePositionAmounts(p) {
243
256
  pendingFundingFeesUsd: 0n,
244
257
  });
245
258
  }
259
+ values.sizeDeltaInTokens = convertToTokenAmountForIncrease(values.sizeDeltaUsd, indexToken.decimals, values.indexPrice, isLong);
246
260
  const acceptablePriceInfo = getAcceptablePriceInfo({
247
261
  marketInfo,
248
262
  isIncrease: true,
@@ -250,6 +264,7 @@ export function getIncreasePositionAmounts(p) {
250
264
  isLong,
251
265
  indexPrice: values.indexPrice,
252
266
  sizeDeltaUsd: values.sizeDeltaUsd,
267
+ sizeDeltaInTokens: values.sizeDeltaInTokens,
253
268
  });
254
269
  values.positionPriceImpactDeltaUsd = acceptablePriceInfo.priceImpactDeltaUsd;
255
270
  values.potentialPriceImpactDiffUsd = getPriceImpactDiffUsd({
@@ -284,12 +299,12 @@ export function getIncreasePositionAmounts(p) {
284
299
  indexPrice: values.indexPrice,
285
300
  sizeDeltaUsd: values.sizeDeltaUsd,
286
301
  maxNegativePriceImpactBps,
302
+ sizeDeltaInTokens: values.sizeDeltaInTokens,
287
303
  });
288
304
  values.acceptablePrice = limitAcceptablePriceInfo.acceptablePrice;
289
305
  values.acceptablePriceDeltaBps = limitAcceptablePriceInfo.acceptablePriceDeltaBps;
290
306
  }
291
307
  }
292
- values.sizeDeltaInTokens = convertToTokenAmount(values.sizeDeltaUsd, indexToken.decimals, values.indexPrice);
293
308
  return values;
294
309
  }
295
310
  export function getTokensRatio({ fromToken, toToken, triggerRatioValue, markPrice, }) {
@@ -408,6 +423,7 @@ export function getNextPositionValuesForIncreaseTrade(p) {
408
423
  nextPendingImpactDeltaUsd = capPositionImpactUsdByMaxImpactPool(marketInfo, nextPendingImpactDeltaUsd);
409
424
  return {
410
425
  nextSizeUsd,
426
+ nextSizeInTokens,
411
427
  nextCollateralUsd,
412
428
  nextEntryPrice,
413
429
  nextLeverage,
@@ -20,5 +20,4 @@ export var TriggerThresholdType;
20
20
  export var ExternalSwapAggregator;
21
21
  (function (ExternalSwapAggregator) {
22
22
  ExternalSwapAggregator["KyberSwap"] = "kyberSwap";
23
- ExternalSwapAggregator["BotanixStaking"] = "botanixStaking";
24
23
  })(ExternalSwapAggregator || (ExternalSwapAggregator = {}));
@@ -6,6 +6,8 @@ export var TradeActionType;
6
6
  TradeActionType["OrderUpdated"] = "OrderUpdated";
7
7
  TradeActionType["OrderFrozen"] = "OrderFrozen";
8
8
  })(TradeActionType || (TradeActionType = {}));
9
+ /** For market orders this means expired (keeper cancelled after requestExpirationTime). */
10
+ export const USER_INITIATED_CANCEL = "USER_INITIATED_CANCEL";
9
11
  export function isPositionTradeAction(tradeAction) {
10
12
  return tradeAction.type === "position";
11
13
  }
@@ -81,6 +81,10 @@ export function createRawTradeActionTransformer(marketsInfoData, wrappedToken, t
81
81
  srcChainId: rawAction.srcChainId ? Number(rawAction.srcChainId) : undefined,
82
82
  indexToken,
83
83
  swapPath,
84
+ positionKey: rawAction.positionKey ?? undefined,
85
+ positionLifecycleId: rawAction.positionLifecycleId ?? undefined,
86
+ positionSizeInUsd: rawAction.positionSizeInUsd ? toBigInt(rawAction.positionSizeInUsd) : undefined,
87
+ positionSizeInTokens: rawAction.positionSizeInTokens ? toBigInt(rawAction.positionSizeInTokens) : undefined,
84
88
  initialCollateralTokenAddress,
85
89
  initialCollateralToken,
86
90
  targetCollateralToken,
@@ -122,6 +126,9 @@ export function createRawTradeActionTransformer(marketsInfoData, wrappedToken, t
122
126
  fundingFeeAmount: rawAction.fundingFeeAmount ? BigInt(rawAction.fundingFeeAmount) : undefined,
123
127
  swapFeeUsd: rawAction.swapFeeUsd ? BigInt(rawAction.swapFeeUsd) : undefined,
124
128
  liquidationFeeAmount: rawAction.liquidationFeeAmount ? BigInt(rawAction.liquidationFeeAmount) : undefined,
129
+ minCollateralFactorForLiquidation: rawAction.minCollateralFactorForLiquidation
130
+ ? BigInt(rawAction.minCollateralFactorForLiquidation)
131
+ : undefined,
125
132
  reason: rawAction.reason ?? undefined,
126
133
  reasonBytes: rawAction.reasonBytes ?? undefined,
127
134
  transactionHash: rawAction.transactionHash,