@gmx-io/sdk 1.8.0 → 1.9.1

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 (127) hide show
  1. package/README.md +1 -1
  2. package/build/cjs/scripts/subsquid-codegen.js +1 -1
  3. package/build/cjs/src/abis/ArbSys.js +11 -0
  4. package/build/cjs/src/abis/index.js +2 -0
  5. package/build/cjs/src/clients/v1/testUtil.js +1 -1
  6. package/build/cjs/src/clients/v2/index.js +8 -1
  7. package/build/cjs/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +16 -88
  8. package/build/cjs/src/codegen/prebuilt/hashedMarketConfigKeys.json +136 -748
  9. package/build/cjs/src/codegen/prebuilt/hashedMarketValuesKeys.json +30 -165
  10. package/build/cjs/src/configs/__tests__/markets.spec.js +1 -16
  11. package/build/cjs/src/configs/api.js +10 -1
  12. package/build/cjs/src/configs/contracts.js +2 -0
  13. package/build/cjs/src/configs/dataStore.js +13 -3
  14. package/build/cjs/src/configs/express.js +1 -0
  15. package/build/cjs/src/configs/markets.js +14 -77
  16. package/build/cjs/src/configs/tokens.js +22 -90
  17. package/build/cjs/src/test/fixtures/arbitrumMarkets.json +0 -72
  18. package/build/cjs/src/test/mock.js +12 -1
  19. package/build/cjs/src/utils/__tests__/fees.spec.js +36 -0
  20. package/build/cjs/src/utils/__tests__/markets.spec.js +233 -0
  21. package/build/cjs/src/utils/__tests__/positionPnlCap.spec.js +30 -3
  22. package/build/cjs/src/utils/__tests__/positions.spec.js +5 -5
  23. package/build/cjs/src/utils/__tests__/prices.spec.js +97 -0
  24. package/build/cjs/src/utils/express/utils/gelatoRelayUtils.js +2 -0
  25. package/build/cjs/src/utils/express/utils/gmxRelayUtils.js +145 -0
  26. package/build/cjs/src/utils/express/utils/gmxRelayUtils.spec.js +163 -0
  27. package/build/cjs/src/utils/express/utils/index.js +1 -0
  28. package/build/cjs/src/utils/fees/index.js +8 -5
  29. package/build/cjs/src/utils/fees/priceImpact.js +4 -9
  30. package/build/cjs/src/utils/markets/utils.js +57 -1
  31. package/build/cjs/src/utils/numbers/index.js +1 -0
  32. package/build/cjs/src/utils/numbers/prbMath.js +154 -0
  33. package/build/cjs/src/utils/positions/utils.js +66 -43
  34. package/build/cjs/src/utils/prices/utils.js +28 -1
  35. package/build/cjs/src/utils/stats/__tests__/api.spec.js +100 -0
  36. package/build/cjs/src/utils/stats/api.js +32 -0
  37. package/build/cjs/src/utils/stats/types.js +4 -0
  38. package/build/cjs/src/utils/trade/__tests__/increase.spec.js +580 -0
  39. package/build/cjs/src/utils/trade/__tests__/increaseInvariants.spec.js +258 -0
  40. package/build/cjs/src/utils/trade/__tests__/increaseMarginCheck.spec.js +837 -0
  41. package/build/cjs/src/utils/trade/increase.js +255 -32
  42. package/build/cjs/src/utils/trade/increaseMarginCheck.js +179 -0
  43. package/build/cjs/src/utils/trade/index.js +1 -0
  44. package/build/cjs/src/utils/trade/trade.js +11 -1
  45. package/build/cjs/src/utils/tradeHistory/utils.js +3 -0
  46. package/build/cjs/src/utils/yield/api.js +9 -1
  47. package/build/esm/scripts/subsquid-codegen.js +1 -1
  48. package/build/esm/src/abis/ArbSys.js +9 -0
  49. package/build/esm/src/abis/index.js +2 -0
  50. package/build/esm/src/clients/v1/testUtil.js +1 -1
  51. package/build/esm/src/clients/v2/index.js +5 -1
  52. package/build/esm/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +16 -88
  53. package/build/esm/src/codegen/prebuilt/hashedMarketConfigKeys.json +136 -748
  54. package/build/esm/src/codegen/prebuilt/hashedMarketValuesKeys.json +30 -165
  55. package/build/esm/src/configs/__tests__/markets.spec.js +2 -17
  56. package/build/esm/src/configs/api.js +8 -0
  57. package/build/esm/src/configs/contracts.js +2 -0
  58. package/build/esm/src/configs/dataStore.js +8 -0
  59. package/build/esm/src/configs/express.js +1 -0
  60. package/build/esm/src/configs/markets.js +14 -77
  61. package/build/esm/src/configs/tokens.js +22 -90
  62. package/build/esm/src/test/fixtures/arbitrumMarkets.json +0 -72
  63. package/build/esm/src/test/mock.js +10 -0
  64. package/build/esm/src/utils/__tests__/fees.spec.js +37 -1
  65. package/build/esm/src/utils/__tests__/markets.spec.js +234 -1
  66. package/build/esm/src/utils/__tests__/positionPnlCap.spec.js +30 -3
  67. package/build/esm/src/utils/__tests__/positions.spec.js +5 -5
  68. package/build/esm/src/utils/__tests__/prices.spec.js +98 -1
  69. package/build/esm/src/utils/express/utils/gelatoRelayUtils.js +2 -0
  70. package/build/esm/src/utils/express/utils/gmxRelayUtils.js +137 -0
  71. package/build/esm/src/utils/express/utils/gmxRelayUtils.spec.js +161 -0
  72. package/build/esm/src/utils/express/utils/index.js +1 -0
  73. package/build/esm/src/utils/fees/index.js +8 -5
  74. package/build/esm/src/utils/fees/priceImpact.js +5 -10
  75. package/build/esm/src/utils/markets/utils.js +57 -2
  76. package/build/esm/src/utils/numbers/index.js +1 -0
  77. package/build/esm/src/utils/numbers/prbMath.js +149 -0
  78. package/build/esm/src/utils/positions/utils.js +63 -42
  79. package/build/esm/src/utils/prices/utils.js +25 -0
  80. package/build/esm/src/utils/stats/__tests__/api.spec.js +98 -0
  81. package/build/esm/src/utils/stats/api.js +26 -0
  82. package/build/esm/src/utils/stats/types.js +1 -0
  83. package/build/esm/src/utils/trade/__tests__/increase.spec.js +578 -0
  84. package/build/esm/src/utils/trade/__tests__/increaseInvariants.spec.js +256 -0
  85. package/build/esm/src/utils/trade/__tests__/increaseMarginCheck.spec.js +835 -0
  86. package/build/esm/src/utils/trade/increase.js +243 -20
  87. package/build/esm/src/utils/trade/increaseMarginCheck.js +173 -0
  88. package/build/esm/src/utils/trade/index.js +1 -0
  89. package/build/esm/src/utils/trade/trade.js +10 -1
  90. package/build/esm/src/utils/tradeHistory/utils.js +3 -0
  91. package/build/esm/src/utils/yield/api.js +7 -0
  92. package/build/tsconfig.tsbuildinfo +1 -1
  93. package/build/types/src/abis/ArbSys.d.ts +12 -0
  94. package/build/types/src/abis/index.d.ts +11 -0
  95. package/build/types/src/clients/v2/index.d.ts +6 -3
  96. package/build/types/src/codegen/prebuilt/index.d.ts +170 -989
  97. package/build/types/src/configs/api.d.ts +1 -0
  98. package/build/types/src/configs/contracts.d.ts +2 -0
  99. package/build/types/src/configs/dataStore.d.ts +4 -0
  100. package/build/types/src/configs/express.d.ts +1 -0
  101. package/build/types/src/test/mock.d.ts +2 -0
  102. package/build/types/src/utils/buildUrl/utils.d.ts +1 -1
  103. package/build/types/src/utils/buyback/types.d.ts +7 -0
  104. package/build/types/src/utils/express/utils/gelatoRelayUtils.d.ts +2 -0
  105. package/build/types/src/utils/express/utils/gmxRelayUtils.d.ts +61 -0
  106. package/build/types/src/utils/express/utils/gmxRelayUtils.spec.d.ts +1 -0
  107. package/build/types/src/utils/express/utils/index.d.ts +1 -0
  108. package/build/types/src/utils/fees/index.d.ts +1 -1
  109. package/build/types/src/utils/markets/utils.d.ts +7 -0
  110. package/build/types/src/utils/numbers/index.d.ts +1 -0
  111. package/build/types/src/utils/numbers/prbMath.d.ts +7 -0
  112. package/build/types/src/utils/positions/utils.d.ts +9 -0
  113. package/build/types/src/utils/prices/utils.d.ts +10 -0
  114. package/build/types/src/utils/stats/__tests__/api.spec.d.ts +1 -0
  115. package/build/types/src/utils/stats/api.d.ts +11 -0
  116. package/build/types/src/utils/stats/types.d.ts +106 -0
  117. package/build/types/src/utils/trade/__tests__/increase.spec.d.ts +1 -0
  118. package/build/types/src/utils/trade/__tests__/increaseInvariants.spec.d.ts +1 -0
  119. package/build/types/src/utils/trade/__tests__/increaseMarginCheck.spec.d.ts +1 -0
  120. package/build/types/src/utils/trade/increase.d.ts +3 -0
  121. package/build/types/src/utils/trade/increaseMarginCheck.d.ts +61 -0
  122. package/build/types/src/utils/trade/index.d.ts +1 -0
  123. package/build/types/src/utils/trade/trade.d.ts +2 -0
  124. package/build/types/src/utils/tradeHistory/types.d.ts +2 -1
  125. package/build/types/src/utils/yield/api.d.ts +4 -1
  126. package/build/types/src/utils/yield/types.d.ts +18 -0
  127. package/package.json +3 -3
@@ -0,0 +1,835 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { mockMarketsInfoData, mockTokensData } from "../../../test/mock";
3
+ import { getMarketInfoWithOpenInterestDelta } from "../../markets";
4
+ import { USD_DECIMALS, expandDecimals } from "../../numbers";
5
+ import { convertToTokenAmount, convertToTokenAmountForIncrease, convertToUsd } from "../../tokens";
6
+ import { PositionMarginFailureReason, getIncreaseResultingPositionMarginState, getIsMaxLeverageMarginReason, getResultingPositionMarginState, } from "../increaseMarginCheck";
7
+ const BTC_PRICE = expandDecimals(20000, 30);
8
+ const tokensData = mockTokensData();
9
+ /** 1% min collateral factor → 100x, 0.5% for liquidation. Fees and impact off unless a test needs them. */
10
+ function buildMarket(overrides = {}) {
11
+ return mockMarketsInfoData(tokensData, ["BTC-BTC-USDC"], {
12
+ "BTC-BTC-USDC": {
13
+ minCollateralFactor: expandDecimals(1, 28),
14
+ minCollateralFactorForLiquidation: expandDecimals(5, 27),
15
+ minCollateralFactorForOpenInterestLong: 0n,
16
+ minCollateralFactorForOpenInterestShort: 0n,
17
+ positionFeeFactorForBalanceWasImproved: 0n,
18
+ positionFeeFactorForBalanceWasNotImproved: 0n,
19
+ positionImpactFactorPositive: 0n,
20
+ positionImpactFactorNegative: 0n,
21
+ maxPositionImpactFactorPositive: 0n,
22
+ maxPositionImpactFactorNegative: 0n,
23
+ maxPositionImpactFactorForLiquidations: 0n,
24
+ longInterestUsd: 0n,
25
+ shortInterestUsd: 0n,
26
+ longInterestInTokens: 0n,
27
+ shortInterestInTokens: 0n,
28
+ ...overrides,
29
+ },
30
+ })["BTC-BTC-USDC"];
31
+ }
32
+ const usdc = tokensData.USDC;
33
+ function usdcAmount(usd) {
34
+ return convertToTokenAmount(usd10(usd), usdc.decimals, usdc.prices.minPrice);
35
+ }
36
+ /** USD value with 30 decimals, accepting fractional amounts. */
37
+ function usd10(usd) {
38
+ return (BigInt(Math.round(usd * 100)) * expandDecimals(1, USD_DECIMALS)) / 100n;
39
+ }
40
+ function btcAmount(usd) {
41
+ return convertToTokenAmount(expandDecimals(usd, USD_DECIMALS), tokensData.BTC.decimals, BTC_PRICE);
42
+ }
43
+ function baseParams(overrides = {}) {
44
+ return {
45
+ marketInfo: buildMarket(),
46
+ collateralToken: usdc,
47
+ // 10 000 USD of size bought exactly at the oracle price → zero pnl
48
+ sizeInUsd: expandDecimals(10000, USD_DECIMALS),
49
+ sizeInTokens: btcAmount(10000),
50
+ collateralAmount: usdcAmount(100),
51
+ pendingImpactAmount: 0n,
52
+ minCollateralUsd: expandDecimals(1, USD_DECIMALS),
53
+ isLong: true,
54
+ userReferralInfo: undefined,
55
+ ...overrides,
56
+ };
57
+ }
58
+ describe("getResultingPositionMarginState", () => {
59
+ it("passes when remaining margin equals the leverage-based minimum", () => {
60
+ // 1% of 10 000 = 100, and the position has exactly 100 of collateral
61
+ const state = getResultingPositionMarginState(baseParams());
62
+ expect(state.minCollateralUsdForLeverage).toBe(expandDecimals(100, USD_DECIMALS));
63
+ expect(state.remainingCollateralUsd).toBe(expandDecimals(100, USD_DECIMALS));
64
+ expect(state.isLiquidatable).toBe(false);
65
+ expect(state.reason).toBeUndefined();
66
+ });
67
+ it("fails with the leverage reason just below the minimum", () => {
68
+ const state = getResultingPositionMarginState(baseParams({ collateralAmount: usdcAmount(99.99) }));
69
+ expect(state.isLiquidatable).toBe(true);
70
+ expect(state.reason).toBe(PositionMarginFailureReason.MinCollateralForLeverage);
71
+ });
72
+ it("uses the regular minCollateralFactor, not the liquidation one", () => {
73
+ // 0.5% of 10 000 = 50, so a liquidation-factor check would pass at 60 of collateral
74
+ const params = baseParams({ collateralAmount: usdcAmount(60) });
75
+ expect(getResultingPositionMarginState(params).reason).toBe(PositionMarginFailureReason.MinCollateralForLeverage);
76
+ });
77
+ it("counts unrealized loss against the remaining margin for a long", () => {
78
+ // bought 10 000 USD worth of BTC at 25 000 while the oracle is at 20 000 → -2 000 pnl
79
+ const state = getResultingPositionMarginState(baseParams({
80
+ sizeInTokens: convertToTokenAmount(expandDecimals(10000, USD_DECIMALS), tokensData.BTC.decimals, expandDecimals(25000, 30)),
81
+ collateralAmount: usdcAmount(2500),
82
+ }));
83
+ expect(state.remainingCollateralUsd).toBe(expandDecimals(500, USD_DECIMALS));
84
+ expect(state.isLiquidatable).toBe(false);
85
+ });
86
+ it("counts unrealized loss against the remaining margin for a short", () => {
87
+ // a short holding more tokens than it sold is losing when priced at the oracle max
88
+ const state = getResultingPositionMarginState(baseParams({
89
+ isLong: false,
90
+ sizeInTokens: btcAmount(12000),
91
+ collateralAmount: usdcAmount(2500),
92
+ }));
93
+ expect(state.remainingCollateralUsd).toBe(expandDecimals(500, USD_DECIMALS));
94
+ expect(state.isLiquidatable).toBe(false);
95
+ });
96
+ it("reports the fixed minimum before the leverage reason", () => {
97
+ const state = getResultingPositionMarginState(baseParams({
98
+ collateralAmount: usdcAmount(0.5),
99
+ minCollateralUsd: expandDecimals(1, USD_DECIMALS),
100
+ }));
101
+ expect(state.reason).toBe(PositionMarginFailureReason.MinCollateral);
102
+ });
103
+ it("reports non-positive remaining margin before the leverage reason", () => {
104
+ const state = getResultingPositionMarginState(baseParams({
105
+ collateralAmount: 0n,
106
+ minCollateralUsd: 0n,
107
+ }));
108
+ expect(state.reason).toBe(PositionMarginFailureReason.NonPositiveRemainingMargin);
109
+ });
110
+ it("deducts the full-close position fee once", () => {
111
+ // 0.5% closing fee on 10 000 = 50
112
+ const state = getResultingPositionMarginState(baseParams({
113
+ marketInfo: buildMarket({
114
+ positionFeeFactorForBalanceWasImproved: expandDecimals(5, 27),
115
+ positionFeeFactorForBalanceWasNotImproved: expandDecimals(5, 27),
116
+ }),
117
+ }));
118
+ expect(state.remainingCollateralUsd).toBe(expandDecimals(50, USD_DECIMALS));
119
+ expect(state.reason).toBe(PositionMarginFailureReason.MinCollateralForLeverage);
120
+ });
121
+ it("applies the pro-tier discount to the closing fee", () => {
122
+ // 0.5% closing fee on 10 000 = 50; a 50% pro discount returns 25 of it
123
+ const state = getResultingPositionMarginState({
124
+ ...baseParams({
125
+ marketInfo: buildMarket({
126
+ positionFeeFactorForBalanceWasImproved: expandDecimals(5, 27),
127
+ positionFeeFactorForBalanceWasNotImproved: expandDecimals(5, 27),
128
+ }),
129
+ }),
130
+ proDiscountFactor: expandDecimals(5, 29),
131
+ });
132
+ expect(state.remainingCollateralUsd).toBe(expandDecimals(75, USD_DECIMALS));
133
+ });
134
+ it("takes the larger of the pro and referral discounts, not their sum", () => {
135
+ const params = baseParams({
136
+ marketInfo: buildMarket({
137
+ positionFeeFactorForBalanceWasImproved: expandDecimals(5, 27),
138
+ positionFeeFactorForBalanceWasNotImproved: expandDecimals(5, 27),
139
+ }),
140
+ });
141
+ // 20% rebate × 50% trader share → a 10% referral discount, 5 of the 50 fee
142
+ const userReferralInfo = {
143
+ totalRebateFactor: expandDecimals(2, 29),
144
+ discountFactor: expandDecimals(5, 29),
145
+ };
146
+ // 50% pro discount (25) beats the referral 5
147
+ const proWins = getResultingPositionMarginState({
148
+ ...params,
149
+ userReferralInfo,
150
+ proDiscountFactor: expandDecimals(5, 29),
151
+ });
152
+ expect(proWins.remainingCollateralUsd).toBe(expandDecimals(75, USD_DECIMALS));
153
+ // 5% pro discount (2.5) loses to the referral 5
154
+ const referralWins = getResultingPositionMarginState({
155
+ ...params,
156
+ userReferralInfo,
157
+ proDiscountFactor: expandDecimals(5, 28),
158
+ });
159
+ expect(referralWins.remainingCollateralUsd).toBe(expandDecimals(55, USD_DECIMALS));
160
+ });
161
+ });
162
+ describe("getIncreaseResultingPositionMarginState", () => {
163
+ const marketInfo = buildMarket();
164
+ // the contract clamps negative impact at maxPositionImpactFactorForLiquidations — 1% of size here
165
+ const marketWithImpactCap = buildMarket({ maxPositionImpactFactorForLiquidations: expandDecimals(1, 28) });
166
+ it("returns undefined when there is no size to validate", () => {
167
+ expect(getIncreaseResultingPositionMarginState({
168
+ marketInfo,
169
+ collateralToken: usdc,
170
+ isLong: true,
171
+ existingPosition: undefined,
172
+ sizeDeltaUsd: 0n,
173
+ sizeDeltaInTokens: 0n,
174
+ collateralDeltaAmount: usdcAmount(100),
175
+ minCollateralUsd: expandDecimals(1, USD_DECIMALS),
176
+ userReferralInfo: undefined,
177
+ })).toBeUndefined();
178
+ });
179
+ it("returns undefined instead of crashing when the oracle prices are zeroed", () => {
180
+ // a delisted market reports zeroed prices while its resting orders are still rendered
181
+ const zeroPriceTokens = mockTokensData({ BTC: { prices: { minPrice: 0n, maxPrice: 0n } } });
182
+ const zeroPriceMarket = mockMarketsInfoData(zeroPriceTokens, ["BTC-BTC-USDC"], {})["BTC-BTC-USDC"];
183
+ expect(getIncreaseResultingPositionMarginState({
184
+ marketInfo: zeroPriceMarket,
185
+ collateralToken: zeroPriceTokens.USDC,
186
+ isLong: true,
187
+ existingPosition: undefined,
188
+ sizeDeltaUsd: expandDecimals(1000, USD_DECIMALS),
189
+ sizeDeltaInTokens: expandDecimals(5, 6),
190
+ collateralDeltaAmount: usdcAmount(100),
191
+ minCollateralUsd: expandDecimals(1, USD_DECIMALS),
192
+ userReferralInfo: undefined,
193
+ })).toBeUndefined();
194
+ });
195
+ it("passes for a fresh position at exactly the max leverage", () => {
196
+ const state = getIncreaseResultingPositionMarginState({
197
+ marketInfo,
198
+ collateralToken: usdc,
199
+ isLong: true,
200
+ existingPosition: undefined,
201
+ sizeDeltaUsd: expandDecimals(10000, USD_DECIMALS),
202
+ sizeDeltaInTokens: btcAmount(10000),
203
+ collateralDeltaAmount: usdcAmount(100),
204
+ minCollateralUsd: expandDecimals(1, USD_DECIMALS),
205
+ userReferralInfo: undefined,
206
+ });
207
+ expect(state?.isLiquidatable).toBe(false);
208
+ });
209
+ it("fails when an existing position's unrealized loss eats the resulting margin", () => {
210
+ // the existing long bought at 25 000 while the oracle is at 20 000 → -2 000 pnl,
211
+ // which the order-level max-leverage check ignores by design
212
+ const existingPosition = {
213
+ sizeInUsd: expandDecimals(10000, USD_DECIMALS),
214
+ sizeInTokens: convertToTokenAmount(expandDecimals(10000, USD_DECIMALS), tokensData.BTC.decimals, expandDecimals(25000, 30)),
215
+ collateralAmount: usdcAmount(2000),
216
+ pendingImpactAmount: 0n,
217
+ };
218
+ const state = getIncreaseResultingPositionMarginState({
219
+ marketInfo,
220
+ collateralToken: usdc,
221
+ isLong: true,
222
+ existingPosition,
223
+ sizeDeltaUsd: expandDecimals(10000, USD_DECIMALS),
224
+ sizeDeltaInTokens: btcAmount(10000),
225
+ collateralDeltaAmount: usdcAmount(100),
226
+ minCollateralUsd: expandDecimals(1, USD_DECIMALS),
227
+ userReferralInfo: undefined,
228
+ });
229
+ // collateral 2 100 − 2 000 of loss = 100 remaining, but 1% of 20 000 of size needs 200
230
+ expect(state?.remainingCollateralUsd).toBe(expandDecimals(100, USD_DECIMALS));
231
+ expect(state?.minCollateralUsdForLeverage).toBe(expandDecimals(200, USD_DECIMALS));
232
+ expect(state?.reason).toBe(PositionMarginFailureReason.MinCollateralForLeverage);
233
+ });
234
+ it("carries the increase's own negative price impact into the resulting position", () => {
235
+ // shorts dominate, so increasing a long is a same-side rebalance towards balance for the
236
+ // close leg (positive close impact, clamped away) while the increase leg pays negative
237
+ // impact that is stored as pending impact on the position
238
+ const imbalancedMarket = buildMarket({
239
+ maxPositionImpactFactorForLiquidations: expandDecimals(1, 28),
240
+ positionImpactFactorNegative: expandDecimals(1, 22),
241
+ positionImpactExponentFactorPositive: expandDecimals(2, 30),
242
+ positionImpactExponentFactorNegative: expandDecimals(2, 30),
243
+ longInterestUsd: expandDecimals(1000000, USD_DECIMALS),
244
+ shortInterestUsd: expandDecimals(500000, USD_DECIMALS),
245
+ longInterestInTokens: btcAmount(1000000),
246
+ shortInterestInTokens: btcAmount(500000),
247
+ useOpenInterestInTokensForBalance: false,
248
+ });
249
+ const run = (marketInfoForRun) => getIncreaseResultingPositionMarginState({
250
+ marketInfo: marketInfoForRun,
251
+ collateralToken: usdc,
252
+ isLong: true,
253
+ existingPosition: undefined,
254
+ sizeDeltaUsd: expandDecimals(10000, USD_DECIMALS),
255
+ sizeDeltaInTokens: btcAmount(10000),
256
+ collateralDeltaAmount: usdcAmount(150),
257
+ minCollateralUsd: expandDecimals(1, USD_DECIMALS),
258
+ userReferralInfo: undefined,
259
+ });
260
+ const withImpact = run(imbalancedMarket);
261
+ const withoutImpact = run(marketWithImpactCap);
262
+ expect(withoutImpact?.isLiquidatable).toBe(false);
263
+ // the increase's negative impact reduces the remaining margin below 1% of the size
264
+ expect(withImpact.remainingCollateralUsd).toBeLessThan(withoutImpact.remainingCollateralUsd);
265
+ expect(withImpact?.reason).toBe(PositionMarginFailureReason.MinCollateralForLeverage);
266
+ });
267
+ });
268
+ describe("getResultingPositionMarginState — oracle sides", () => {
269
+ // a spread on both tokens, so picking the wrong side is visible
270
+ const spreadTokens = mockTokensData({
271
+ BTC: { prices: { minPrice: expandDecimals(20000, 30), maxPrice: expandDecimals(25000, 30) } },
272
+ USDC: { prices: { minPrice: expandDecimals(99, 28), maxPrice: expandDecimals(101, 28) } },
273
+ });
274
+ const spreadUsdc = spreadTokens.USDC;
275
+ const spreadBtc = spreadTokens.BTC;
276
+ function spreadMarket() {
277
+ return mockMarketsInfoData(spreadTokens, ["BTC-BTC-USDC"], {
278
+ "BTC-BTC-USDC": {
279
+ minCollateralFactor: expandDecimals(1, 28),
280
+ minCollateralFactorForLiquidation: expandDecimals(5, 27),
281
+ minCollateralFactorForOpenInterestLong: 0n,
282
+ minCollateralFactorForOpenInterestShort: 0n,
283
+ positionFeeFactorForBalanceWasImproved: 0n,
284
+ positionFeeFactorForBalanceWasNotImproved: 0n,
285
+ positionImpactFactorPositive: 0n,
286
+ positionImpactFactorNegative: 0n,
287
+ maxPositionImpactFactorPositive: 0n,
288
+ maxPositionImpactFactorNegative: 0n,
289
+ // 1% of size, high enough not to clamp the impact these tests use
290
+ maxPositionImpactFactorForLiquidations: expandDecimals(1, 28),
291
+ longInterestUsd: 0n,
292
+ shortInterestUsd: 0n,
293
+ longInterestInTokens: 0n,
294
+ shortInterestInTokens: 0n,
295
+ },
296
+ })["BTC-BTC-USDC"];
297
+ }
298
+ // bought exactly at the min price, so the pnl leg contributes nothing
299
+ const spreadParams = {
300
+ marketInfo: spreadMarket(),
301
+ collateralToken: spreadUsdc,
302
+ sizeInUsd: expandDecimals(10000, USD_DECIMALS),
303
+ sizeInTokens: convertToTokenAmount(expandDecimals(10000, USD_DECIMALS), spreadBtc.decimals, expandDecimals(20000, 30)),
304
+ collateralAmount: expandDecimals(1000, spreadUsdc.decimals),
305
+ pendingImpactAmount: 0n,
306
+ minCollateralUsd: expandDecimals(1, USD_DECIMALS),
307
+ isLong: true,
308
+ userReferralInfo: undefined,
309
+ };
310
+ it("values the collateral at its min price", () => {
311
+ // 1 000 USDC at 0.99, not at 1.01 or at the mid price
312
+ expect(getResultingPositionMarginState(spreadParams).remainingCollateralUsd).toBe(expandDecimals(990, USD_DECIMALS));
313
+ });
314
+ it("ignores a net-positive pending impact", () => {
315
+ // the contract clamps the total impact at zero, so favourable impact never adds margin
316
+ const state = getResultingPositionMarginState({
317
+ ...spreadParams,
318
+ pendingImpactAmount: convertToTokenAmount(expandDecimals(50, USD_DECIMALS), spreadBtc.decimals, expandDecimals(20000, 30)),
319
+ });
320
+ expect(state.remainingCollateralUsd).toBe(expandDecimals(990, USD_DECIMALS));
321
+ });
322
+ it("values a negative pending impact at the index max price", () => {
323
+ const pendingImpactAmount = -convertToTokenAmount(expandDecimals(50, USD_DECIMALS), spreadBtc.decimals, expandDecimals(25000, 30));
324
+ const state = getResultingPositionMarginState({ ...spreadParams, pendingImpactAmount });
325
+ const atMaxPrice = convertToUsd(pendingImpactAmount, spreadBtc.decimals, expandDecimals(25000, 30));
326
+ const atMinPrice = convertToUsd(pendingImpactAmount, spreadBtc.decimals, expandDecimals(20000, 30));
327
+ expect(state.remainingCollateralUsd).toBe(expandDecimals(990, USD_DECIMALS) + atMaxPrice);
328
+ expect(state.remainingCollateralUsd).not.toBe(expandDecimals(990, USD_DECIMALS) + atMinPrice);
329
+ });
330
+ });
331
+ describe("getIncreaseResultingPositionMarginState — open interest projection", () => {
332
+ // linear impact (exponent 1) keeps every leg a round number:
333
+ // a crossover pays factorNegative on the side it lands on and earns factorPositive on the side it leaves
334
+ function impactMarket(useOpenInterestInTokensForBalance) {
335
+ return buildMarket({
336
+ positionImpactFactorPositive: expandDecimals(1, 27), // 0.1%
337
+ positionImpactFactorNegative: expandDecimals(3, 27), // 0.3%
338
+ positionImpactExponentFactorPositive: expandDecimals(1, 30),
339
+ positionImpactExponentFactorNegative: expandDecimals(1, 30),
340
+ maxPositionImpactFactorPositive: expandDecimals(1, 29),
341
+ maxPositionImpactFactorNegative: expandDecimals(1, 29),
342
+ maxPositionImpactFactorForLiquidations: expandDecimals(1, 29),
343
+ // longs 50 000 (all USDC-collateralised) vs shorts 100 000
344
+ longInterestUsd: expandDecimals(50000, USD_DECIMALS),
345
+ shortInterestUsd: expandDecimals(100000, USD_DECIMALS),
346
+ longInterestInTokens: btcAmount(50000),
347
+ shortInterestInTokens: btcAmount(100000),
348
+ longInterestUsdUsingLongToken: 0n,
349
+ longInterestInTokensUsingLongToken: 0n,
350
+ longInterestUsdUsingShortToken: expandDecimals(50000, USD_DECIMALS),
351
+ longInterestInTokensUsingShortToken: btcAmount(50000),
352
+ useOpenInterestInTokensForBalance,
353
+ });
354
+ }
355
+ const sizeDeltaUsd = expandDecimals(100000, USD_DECIMALS);
356
+ const sizeDeltaInTokens = btcAmount(100000);
357
+ it.each([false, true])("validates against the market state after the order (useOpenInterestInTokensForBalance=%s)", (useOpenInterestInTokensForBalance) => {
358
+ const marketInfo = impactMarket(useOpenInterestInTokensForBalance);
359
+ const state = getIncreaseResultingPositionMarginState({
360
+ marketInfo,
361
+ collateralToken: usdc,
362
+ isLong: true,
363
+ existingPosition: undefined,
364
+ sizeDeltaUsd,
365
+ sizeDeltaInTokens,
366
+ collateralDeltaAmount: usdcAmount(5000),
367
+ minCollateralUsd: expandDecimals(1, USD_DECIMALS),
368
+ userReferralInfo: undefined,
369
+ });
370
+ // increase: longs 50 000 → 150 000 crosses the 100 000 of shorts, 50 000 on each side:
371
+ // +0.1% × 50 000 − 0.3% × 50 000 = −100 → pending impact −100 / 20 000 = −0.005 BTC
372
+ // close on the projected market: 150 000 → 50 000 crosses back, again −100
373
+ // total −200, under the 10% liquidation cap → 5 000 − 200
374
+ expect(state?.remainingCollateralUsd).toBe(expandDecimals(4800, USD_DECIMALS));
375
+ expect(state?.isLiquidatable).toBe(false);
376
+ // on the pre-order market the close would run 50 000 → 0 on the shorts' side: −0.3% × 50 000 = −150
377
+ const withoutProjection = getResultingPositionMarginState({
378
+ marketInfo,
379
+ collateralToken: usdc,
380
+ sizeInUsd: sizeDeltaUsd,
381
+ sizeInTokens: sizeDeltaInTokens,
382
+ collateralAmount: usdcAmount(5000),
383
+ pendingImpactAmount: -500000n,
384
+ minCollateralUsd: expandDecimals(1, USD_DECIMALS),
385
+ isLong: true,
386
+ userReferralInfo: undefined,
387
+ });
388
+ expect(withoutProjection.remainingCollateralUsd).toBe(expandDecimals(4750, USD_DECIMALS));
389
+ const projected = getMarketInfoWithOpenInterestDelta({
390
+ marketInfo,
391
+ collateralToken: usdc,
392
+ isLong: true,
393
+ sizeDeltaUsd,
394
+ sizeDeltaInTokens,
395
+ });
396
+ expect(projected).toMatchObject({
397
+ longInterestUsd: expandDecimals(150000, USD_DECIMALS),
398
+ longInterestInTokens: 750000000n,
399
+ longInterestUsdUsingShortToken: expandDecimals(150000, USD_DECIMALS),
400
+ longInterestInTokensUsingShortToken: 750000000n,
401
+ shortInterestUsd: expandDecimals(100000, USD_DECIMALS),
402
+ });
403
+ });
404
+ });
405
+ /**
406
+ * Ported from the contracts repo: `test/exchange/MarketIncreaseOrder.ts`,
407
+ * "validates collateral amount". The market config mirrors `hardhatBaseMarketConfig`
408
+ * from `config/markets.ts`, the numbers are the ones the contract test uses.
409
+ *
410
+ * A short is opened at 5 000 and the index then moves to 5 500; the second increase is
411
+ * cancelled by the contract with `LiquidatablePosition`, and goes through once the added
412
+ * collateral is doubled.
413
+ */
414
+ describe("contract parity — MarketIncreaseOrder «validates collateral amount»", () => {
415
+ const ETH_PRICE = expandDecimals(5500, 30);
416
+ const hardhatTokens = mockTokensData({
417
+ ETH: { prices: { minPrice: ETH_PRICE, maxPrice: ETH_PRICE } },
418
+ });
419
+ const hardhatUsdc = hardhatTokens.USDC;
420
+ // hardhatBaseMarketConfig: 1% min collateral factor, 1% for liquidation,
421
+ // no open-interest scaling, 1% cap on the liquidation impact; the test sets 0.05% position fee
422
+ const marketInfo = mockMarketsInfoData(hardhatTokens, ["ETH-ETH-USDC"], {
423
+ "ETH-ETH-USDC": {
424
+ minCollateralFactor: expandDecimals(1, 28),
425
+ minCollateralFactorForLiquidation: expandDecimals(1, 28),
426
+ minCollateralFactorForOpenInterestLong: 0n,
427
+ minCollateralFactorForOpenInterestShort: 0n,
428
+ positionFeeFactorForBalanceWasImproved: expandDecimals(5, 26),
429
+ positionFeeFactorForBalanceWasNotImproved: expandDecimals(5, 26),
430
+ positionImpactFactorPositive: 0n,
431
+ positionImpactFactorNegative: 0n,
432
+ maxPositionImpactFactorPositive: 0n,
433
+ maxPositionImpactFactorNegative: 0n,
434
+ maxPositionImpactFactorForLiquidations: expandDecimals(1, 28),
435
+ longInterestUsd: 0n,
436
+ shortInterestUsd: 0n,
437
+ longInterestInTokens: 0n,
438
+ shortInterestInTokens: 0n,
439
+ },
440
+ })["ETH-ETH-USDC"];
441
+ const sizeDeltaUsd = expandDecimals(20000, USD_DECIMALS);
442
+ // the first order sold 20 000 USD worth of ETH at 5 000
443
+ const existingPosition = {
444
+ sizeInUsd: sizeDeltaUsd,
445
+ sizeInTokens: expandDecimals(4, 18),
446
+ collateralAmount: expandDecimals(990, 6), // 1 000 USDC less the 0.05% position fee
447
+ pendingImpactAmount: 0n,
448
+ };
449
+ // a short's size in tokens rounds up, as the contract does: 20 000 / 5 500 = 3.6363…63 → …64 wei
450
+ const sizeDeltaInTokens = convertToTokenAmountForIncrease(sizeDeltaUsd, 18, ETH_PRICE, false);
451
+ // that extra wei is worth 5 500 × 1e-18 = 5.5e-15 USD; valued at 5 500 the 3.6363…64 ETH come to
452
+ // 20 000 + 2e-15 USD, so the loss carries 2e-15 USD of round-up dust
453
+ const ROUND_UP_DUST = 2n * expandDecimals(1, 15);
454
+ function runIncrease(collateralDeltaAmount) {
455
+ return getIncreaseResultingPositionMarginState({
456
+ marketInfo,
457
+ collateralToken: hardhatUsdc,
458
+ isLong: false,
459
+ existingPosition,
460
+ sizeDeltaUsd,
461
+ sizeDeltaInTokens,
462
+ collateralDeltaAmount,
463
+ minCollateralUsd: expandDecimals(1, USD_DECIMALS),
464
+ userReferralInfo: undefined,
465
+ });
466
+ }
467
+ it("sizes the short's tokens with the contract's round-up", () => {
468
+ expect(sizeDeltaInTokens).toBe(3636363636363636364n);
469
+ });
470
+ it("rejects the second increase the contract cancels", () => {
471
+ // 1 000 USDC added, less the 0.05% fee
472
+ const state = runIncrease(expandDecimals(990, 6));
473
+ // collateral 1 980, unrealized loss 2 000, closing fee 20 → the margin goes negative
474
+ expect(state?.remainingCollateralUsd).toBe(-expandDecimals(40, USD_DECIMALS) - ROUND_UP_DUST);
475
+ expect(state?.isLiquidatable).toBe(true);
476
+ // the fixed minimum is checked before the leverage one, so this is the reason the contract reports
477
+ expect(state?.reason).toBe(PositionMarginFailureReason.MinCollateral);
478
+ });
479
+ it("accepts the same increase with doubled collateral", () => {
480
+ // 2 000 USDC added, less the 0.05% fee
481
+ const state = runIncrease(expandDecimals(1990, 6));
482
+ // collateral 2 980, unrealized loss 2 000, closing fee 20
483
+ expect(state?.remainingCollateralUsd).toBe(expandDecimals(960, USD_DECIMALS) - ROUND_UP_DUST);
484
+ expect(state?.minCollateralUsdForLeverage).toBe(expandDecimals(400, USD_DECIMALS));
485
+ expect(state?.isLiquidatable).toBe(false);
486
+ expect(state?.reason).toBeUndefined();
487
+ });
488
+ });
489
+ describe("getIncreaseResultingPositionMarginState — open-interest min collateral gate", () => {
490
+ // 2e-8 multiplier: with 1 000 000 of post-order side OI the OI-scaled factor is 2%,
491
+ // above the 1% market minCollateralFactor
492
+ const OI_MULTIPLIER = expandDecimals(2, 22);
493
+ function gateArgs(collateralUsd, marketOverrides = {}) {
494
+ return {
495
+ marketInfo: buildMarket({
496
+ minCollateralFactorForOpenInterestLong: OI_MULTIPLIER,
497
+ longInterestUsd: expandDecimals(990000, USD_DECIMALS),
498
+ ...marketOverrides,
499
+ }),
500
+ collateralToken: usdc,
501
+ isLong: true,
502
+ existingPosition: undefined,
503
+ sizeDeltaUsd: expandDecimals(10000, USD_DECIMALS),
504
+ sizeDeltaInTokens: btcAmount(10000),
505
+ collateralDeltaAmount: usdcAmount(collateralUsd),
506
+ minCollateralUsd: expandDecimals(1, USD_DECIMALS),
507
+ userReferralInfo: undefined,
508
+ };
509
+ }
510
+ it("fails with its own reason when the OI-scaled factor exceeds the market one", () => {
511
+ // post-order OI 1 000 000 → factor 2%, threshold 200; the plain leverage gate (1% → 100) passes
512
+ const state = getIncreaseResultingPositionMarginState(gateArgs(150));
513
+ expect(state?.isLiquidatable).toBe(true);
514
+ expect(state?.reason).toBe(PositionMarginFailureReason.InsufficientCollateralUsd);
515
+ expect(getIsMaxLeverageMarginReason(state?.reason)).toBe(true);
516
+ expect(state?.remainingCollateralUsd).toBe(expandDecimals(150, USD_DECIMALS));
517
+ expect(state?.minCollateralUsdForLeverage).toBe(expandDecimals(200, USD_DECIMALS));
518
+ });
519
+ it("passes at exact equality with the threshold", () => {
520
+ expect(getIncreaseResultingPositionMarginState(gateArgs(200))?.isLiquidatable).toBe(false);
521
+ });
522
+ it("evaluates the factor against the post-order open interest", () => {
523
+ // pre-order OI would give 1.98% → 198 and let 199 pass; post-order 2% → 200 rejects it
524
+ const state = getIncreaseResultingPositionMarginState(gateArgs(199));
525
+ expect(state?.reason).toBe(PositionMarginFailureReason.InsufficientCollateralUsd);
526
+ });
527
+ it("takes precedence over the leverage reason when both fail", () => {
528
+ expect(getIncreaseResultingPositionMarginState(gateArgs(50))?.reason).toBe(PositionMarginFailureReason.InsufficientCollateralUsd);
529
+ });
530
+ it("falls back to the market factor when the multiplier contribution is smaller", () => {
531
+ // 10 000 of post-order OI → OI factor 0.02%, the 1% market factor governs → 150 passes
532
+ const state = getIncreaseResultingPositionMarginState(gateArgs(150, { longInterestUsd: 0n }));
533
+ expect(state?.isLiquidatable).toBe(false);
534
+ });
535
+ });
536
+ describe("getIncreaseResultingPositionMarginState — evaluation at the trigger price", () => {
537
+ const marketInfo = buildMarket();
538
+ const minCollateralUsd = expandDecimals(1, USD_DECIMALS);
539
+ // existing long opened at the current price (20 000): flat pnl at current prices
540
+ const existingPosition = {
541
+ sizeInUsd: expandDecimals(1000, USD_DECIMALS),
542
+ sizeInTokens: btcAmount(1000),
543
+ collateralAmount: usdcAmount(60),
544
+ pendingImpactAmount: 0n,
545
+ };
546
+ /** Rounding loss of converting `usd` into whole token units at `price` and back. */
547
+ function tokenConversionDust(usd, price) {
548
+ const tokens = convertToTokenAmount(usd, tokensData.BTC.decimals, price);
549
+ return usd - convertToUsd(tokens, tokensData.BTC.decimals, price);
550
+ }
551
+ // the order enters at the trigger, so its own tokens have zero pnl at that price
552
+ function increaseAt(triggerPrice, indexPriceForEvaluation) {
553
+ const sizeDeltaUsd = expandDecimals(4000, USD_DECIMALS);
554
+ return getIncreaseResultingPositionMarginState({
555
+ marketInfo,
556
+ collateralToken: usdc,
557
+ isLong: true,
558
+ existingPosition,
559
+ sizeDeltaUsd,
560
+ sizeDeltaInTokens: convertToTokenAmount(sizeDeltaUsd, tokensData.BTC.decimals, triggerPrice),
561
+ collateralDeltaAmount: usdcAmount(10),
562
+ minCollateralUsd,
563
+ userReferralInfo: undefined,
564
+ indexPriceForEvaluation,
565
+ });
566
+ }
567
+ it("a limit below the market is unhealthy at its trigger while looking healthy at current prices", () => {
568
+ const triggerPrice = expandDecimals(18000, USD_DECIMALS); // −10%
569
+ // current-price evaluation values the trigger-priced tokens at 20 000 → fake instant profit
570
+ const atCurrent = increaseAt(triggerPrice, undefined);
571
+ expect(atCurrent?.isLiquidatable).toBe(false);
572
+ // at the trigger the existing position loses 10% → 100 of loss against 70 of margin
573
+ const atTrigger = increaseAt(triggerPrice, triggerPrice);
574
+ expect(atTrigger?.isLiquidatable).toBe(true);
575
+ // the new tokens are flat at the trigger up to the token-conversion dust
576
+ expect(atTrigger?.remainingCollateralUsd).toBe(-expandDecimals(30, USD_DECIMALS) - tokenConversionDust(expandDecimals(4000, USD_DECIMALS), triggerPrice));
577
+ // remaining is below the absolute minimum, so the reason is not about leverage
578
+ expect(atTrigger?.reason).toBe(PositionMarginFailureReason.MinCollateral);
579
+ });
580
+ it("a stop above the market is healthy at its trigger while looking liquidatable at current prices", () => {
581
+ const triggerPrice = expandDecimals(22000, USD_DECIMALS); // +10%
582
+ // current-price evaluation books an instant 10% loss on the trigger-priced tokens
583
+ const atCurrent = increaseAt(triggerPrice, undefined);
584
+ expect(atCurrent?.isLiquidatable).toBe(true);
585
+ // at the trigger the new tokens are flat and the existing position is in profit
586
+ const atTrigger = increaseAt(triggerPrice, triggerPrice);
587
+ expect(atTrigger?.isLiquidatable).toBe(false);
588
+ // 70 of margin + 100 of existing profit, minus the token-conversion dust of the new tokens
589
+ expect(atTrigger?.remainingCollateralUsd).toBe(expandDecimals(170, USD_DECIMALS) - tokenConversionDust(expandDecimals(4000, USD_DECIMALS), triggerPrice));
590
+ });
591
+ it("values an index-token collateral at the evaluation price too", () => {
592
+ const triggerPrice = expandDecimals(18000, USD_DECIMALS);
593
+ const sizeDeltaUsd = expandDecimals(1000, USD_DECIMALS);
594
+ const state = getIncreaseResultingPositionMarginState({
595
+ marketInfo,
596
+ collateralToken: tokensData.BTC,
597
+ isLong: true,
598
+ existingPosition: undefined,
599
+ sizeDeltaUsd,
600
+ sizeDeltaInTokens: convertToTokenAmount(sizeDeltaUsd, tokensData.BTC.decimals, triggerPrice),
601
+ // 0.005 BTC of collateral: 100 USD at the current price, 90 USD at the trigger
602
+ collateralDeltaAmount: btcAmount(100),
603
+ minCollateralUsd,
604
+ userReferralInfo: undefined,
605
+ indexPriceForEvaluation: triggerPrice,
606
+ });
607
+ expect(state?.remainingCollateralUsd).toBe(expandDecimals(90, USD_DECIMALS) - tokenConversionDust(sizeDeltaUsd, triggerPrice));
608
+ });
609
+ it("overrides the price of a synthetic-equivalent collateral too", () => {
610
+ // a synthetic BTC index (different address, same symbol) paired with a "WBTC"-style
611
+ // collateral: equivalence goes through getIsEquivalentTokens, not through addresses
612
+ const syntheticTokens = mockTokensData({
613
+ BTCSYN: {
614
+ address: "BTCSYN",
615
+ name: "Bitcoin (synthetic)",
616
+ symbol: "BTC",
617
+ decimals: 8,
618
+ isSynthetic: true,
619
+ prices: { minPrice: BTC_PRICE, maxPrice: BTC_PRICE },
620
+ },
621
+ WBTC: {
622
+ address: "WBTC",
623
+ name: "Wrapped Bitcoin",
624
+ symbol: "BTC",
625
+ decimals: 8,
626
+ prices: { minPrice: BTC_PRICE, maxPrice: BTC_PRICE },
627
+ },
628
+ });
629
+ const syntheticMarket = mockMarketsInfoData(syntheticTokens, ["BTCSYN-WBTC-USDC"], {
630
+ "BTCSYN-WBTC-USDC": {
631
+ minCollateralFactor: expandDecimals(1, 28),
632
+ minCollateralFactorForLiquidation: expandDecimals(5, 27),
633
+ minCollateralFactorForOpenInterestLong: 0n,
634
+ minCollateralFactorForOpenInterestShort: 0n,
635
+ positionFeeFactorForBalanceWasImproved: 0n,
636
+ positionFeeFactorForBalanceWasNotImproved: 0n,
637
+ positionImpactFactorPositive: 0n,
638
+ positionImpactFactorNegative: 0n,
639
+ maxPositionImpactFactorPositive: 0n,
640
+ maxPositionImpactFactorNegative: 0n,
641
+ maxPositionImpactFactorForLiquidations: 0n,
642
+ longInterestUsd: 0n,
643
+ shortInterestUsd: 0n,
644
+ longInterestInTokens: 0n,
645
+ shortInterestInTokens: 0n,
646
+ },
647
+ })["BTCSYN-WBTC-USDC"];
648
+ const triggerPrice = expandDecimals(18000, USD_DECIMALS);
649
+ const sizeDeltaUsd = expandDecimals(1000, USD_DECIMALS);
650
+ const wbtc = syntheticMarket.longToken;
651
+ const collateralDeltaAmount = convertToTokenAmount(expandDecimals(100, USD_DECIMALS), wbtc.decimals, BTC_PRICE);
652
+ const state = getIncreaseResultingPositionMarginState({
653
+ marketInfo: syntheticMarket,
654
+ collateralToken: wbtc,
655
+ isLong: true,
656
+ existingPosition: undefined,
657
+ sizeDeltaUsd,
658
+ sizeDeltaInTokens: convertToTokenAmount(sizeDeltaUsd, syntheticMarket.indexToken.decimals, triggerPrice),
659
+ // 100 USD of collateral at the current 20 000, worth 90 USD at the 18 000 trigger
660
+ collateralDeltaAmount,
661
+ minCollateralUsd,
662
+ userReferralInfo: undefined,
663
+ indexPriceForEvaluation: triggerPrice,
664
+ });
665
+ // the collateral is valued at the trigger (~90 USD), not at the current price (~100 USD)
666
+ expect(state.remainingCollateralUsd).toBeLessThanOrEqual(expandDecimals(90, USD_DECIMALS));
667
+ expect(state.remainingCollateralUsd).toBeGreaterThan(expandDecimals(89, USD_DECIMALS));
668
+ });
669
+ });
670
+ describe("pool pnl cap — profitable position while the cap binds, min < max", () => {
671
+ const spreadTokens = mockTokensData({
672
+ BTC: { prices: { minPrice: expandDecimals(20000, 30), maxPrice: expandDecimals(20400, 30) } },
673
+ USDC: { prices: { minPrice: expandDecimals(99, 28), maxPrice: expandDecimals(101, 28) } },
674
+ });
675
+ const spreadUsdc = spreadTokens.USDC;
676
+ const spreadBtc = spreadTokens.BTC;
677
+ function cappedMarket(overrides) {
678
+ return mockMarketsInfoData(spreadTokens, ["BTC-BTC-USDC"], {
679
+ "BTC-BTC-USDC": {
680
+ minCollateralFactor: expandDecimals(1, 28),
681
+ minCollateralFactorForLiquidation: expandDecimals(5, 27),
682
+ minCollateralFactorForOpenInterestLong: 0n,
683
+ minCollateralFactorForOpenInterestShort: 0n,
684
+ positionFeeFactorForBalanceWasImproved: 0n,
685
+ positionFeeFactorForBalanceWasNotImproved: 0n,
686
+ positionImpactFactorPositive: 0n,
687
+ positionImpactFactorNegative: 0n,
688
+ maxPositionImpactFactorPositive: 0n,
689
+ maxPositionImpactFactorNegative: 0n,
690
+ maxPositionImpactFactorForLiquidations: 0n,
691
+ // traders may take at most 10% of the pool
692
+ maxPnlFactorForTradersLong: expandDecimals(1, 29),
693
+ maxPnlFactorForTradersShort: expandDecimals(1, 29),
694
+ ...overrides,
695
+ },
696
+ })["BTC-BTC-USDC"];
697
+ }
698
+ it.each([
699
+ {
700
+ side: "long",
701
+ isLong: true,
702
+ // 10 BTC pool at the 20 000 min price = 200 000 → max pnl 20 000;
703
+ // 5 BTC of long OI opened for 62 000: at the maximising 20 400 the pool owes 102 000 − 62 000 = 40 000,
704
+ // at 20 000 only 38 000
705
+ marketInfo: cappedMarket({
706
+ longPoolAmount: expandDecimals(10, 8),
707
+ longInterestUsd: expandDecimals(62000, USD_DECIMALS),
708
+ longInterestInTokens: expandDecimals(5, 8),
709
+ longInterestUsdUsingLongToken: 0n,
710
+ longInterestInTokensUsingLongToken: 0n,
711
+ longInterestUsdUsingShortToken: expandDecimals(62000, USD_DECIMALS),
712
+ longInterestInTokensUsingShortToken: expandDecimals(5, 8),
713
+ }),
714
+ // 10 000 bought at 16 000 = 0.625 BTC, worth 12 500 at the 20 000 min price → +2 500 raw
715
+ sizeInTokens: 62500000n,
716
+ rawPnlUsd: expandDecimals(2500, USD_DECIMALS),
717
+ // 2 500 × 20 000 / 40 000
718
+ cappedPnlUsd: expandDecimals(1250, USD_DECIMALS),
719
+ // 2 500 × 20 000 / 38 000 — the cap ratio at the minimising price
720
+ cappedAtMinimisingPriceUsd: (expandDecimals(2500, USD_DECIMALS) * 20000n) / 38000n,
721
+ },
722
+ {
723
+ side: "short",
724
+ isLong: false,
725
+ // 200 000 USDC pool at 0.99 = 198 000 → max pnl 19 800;
726
+ // 5 BTC of short OI sold for 139 600: at the maximising 20 000 the pool owes 139 600 − 100 000 = 39 600,
727
+ // at 20 400 only 37 600
728
+ marketInfo: cappedMarket({
729
+ shortPoolAmount: expandDecimals(200000, 6),
730
+ shortInterestUsd: expandDecimals(139600, USD_DECIMALS),
731
+ shortInterestInTokens: expandDecimals(5, 8),
732
+ shortInterestUsdUsingLongToken: 0n,
733
+ shortInterestInTokensUsingLongToken: 0n,
734
+ shortInterestUsdUsingShortToken: expandDecimals(139600, USD_DECIMALS),
735
+ shortInterestInTokensUsingShortToken: expandDecimals(5, 8),
736
+ }),
737
+ // 10 000 sold at 25 000 = 0.4 BTC, bought back for 8 160 at the 20 400 max price → +1 840 raw
738
+ sizeInTokens: 40000000n,
739
+ rawPnlUsd: expandDecimals(1840, USD_DECIMALS),
740
+ // 1 840 × 19 800 / 39 600
741
+ cappedPnlUsd: expandDecimals(920, USD_DECIMALS),
742
+ // 1 840 × 19 800 / 37 600
743
+ cappedAtMinimisingPriceUsd: (expandDecimals(1840, USD_DECIMALS) * 19800n) / 37600n,
744
+ },
745
+ ])("scales a $side's profit by the pool cap taken at the price that maximises the pool's pnl", ({ isLong, marketInfo, sizeInTokens, rawPnlUsd, cappedPnlUsd, cappedAtMinimisingPriceUsd }) => {
746
+ const state = getResultingPositionMarginState({
747
+ marketInfo,
748
+ collateralToken: spreadUsdc,
749
+ sizeInUsd: expandDecimals(10000, USD_DECIMALS),
750
+ sizeInTokens,
751
+ // 1 000 USDC at 0.99
752
+ collateralAmount: expandDecimals(1000, spreadUsdc.decimals),
753
+ pendingImpactAmount: 0n,
754
+ minCollateralUsd: expandDecimals(1, USD_DECIMALS),
755
+ isLong,
756
+ userReferralInfo: undefined,
757
+ });
758
+ const collateralUsd = expandDecimals(990, USD_DECIMALS);
759
+ expect(state.remainingCollateralUsd).toBe(collateralUsd + cappedPnlUsd);
760
+ expect(state.remainingCollateralUsd).not.toBe(collateralUsd + cappedAtMinimisingPriceUsd);
761
+ expect(state.remainingCollateralUsd).not.toBe(collateralUsd + rawPnlUsd);
762
+ expect(state.isLiquidatable).toBe(false);
763
+ expect(spreadBtc.prices.minPrice).toBeLessThan(spreadBtc.prices.maxPrice);
764
+ });
765
+ });
766
+ describe("getIncreaseResultingPositionMarginState — collateral delta and impact clamp", () => {
767
+ const marketInfo = buildMarket();
768
+ const minCollateralUsd = expandDecimals(1, USD_DECIMALS);
769
+ // 10 000 of size opened at the oracle price with 1 000 USDC
770
+ const existingPosition = {
771
+ sizeInUsd: expandDecimals(10000, USD_DECIMALS),
772
+ sizeInTokens: btcAmount(10000),
773
+ collateralAmount: usdcAmount(1000),
774
+ pendingImpactAmount: 0n,
775
+ };
776
+ function sizeOnlyIncrease(collateralDeltaAmount) {
777
+ return getIncreaseResultingPositionMarginState({
778
+ marketInfo,
779
+ collateralToken: usdc,
780
+ isLong: true,
781
+ existingPosition,
782
+ sizeDeltaUsd: expandDecimals(10000, USD_DECIMALS),
783
+ sizeDeltaInTokens: btcAmount(10000),
784
+ collateralDeltaAmount,
785
+ minCollateralUsd,
786
+ userReferralInfo: undefined,
787
+ });
788
+ }
789
+ it("a negative collateralDeltaAmount is paid from the existing collateral", () => {
790
+ // 1 000 − 50, flat pnl, no fees
791
+ const state = sizeOnlyIncrease(-usdcAmount(50));
792
+ expect(state?.remainingCollateralUsd).toBe(expandDecimals(950, USD_DECIMALS));
793
+ expect(state?.isLiquidatable).toBe(false);
794
+ });
795
+ it("clamps the collateral at zero when the fees exceed it", () => {
796
+ // 1 000 − 1 100 → 0; the open-interest gate runs first and sees no collateral against
797
+ // 1% of the 20 000 of resulting size, so its reason wins over MinCollateral
798
+ const state = sizeOnlyIncrease(-usdcAmount(1100));
799
+ expect(state?.remainingCollateralUsd).toBe(0n);
800
+ expect(state?.isLiquidatable).toBe(true);
801
+ expect(state?.reason).toBe(PositionMarginFailureReason.InsufficientCollateralUsd);
802
+ });
803
+ it("the summed negative impact is clamped by maxPositionImpactFactorForLiquidations after the pending impact is added", () => {
804
+ // linear impact, shorts 30 000 vs longs 10 000: closing the 10 000 long widens the gap by 10 000
805
+ // → exit impact −2% × 10 000 = −200
806
+ const impactMarket = (maxPositionImpactFactorForLiquidations) => buildMarket({
807
+ positionImpactFactorNegative: expandDecimals(2, 28),
808
+ positionImpactExponentFactorPositive: expandDecimals(1, 30),
809
+ positionImpactExponentFactorNegative: expandDecimals(1, 30),
810
+ maxPositionImpactFactorNegative: expandDecimals(1, 29),
811
+ maxPositionImpactFactorForLiquidations,
812
+ longInterestUsd: expandDecimals(10000, USD_DECIMALS),
813
+ shortInterestUsd: expandDecimals(30000, USD_DECIMALS),
814
+ longInterestInTokens: btcAmount(10000),
815
+ shortInterestInTokens: btcAmount(30000),
816
+ useOpenInterestInTokensForBalance: false,
817
+ });
818
+ const run = (maxPositionImpactFactorForLiquidations) => getResultingPositionMarginState({
819
+ marketInfo: impactMarket(maxPositionImpactFactorForLiquidations),
820
+ collateralToken: usdc,
821
+ sizeInUsd: expandDecimals(10000, USD_DECIMALS),
822
+ sizeInTokens: btcAmount(10000),
823
+ collateralAmount: usdcAmount(1000),
824
+ // −300 USD at the 20 000 index price = −0.015 BTC
825
+ pendingImpactAmount: -1500000n,
826
+ minCollateralUsd,
827
+ isLong: true,
828
+ userReferralInfo: undefined,
829
+ });
830
+ // −300 − 200 = −500, clamped at 1% of 10 000 → 1 000 − 100
831
+ expect(run(expandDecimals(1, 28)).remainingCollateralUsd).toBe(expandDecimals(900, USD_DECIMALS));
832
+ // with a 10% cap the whole −500 goes through
833
+ expect(run(expandDecimals(1, 29)).remainingCollateralUsd).toBe(expandDecimals(500, USD_DECIMALS));
834
+ });
835
+ });