@gmx-io/sdk 2.9.2 → 3.0.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.
Files changed (184) hide show
  1. package/build/cjs/src/abis/RatioVesterReader.js +45 -0
  2. package/build/cjs/src/abis/index.js +2 -0
  3. package/build/cjs/src/clients/v1/modules/oracle.js +15 -0
  4. package/build/cjs/src/clients/v1/modules/oracle.spec.js +20 -0
  5. package/build/cjs/src/clients/v1/modules/orders/helpers.js +16 -12
  6. package/build/cjs/src/clients/v1/modules/orders/helpers.spec.js +21 -0
  7. package/build/cjs/src/clients/v1/modules/orders/orders.js +4 -0
  8. package/build/cjs/src/clients/v1/modules/orders/utils.js +1 -0
  9. package/build/cjs/src/clients/v2/__tests__/subaccount.spec.js +74 -17
  10. package/build/cjs/src/clients/v2/__tests__/subaccountLifecycle.spec.js +1 -1
  11. package/build/cjs/src/clients/v2/__tests__/testUtil.js +14 -2
  12. package/build/cjs/src/clients/v2/index.js +28 -7
  13. package/build/cjs/src/clients/v2/solana.spec.js +81 -4
  14. package/build/cjs/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +48 -0
  15. package/build/cjs/src/codegen/prebuilt/hashedMarketConfigKeys.json +782 -0
  16. package/build/cjs/src/codegen/prebuilt/hashedMarketValuesKeys.json +90 -0
  17. package/build/cjs/src/configs/contracts.js +10 -0
  18. package/build/cjs/src/configs/dataStore.js +22 -4
  19. package/build/cjs/src/configs/express.js +1 -2
  20. package/build/cjs/src/configs/markets.js +42 -0
  21. package/build/cjs/src/configs/tokens.js +2 -0
  22. package/build/cjs/src/test/mockCrossFetch.js +1 -0
  23. package/build/cjs/src/utils/__tests__/fees.spec.js +52 -0
  24. package/build/cjs/src/utils/__tests__/gmsolUnits.spec.js +101 -0
  25. package/build/cjs/src/utils/__tests__/orderTransactions/batchUtils.spec.js +66 -0
  26. package/build/cjs/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +6 -6
  27. package/build/cjs/src/utils/__tests__/orderTransactions/exchangeRouterMulticall.spec.js +40 -0
  28. package/build/cjs/src/utils/__tests__/orderTransactions/updateOrder.spec.js +4 -2
  29. package/build/cjs/src/utils/__tests__/tokens.spec.js +63 -0
  30. package/build/cjs/src/utils/errors/transactionsErrors.js +6 -0
  31. package/build/cjs/src/utils/fees/index.js +5 -0
  32. package/build/cjs/src/utils/fees/priceImpact.js +39 -6
  33. package/build/cjs/src/utils/gmsol/__tests__/fixtures/nativeMath.json +3171 -0
  34. package/build/cjs/src/utils/gmsol/__tests__/nativeMath.spec.js +213 -0
  35. package/build/cjs/src/utils/gmsol/constants.js +4 -1
  36. package/build/cjs/src/utils/gmsol/fees.js +19 -0
  37. package/build/cjs/src/utils/gmsol/index.js +29 -1
  38. package/build/cjs/src/utils/gmsol/markets.js +206 -0
  39. package/build/cjs/src/utils/gmsol/numbers.js +55 -1
  40. package/build/cjs/src/utils/gmsol/positions.js +152 -0
  41. package/build/cjs/src/utils/gmsol/units.js +106 -0
  42. package/build/cjs/src/utils/http/http.js +21 -25
  43. package/build/cjs/src/utils/http/httpFallback.js +3 -3
  44. package/build/cjs/src/utils/http/validation.js +9 -1
  45. package/build/cjs/src/utils/markets/hashKeys.js +8 -0
  46. package/build/cjs/src/utils/markets/multicall.js +10 -0
  47. package/build/cjs/src/utils/markets/utils.js +2 -0
  48. package/build/cjs/src/utils/multichain/__tests__/api.spec.js +49 -0
  49. package/build/cjs/src/utils/multichain/api.js +29 -2
  50. package/build/cjs/src/utils/orderTransactions/utils.js +63 -5
  51. package/build/cjs/src/utils/orders/api.js +66 -3
  52. package/build/cjs/src/utils/positions/__tests__/liquidationImpact.spec.js +44 -0
  53. package/build/cjs/src/utils/positions/__tests__/liquidationPrice.spec.js +159 -2
  54. package/build/cjs/src/utils/positions/__tests__/trackingCollateral.spec.js +395 -0
  55. package/build/cjs/src/utils/positions/api.js +4 -0
  56. package/build/cjs/src/utils/positions/utils.js +119 -44
  57. package/build/cjs/src/utils/prices/api.js +2 -2
  58. package/build/cjs/src/utils/referrals/api.js +5 -4
  59. package/build/cjs/src/utils/subaccount/generateSubaccount.js +14 -14
  60. package/build/cjs/src/utils/subaccount/sdkClient.js +40 -19
  61. package/build/cjs/src/utils/tokens/utils.js +23 -7
  62. package/build/cjs/src/utils/trade/__tests__/decrease.spec.js +152 -0
  63. package/build/cjs/src/utils/trade/__tests__/gmsolTradeMath.spec.js +43 -0
  64. package/build/cjs/src/utils/trade/decrease.js +113 -33
  65. package/build/cjs/src/utils/trade/decreaseMarginCheck.js +38 -2
  66. package/build/cjs/src/utils/trade/decreaseOutputs.js +20 -5
  67. package/build/cjs/src/utils/trade/increase.js +30 -11
  68. package/build/cjs/src/utils/trade/increaseMarginCheck.js +14 -35
  69. package/build/esm/src/abis/RatioVesterReader.js +43 -0
  70. package/build/esm/src/abis/index.js +2 -0
  71. package/build/esm/src/clients/v1/modules/oracle.js +15 -0
  72. package/build/esm/src/clients/v1/modules/oracle.spec.js +18 -0
  73. package/build/esm/src/clients/v1/modules/orders/helpers.js +17 -13
  74. package/build/esm/src/clients/v1/modules/orders/helpers.spec.js +21 -0
  75. package/build/esm/src/clients/v1/modules/orders/orders.js +4 -0
  76. package/build/esm/src/clients/v1/modules/orders/utils.js +1 -0
  77. package/build/esm/src/clients/v2/__tests__/subaccount.spec.js +74 -17
  78. package/build/esm/src/clients/v2/__tests__/subaccountLifecycle.spec.js +2 -2
  79. package/build/esm/src/clients/v2/__tests__/testUtil.js +13 -2
  80. package/build/esm/src/clients/v2/index.js +29 -8
  81. package/build/esm/src/clients/v2/solana.spec.js +79 -2
  82. package/build/esm/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +48 -0
  83. package/build/esm/src/codegen/prebuilt/hashedMarketConfigKeys.json +782 -0
  84. package/build/esm/src/codegen/prebuilt/hashedMarketValuesKeys.json +90 -0
  85. package/build/esm/src/configs/contracts.js +10 -0
  86. package/build/esm/src/configs/dataStore.js +14 -0
  87. package/build/esm/src/configs/express.js +0 -1
  88. package/build/esm/src/configs/markets.js +42 -0
  89. package/build/esm/src/configs/tokens.js +2 -0
  90. package/build/esm/src/test/mockCrossFetch.js +1 -0
  91. package/build/esm/src/utils/__tests__/fees.spec.js +53 -1
  92. package/build/esm/src/utils/__tests__/gmsolUnits.spec.js +99 -0
  93. package/build/esm/src/utils/__tests__/orderTransactions/batchUtils.spec.js +68 -2
  94. package/build/esm/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +6 -6
  95. package/build/esm/src/utils/__tests__/orderTransactions/exchangeRouterMulticall.spec.js +40 -0
  96. package/build/esm/src/utils/__tests__/orderTransactions/updateOrder.spec.js +5 -3
  97. package/build/esm/src/utils/__tests__/tokens.spec.js +64 -1
  98. package/build/esm/src/utils/errors/transactionsErrors.js +6 -0
  99. package/build/esm/src/utils/fees/index.js +5 -0
  100. package/build/esm/src/utils/fees/priceImpact.js +36 -5
  101. package/build/esm/src/utils/gmsol/__tests__/fixtures/nativeMath.json +3171 -0
  102. package/build/esm/src/utils/gmsol/__tests__/nativeMath.spec.js +208 -0
  103. package/build/esm/src/utils/gmsol/constants.js +3 -0
  104. package/build/esm/src/utils/gmsol/fees.js +15 -0
  105. package/build/esm/src/utils/gmsol/index.js +6 -2
  106. package/build/esm/src/utils/gmsol/markets.js +193 -0
  107. package/build/esm/src/utils/gmsol/numbers.js +55 -1
  108. package/build/esm/src/utils/gmsol/positions.js +148 -0
  109. package/build/esm/src/utils/gmsol/units.js +97 -0
  110. package/build/esm/src/utils/http/http.js +21 -25
  111. package/build/esm/src/utils/http/httpFallback.js +3 -3
  112. package/build/esm/src/utils/http/validation.js +7 -0
  113. package/build/esm/src/utils/markets/hashKeys.js +9 -1
  114. package/build/esm/src/utils/markets/multicall.js +10 -0
  115. package/build/esm/src/utils/markets/utils.js +2 -0
  116. package/build/esm/src/utils/multichain/__tests__/api.spec.js +46 -0
  117. package/build/esm/src/utils/multichain/api.js +29 -2
  118. package/build/esm/src/utils/orderTransactions/utils.js +59 -5
  119. package/build/esm/src/utils/orders/api.js +64 -2
  120. package/build/esm/src/utils/positions/__tests__/liquidationImpact.spec.js +42 -0
  121. package/build/esm/src/utils/positions/__tests__/liquidationPrice.spec.js +161 -4
  122. package/build/esm/src/utils/positions/__tests__/trackingCollateral.spec.js +393 -0
  123. package/build/esm/src/utils/positions/api.js +4 -0
  124. package/build/esm/src/utils/positions/utils.js +115 -44
  125. package/build/esm/src/utils/prices/api.js +2 -2
  126. package/build/esm/src/utils/referrals/api.js +6 -5
  127. package/build/esm/src/utils/subaccount/generateSubaccount.js +13 -14
  128. package/build/esm/src/utils/subaccount/sdkClient.js +38 -19
  129. package/build/esm/src/utils/tokens/utils.js +20 -6
  130. package/build/esm/src/utils/trade/__tests__/decrease.spec.js +150 -0
  131. package/build/esm/src/utils/trade/__tests__/gmsolTradeMath.spec.js +43 -0
  132. package/build/esm/src/utils/trade/decrease.js +115 -35
  133. package/build/esm/src/utils/trade/decreaseMarginCheck.js +37 -2
  134. package/build/esm/src/utils/trade/decreaseOutputs.js +19 -5
  135. package/build/esm/src/utils/trade/increase.js +32 -13
  136. package/build/esm/src/utils/trade/increaseMarginCheck.js +18 -39
  137. package/build/tsconfig.tsbuildinfo +1 -1
  138. package/build/types/src/abis/RatioVesterReader.d.ts +74 -0
  139. package/build/types/src/abis/index.d.ts +73 -0
  140. package/build/types/src/clients/v1/modules/oracle.d.ts +6 -1
  141. package/build/types/src/clients/v1/modules/oracle.spec.d.ts +1 -0
  142. package/build/types/src/clients/v2/__tests__/testUtil.d.ts +1 -0
  143. package/build/types/src/clients/v2/index.d.ts +26 -5
  144. package/build/types/src/codegen/prebuilt/index.d.ts +1045 -125
  145. package/build/types/src/configs/contracts.d.ts +10 -0
  146. package/build/types/src/configs/dataStore.d.ts +8 -0
  147. package/build/types/src/configs/express.d.ts +0 -1
  148. package/build/types/src/utils/__tests__/gmsolUnits.spec.d.ts +1 -0
  149. package/build/types/src/utils/errors/parseError.d.ts +1 -1
  150. package/build/types/src/utils/errors/transactionsErrors.d.ts +6 -0
  151. package/build/types/src/utils/fees/priceImpact.d.ts +10 -0
  152. package/build/types/src/utils/gmsol/__tests__/nativeMath.spec.d.ts +1 -0
  153. package/build/types/src/utils/gmsol/constants.d.ts +4 -0
  154. package/build/types/src/utils/gmsol/fees.d.ts +6 -0
  155. package/build/types/src/utils/gmsol/index.d.ts +7 -3
  156. package/build/types/src/utils/gmsol/markets.d.ts +49 -0
  157. package/build/types/src/utils/gmsol/numbers.d.ts +10 -0
  158. package/build/types/src/utils/gmsol/positions.d.ts +7 -0
  159. package/build/types/src/utils/gmsol/types.d.ts +96 -0
  160. package/build/types/src/utils/gmsol/units.d.ts +53 -0
  161. package/build/types/src/utils/http/types.d.ts +1 -0
  162. package/build/types/src/utils/http/validation.d.ts +1 -0
  163. package/build/types/src/utils/markets/types.d.ts +5 -2
  164. package/build/types/src/utils/multichain/api.d.ts +4 -1
  165. package/build/types/src/utils/orderTransactions/utils.d.ts +19 -4
  166. package/build/types/src/utils/orders/api.d.ts +2 -1
  167. package/build/types/src/utils/orders/types.d.ts +24 -0
  168. package/build/types/src/utils/positions/__tests__/liquidationImpact.spec.d.ts +1 -0
  169. package/build/types/src/utils/positions/__tests__/trackingCollateral.spec.d.ts +1 -0
  170. package/build/types/src/utils/positions/types.d.ts +2 -0
  171. package/build/types/src/utils/positions/utils.d.ts +30 -0
  172. package/build/types/src/utils/prices/api.d.ts +2 -0
  173. package/build/types/src/utils/referrals/types.d.ts +4 -0
  174. package/build/types/src/utils/subaccount/generateSubaccount.d.ts +9 -4
  175. package/build/types/src/utils/subaccount/sdkClient.d.ts +7 -1
  176. package/build/types/src/utils/subaccount/types.d.ts +2 -0
  177. package/build/types/src/utils/tokens/types.d.ts +1 -0
  178. package/build/types/src/utils/tokens/utils.d.ts +6 -0
  179. package/build/types/src/utils/trade/__tests__/decrease.spec.d.ts +1 -0
  180. package/build/types/src/utils/trade/decrease.d.ts +3 -0
  181. package/build/types/src/utils/trade/decreaseMarginCheck.d.ts +11 -0
  182. package/build/types/src/utils/trade/decreaseOutputs.d.ts +7 -2
  183. package/build/types/src/utils/trade/increaseMarginCheck.d.ts +1 -0
  184. package/package.json +10 -1
@@ -1,10 +1,14 @@
1
1
  import { parseUnits } from "viem";
2
2
  import { describe, expect, it } from "vitest";
3
- import { mockMarginCheckMarketInfo, mockTokensData } from "../../../test/mock";
4
- import { PRECISION } from "../../numbers";
3
+ import { mockMarginCheckMarketInfo, mockMarketsInfoData, mockTokensData } from "../../../test/mock";
4
+ import { bigMath } from "../../bigmath";
5
+ import { applyFactor, expandDecimals, PRECISION } from "../../numbers";
5
6
  import { getLiquidationPrice } from "..";
7
+ import { convertToUsd, getTokenData } from "../../tokens";
8
+ const usd = (value) => parseUnits(value, 30);
9
+ const eth = (value) => parseUnits(value, 18);
6
10
  describe("gmsol liquidation price", () => {
7
- it("solves index collateral funding at the liquidation price without changing EVM math FESOL-57", () => {
11
+ it("solves index collateral funding at the liquidation price FESOL-57", () => {
8
12
  // Rust 8af1e70c: $1,000 size / 10 tokens, $5 floor, $2 borrowing and $0.60 close fee.
9
13
  for (const [isLong, collateral, funding, expected] of [
10
14
  [true, 10n, 1n, parseUnits("53.03157894736842", 30)],
@@ -54,9 +58,162 @@ describe("gmsol liquidation price", () => {
54
58
  }
55
59
  }
56
60
  if (isLong && collateral === 10n && funding === 1n) {
57
- expect(getLiquidationPrice({ ...params, marketInfo: { ...marketInfo, tradeMath: undefined } })).toBe(parseUnits(price === 100n ? "55.38" : "56.38", 30));
61
+ expect(getLiquidationPrice({ ...params, marketInfo: { ...marketInfo, tradeMath: undefined } })).toBe(usd("1007.6") / 19n);
58
62
  }
59
63
  }
60
64
  }
61
65
  });
62
66
  });
67
+ describe("EVM liquidation price", () => {
68
+ it("values the funding owed in index-equivalent collateral at the liquidation price", () => {
69
+ const btcPrices = { minPrice: usd("100000"), maxPrice: usd("100000") };
70
+ const tokensData = mockTokensData({
71
+ ETH: { prices: { minPrice: usd("2238.122929246671"), maxPrice: usd("2238.122929246671") } },
72
+ BTC: { isSynthetic: true, prices: btcPrices },
73
+ WBTC: { address: "WBTC", name: "Wrapped Bitcoin", symbol: "BTC", decimals: 18, prices: btcPrices },
74
+ });
75
+ const liquidationFactor = usd("0.005");
76
+ const minCollateralUsd = usd("1");
77
+ const weth = { market: "ETH-ETH-USDC", collateral: "ETH", feeFactor: usd("0.0007"), impactFactor: usd("0.01") };
78
+ const cases = [
79
+ {
80
+ // Reader.isPositionLiquidatable flips at onChainPrice for this position at Arbitrum block 521637011
81
+ name: "recorded WETH short",
82
+ ...weth,
83
+ isLong: false,
84
+ sizeInUsd: usd("2740036.31980427626177387123979331729"),
85
+ sizeInTokens: 799909837986426323532n,
86
+ collateralAmount: 587819787400706175153n,
87
+ fundingFeeAmount: 44129191041547970203n,
88
+ borrowingUsd: usd("101994.985119321664697627456589705987"),
89
+ feeFactor: usd("0.0006"),
90
+ impactFactor: 0n,
91
+ onChainPrice: usd("10236.1443"),
92
+ },
93
+ {
94
+ name: "WETH long",
95
+ ...weth,
96
+ isLong: true,
97
+ sizeInUsd: usd("12000"),
98
+ sizeInTokens: eth("5"),
99
+ collateralAmount: eth("1"),
100
+ fundingFeeAmount: eth("0.05"),
101
+ borrowingUsd: usd("30"),
102
+ },
103
+ {
104
+ name: "WETH short",
105
+ ...weth,
106
+ isLong: false,
107
+ sizeInUsd: usd("10000"),
108
+ sizeInTokens: eth("4"),
109
+ collateralAmount: eth("1.5"),
110
+ fundingFeeAmount: eth("0.1"),
111
+ borrowingUsd: usd("20"),
112
+ },
113
+ {
114
+ name: "short profit covers funding exceeding collateral",
115
+ ...weth,
116
+ isLong: false,
117
+ sizeInUsd: usd("10000"),
118
+ sizeInTokens: eth("2"),
119
+ collateralAmount: eth("1"),
120
+ fundingFeeAmount: eth("3"),
121
+ borrowingUsd: usd("20"),
122
+ },
123
+ {
124
+ name: "no funding or fees",
125
+ ...weth,
126
+ isLong: true,
127
+ sizeInUsd: usd("12000"),
128
+ sizeInTokens: eth("5"),
129
+ collateralAmount: eth("1"),
130
+ fundingFeeAmount: 0n,
131
+ borrowingUsd: 0n,
132
+ feeFactor: 0n,
133
+ impactFactor: 0n,
134
+ },
135
+ {
136
+ name: "18-decimal collateral for an 8-decimal index",
137
+ market: "BTC-WBTC-USDC",
138
+ collateral: "WBTC",
139
+ isLong: true,
140
+ sizeInUsd: usd("50000"),
141
+ sizeInTokens: 50000000n,
142
+ collateralAmount: eth("0.1"),
143
+ fundingFeeAmount: eth("0.002"),
144
+ borrowingUsd: usd("25"),
145
+ feeFactor: usd("0.0007"),
146
+ impactFactor: usd("0.01"),
147
+ },
148
+ {
149
+ name: "short size equal to the collateral net of funding",
150
+ ...weth,
151
+ isLong: false,
152
+ sizeInUsd: usd("4800"),
153
+ sizeInTokens: eth("2"),
154
+ collateralAmount: eth("2.1"),
155
+ fundingFeeAmount: eth("0.1"),
156
+ borrowingUsd: 0n,
157
+ hasPrice: false,
158
+ },
159
+ ];
160
+ for (const c of cases) {
161
+ const marketInfo = mockMarketsInfoData(tokensData, [c.market], {
162
+ [c.market]: {
163
+ minCollateralFactorForLiquidation: liquidationFactor,
164
+ positionFeeFactorForBalanceWasNotImproved: c.feeFactor,
165
+ maxPositionImpactFactorForLiquidations: c.impactFactor,
166
+ },
167
+ })[c.market];
168
+ const collateralToken = getTokenData(tokensData, c.collateral);
169
+ const toCollateralUsd = (amount) => convertToUsd(amount, collateralToken.decimals, collateralToken.prices.minPrice);
170
+ const getRemainingCollateralUsd = (price) => {
171
+ const toUsd = (amount, decimals) => (amount * price) / expandDecimals(1, decimals);
172
+ const positionValueUsd = toUsd(c.sizeInTokens, marketInfo.indexToken.decimals);
173
+ return (toUsd(c.collateralAmount - c.fundingFeeAmount, collateralToken.decimals) +
174
+ (c.isLong ? positionValueUsd - c.sizeInUsd : c.sizeInUsd - positionValueUsd) -
175
+ applyFactor(c.sizeInUsd, c.impactFactor) -
176
+ c.borrowingUsd -
177
+ applyFactor(c.sizeInUsd, c.feeFactor));
178
+ };
179
+ const thresholdUsd = bigMath.max(applyFactor(c.sizeInUsd, liquidationFactor), minCollateralUsd);
180
+ const [safeSide, liquidatableSide] = c.isLong ? [1000001n, 999999n] : [999999n, 1000001n];
181
+ // getPositionInfo passes the exact funding amount, other callers only its USD value
182
+ for (const fundingFeeAmount of [c.fundingFeeAmount, undefined]) {
183
+ const params = {
184
+ marketInfo,
185
+ collateralToken,
186
+ sizeInUsd: c.sizeInUsd,
187
+ sizeInTokens: c.sizeInTokens,
188
+ collateralAmount: c.collateralAmount,
189
+ collateralUsd: toCollateralUsd(c.collateralAmount),
190
+ pendingFundingFeesUsd: toCollateralUsd(c.fundingFeeAmount),
191
+ fundingFeeAmount,
192
+ pendingBorrowingFeesUsd: c.borrowingUsd,
193
+ pendingImpactAmount: 0n,
194
+ minCollateralUsd,
195
+ isLong: c.isLong,
196
+ useMaxPriceImpact: true,
197
+ userReferralInfo: undefined,
198
+ };
199
+ const liquidationPrice = getLiquidationPrice(params);
200
+ expect(getLiquidationPrice({
201
+ ...params,
202
+ collateralToken: { ...collateralToken, prices: { minPrice: 0n, maxPrice: 0n } },
203
+ }), c.name).toBe(fundingFeeAmount === undefined && params.pendingFundingFeesUsd !== 0n ? undefined : liquidationPrice);
204
+ if (c.hasPrice === false) {
205
+ expect(liquidationPrice, c.name).toBeUndefined();
206
+ continue;
207
+ }
208
+ expect(liquidationPrice, c.name).toBeDefined();
209
+ if (c.onChainPrice !== undefined) {
210
+ expect(bigMath.abs(liquidationPrice - c.onChainPrice) * 1000000n < c.onChainPrice, c.name).toBe(true);
211
+ }
212
+ const safeUsd = getRemainingCollateralUsd((liquidationPrice * safeSide) / 1000000n);
213
+ const liquidatableUsd = getRemainingCollateralUsd((liquidationPrice * liquidatableSide) / 1000000n);
214
+ expect(safeUsd > thresholdUsd, c.name).toBe(true);
215
+ expect(liquidatableUsd < thresholdUsd, c.name).toBe(true);
216
+ }
217
+ }
218
+ });
219
+ });
@@ -0,0 +1,393 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { ARBITRUM } from "../../../configs/chains";
3
+ import { BASIS_POINTS_DIVISOR_BIGINT, USD_DECIMALS } from "../../../configs/factors";
4
+ import { getNativeToken, getTokenBySymbol, getWrappedToken } from "../../../configs/tokens";
5
+ import { bigMath } from "../../bigmath";
6
+ import { mockMarketsInfoData } from "../../markets/__tests__/mockMarkets";
7
+ import { applyFactor, expandDecimals } from "../../numbers";
8
+ import { OrderType, SwapPricingType } from "../../orders/types";
9
+ import { getCollateralAmountInIndexTokens, getCollateralPriceAtIndexPrice, getLiquidationPrice, getLiquidationPriceImpactDeltaUsd, getPositionInfo, } from "..";
10
+ import { getSwapPathStats } from "../../swap";
11
+ import { convertToTokenAmount, convertToUsd } from "../../tokens";
12
+ import { getDecreasePositionAmounts } from "../../trade/decrease";
13
+ import { getIncreasePositionAmounts } from "../../trade/increase";
14
+ import { getMarketInfoAtIndexPrice } from "../../trade/increaseMarginCheck";
15
+ const usd = (value) => expandDecimals(Math.round(value * 1e6), USD_DECIMALS - 6);
16
+ const amount = (value, decimals) => (BigInt(Math.round(value * 1e8)) * expandDecimals(1, decimals)) / 100000000n;
17
+ const isWithinBps = (value, expected, bps) => bigMath.abs(value - expected) * 10000n <= bigMath.abs(expected) * bps;
18
+ const withPrices = (token, minPrice, maxPrice) => ({
19
+ ...token,
20
+ prices: { minPrice: usd(minPrice), maxPrice: usd(maxPrice) },
21
+ });
22
+ const atPrice = (token, price) => ({
23
+ ...token,
24
+ prices: { minPrice: price, maxPrice: price },
25
+ });
26
+ const BTC = withPrices(getTokenBySymbol(ARBITRUM, "BTC", { isSynthetic: true }), 99990, 100010);
27
+ const TBTC = withPrices(getTokenBySymbol(ARBITRUM, "TBTC"), 99900, 99950);
28
+ const ETH = withPrices(getNativeToken(ARBITRUM), 2400, 2400.5);
29
+ const WETH = withPrices(getWrappedToken(ARBITRUM), 2400, 2400.5);
30
+ const WSTETH = withPrices(getTokenBySymbol(ARBITRUM, "WSTETH"), 2900, 2901);
31
+ const USDC = withPrices(getTokenBySymbol(ARBITRUM, "USDC"), 1, 1);
32
+ const USDE = withPrices(getTokenBySymbol(ARBITRUM, "USDE"), 1, 1);
33
+ const MIN_COLLATERAL_FACTOR_FOR_LIQUIDATION = expandDecimals(5, 27);
34
+ const POSITION_FEE_FACTOR = expandDecimals(7, 26);
35
+ const MIN_COLLATERAL_USD = usd(1);
36
+ function getMarketInfo(indexToken, longToken, shortToken) {
37
+ const tokensData = Object.fromEntries([indexToken, longToken, shortToken].map((token) => [token.address, token]));
38
+ const key = `${indexToken.address}-${longToken.address}-${shortToken.address}`;
39
+ return mockMarketsInfoData(tokensData, [key], {
40
+ [key]: {
41
+ minCollateralFactorForLiquidation: MIN_COLLATERAL_FACTOR_FOR_LIQUIDATION,
42
+ positionFeeFactorForBalanceWasImproved: POSITION_FEE_FACTOR,
43
+ positionFeeFactorForBalanceWasNotImproved: POSITION_FEE_FACTOR,
44
+ maxPositionImpactFactorForLiquidations: expandDecimals(1, 28),
45
+ },
46
+ })[key];
47
+ }
48
+ describe("tBTC and wstETH collateral", () => {
49
+ it("returns the index price where the contract's remaining collateral reaches the liquidation threshold TRD-41", () => {
50
+ const cases = [
51
+ {
52
+ name: "tBTC long",
53
+ market: [BTC, TBTC, TBTC],
54
+ collateral: TBTC,
55
+ moves: "ratio",
56
+ isLong: true,
57
+ sizeUsd: 50000,
58
+ collateralAmount: 0.25,
59
+ fundingUsd: 2500,
60
+ borrowingUsd: 300,
61
+ },
62
+ {
63
+ name: "tBTC short",
64
+ market: [BTC, TBTC, TBTC],
65
+ collateral: TBTC,
66
+ moves: "ratio",
67
+ isLong: false,
68
+ sizeUsd: 30000,
69
+ collateralAmount: 0.1,
70
+ fundingUsd: 1000,
71
+ borrowingUsd: 100,
72
+ },
73
+ {
74
+ name: "wstETH long",
75
+ market: [ETH, WSTETH, USDE],
76
+ collateral: WSTETH,
77
+ moves: "ratio",
78
+ isLong: true,
79
+ sizeUsd: 5000,
80
+ collateralAmount: 500 / 2900,
81
+ fundingUsd: 50,
82
+ borrowingUsd: 5,
83
+ },
84
+ {
85
+ name: "wstETH short",
86
+ market: [ETH, WSTETH, USDE],
87
+ collateral: WSTETH,
88
+ moves: "ratio",
89
+ isLong: false,
90
+ sizeUsd: 10000,
91
+ collateralAmount: 2000 / 2900,
92
+ fundingUsd: 200,
93
+ borrowingUsd: 20,
94
+ },
95
+ {
96
+ name: "WETH long",
97
+ market: [ETH, WETH, USDC],
98
+ collateral: WETH,
99
+ moves: "index",
100
+ isLong: true,
101
+ sizeUsd: 12000,
102
+ collateralAmount: 1,
103
+ fundingUsd: 0,
104
+ borrowingUsd: 30,
105
+ },
106
+ {
107
+ name: "USDC long",
108
+ market: [ETH, WETH, USDC],
109
+ collateral: USDC,
110
+ moves: "none",
111
+ isLong: true,
112
+ sizeUsd: 10000,
113
+ collateralAmount: 2000,
114
+ fundingUsd: 100,
115
+ borrowingUsd: 20,
116
+ },
117
+ ];
118
+ for (const c of cases) {
119
+ const [indexToken, longToken, shortToken] = c.market;
120
+ const marketInfo = getMarketInfo(indexToken, longToken, shortToken);
121
+ const indexPrecision = expandDecimals(1, indexToken.decimals);
122
+ const collateralPrecision = expandDecimals(1, c.collateral.decimals);
123
+ const currentIndexPrice = c.isLong ? indexToken.prices.minPrice : indexToken.prices.maxPrice;
124
+ const sizeInUsd = usd(c.sizeUsd);
125
+ const sizeInTokens = (sizeInUsd * indexPrecision) / currentIndexPrice;
126
+ const collateralAmount = amount(c.collateralAmount, c.collateral.decimals);
127
+ const collateralUsd = (collateralAmount * c.collateral.prices.minPrice) / collateralPrecision;
128
+ const pendingFundingFeesUsd = usd(c.fundingUsd);
129
+ const pendingBorrowingFeesUsd = usd(c.borrowingUsd);
130
+ const liquidationPrice = getLiquidationPrice({
131
+ sizeInUsd,
132
+ sizeInTokens,
133
+ collateralAmount,
134
+ collateralUsd,
135
+ collateralToken: c.collateral,
136
+ marketInfo,
137
+ pendingFundingFeesUsd,
138
+ pendingBorrowingFeesUsd,
139
+ pendingImpactAmount: 0n,
140
+ minCollateralUsd: MIN_COLLATERAL_USD,
141
+ isLong: c.isLong,
142
+ useMaxPriceImpact: true,
143
+ userReferralInfo: undefined,
144
+ });
145
+ expect(liquidationPrice, c.name).toBeDefined();
146
+ const priceImpactUsd = getLiquidationPriceImpactDeltaUsd({
147
+ marketInfo,
148
+ sizeInUsd,
149
+ sizeInTokens,
150
+ pendingImpactAmount: 0n,
151
+ isLong: c.isLong,
152
+ useMaxPriceImpact: true,
153
+ });
154
+ // funding fees are held in collateral tokens, borrowing and closing fees are USD amounts
155
+ const getRemainingCollateralUsd = (indexPrice) => {
156
+ const collateralPrice = {
157
+ none: c.collateral.prices.minPrice,
158
+ index: indexPrice,
159
+ ratio: (c.collateral.prices.minPrice * indexPrice) / currentIndexPrice,
160
+ }[c.moves];
161
+ const fundingUsd = (pendingFundingFeesUsd * collateralPrice) / c.collateral.prices.minPrice;
162
+ const positionValueUsd = (sizeInTokens * indexPrice) / indexPrecision;
163
+ const pnlUsd = c.isLong ? positionValueUsd - sizeInUsd : sizeInUsd - positionValueUsd;
164
+ return ((collateralAmount * collateralPrice) / collateralPrecision -
165
+ fundingUsd -
166
+ pendingBorrowingFeesUsd -
167
+ applyFactor(sizeInUsd, POSITION_FEE_FACTOR) +
168
+ priceImpactUsd +
169
+ pnlUsd);
170
+ };
171
+ const threshold = applyFactor(sizeInUsd, MIN_COLLATERAL_FACTOR_FOR_LIQUIDATION);
172
+ const safeSide = c.isLong ? 10001n : 9999n;
173
+ const liquidatableSide = c.isLong ? 9999n : 10001n;
174
+ expect(getRemainingCollateralUsd((liquidationPrice * safeSide) / 10000n) > threshold, c.name).toBe(true);
175
+ expect(getRemainingCollateralUsd((liquidationPrice * liquidatableSide) / 10000n) < threshold, c.name).toBe(true);
176
+ }
177
+ });
178
+ it("values tBTC and wstETH collateral at the trigger price for TP/SL TRD-41", () => {
179
+ const cases = [
180
+ { name: "tBTC long", market: [BTC, TBTC, TBTC], collateral: TBTC, moves: "ratio", isLong: true },
181
+ { name: "tBTC short", market: [BTC, TBTC, TBTC], collateral: TBTC, moves: "ratio", isLong: false },
182
+ { name: "wstETH long", market: [ETH, WSTETH, USDE], collateral: WSTETH, moves: "ratio", isLong: true },
183
+ { name: "WETH long", market: [ETH, WETH, USDC], collateral: WETH, moves: "index", isLong: true },
184
+ { name: "USDC short", market: [ETH, WETH, USDC], collateral: USDC, moves: "none", isLong: false },
185
+ ];
186
+ for (const c of cases) {
187
+ const [indexToken] = c.market;
188
+ const marketInfo = getMarketInfo(...c.market);
189
+ const currentIndexPrice = c.isLong ? indexToken.prices.minPrice : indexToken.prices.maxPrice;
190
+ const triggerPrice = (currentIndexPrice * 8n) / 10n;
191
+ const collateralAmount = convertToTokenAmount(usd(3000), c.collateral.decimals, c.collateral.prices.minPrice);
192
+ const sizeInUsd = usd(9000);
193
+ const expectedCollateralPrice = {
194
+ none: c.collateral.prices.minPrice,
195
+ index: triggerPrice,
196
+ ratio: (c.collateral.prices.minPrice * triggerPrice) / currentIndexPrice,
197
+ }[c.moves];
198
+ const position = getPositionInfo({
199
+ position: {
200
+ key: c.name,
201
+ contractKey: c.name,
202
+ account: "",
203
+ marketAddress: marketInfo.marketTokenAddress,
204
+ collateralTokenAddress: c.collateral.address,
205
+ sizeInUsd,
206
+ sizeInTokens: convertToTokenAmount(sizeInUsd, indexToken.decimals, currentIndexPrice),
207
+ collateralAmount,
208
+ pendingBorrowingFeesUsd: 0n,
209
+ increasedAtTime: 0n,
210
+ decreasedAtTime: 0n,
211
+ isLong: c.isLong,
212
+ fundingFeeAmount: 0n,
213
+ claimableLongTokenAmount: 0n,
214
+ claimableShortTokenAmount: 0n,
215
+ pnl: 0n,
216
+ positionFeeAmount: 0n,
217
+ traderDiscountAmount: 0n,
218
+ uiFeeAmount: 0n,
219
+ pendingImpactAmount: 0n,
220
+ positionValueInUsd: 0n,
221
+ data: "",
222
+ },
223
+ marketInfo,
224
+ minCollateralUsd: MIN_COLLATERAL_USD,
225
+ });
226
+ const decreaseAmounts = getDecreasePositionAmounts({
227
+ marketInfo,
228
+ collateralToken: c.collateral,
229
+ isLong: c.isLong,
230
+ position,
231
+ closeSizeUsd: sizeInUsd / 2n,
232
+ keepLeverage: true,
233
+ triggerPrice,
234
+ triggerOrderType: c.isLong ? OrderType.StopLossDecrease : OrderType.LimitDecrease,
235
+ userReferralInfo: undefined,
236
+ minCollateralUsd: MIN_COLLATERAL_USD,
237
+ minPositionSizeUsd: 0n,
238
+ uiFeeFactor: 0n,
239
+ isSetAcceptablePriceImpactEnabled: false,
240
+ });
241
+ expect(decreaseAmounts.collateralPrice, c.name).toBe(expectedCollateralPrice);
242
+ // Loss % and Gain % value the collateral as index tokens at the trigger price
243
+ const collateralInIndexTokens = getCollateralAmountInIndexTokens({
244
+ collateralToken: c.collateral,
245
+ indexToken,
246
+ collateralAmount,
247
+ isLong: c.isLong,
248
+ });
249
+ if (c.moves === "none") {
250
+ expect(collateralInIndexTokens, c.name).toBeUndefined();
251
+ continue;
252
+ }
253
+ const valueInIndexTokens = convertToUsd(collateralInIndexTokens, indexToken.decimals, triggerPrice);
254
+ const collateralValueAtTrigger = convertToUsd(collateralAmount, c.collateral.decimals, expectedCollateralPrice);
255
+ expect(isWithinBps(valueInIndexTokens, collateralValueAtTrigger, 1n), c.name).toBe(true);
256
+ }
257
+ expect(getCollateralPriceAtIndexPrice({
258
+ collateralToken: TBTC,
259
+ indexToken: withPrices(BTC, 0, 0),
260
+ indexPrice: usd(80000),
261
+ isLong: true,
262
+ })).toBe(TBTC.prices.minPrice);
263
+ expect(getCollateralPriceAtIndexPrice({ collateralToken: TBTC, indexToken: ETH, indexPrice: usd(2000), isLong: true })).toBe(TBTC.prices.minPrice);
264
+ });
265
+ it("values tBTC and wstETH collateral at the trigger price in limit increase orders TRD-41", () => {
266
+ const leverage = 5n * BASIS_POINTS_DIVISOR_BIGINT;
267
+ const depositUsd = usd(100);
268
+ const cases = [
269
+ {
270
+ name: "wstETH short paid in USDe",
271
+ market: [ETH, WSTETH, USDE],
272
+ payToken: USDE,
273
+ collateral: WSTETH,
274
+ isLong: false,
275
+ triggerBps: 11000n,
276
+ },
277
+ {
278
+ name: "wstETH long paid in USDe",
279
+ market: [ETH, WSTETH, USDE],
280
+ payToken: USDE,
281
+ collateral: WSTETH,
282
+ isLong: true,
283
+ triggerBps: 9000n,
284
+ },
285
+ {
286
+ name: "wstETH short paid in wstETH",
287
+ market: [ETH, WSTETH, USDE],
288
+ payToken: WSTETH,
289
+ collateral: WSTETH,
290
+ isLong: false,
291
+ triggerBps: 11000n,
292
+ },
293
+ {
294
+ name: "tBTC long paid in tBTC",
295
+ market: [BTC, TBTC, TBTC],
296
+ payToken: TBTC,
297
+ collateral: TBTC,
298
+ isLong: true,
299
+ triggerBps: 9000n,
300
+ },
301
+ ];
302
+ for (const c of cases) {
303
+ const [indexToken] = c.market;
304
+ const marketInfo = getMarketInfo(...c.market);
305
+ const marketsInfoData = { [marketInfo.marketTokenAddress]: marketInfo };
306
+ const currentIndexPrice = c.isLong ? indexToken.prices.minPrice : indexToken.prices.maxPrice;
307
+ const triggerPrice = (currentIndexPrice * c.triggerBps) / 10000n;
308
+ const collateralPriceAtTrigger = (c.collateral.prices.minPrice * triggerPrice) / currentIndexPrice;
309
+ const collateralMaxPriceAtTrigger = (c.collateral.prices.maxPrice * triggerPrice) / currentIndexPrice;
310
+ const payAmount = convertToTokenAmount(depositUsd, c.payToken.decimals, c.payToken.prices.minPrice);
311
+ const isSwap = c.payToken.address !== c.collateral.address;
312
+ const getSwapStats = (markets, usdIn) => getSwapPathStats({
313
+ marketsInfoData: markets,
314
+ swapPath: [marketInfo.marketTokenAddress],
315
+ initialCollateralAddress: c.payToken.address,
316
+ wrappedNativeTokenAddress: WETH.address,
317
+ usdIn,
318
+ shouldUnwrapNativeToken: false,
319
+ shouldApplyPriceImpact: true,
320
+ swapPricingType: SwapPricingType.Swap,
321
+ });
322
+ const increaseAmounts = getIncreasePositionAmounts({
323
+ marketInfo,
324
+ indexToken,
325
+ initialCollateralToken: c.payToken,
326
+ collateralToken: c.collateral,
327
+ isLong: c.isLong,
328
+ initialCollateralAmount: payAmount,
329
+ indexTokenAmount: undefined,
330
+ position: undefined,
331
+ externalSwapQuote: undefined,
332
+ userReferralInfo: undefined,
333
+ strategy: "leverageByCollateral",
334
+ leverage,
335
+ triggerPrice,
336
+ limitOrderType: OrderType.LimitIncrease,
337
+ findSwapPath: ((usdIn) => (isSwap ? getSwapStats(marketsInfoData, usdIn) : undefined)),
338
+ uiFeeFactor: 0n,
339
+ marketsInfoData,
340
+ chainId: ARBITRUM,
341
+ externalSwapQuoteParams: undefined,
342
+ isSetAcceptablePriceImpactEnabled: false,
343
+ });
344
+ // the keeper executes at the trigger: the collateral and its oracle spread are repriced with the index,
345
+ // and the swap pays out at the collateral's max price
346
+ const atTrigger = (token) => token.address === c.collateral.address
347
+ ? { ...token, prices: { minPrice: collateralPriceAtTrigger, maxPrice: collateralMaxPriceAtTrigger } }
348
+ : token;
349
+ const marketAtTrigger = {
350
+ ...marketInfo,
351
+ indexToken: atPrice(indexToken, triggerPrice),
352
+ longToken: atTrigger(marketInfo.longToken),
353
+ shortToken: atTrigger(marketInfo.shortToken),
354
+ };
355
+ const collateralAmountAtExecution = isSwap
356
+ ? getSwapStats({ [marketInfo.marketTokenAddress]: marketAtTrigger }, depositUsd).amountOut
357
+ : payAmount;
358
+ const collateralUsdAtExecution = convertToUsd(collateralAmountAtExecution, c.collateral.decimals, collateralPriceAtTrigger) -
359
+ increaseAmounts.positionFeeUsd;
360
+ expect(isWithinBps(increaseAmounts.collateralDeltaAmount, convertToTokenAmount(collateralUsdAtExecution, c.collateral.decimals, collateralPriceAtTrigger), 1n), c.name).toBe(true);
361
+ expect(isWithinBps(increaseAmounts.sizeDeltaUsd, bigMath.mulDiv(collateralUsdAtExecution, leverage, BASIS_POINTS_DIVISOR_BIGINT), 1n), c.name).toBe(true);
362
+ const { collateralToken: collateralAtEvaluation } = getMarketInfoAtIndexPrice({
363
+ marketInfo,
364
+ collateralToken: c.collateral,
365
+ indexPrice: triggerPrice,
366
+ isLong: c.isLong,
367
+ });
368
+ expect(collateralAtEvaluation.prices, c.name).toEqual({
369
+ minPrice: collateralPriceAtTrigger,
370
+ maxPrice: collateralMaxPriceAtTrigger,
371
+ });
372
+ }
373
+ // a stablecoin collateral keeps its prices at the trigger, and so does the wstETH the position does not hold
374
+ const usdeWithSpread = withPrices(USDE, 0.999, 1.001);
375
+ const atTrigger = getMarketInfoAtIndexPrice({
376
+ marketInfo: getMarketInfo(ETH, WSTETH, usdeWithSpread),
377
+ collateralToken: usdeWithSpread,
378
+ indexPrice: usd(2640),
379
+ isLong: false,
380
+ });
381
+ expect(atTrigger.collateralToken.prices).toEqual(usdeWithSpread.prices);
382
+ expect(atTrigger.marketInfo.longToken.prices).toEqual(WSTETH.prices);
383
+ expect(atTrigger.marketInfo.indexToken.prices).toEqual({ minPrice: usd(2640), maxPrice: usd(2640) });
384
+ // the index price is not loaded yet: wstETH keeps its prices
385
+ const withoutIndexPrice = getMarketInfoAtIndexPrice({
386
+ marketInfo: { ...getMarketInfo(ETH, WSTETH, USDE), indexToken: withPrices(ETH, 0, 0) },
387
+ collateralToken: WSTETH,
388
+ indexPrice: usd(2640),
389
+ isLong: true,
390
+ });
391
+ expect(withoutIndexPrice.collateralToken.prices).toEqual(WSTETH.prices);
392
+ });
393
+ });
@@ -1,6 +1,7 @@
1
1
  import { getSolanaResponseHandler } from "../http/solana";
2
2
  import { assertApiFields, assertApiRecords } from "../http/validation";
3
3
  import { deserializeBigIntsInObject } from "../numbers";
4
+ import { parseApiOrders } from "../orders/api";
4
5
  export async function fetchApiPositionsInfo(ctx, params) {
5
6
  const positions = await ctx.api.fetchJson("/v1/positions", {
6
7
  query: {
@@ -14,6 +15,9 @@ export async function fetchApiPositionsInfo(ctx, params) {
14
15
  return positions.map((position, index) => {
15
16
  const parsed = deserializeBigIntsInObject(position, { handleInts: true });
16
17
  assertApiFields(parsed, [{ name: "positionValueInUsd", type: "bigint" }], "/v1/positions", index);
18
+ if (position.relatedOrders !== undefined) {
19
+ parsed.relatedOrders = parseApiOrders(position.relatedOrders, "/v1/positions");
20
+ }
17
21
  return parsed;
18
22
  });
19
23
  }