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