@gmx-io/sdk 2.2.1 → 2.3.2

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 (31) hide show
  1. package/build/cjs/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +32 -0
  2. package/build/cjs/src/codegen/prebuilt/hashedMarketConfigKeys.json +272 -0
  3. package/build/cjs/src/codegen/prebuilt/hashedMarketValuesKeys.json +60 -0
  4. package/build/cjs/src/configs/markets.js +28 -0
  5. package/build/cjs/src/test/mock.js +32 -4
  6. package/build/cjs/src/utils/markets/utils.js +45 -1
  7. package/build/cjs/src/utils/trade/__tests__/increaseMarginCheck.spec.js +14 -35
  8. package/build/cjs/src/utils/trade/__tests__/twapIncreaseMarginCheck.spec.js +368 -0
  9. package/build/cjs/src/utils/trade/increaseMarginCheck.js +27 -13
  10. package/build/cjs/src/utils/trade/twapIncreaseMarginCheck.js +180 -0
  11. package/build/cjs/src/utils/twap/index.js +13 -4
  12. package/build/esm/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +32 -0
  13. package/build/esm/src/codegen/prebuilt/hashedMarketConfigKeys.json +272 -0
  14. package/build/esm/src/codegen/prebuilt/hashedMarketValuesKeys.json +60 -0
  15. package/build/esm/src/configs/markets.js +28 -0
  16. package/build/esm/src/test/mock.js +27 -0
  17. package/build/esm/src/utils/markets/utils.js +44 -1
  18. package/build/esm/src/utils/trade/__tests__/increaseMarginCheck.spec.js +15 -36
  19. package/build/esm/src/utils/trade/__tests__/twapIncreaseMarginCheck.spec.js +366 -0
  20. package/build/esm/src/utils/trade/increaseMarginCheck.js +24 -11
  21. package/build/esm/src/utils/trade/twapIncreaseMarginCheck.js +172 -0
  22. package/build/esm/src/utils/twap/index.js +10 -3
  23. package/build/tsconfig.tsbuildinfo +1 -1
  24. package/build/types/src/codegen/prebuilt/index.d.ts +364 -0
  25. package/build/types/src/test/mock.d.ts +5 -0
  26. package/build/types/src/utils/markets/utils.d.ts +3 -0
  27. package/build/types/src/utils/trade/__tests__/twapIncreaseMarginCheck.spec.d.ts +1 -0
  28. package/build/types/src/utils/trade/increaseMarginCheck.d.ts +15 -7
  29. package/build/types/src/utils/trade/twapIncreaseMarginCheck.d.ts +50 -0
  30. package/build/types/src/utils/twap/index.d.ts +2 -0
  31. package/package.json +10 -1
@@ -890,6 +890,34 @@ export const MARKETS = {
890
890
  longTokenAddress: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
891
891
  shortTokenAddress: "0x004B506865409877C9fA29bfb1ebA929984B9bbC",
892
892
  },
893
+ // NEAR/USD [USDG-USDG]
894
+ "0x54bc430A788DFFD4ae35e751E10899489f5a953f": {
895
+ marketTokenAddress: "0x54bc430A788DFFD4ae35e751E10899489f5a953f",
896
+ indexTokenAddress: "0x1FF7F3EFBb9481Cbd7db4F932cBCD4467144237C",
897
+ longTokenAddress: "0x004B506865409877C9fA29bfb1ebA929984B9bbC",
898
+ shortTokenAddress: "0x004B506865409877C9fA29bfb1ebA929984B9bbC",
899
+ },
900
+ // XRP/USD [USDG-USDG]
901
+ "0xc9ED746D613eEfC0F196658f6030e90482593004": {
902
+ marketTokenAddress: "0xc9ED746D613eEfC0F196658f6030e90482593004",
903
+ indexTokenAddress: "0xc14e065b0067dE91534e032868f5Ac6ecf2c6868",
904
+ longTokenAddress: "0x004B506865409877C9fA29bfb1ebA929984B9bbC",
905
+ shortTokenAddress: "0x004B506865409877C9fA29bfb1ebA929984B9bbC",
906
+ },
907
+ // ZEC/USD [USDG-USDG]
908
+ "0x2CeEafcA180B07C9d1d2f1086f8f59AAFd282832": {
909
+ marketTokenAddress: "0x2CeEafcA180B07C9d1d2f1086f8f59AAFd282832",
910
+ indexTokenAddress: "0x6eAbbaA3278556Dc5b19c034dc26c0eaB60d65B5",
911
+ longTokenAddress: "0x004B506865409877C9fA29bfb1ebA929984B9bbC",
912
+ shortTokenAddress: "0x004B506865409877C9fA29bfb1ebA929984B9bbC",
913
+ },
914
+ // HYPE/USD [USDG-USDG]
915
+ "0x162C091263fBb3dfAf1D55DCC979533EB341DA5f": {
916
+ marketTokenAddress: "0x162C091263fBb3dfAf1D55DCC979533EB341DA5f",
917
+ indexTokenAddress: "0xfDFA0A749dA3bCcee20aE0B4AD50E39B26F58f7C",
918
+ longTokenAddress: "0x004B506865409877C9fA29bfb1ebA929984B9bbC",
919
+ shortTokenAddress: "0x004B506865409877C9fA29bfb1ebA929984B9bbC",
920
+ },
893
921
  },
894
922
  [AVALANCHE]: {
895
923
  // BTC/USD [BTC-USDC]
@@ -1,4 +1,5 @@
1
1
  import { USD_DECIMALS } from "../configs/factors";
2
+ import { mockMarketsInfoData } from "../utils/markets/__tests__/mockMarkets";
2
3
  import { expandDecimals } from "../utils/numbers";
3
4
  import { convertToTokenAmount } from "../utils/tokens";
4
5
  import { ExternalSwapAggregator } from "../utils/trade/types";
@@ -129,6 +130,32 @@ export function mockTokensData(overrides = {}) {
129
130
  * @param marketKeys - array of market keys in the following format: indexToken-longToken-shortToken
130
131
  */
131
132
  export { mockMarketsData, mockMarketsInfoData } from "../utils/markets/__tests__/mockMarkets";
133
+ /**
134
+ * A BTC market with a 1% min collateral factor (100x) and 0.5% for liquidation.
135
+ * Fees, price impact and open interest are off unless overridden.
136
+ */
137
+ export function mockMarginCheckMarketInfo(tokensData, overrides = {}) {
138
+ return mockMarketsInfoData(tokensData, ["BTC-BTC-USDC"], {
139
+ "BTC-BTC-USDC": {
140
+ minCollateralFactor: expandDecimals(1, 28),
141
+ minCollateralFactorForLiquidation: expandDecimals(5, 27),
142
+ minCollateralFactorForOpenInterestLong: 0n,
143
+ minCollateralFactorForOpenInterestShort: 0n,
144
+ positionFeeFactorForBalanceWasImproved: 0n,
145
+ positionFeeFactorForBalanceWasNotImproved: 0n,
146
+ positionImpactFactorPositive: 0n,
147
+ positionImpactFactorNegative: 0n,
148
+ maxPositionImpactFactorPositive: 0n,
149
+ maxPositionImpactFactorNegative: 0n,
150
+ maxPositionImpactFactorForLiquidations: 0n,
151
+ longInterestUsd: 0n,
152
+ shortInterestUsd: 0n,
153
+ longInterestInTokens: 0n,
154
+ shortInterestInTokens: 0n,
155
+ ...overrides,
156
+ },
157
+ })["BTC-BTC-USDC"];
158
+ }
132
159
  export function mockExternalSwap({ inToken, outToken, amountIn, amountOut, priceIn, priceOut, feesUsd = expandDecimals(5, USD_DECIMALS), // $5 default fee
133
160
  data = "0x1", to = "0x6352a56caadC4F1E25CD6c75970Fa768A3304e64", receiver = "0x1234567890123456789012345678901234567890", }) {
134
161
  const usdIn = (amountIn * priceIn) / expandDecimals(1, inToken.decimals);
@@ -3,7 +3,7 @@ import { BASIS_POINTS_DIVISOR, BASIS_POINTS_DIVISOR_BIGINT } from "../../configs
3
3
  import { UI_MAX_LEVERAGE_BY_MARKET } from "../../configs/markets";
4
4
  import { convertTokenAddress, getTokenVisualMultiplier, NATIVE_TOKEN_ADDRESS } from "../../configs/tokens";
5
5
  import { bigMath } from "../bigmath";
6
- import { getBorrowingFactorPerPeriod, getFundingFactorPerPeriod } from "../fees";
6
+ import { applySwapImpactWithCap, getBorrowingFactorPerPeriod, getFundingFactorPerPeriod } from "../fees";
7
7
  import { applyFactor, expandDecimals, PRECISION } from "../numbers";
8
8
  import { getByKey } from "../objects";
9
9
  import { periodToSeconds } from "../time";
@@ -309,6 +309,49 @@ export function getMarketInfoWithOpenInterestDelta({ marketInfo, collateralToken
309
309
  }
310
310
  return next;
311
311
  }
312
+ /** The market a swap step leaves: the pools and the swap impact pools move as in `SwapUtils._swap`. */
313
+ export function getMarketInfoWithSwapDelta(marketInfo, swapStep) {
314
+ const isLongTokenIn = getTokenPoolType(marketInfo, swapStep.tokenInAddress) === "long";
315
+ const tokenIn = isLongTokenIn ? marketInfo.longToken : marketInfo.shortToken;
316
+ const tokenOut = isLongTokenIn ? marketInfo.shortToken : marketInfo.longToken;
317
+ let poolAmountIn = swapStep.amountInAfterFees;
318
+ let poolAmountOut = swapStep.amountOut;
319
+ let impactPoolDeltaIn = 0n;
320
+ let impactPoolDeltaOut = 0n;
321
+ if (swapStep.priceImpactDeltaUsd > 0n) {
322
+ const { impactDeltaAmount, cappedDiffUsd } = applySwapImpactWithCap(marketInfo, tokenOut, swapStep.priceImpactDeltaUsd);
323
+ poolAmountOut -= impactDeltaAmount;
324
+ impactPoolDeltaOut = -impactDeltaAmount;
325
+ if (cappedDiffUsd > 0n) {
326
+ const tokenInImpactAmount = applySwapImpactWithCap(marketInfo, tokenIn, cappedDiffUsd).impactDeltaAmount;
327
+ poolAmountIn += tokenInImpactAmount;
328
+ impactPoolDeltaIn = -tokenInImpactAmount;
329
+ }
330
+ }
331
+ else if (swapStep.priceImpactDeltaUsd < 0n) {
332
+ const { impactDeltaAmount } = applySwapImpactWithCap(marketInfo, tokenIn, swapStep.priceImpactDeltaUsd);
333
+ poolAmountIn += impactDeltaAmount;
334
+ impactPoolDeltaIn = -impactDeltaAmount;
335
+ }
336
+ const [longDelta, shortDelta] = isLongTokenIn ? [poolAmountIn, -poolAmountOut] : [-poolAmountOut, poolAmountIn];
337
+ const [longImpactDelta, shortImpactDelta] = isLongTokenIn
338
+ ? [impactPoolDeltaIn, impactPoolDeltaOut]
339
+ : [impactPoolDeltaOut, impactPoolDeltaIn];
340
+ const next = {
341
+ ...marketInfo,
342
+ longPoolAmount: marketInfo.longPoolAmount + longDelta,
343
+ shortPoolAmount: marketInfo.shortPoolAmount + shortDelta,
344
+ swapImpactPoolAmountLong: marketInfo.swapImpactPoolAmountLong + longImpactDelta,
345
+ swapImpactPoolAmountShort: marketInfo.swapImpactPoolAmountShort + shortImpactDelta,
346
+ };
347
+ if (marketInfo.virtualPoolAmountForLongToken > 0n) {
348
+ next.virtualPoolAmountForLongToken = marketInfo.virtualPoolAmountForLongToken + longDelta;
349
+ }
350
+ if (marketInfo.virtualPoolAmountForShortToken > 0n) {
351
+ next.virtualPoolAmountForShortToken = marketInfo.virtualPoolAmountForShortToken + shortDelta;
352
+ }
353
+ return next;
354
+ }
312
355
  export function getOpenInterestForBalance(marketInfo, isLong) {
313
356
  if (marketInfo.useOpenInterestInTokensForBalance) {
314
357
  const interestInTokens = isLong ? marketInfo.longInterestInTokens : marketInfo.shortInterestInTokens;
@@ -1,34 +1,11 @@
1
1
  import { describe, expect, it } from "vitest";
2
- import { mockMarketsInfoData, mockTokensData } from "../../../test/mock";
2
+ import { mockMarginCheckMarketInfo, mockMarketsInfoData, mockTokensData } from "../../../test/mock";
3
3
  import { getMarketInfoWithOpenInterestDelta } from "../../markets";
4
4
  import { USD_DECIMALS, expandDecimals } from "../../numbers";
5
5
  import { convertToTokenAmount, convertToTokenAmountForIncrease, convertToUsd } from "../../tokens";
6
6
  import { PositionMarginFailureReason, getIncreaseResultingPositionMarginState, getIsMaxLeverageMarginReason, getResultingPositionMarginState, } from "../increaseMarginCheck";
7
7
  const BTC_PRICE = expandDecimals(20000, 30);
8
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
9
  const usdc = tokensData.USDC;
33
10
  function usdcAmount(usd) {
34
11
  return convertToTokenAmount(usd10(usd), usdc.decimals, usdc.prices.minPrice);
@@ -42,7 +19,7 @@ function btcAmount(usd) {
42
19
  }
43
20
  function baseParams(overrides = {}) {
44
21
  return {
45
- marketInfo: buildMarket(),
22
+ marketInfo: mockMarginCheckMarketInfo(tokensData),
46
23
  collateralToken: usdc,
47
24
  // 10 000 USD of size bought exactly at the oracle price → zero pnl
48
25
  sizeInUsd: expandDecimals(10000, USD_DECIMALS),
@@ -110,7 +87,7 @@ describe("getResultingPositionMarginState", () => {
110
87
  it("deducts the full-close position fee once", () => {
111
88
  // 0.5% closing fee on 10 000 = 50
112
89
  const state = getResultingPositionMarginState(baseParams({
113
- marketInfo: buildMarket({
90
+ marketInfo: mockMarginCheckMarketInfo(tokensData, {
114
91
  positionFeeFactorForBalanceWasImproved: expandDecimals(5, 27),
115
92
  positionFeeFactorForBalanceWasNotImproved: expandDecimals(5, 27),
116
93
  }),
@@ -122,7 +99,7 @@ describe("getResultingPositionMarginState", () => {
122
99
  // 0.5% closing fee on 10 000 = 50; a 50% pro discount returns 25 of it
123
100
  const state = getResultingPositionMarginState({
124
101
  ...baseParams({
125
- marketInfo: buildMarket({
102
+ marketInfo: mockMarginCheckMarketInfo(tokensData, {
126
103
  positionFeeFactorForBalanceWasImproved: expandDecimals(5, 27),
127
104
  positionFeeFactorForBalanceWasNotImproved: expandDecimals(5, 27),
128
105
  }),
@@ -133,7 +110,7 @@ describe("getResultingPositionMarginState", () => {
133
110
  });
134
111
  it("takes the larger of the pro and referral discounts, not their sum", () => {
135
112
  const params = baseParams({
136
- marketInfo: buildMarket({
113
+ marketInfo: mockMarginCheckMarketInfo(tokensData, {
137
114
  positionFeeFactorForBalanceWasImproved: expandDecimals(5, 27),
138
115
  positionFeeFactorForBalanceWasNotImproved: expandDecimals(5, 27),
139
116
  }),
@@ -160,9 +137,11 @@ describe("getResultingPositionMarginState", () => {
160
137
  });
161
138
  });
162
139
  describe("getIncreaseResultingPositionMarginState", () => {
163
- const marketInfo = buildMarket();
140
+ const marketInfo = mockMarginCheckMarketInfo(tokensData);
164
141
  // the contract clamps negative impact at maxPositionImpactFactorForLiquidations — 1% of size here
165
- const marketWithImpactCap = buildMarket({ maxPositionImpactFactorForLiquidations: expandDecimals(1, 28) });
142
+ const marketWithImpactCap = mockMarginCheckMarketInfo(tokensData, {
143
+ maxPositionImpactFactorForLiquidations: expandDecimals(1, 28),
144
+ });
166
145
  it("returns undefined when there is no size to validate", () => {
167
146
  expect(getIncreaseResultingPositionMarginState({
168
147
  marketInfo,
@@ -235,7 +214,7 @@ describe("getIncreaseResultingPositionMarginState", () => {
235
214
  // shorts dominate, so increasing a long is a same-side rebalance towards balance for the
236
215
  // close leg (positive close impact, clamped away) while the increase leg pays negative
237
216
  // impact that is stored as pending impact on the position
238
- const imbalancedMarket = buildMarket({
217
+ const imbalancedMarket = mockMarginCheckMarketInfo(tokensData, {
239
218
  maxPositionImpactFactorForLiquidations: expandDecimals(1, 28),
240
219
  positionImpactFactorNegative: expandDecimals(1, 22),
241
220
  positionImpactExponentFactorPositive: expandDecimals(2, 30),
@@ -332,7 +311,7 @@ describe("getIncreaseResultingPositionMarginState — open interest projection",
332
311
  // linear impact (exponent 1) keeps every leg a round number:
333
312
  // a crossover pays factorNegative on the side it lands on and earns factorPositive on the side it leaves
334
313
  function impactMarket(useOpenInterestInTokensForBalance) {
335
- return buildMarket({
314
+ return mockMarginCheckMarketInfo(tokensData, {
336
315
  positionImpactFactorPositive: expandDecimals(1, 27), // 0.1%
337
316
  positionImpactFactorNegative: expandDecimals(3, 27), // 0.3%
338
317
  positionImpactExponentFactorPositive: expandDecimals(1, 30),
@@ -492,7 +471,7 @@ describe("getIncreaseResultingPositionMarginState — open-interest min collater
492
471
  const OI_MULTIPLIER = expandDecimals(2, 22);
493
472
  function gateArgs(collateralUsd, marketOverrides = {}) {
494
473
  return {
495
- marketInfo: buildMarket({
474
+ marketInfo: mockMarginCheckMarketInfo(tokensData, {
496
475
  minCollateralFactorForOpenInterestLong: OI_MULTIPLIER,
497
476
  longInterestUsd: expandDecimals(990000, USD_DECIMALS),
498
477
  ...marketOverrides,
@@ -534,7 +513,7 @@ describe("getIncreaseResultingPositionMarginState — open-interest min collater
534
513
  });
535
514
  });
536
515
  describe("getIncreaseResultingPositionMarginState — evaluation at the trigger price", () => {
537
- const marketInfo = buildMarket();
516
+ const marketInfo = mockMarginCheckMarketInfo(tokensData);
538
517
  const minCollateralUsd = expandDecimals(1, USD_DECIMALS);
539
518
  // existing long opened at the current price (20 000): flat pnl at current prices
540
519
  const existingPosition = {
@@ -764,7 +743,7 @@ describe("pool pnl cap — profitable position while the cap binds, min < max",
764
743
  });
765
744
  });
766
745
  describe("getIncreaseResultingPositionMarginState — collateral delta and impact clamp", () => {
767
- const marketInfo = buildMarket();
746
+ const marketInfo = mockMarginCheckMarketInfo(tokensData);
768
747
  const minCollateralUsd = expandDecimals(1, USD_DECIMALS);
769
748
  // 10 000 of size opened at the oracle price with 1 000 USDC
770
749
  const existingPosition = {
@@ -803,7 +782,7 @@ describe("getIncreaseResultingPositionMarginState — collateral delta and impac
803
782
  it("the summed negative impact is clamped by maxPositionImpactFactorForLiquidations after the pending impact is added", () => {
804
783
  // linear impact, shorts 30 000 vs longs 10 000: closing the 10 000 long widens the gap by 10 000
805
784
  // → exit impact −2% × 10 000 = −200
806
- const impactMarket = (maxPositionImpactFactorForLiquidations) => buildMarket({
785
+ const impactMarket = (maxPositionImpactFactorForLiquidations) => mockMarginCheckMarketInfo(tokensData, {
807
786
  positionImpactFactorNegative: expandDecimals(2, 28),
808
787
  positionImpactExponentFactorPositive: expandDecimals(1, 30),
809
788
  positionImpactExponentFactorNegative: expandDecimals(1, 30),
@@ -0,0 +1,366 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { mockMarginCheckMarketInfo, mockTokensData, usdToToken } from "../../../test/mock";
3
+ import { bigMath } from "../../bigmath";
4
+ import { getBorrowingFeeRateUsd } from "../../fees";
5
+ import { getMarketInfoWithSwapDelta } from "../../markets";
6
+ import { USD_DECIMALS, expandDecimals } from "../../numbers";
7
+ import { SwapPricingType } from "../../orders/types";
8
+ import { getSwapPathStats } from "../../swap/swapStats";
9
+ import { convertToUsd } from "../../tokens";
10
+ import { PositionMarginFailureReason, getIncreaseResultingPositionMarginState, getIncreaseResultingPositionState, getIsMaxLeverageMarginReason, } from "../increaseMarginCheck";
11
+ import { getTwapIncreasePartsGrossCollateralUsd, getTwapIncreaseSequentialMarginState, } from "../twapIncreaseMarginCheck";
12
+ import { getTwapPartDelaysSeconds } from "../../twap";
13
+ const tokensData = mockTokensData();
14
+ const usdc = tokensData.USDC;
15
+ function usd(amount) {
16
+ return expandDecimals(amount, USD_DECIMALS);
17
+ }
18
+ /** A position of `sizeUsd` whose tokens are worth `valueUsd` at the oracle: the loss is the difference. */
19
+ function position({ sizeUsd, valueUsd, collateralUsd }) {
20
+ return {
21
+ sizeInUsd: usd(sizeUsd),
22
+ sizeInTokens: usdToToken(valueUsd, tokensData.BTC),
23
+ collateralAmount: usdToToken(collateralUsd, usdc),
24
+ pendingImpactAmount: 0n,
25
+ };
26
+ }
27
+ const HOUR = 3600;
28
+ // parts spaced an hour apart, the first one executable now
29
+ function hourlyDelays(numberOfParts) {
30
+ return getTwapPartDelaysSeconds({ hours: numberOfParts - 1, minutes: 0 }, numberOfParts);
31
+ }
32
+ // a 50x position of 10 000 on 200 of collateral, topped up by four parts of 25 each
33
+ function baseParams({ partGrossCollateralUsd = usd(25), ...overrides } = {}) {
34
+ const numberOfParts = overrides.numberOfParts ?? 4;
35
+ return {
36
+ marketInfo: mockMarginCheckMarketInfo(tokensData),
37
+ collateralToken: usdc,
38
+ isLong: true,
39
+ existingPosition: position({ sizeUsd: 10000, valueUsd: 10000, collateralUsd: 200 }),
40
+ numberOfParts,
41
+ partDelaysSeconds: hourlyDelays(numberOfParts),
42
+ partGrossCollateralUsds: Array.from({ length: numberOfParts }, () => partGrossCollateralUsd),
43
+ partSizeDeltaUsd: usd(10000),
44
+ pendingFeesUsd: 0n,
45
+ uiFeeFactor: 0n,
46
+ minCollateralUsd: usd(1),
47
+ userReferralInfo: undefined,
48
+ ...overrides,
49
+ };
50
+ }
51
+ describe("getTwapIncreaseSequentialMarginState", () => {
52
+ describe.each([
53
+ { side: "long", isLong: true },
54
+ { side: "short", isLong: false },
55
+ ])("$side", ({ isLong }) => {
56
+ // after part k the position holds 10 000 + k × size on 200 + k × 25 of collateral against a 1% minimum
57
+ it.each([
58
+ {
59
+ name: "every part stays within the max leverage",
60
+ partSizeUsd: 1000,
61
+ partDelaysSeconds: hourlyDelays(4),
62
+ failingPartIndex: undefined,
63
+ blocking: false,
64
+ },
65
+ {
66
+ name: "a later part crosses the max leverage",
67
+ partSizeUsd: 10000,
68
+ partDelaysSeconds: hourlyDelays(4),
69
+ failingPartIndex: 1,
70
+ blocking: false,
71
+ },
72
+ {
73
+ name: "the first part crosses the max leverage",
74
+ partSizeUsd: 20000,
75
+ partDelaysSeconds: hourlyDelays(4),
76
+ failingPartIndex: 0,
77
+ blocking: true,
78
+ },
79
+ {
80
+ name: "a zero duration makes the crossing part eligible now",
81
+ partSizeUsd: 10000,
82
+ partDelaysSeconds: [0, 0, 0, 0],
83
+ failingPartIndex: 1,
84
+ blocking: true,
85
+ },
86
+ ])("$name", ({ partSizeUsd, partDelaysSeconds, failingPartIndex, blocking }) => {
87
+ const state = getTwapIncreaseSequentialMarginState(baseParams({ isLong, partSizeDeltaUsd: usd(partSizeUsd), partDelaysSeconds }));
88
+ expect(state.failingPartIndex).toBe(failingPartIndex);
89
+ expect(state.isFailingPartEligibleNow).toBe(blocking);
90
+ expect(state.marginState.isLiquidatable).toBe(failingPartIndex !== undefined);
91
+ if (failingPartIndex !== undefined) {
92
+ expect(getIsMaxLeverageMarginReason(state.marginState.reason)).toBe(true);
93
+ }
94
+ });
95
+ });
96
+ it("settles the existing position's pending fees once, with the first part", () => {
97
+ // 500 of collateral plus 100 deposited across the parts, less 40 of pending fees, leaves 560 whatever the split
98
+ const remaining = [1, 2, 4].map((numberOfParts) => getTwapIncreaseSequentialMarginState(baseParams({
99
+ existingPosition: position({ sizeUsd: 10000, valueUsd: 10000, collateralUsd: 500 }),
100
+ numberOfParts,
101
+ partSizeDeltaUsd: usd(4000 / numberOfParts),
102
+ partGrossCollateralUsd: usd(100 / numberOfParts),
103
+ pendingFeesUsd: usd(40),
104
+ })).marginState.remainingCollateralUsd);
105
+ expect(remaining).toEqual([usd(560), usd(560), usd(560)]);
106
+ });
107
+ it("charges every part the open interest left by the parts before it", () => {
108
+ // 1e-8 of min collateral per usd of long open interest: 1% at the 1M already open
109
+ const marketInfo = mockMarginCheckMarketInfo(tokensData, {
110
+ minCollateralFactorForOpenInterestLong: expandDecimals(1, 22),
111
+ longInterestUsd: usd(1000000),
112
+ longInterestInTokens: usdToToken(1000000, tokensData.BTC),
113
+ });
114
+ const part = {
115
+ sizeDeltaUsd: usd(250000),
116
+ sizeDeltaInTokens: usdToToken(250000, tokensData.BTC),
117
+ collateralDeltaAmount: usdToToken(4000, usdc),
118
+ };
119
+ const state = getTwapIncreaseSequentialMarginState(baseParams({
120
+ marketInfo,
121
+ existingPosition: undefined,
122
+ partSizeDeltaUsd: part.sizeDeltaUsd,
123
+ partGrossCollateralUsd: usd(4000),
124
+ }));
125
+ // parts 1 and 2 clear 1.25% and 1.5% of their cumulative size; part 3 needs 1.75% of 750 000 = 13 125 on 12 000
126
+ expect(state.failingPartIndex).toBe(2);
127
+ expect(state.marginState.reason).toBe(PositionMarginFailureReason.InsufficientCollateralUsd);
128
+ const standalone = getIncreaseResultingPositionMarginState({
129
+ marketInfo,
130
+ collateralToken: usdc,
131
+ isLong: true,
132
+ existingPosition: undefined,
133
+ ...part,
134
+ minCollateralUsd: usd(1),
135
+ userReferralInfo: undefined,
136
+ });
137
+ expect(standalone?.isLiquidatable).toBe(false);
138
+ });
139
+ it("counts the existing position's unrealized loss against the remaining margin of later parts", () => {
140
+ // four parts of 5 000 on 25 of collateral each; 2 350 of loss on 2 500 of collateral
141
+ const parts = { partSizeDeltaUsd: usd(5000), partGrossCollateralUsd: usd(25) };
142
+ const flat = getTwapIncreaseSequentialMarginState(baseParams({ ...parts, existingPosition: position({ sizeUsd: 10000, valueUsd: 10000, collateralUsd: 2500 }) }));
143
+ const losing = getTwapIncreaseSequentialMarginState(baseParams({ ...parts, existingPosition: position({ sizeUsd: 10000, valueUsd: 7650, collateralUsd: 2500 }) }));
144
+ expect(flat.failingPartIndex).toBeUndefined();
145
+ // 150 + 25 × k of remaining margin against 1% of 10 000 + 5 000 × k: the third part is the first short of it
146
+ expect(losing.failingPartIndex).toBe(2);
147
+ expect(losing.marginState.reason).toBe(PositionMarginFailureReason.MinCollateralForLeverage);
148
+ });
149
+ it("carries each part's price impact into the next part without double counting", () => {
150
+ const marketInfo = mockMarginCheckMarketInfo(tokensData, {
151
+ positionImpactFactorPositive: expandDecimals(5, 22),
152
+ positionImpactFactorNegative: expandDecimals(1, 23),
153
+ maxPositionImpactFactorNegative: expandDecimals(1, 28),
154
+ maxPositionImpactFactorForLiquidations: expandDecimals(1, 28),
155
+ });
156
+ const parts = { existingPosition: undefined, partSizeDeltaUsd: usd(50000), partGrossCollateralUsd: usd(5000) };
157
+ const split = getTwapIncreaseSequentialMarginState(baseParams({ ...parts, marketInfo }));
158
+ const noImpact = getTwapIncreaseSequentialMarginState(baseParams(parts));
159
+ const aggregate = getIncreaseResultingPositionState({
160
+ marketInfo,
161
+ collateralToken: usdc,
162
+ isLong: true,
163
+ existingPosition: undefined,
164
+ sizeDeltaUsd: usd(200000),
165
+ sizeDeltaInTokens: usdToToken(200000, tokensData.BTC),
166
+ collateralDeltaAmount: usdToToken(20000, usdc),
167
+ minCollateralUsd: usd(1),
168
+ userReferralInfo: undefined,
169
+ });
170
+ expect(aggregate.position.pendingImpactAmount).toBeLessThan(0n);
171
+ expect(split.marginState.remainingCollateralUsd).toBeLessThan(noImpact.marginState.remainingCollateralUsd);
172
+ // the impact of four steps through the same open interest telescopes to the one-shot impact, up to rounding
173
+ expect(bigMath.abs(split.marginState.remainingCollateralUsd - aggregate.marginState.remainingCollateralUsd)).toBeLessThan(expandDecimals(1, 28));
174
+ });
175
+ });
176
+ describe("getTwapIncreaseSequentialMarginState — the market's max allowed leverage", () => {
177
+ // 0.5% for both factors: the contract accepts up to 200x, the ui caps an order's resulting position at 100x
178
+ const capOnlyMarket = mockMarginCheckMarketInfo(tokensData, { minCollateralFactor: expandDecimals(5, 27) });
179
+ it.each([
180
+ {
181
+ name: "a fresh position's first part at 150x",
182
+ existingPosition: undefined,
183
+ partSizeUsd: 3750,
184
+ failingPartIndex: 0,
185
+ isFailingPartEligibleNow: true,
186
+ },
187
+ {
188
+ // 30 800 of size on 300 of collateral after the fourth part: 102.7x
189
+ name: "the last part on a 50x position",
190
+ existingPosition: position({ sizeUsd: 10000, valueUsd: 10000, collateralUsd: 200 }),
191
+ partSizeUsd: 5200,
192
+ failingPartIndex: 3,
193
+ isFailingPartEligibleNow: false,
194
+ },
195
+ ].flatMap((row) => [
196
+ { ...row, side: "long", isLong: true },
197
+ { ...row, side: "short", isLong: false },
198
+ ]))("fails $name ($side) that the contract would accept", ({ existingPosition, partSizeUsd, isLong, failingPartIndex, isFailingPartEligibleNow }) => {
199
+ const state = getTwapIncreaseSequentialMarginState(baseParams({ marketInfo: capOnlyMarket, isLong, existingPosition, partSizeDeltaUsd: usd(partSizeUsd) }));
200
+ expect(state).toMatchObject({ failingPartIndex, isFailingPartEligibleNow });
201
+ expect(state.marginState.reason).toBe(PositionMarginFailureReason.MaxAllowedLeverage);
202
+ expect(getIsMaxLeverageMarginReason(state.marginState.reason)).toBe(true);
203
+ expect(state.contractMarginState.isLiquidatable).toBe(false);
204
+ });
205
+ });
206
+ describe("getTwapIncreaseSequentialMarginState — fees accrued between the parts PRO-4134", () => {
207
+ // 2e-8 of borrowing per second: 1 h on 10 000 of size costs 0.72
208
+ const borrowingMarket = mockMarginCheckMarketInfo(tokensData, {
209
+ borrowingFactorPerSecondForLongs: expandDecimals(2, 22),
210
+ borrowingFactorPerSecondForShorts: expandDecimals(2, 22),
211
+ });
212
+ // four parts of 7 500 on 25 each: the second part lands exactly on the 1% minimum (250 on 25 000)
213
+ const edgeParts = { partSizeDeltaUsd: usd(7500), partGrossCollateralUsd: usd(25) };
214
+ it("settles the borrowing accrued since the previous part at the snapshot rate", () => {
215
+ const parts = { existingPosition: undefined, partSizeDeltaUsd: usd(5000), partGrossCollateralUsd: usd(500) };
216
+ const noDelay = getTwapIncreaseSequentialMarginState(baseParams({ ...parts, marketInfo: borrowingMarket, partDelaysSeconds: [0, 0, 0, 0] }));
217
+ const hourly = getTwapIncreaseSequentialMarginState(baseParams({ ...parts, marketInfo: borrowingMarket }));
218
+ // parts 2–4 each pay an hour of borrowing on the size the previous parts left: 5 000, 10 000, 15 000
219
+ const accruedUsd = [5000, 10000, 15000].reduce((sum, sizeUsd) => sum + getBorrowingFeeRateUsd(borrowingMarket, true, usd(sizeUsd), BigInt(HOUR)), 0n);
220
+ expect(accruedUsd).toBe(usd(216) / 100n);
221
+ expect(noDelay.marginState.remainingCollateralUsd - hourly.marginState.remainingCollateralUsd).toBe(accruedUsd);
222
+ });
223
+ it("fails a later part that passes at the snapshot once the borrowing before it is settled", () => {
224
+ const atSnapshot = getTwapIncreaseSequentialMarginState(baseParams({ ...edgeParts, marketInfo: borrowingMarket, partDelaysSeconds: [0, 0, 0, 0] }));
225
+ const hourly = getTwapIncreaseSequentialMarginState(baseParams({ ...edgeParts, marketInfo: borrowingMarket }));
226
+ expect(atSnapshot.failingPartIndex).toBe(2);
227
+ expect(hourly).toMatchObject({ failingPartIndex: 1, isFailingPartEligibleNow: false });
228
+ // 1.26 of borrowing on 17 500 pushes the part past both the 100x cap and the contract's 1% minimum
229
+ expect(getIsMaxLeverageMarginReason(hourly.marginState.reason)).toBe(true);
230
+ expect(hourly.contractMarginState.isLiquidatable).toBe(true);
231
+ expect(getIsMaxLeverageMarginReason(hourly.contractMarginState.reason)).toBe(true);
232
+ });
233
+ it("charges the existing position for the wait before a first part that is not executable yet", () => {
234
+ const delays = hourlyDelays(4);
235
+ const now = getTwapIncreaseSequentialMarginState(baseParams({ ...edgeParts, marketInfo: borrowingMarket }));
236
+ const inAnHour = getTwapIncreaseSequentialMarginState(baseParams({ ...edgeParts, marketInfo: borrowingMarket, partDelaysSeconds: delays.map((d) => d + HOUR) }));
237
+ expect(inAnHour.isFailingPartEligibleNow).toBe(false);
238
+ expect(now.marginState.remainingCollateralUsd - inAnHour.marginState.remainingCollateralUsd).toBe(getBorrowingFeeRateUsd(borrowingMarket, true, usd(10000), BigInt(HOUR)));
239
+ });
240
+ it("settles funding only for the side that pays it", () => {
241
+ // longs pay 1e-8 per second; the market needs open interest on both sides to split the funding
242
+ const fundingMarket = (longsPayShorts) => mockMarginCheckMarketInfo(tokensData, {
243
+ fundingFactorPerSecond: expandDecimals(1, 22),
244
+ longsPayShorts,
245
+ longInterestUsd: usd(1000000),
246
+ shortInterestUsd: usd(1000000),
247
+ longInterestInTokens: usdToToken(1000000, tokensData.BTC),
248
+ shortInterestInTokens: usdToToken(1000000, tokensData.BTC),
249
+ });
250
+ const parts = { existingPosition: undefined, partSizeDeltaUsd: usd(5000), partGrossCollateralUsd: usd(500) };
251
+ const remaining = (longsPayShorts) => getTwapIncreaseSequentialMarginState(baseParams({ ...parts, marketInfo: fundingMarket(longsPayShorts) }))
252
+ .marginState.remainingCollateralUsd;
253
+ // paying: an hour on 5 000 + 10 000 + 15 000 at 1e-8/s = 1.08; receiving: nothing leaves the collateral
254
+ expect(remaining(false) - remaining(true)).toBe(usd(108) / 100n);
255
+ expect(remaining(false)).toBe(getTwapIncreaseSequentialMarginState(baseParams(parts)).marginState.remainingCollateralUsd);
256
+ });
257
+ });
258
+ describe("getTwapIncreasePartsGrossCollateralUsd — each part swaps its own deposit PRO-4134", () => {
259
+ const NO_NATIVE = "0x0000000000000000000000000000000000000000";
260
+ // the mock pools hold 1 000 of each token: four deposits of 100 BTC-worth move them a lot
261
+ const market = mockMarginCheckMarketInfo(tokensData);
262
+ const marketsInfoData = { [market.marketTokenAddress]: market };
263
+ const btc = tokensData.BTC;
264
+ function quote(numberOfParts, depositUsd, swapPath = [market.marketTokenAddress]) {
265
+ return getTwapIncreasePartsGrossCollateralUsd({
266
+ marketsInfoData,
267
+ swapPath,
268
+ initialCollateralToken: btc,
269
+ collateralToken: usdc,
270
+ initialCollateralAmountPerPart: usdToToken(depositUsd, btc),
271
+ numberOfParts,
272
+ uiFeeFactor: 0n,
273
+ wrappedNativeTokenAddress: NO_NATIVE,
274
+ });
275
+ }
276
+ it("gives every part its deposit when no swap is needed", () => {
277
+ expect(quote(4, 25, [])).toEqual([usd(25), usd(25), usd(25), usd(25)]);
278
+ });
279
+ it("quotes each part against the pool the previous parts leave, so the first part gets the most", () => {
280
+ const parts = quote(4, 100);
281
+ const oneShot = getSwapPathStats({
282
+ marketsInfoData,
283
+ swapPath: [market.marketTokenAddress],
284
+ initialCollateralAddress: btc.address,
285
+ wrappedNativeTokenAddress: NO_NATIVE,
286
+ usdIn: usd(400),
287
+ shouldUnwrapNativeToken: false,
288
+ shouldApplyPriceImpact: true,
289
+ swapPricingType: SwapPricingType.Swap,
290
+ });
291
+ const oneShotUsd = convertToUsd(oneShot.amountOut, usdc.decimals, usdc.prices.minPrice);
292
+ const total = parts.reduce((sum, part) => sum + part, 0n);
293
+ expect(parts[0]).toBeGreaterThan(parts[1]);
294
+ expect(parts[1]).toBeGreaterThan(parts[2]);
295
+ expect(parts[2]).toBeGreaterThan(parts[3]);
296
+ // a split of the one-shot output would give every part the average price impact
297
+ expect(parts[0]).toBeGreaterThan(oneShotUsd / 4n);
298
+ expect(parts[3]).toBeLessThan(oneShotUsd / 4n);
299
+ // the impact telescopes: the four swaps together cost about what the one-shot swap does
300
+ expect(bigMath.abs(total - oneShotUsd)).toBeLessThan(oneShotUsd / 100n);
301
+ });
302
+ });
303
+ describe("getMarketInfoWithSwapDelta — the pools a swap step leaves, as SwapUtils._swap leaves them", () => {
304
+ const btc = tokensData.BTC;
305
+ function swapStep(overrides = {}) {
306
+ return {
307
+ marketAddress: "",
308
+ tokenInAddress: btc.address,
309
+ tokenOutAddress: usdc.address,
310
+ isWrap: false,
311
+ isUnwrap: false,
312
+ swapFeeAmount: usdToToken(1, btc),
313
+ swapFeeUsd: usd(1),
314
+ priceImpactDeltaUsd: 0n,
315
+ amountIn: usdToToken(100, btc),
316
+ amountInAfterFees: usdToToken(99, btc),
317
+ usdIn: usd(100),
318
+ amountOut: usdToToken(99, usdc),
319
+ usdOut: usd(99),
320
+ ...overrides,
321
+ };
322
+ }
323
+ it("moves the swapped amounts between the pools, and the virtual pools when the market has them", () => {
324
+ const market = mockMarginCheckMarketInfo(tokensData, {
325
+ virtualPoolAmountForLongToken: usdToToken(5000, btc),
326
+ virtualPoolAmountForShortToken: 0n,
327
+ });
328
+ const next = getMarketInfoWithSwapDelta(market, swapStep());
329
+ expect(next.longPoolAmount - market.longPoolAmount).toBe(usdToToken(99, btc));
330
+ expect(market.shortPoolAmount - next.shortPoolAmount).toBe(usdToToken(99, usdc));
331
+ expect(next.virtualPoolAmountForLongToken - market.virtualPoolAmountForLongToken).toBe(usdToToken(99, btc));
332
+ expect(next.virtualPoolAmountForShortToken).toBe(0n);
333
+ expect(next.swapImpactPoolAmountLong).toBe(market.swapImpactPoolAmountLong);
334
+ expect(next.swapImpactPoolAmountShort).toBe(market.swapImpactPoolAmountShort);
335
+ });
336
+ it("keeps a negative impact out of the pool: it goes to the swap impact pool of the token in", () => {
337
+ const market = mockMarginCheckMarketInfo(tokensData);
338
+ // of the 99 left after fees, 2 of impact stay in the impact pool and 97 reach the pool; 97 leave the other side
339
+ const next = getMarketInfoWithSwapDelta(market, swapStep({ priceImpactDeltaUsd: -usd(2), amountOut: usdToToken(97, usdc), usdOut: usd(97) }));
340
+ expect(next.longPoolAmount - market.longPoolAmount).toBe(usdToToken(97, btc));
341
+ expect(next.swapImpactPoolAmountLong - market.swapImpactPoolAmountLong).toBe(usdToToken(2, btc));
342
+ expect(market.shortPoolAmount - next.shortPoolAmount).toBe(usdToToken(97, usdc));
343
+ expect(next.swapImpactPoolAmountShort).toBe(market.swapImpactPoolAmountShort);
344
+ });
345
+ it("pays a positive impact from the impact pools, the token out first, then the token in", () => {
346
+ const market = mockMarginCheckMarketInfo(tokensData, {
347
+ swapImpactPoolAmountShort: usdToToken(3, usdc),
348
+ swapImpactPoolAmountLong: usdToToken(10, btc),
349
+ });
350
+ // 5 of impact on top of the 99 swapped: 3 USDC drain the short impact pool, 2 worth of BTC come from the long one
351
+ const next = getMarketInfoWithSwapDelta(market, swapStep({ priceImpactDeltaUsd: usd(5), amountOut: usdToToken(104, usdc), usdOut: usd(104) }));
352
+ expect(next.swapImpactPoolAmountShort).toBe(0n);
353
+ expect(market.swapImpactPoolAmountLong - next.swapImpactPoolAmountLong).toBe(usdToToken(2, btc));
354
+ expect(market.shortPoolAmount - next.shortPoolAmount).toBe(usdToToken(101, usdc));
355
+ expect(next.longPoolAmount - market.longPoolAmount).toBe(usdToToken(101, btc));
356
+ });
357
+ });
358
+ describe("getTwapPartDelaysSeconds", () => {
359
+ it.each([
360
+ { duration: { hours: 10, minutes: 0 }, numberOfParts: 5, delays: [0, 9000, 18000, 27000, 36000] },
361
+ { duration: { hours: 0, minutes: 0 }, numberOfParts: 5, delays: [0, 0, 0, 0, 0] },
362
+ { duration: { hours: 10, minutes: 0 }, numberOfParts: 1, delays: [0] },
363
+ ])("$duration.hours h over $numberOfParts parts", ({ duration, numberOfParts, delays }) => {
364
+ expect(getTwapPartDelaysSeconds(duration, numberOfParts)).toEqual(delays);
365
+ });
366
+ });