@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,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getIncreaseResultingPositionMarginState = exports.getResultingPositionMarginState = exports.getIsMaxLeverageMarginReason = exports.PositionMarginFailureReason = void 0;
3
+ exports.getIncreaseResultingPositionState = exports.getIncreaseResultingPositionMarginState = exports.getResultingPositionMarginState = exports.getIsMaxLeverageMarginReason = exports.PositionMarginFailureReason = void 0;
4
4
  const fees_1 = require("../fees");
5
5
  const markets_1 = require("../markets");
6
6
  const numbers_1 = require("../numbers");
@@ -12,10 +12,12 @@ var PositionMarginFailureReason;
12
12
  PositionMarginFailureReason["NonPositiveRemainingMargin"] = "< 0";
13
13
  PositionMarginFailureReason["MinCollateralForLeverage"] = "min collateral for leverage";
14
14
  PositionMarginFailureReason["InsufficientCollateralUsd"] = "insufficient collateral usd";
15
+ PositionMarginFailureReason["MaxAllowedLeverage"] = "max allowed leverage";
15
16
  })(PositionMarginFailureReason || (exports.PositionMarginFailureReason = PositionMarginFailureReason = {}));
16
17
  function getIsMaxLeverageMarginReason(reason) {
17
18
  return (reason === PositionMarginFailureReason.MinCollateralForLeverage ||
18
- reason === PositionMarginFailureReason.InsufficientCollateralUsd);
19
+ reason === PositionMarginFailureReason.InsufficientCollateralUsd ||
20
+ reason === PositionMarginFailureReason.MaxAllowedLeverage);
19
21
  }
20
22
  exports.getIsMaxLeverageMarginReason = getIsMaxLeverageMarginReason;
21
23
  /**
@@ -103,6 +105,10 @@ function withPriceOverride(token, indexToken, price) {
103
105
  * then `validatePosition` on the resulting position.
104
106
  */
105
107
  function getIncreaseResultingPositionMarginState(p) {
108
+ return getIncreaseResultingPositionState(p)?.marginState;
109
+ }
110
+ exports.getIncreaseResultingPositionMarginState = getIncreaseResultingPositionMarginState;
111
+ function getIncreaseResultingPositionState(p) {
106
112
  const { isLong, existingPosition, sizeDeltaUsd, sizeDeltaInTokens, collateralDeltaAmount, minCollateralUsd, userReferralInfo, proDiscountFactor, indexPriceForEvaluation, } = p;
107
113
  let { marketInfo, collateralToken } = p;
108
114
  if (sizeDeltaUsd <= 0n || sizeDeltaInTokens <= 0n) {
@@ -154,26 +160,34 @@ function getIncreaseResultingPositionMarginState(p) {
154
160
  minCollateralFactorForOpenInterest = nextMarketInfo.minCollateralFactor;
155
161
  }
156
162
  const minCollateralUsdForOpenInterest = (0, numbers_1.applyFactor)(nextSizeInUsd, minCollateralFactorForOpenInterest);
163
+ const position = {
164
+ sizeInUsd: nextSizeInUsd,
165
+ sizeInTokens: nextSizeInTokens,
166
+ collateralAmount: nextCollateralAmountClamped,
167
+ pendingImpactAmount: nextPendingImpactAmount,
168
+ };
157
169
  if (remainingCollateralUsdForOpenInterest < minCollateralUsdForOpenInterest) {
158
170
  return {
159
- isLiquidatable: true,
160
- reason: PositionMarginFailureReason.InsufficientCollateralUsd,
161
- remainingCollateralUsd: remainingCollateralUsdForOpenInterest,
162
- minCollateralUsd,
163
- minCollateralUsdForLeverage: minCollateralUsdForOpenInterest,
171
+ marginState: {
172
+ isLiquidatable: true,
173
+ reason: PositionMarginFailureReason.InsufficientCollateralUsd,
174
+ remainingCollateralUsd: remainingCollateralUsdForOpenInterest,
175
+ minCollateralUsd,
176
+ minCollateralUsdForLeverage: minCollateralUsdForOpenInterest,
177
+ },
178
+ position,
179
+ marketInfo: nextMarketInfo,
164
180
  };
165
181
  }
166
- return getResultingPositionMarginState({
182
+ const marginState = getResultingPositionMarginState({
167
183
  marketInfo: nextMarketInfo,
168
184
  collateralToken,
169
- sizeInUsd: nextSizeInUsd,
170
- sizeInTokens: nextSizeInTokens,
171
- collateralAmount: nextCollateralAmountClamped,
172
- pendingImpactAmount: nextPendingImpactAmount,
185
+ ...position,
173
186
  minCollateralUsd,
174
187
  isLong,
175
188
  userReferralInfo,
176
189
  proDiscountFactor,
177
190
  });
191
+ return { marginState, position, marketInfo: nextMarketInfo };
178
192
  }
179
- exports.getIncreaseResultingPositionMarginState = getIncreaseResultingPositionMarginState;
193
+ exports.getIncreaseResultingPositionState = getIncreaseResultingPositionState;
@@ -0,0 +1,180 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getIsTwapIncreaseSequenceSafe = exports.getTwapIncreaseSequentialMarginState = exports.getTwapIncreasePartsGrossCollateralUsd = exports.getTwapIncreasePartAmounts = exports.getTwapIncreaseAggregateAmounts = void 0;
4
+ const factors_1 = require("../../configs/factors");
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 positions_1 = require("../positions");
11
+ const prices_1 = require("../prices");
12
+ const swapStats_1 = require("../swap/swapStats");
13
+ const tokens_1 = require("../tokens");
14
+ const increaseMarginCheck_1 = require("./increaseMarginCheck");
15
+ function getTwapIncreaseAggregateAmounts(increaseAmounts) {
16
+ return {
17
+ sizeDeltaUsd: increaseAmounts.sizeDeltaUsd,
18
+ pendingFeesUsd: increaseAmounts.borrowingFeeUsd + increaseAmounts.fundingFeeUsd,
19
+ };
20
+ }
21
+ exports.getTwapIncreaseAggregateAmounts = getTwapIncreaseAggregateAmounts;
22
+ function getTwapIncreasePartAmounts({ sizeDeltaUsd, pendingFeesUsd }, numberOfParts) {
23
+ if (numberOfParts < 1) {
24
+ return { partSizeDeltaUsd: 0n, pendingFeesUsd };
25
+ }
26
+ return { partSizeDeltaUsd: sizeDeltaUsd / BigInt(numberOfParts), pendingFeesUsd };
27
+ }
28
+ exports.getTwapIncreasePartAmounts = getTwapIncreasePartAmounts;
29
+ function getTwapIncreasePartsGrossCollateralUsd(p) {
30
+ const { swapPath, initialCollateralToken, collateralToken, initialCollateralAmountPerPart, numberOfParts, uiFeeFactor, wrappedNativeTokenAddress, } = p;
31
+ if (numberOfParts < 1) {
32
+ return [];
33
+ }
34
+ const usdIn = (0, tokens_1.convertToUsd)(initialCollateralAmountPerPart, initialCollateralToken.decimals, initialCollateralToken.prices.minPrice);
35
+ if (swapPath.length === 0) {
36
+ return Array.from({ length: numberOfParts }, () => usdIn);
37
+ }
38
+ let marketsInfoData = p.marketsInfoData;
39
+ const partGrossCollateralUsds = [];
40
+ for (let partIndex = 0; partIndex < numberOfParts; partIndex++) {
41
+ const swapPathStats = (0, swapStats_1.getSwapPathStats)({
42
+ marketsInfoData,
43
+ swapPath,
44
+ initialCollateralAddress: initialCollateralToken.address,
45
+ wrappedNativeTokenAddress,
46
+ usdIn,
47
+ shouldUnwrapNativeToken: false,
48
+ shouldApplyPriceImpact: true,
49
+ swapPricingType: types_1.SwapPricingType.Swap,
50
+ });
51
+ if (!swapPathStats || swapPathStats.amountOut <= 0n) {
52
+ return undefined;
53
+ }
54
+ const grossCollateralUsd = (0, tokens_1.convertToUsd)(swapPathStats.amountOut, collateralToken.decimals, collateralToken.prices.minPrice);
55
+ const swapUiFeeUsd = (0, numbers_1.applyFactor)((0, fees_1.getTotalSwapVolumeFromSwapStats)(swapPathStats.swapSteps), uiFeeFactor);
56
+ partGrossCollateralUsds.push(grossCollateralUsd - swapUiFeeUsd);
57
+ marketsInfoData = swapPathStats.swapSteps.reduce((acc, swapStep) => ({
58
+ ...acc,
59
+ [swapStep.marketAddress]: (0, markets_1.getMarketInfoWithSwapDelta)(acc[swapStep.marketAddress], swapStep),
60
+ }), marketsInfoData);
61
+ }
62
+ return partGrossCollateralUsds;
63
+ }
64
+ exports.getTwapIncreasePartsGrossCollateralUsd = getTwapIncreasePartsGrossCollateralUsd;
65
+ function getMaxAllowedLeverageMarginState({ position, collateralToken, maxAllowedLeverage, minCollateralUsd, }) {
66
+ const collateralUsd = (0, tokens_1.convertToUsd)(position.collateralAmount, collateralToken.decimals, collateralToken.prices.minPrice);
67
+ const leverage = (0, positions_1.getLeverage)({
68
+ sizeInUsd: position.sizeInUsd,
69
+ collateralUsd,
70
+ pnl: undefined,
71
+ pendingBorrowingFeesUsd: 0n,
72
+ pendingFundingFeesUsd: 0n,
73
+ });
74
+ if (maxAllowedLeverage <= 0n || leverage === undefined || leverage <= maxAllowedLeverage) {
75
+ return undefined;
76
+ }
77
+ return {
78
+ isLiquidatable: true,
79
+ reason: increaseMarginCheck_1.PositionMarginFailureReason.MaxAllowedLeverage,
80
+ remainingCollateralUsd: collateralUsd,
81
+ minCollateralUsd,
82
+ minCollateralUsdForLeverage: bigmath_1.bigMath.mulDiv(position.sizeInUsd, factors_1.BASIS_POINTS_DIVISOR_BIGINT, maxAllowedLeverage),
83
+ };
84
+ }
85
+ function getPositionFeesAccruedUsd(marketInfo, isLong, sizeInUsd, periodSeconds) {
86
+ if (periodSeconds <= 0 || sizeInUsd <= 0n) {
87
+ return 0n;
88
+ }
89
+ const period = BigInt(periodSeconds);
90
+ const borrowingUsd = (0, fees_1.getBorrowingFeeRateUsd)(marketInfo, isLong, sizeInUsd, period);
91
+ const fundingUsd = (0, fees_1.getFundingFeeRateUsd)(marketInfo, isLong, sizeInUsd, period);
92
+ return borrowingUsd + (fundingUsd < 0n ? -fundingUsd : 0n);
93
+ }
94
+ function getTwapIncreaseSequentialMarginState(p) {
95
+ const { collateralToken, isLong, numberOfParts, partDelaysSeconds, partGrossCollateralUsds, partSizeDeltaUsd, pendingFeesUsd, uiFeeFactor, minCollateralUsd, userReferralInfo, proDiscountFactor, } = p;
96
+ if (numberOfParts < 1 || partSizeDeltaUsd <= 0n || partGrossCollateralUsds.length < numberOfParts) {
97
+ return undefined;
98
+ }
99
+ const { indexToken } = p.marketInfo;
100
+ const indexPrice = (0, prices_1.getMarkPrice)({ prices: indexToken.prices, isIncrease: true, isLong });
101
+ const collateralPrice = collateralToken.prices.minPrice;
102
+ if (indexPrice <= 0n || collateralPrice <= 0n) {
103
+ return undefined;
104
+ }
105
+ const partSizeDeltaInTokens = (0, tokens_1.convertToTokenAmountForIncrease)(partSizeDeltaUsd, indexToken.decimals, indexPrice, isLong);
106
+ if (partSizeDeltaInTokens <= 0n) {
107
+ return undefined;
108
+ }
109
+ const maxAllowedLeverage = BigInt((0, markets_1.getMaxAllowedLeverage)({
110
+ marketAddress: p.marketInfo.marketTokenAddress,
111
+ minCollateralFactor: p.marketInfo.minCollateralFactor,
112
+ minCollateralFactorForLiquidation: p.marketInfo.minCollateralFactorForLiquidation,
113
+ positionFeeFactorForBalanceWasNotImproved: p.marketInfo.positionFeeFactorForBalanceWasNotImproved,
114
+ }));
115
+ let marketInfo = p.marketInfo;
116
+ let position = p.existingPosition;
117
+ let contractMarginState;
118
+ let previousPartDelaySeconds = 0;
119
+ for (let partIndex = 0; partIndex < numberOfParts; partIndex++) {
120
+ const partDelaySeconds = Math.max(0, partDelaysSeconds[partIndex] ?? 0);
121
+ const accruedFeesUsd = position
122
+ ? getPositionFeesAccruedUsd(marketInfo, isLong, position.sizeInUsd, partDelaySeconds - previousPartDelaySeconds)
123
+ : 0n;
124
+ previousPartDelaySeconds = partDelaySeconds;
125
+ const { balanceWasImproved } = (0, fees_1.getPriceImpactForPosition)(marketInfo, partSizeDeltaUsd, isLong, {
126
+ fallbackToZero: true,
127
+ sizeDeltaInTokens: partSizeDeltaInTokens,
128
+ });
129
+ const { positionFeeUsd } = (0, fees_1.getPositionFee)(marketInfo, partSizeDeltaUsd, balanceWasImproved, userReferralInfo, undefined, proDiscountFactor);
130
+ const uiFeeUsd = (0, numbers_1.applyFactor)(partSizeDeltaUsd, uiFeeFactor);
131
+ const settledFeesUsd = (partIndex === 0 ? pendingFeesUsd : 0n) + accruedFeesUsd;
132
+ const collateralDeltaUsd = partGrossCollateralUsds[partIndex] - positionFeeUsd - uiFeeUsd - settledFeesUsd;
133
+ const collateralDeltaAmount = (0, tokens_1.convertToTokenAmount)(collateralDeltaUsd, collateralToken.decimals, collateralPrice);
134
+ const resultingState = (0, increaseMarginCheck_1.getIncreaseResultingPositionState)({
135
+ marketInfo,
136
+ collateralToken,
137
+ isLong,
138
+ existingPosition: position,
139
+ sizeDeltaUsd: partSizeDeltaUsd,
140
+ sizeDeltaInTokens: partSizeDeltaInTokens,
141
+ collateralDeltaAmount,
142
+ minCollateralUsd,
143
+ userReferralInfo,
144
+ proDiscountFactor,
145
+ });
146
+ if (!resultingState) {
147
+ return undefined;
148
+ }
149
+ contractMarginState = resultingState.marginState;
150
+ const marginState = getMaxAllowedLeverageMarginState({
151
+ position: resultingState.position,
152
+ collateralToken,
153
+ maxAllowedLeverage,
154
+ minCollateralUsd,
155
+ }) ?? contractMarginState;
156
+ if (marginState.isLiquidatable) {
157
+ return {
158
+ numberOfParts,
159
+ failingPartIndex: partIndex,
160
+ isFailingPartEligibleNow: partDelaySeconds === 0,
161
+ marginState,
162
+ contractMarginState,
163
+ };
164
+ }
165
+ marketInfo = resultingState.marketInfo;
166
+ position = resultingState.position;
167
+ }
168
+ return {
169
+ numberOfParts,
170
+ failingPartIndex: undefined,
171
+ isFailingPartEligibleNow: false,
172
+ marginState: contractMarginState,
173
+ contractMarginState: contractMarginState,
174
+ };
175
+ }
176
+ exports.getTwapIncreaseSequentialMarginState = getTwapIncreaseSequentialMarginState;
177
+ function getIsTwapIncreaseSequenceSafe(state) {
178
+ return state?.failingPartIndex === undefined;
179
+ }
180
+ exports.getIsTwapIncreaseSequenceSafe = getIsTwapIncreaseSequenceSafe;
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.makeTwapValidFromTimeGetter = exports.getTwapOrderKey = exports.changeTwapNumberOfPartsValue = exports.getTwapValidFromTime = exports.getTwapDurationInSeconds = exports.getIsValidTwapParams = exports.UI_FEE_SOURCE_API = exports.UI_FEE_SOURCE_UI = void 0;
17
+ exports.makeTwapValidFromTimeGetter = exports.getTwapOrderKey = exports.changeTwapNumberOfPartsValue = exports.getTwapPartDelaysSeconds = exports.getTwapValidFromTime = exports.getTwapPartDelaySeconds = exports.getTwapDurationInSeconds = exports.getIsValidTwapParams = exports.UI_FEE_SOURCE_API = exports.UI_FEE_SOURCE_UI = void 0;
18
18
  const twap_1 = require("../../configs/twap");
19
19
  const orders_1 = require("../orders");
20
20
  __exportStar(require("./types"), exports);
@@ -32,13 +32,22 @@ function getTwapDurationInSeconds(duration) {
32
32
  return duration.hours * 60 * 60 + duration.minutes * 60;
33
33
  }
34
34
  exports.getTwapDurationInSeconds = getTwapDurationInSeconds;
35
+ function getTwapPartDelaySeconds(duration, numberOfParts, partIndex) {
36
+ if (numberOfParts <= 1) {
37
+ return 0;
38
+ }
39
+ return Math.floor((getTwapDurationInSeconds(duration) / (numberOfParts - 1)) * partIndex);
40
+ }
41
+ exports.getTwapPartDelaySeconds = getTwapPartDelaySeconds;
35
42
  function getTwapValidFromTime(duration, numberOfParts, partIndex) {
36
- const durationMinutes = duration.hours * 60 + duration.minutes;
37
- const durationMs = durationMinutes * 60;
38
43
  const startTime = Math.ceil(Date.now() / 1000);
39
- return BigInt(Math.floor(startTime + (durationMs / (numberOfParts - 1)) * partIndex));
44
+ return BigInt(startTime + getTwapPartDelaySeconds(duration, numberOfParts, partIndex));
40
45
  }
41
46
  exports.getTwapValidFromTime = getTwapValidFromTime;
47
+ function getTwapPartDelaysSeconds(duration, numberOfParts) {
48
+ return Array.from({ length: numberOfParts }, (_, partIndex) => getTwapPartDelaySeconds(duration, numberOfParts, partIndex));
49
+ }
50
+ exports.getTwapPartDelaysSeconds = getTwapPartDelaysSeconds;
42
51
  function changeTwapNumberOfPartsValue(value) {
43
52
  if (value < twap_1.MIN_TWAP_NUMBER_OF_PARTS) {
44
53
  return twap_1.MIN_TWAP_NUMBER_OF_PARTS;
@@ -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),