@gmx-io/sdk 2.3.2 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/build/cjs/src/configs/chains.js +13 -1
  2. package/build/cjs/src/configs/markets.js +12 -7
  3. package/build/cjs/src/configs/tokens.js +12 -7
  4. package/build/cjs/src/utils/__tests__/numbers.spec.js +24 -0
  5. package/build/cjs/src/utils/__tests__/parseError.spec.js +61 -0
  6. package/build/cjs/src/utils/errors/parseError.js +10 -0
  7. package/build/cjs/src/utils/errors/transactionsErrors.js +6 -0
  8. package/build/cjs/src/utils/markets/__tests__/multicall.spec.js +27 -0
  9. package/build/cjs/src/utils/markets/multicall.js +5 -7
  10. package/build/cjs/src/utils/numbers/utils.js +7 -1
  11. package/build/cjs/src/utils/orders/utils.js +8 -1
  12. package/build/cjs/src/utils/paxos/__tests__/api.spec.js +23 -3
  13. package/build/cjs/src/utils/paxos/api.js +6 -0
  14. package/build/cjs/src/utils/swap/preparedSwapData.js +6 -4
  15. package/build/cjs/src/utils/swap/swapPath.js +1 -1
  16. package/build/cjs/src/utils/trade/__tests__/decreaseMarginCheck.spec.js +224 -0
  17. package/build/cjs/src/utils/trade/__tests__/getMaxWithdrawAmount.spec.js +128 -9
  18. package/build/cjs/src/utils/trade/decrease.js +198 -33
  19. package/build/cjs/src/utils/trade/decreaseMarginCheck.js +157 -0
  20. package/build/cjs/src/utils/trade/increaseMarginCheck.js +27 -15
  21. package/build/cjs/src/utils/trade/index.js +1 -0
  22. package/build/esm/src/configs/chains.js +11 -0
  23. package/build/esm/src/configs/markets.js +13 -8
  24. package/build/esm/src/configs/tokens.js +13 -8
  25. package/build/esm/src/utils/__tests__/numbers.spec.js +25 -1
  26. package/build/esm/src/utils/__tests__/parseError.spec.js +62 -1
  27. package/build/esm/src/utils/errors/parseError.js +11 -1
  28. package/build/esm/src/utils/errors/transactionsErrors.js +6 -0
  29. package/build/esm/src/utils/markets/__tests__/multicall.spec.js +25 -0
  30. package/build/esm/src/utils/markets/multicall.js +5 -7
  31. package/build/esm/src/utils/numbers/utils.js +5 -0
  32. package/build/esm/src/utils/orders/utils.js +6 -0
  33. package/build/esm/src/utils/paxos/__tests__/api.spec.js +23 -3
  34. package/build/esm/src/utils/paxos/api.js +6 -0
  35. package/build/esm/src/utils/swap/preparedSwapData.js +6 -4
  36. package/build/esm/src/utils/swap/swapPath.js +2 -2
  37. package/build/esm/src/utils/trade/__tests__/decreaseMarginCheck.spec.js +222 -0
  38. package/build/esm/src/utils/trade/__tests__/getMaxWithdrawAmount.spec.js +129 -10
  39. package/build/esm/src/utils/trade/decrease.js +195 -32
  40. package/build/esm/src/utils/trade/decreaseMarginCheck.js +152 -0
  41. package/build/esm/src/utils/trade/increaseMarginCheck.js +25 -14
  42. package/build/esm/src/utils/trade/index.js +1 -0
  43. package/build/tsconfig.tsbuildinfo +1 -1
  44. package/build/types/src/configs/chains.d.ts +6 -2
  45. package/build/types/src/configs/markets.d.ts +4 -4
  46. package/build/types/src/utils/markets/__tests__/multicall.spec.d.ts +1 -0
  47. package/build/types/src/utils/numbers/utils.d.ts +1 -0
  48. package/build/types/src/utils/orderTransactions/api.d.ts +1 -0
  49. package/build/types/src/utils/orders/utils.d.ts +1 -0
  50. package/build/types/src/utils/paxos/types.d.ts +2 -0
  51. package/build/types/src/utils/trade/__tests__/decreaseMarginCheck.spec.d.ts +1 -0
  52. package/build/types/src/utils/trade/decrease.d.ts +18 -0
  53. package/build/types/src/utils/trade/decreaseMarginCheck.d.ts +52 -0
  54. package/build/types/src/utils/trade/increaseMarginCheck.d.ts +11 -1
  55. package/build/types/src/utils/trade/index.d.ts +1 -0
  56. package/build/types/src/utils/trade/types.d.ts +1 -0
  57. package/package.json +1 -1
@@ -0,0 +1,222 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { mockMarketsInfoData, mockTokensData } from "../../../test/mock";
3
+ import { USD_DECIMALS, expandDecimals } from "../../numbers";
4
+ import { convertToTokenAmount } from "../../tokens";
5
+ import { getDecreaseResultingPositionMarginState, } from "../decreaseMarginCheck";
6
+ import { PositionMarginFailureReason } from "../increaseMarginCheck";
7
+ const tokensData = mockTokensData();
8
+ const usdc = tokensData.USDC;
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: expandDecimals(1000000, USD_DECIMALS),
25
+ shortInterestUsd: expandDecimals(1000000, USD_DECIMALS),
26
+ longInterestInTokens: expandDecimals(50, 8),
27
+ shortInterestInTokens: expandDecimals(50, 8),
28
+ ...overrides,
29
+ },
30
+ })["BTC-BTC-USDC"];
31
+ }
32
+ /** USD value with 30 decimals, accepting fractional amounts. */
33
+ function usd(value) {
34
+ return (BigInt(Math.round(value * 100)) * expandDecimals(1, USD_DECIMALS)) / 100n;
35
+ }
36
+ function usdcAmount(value) {
37
+ return convertToTokenAmount(usd(value), usdc.decimals, usdc.prices.minPrice);
38
+ }
39
+ /** tokens of a 10 000 USD long that are worth `value` at the oracle price */
40
+ function sizeInTokensWorth(value) {
41
+ return convertToTokenAmount(usd(value), tokensData.BTC.decimals, tokensData.BTC.prices.minPrice);
42
+ }
43
+ const LOSING_2000 = sizeInTokensWorth(8000);
44
+ const FLAT = sizeInTokensWorth(10000);
45
+ const PROFITABLE_2000 = sizeInTokensWorth(12000);
46
+ /**
47
+ * A 10 000 USD long. `closeShare` closes that share of it and pays `realizedLossUsd` out of the collateral,
48
+ * the way `getDecreasePositionAmounts` reports it in `payedRemainingCollateralAmount`.
49
+ */
50
+ function params({ position, closeShare = 0, realizedLossUsd = 0, ...overrides } = {}) {
51
+ const fullPosition = {
52
+ sizeInUsd: usd(10000),
53
+ sizeInTokens: LOSING_2000,
54
+ collateralAmount: usdcAmount(2060),
55
+ pendingImpactAmount: 0n,
56
+ ...position,
57
+ };
58
+ const closeBps = BigInt(Math.round(closeShare * 10000));
59
+ return {
60
+ marketInfo: buildMarket(),
61
+ collateralToken: usdc,
62
+ isLong: true,
63
+ position: fullPosition,
64
+ sizeDeltaUsd: (fullPosition.sizeInUsd * closeBps) / 10000n,
65
+ sizeDeltaInTokens: (fullPosition.sizeInTokens * closeBps) / 10000n,
66
+ collateralDeltaAmount: 0n,
67
+ payedRemainingCollateralAmount: usdcAmount(realizedLossUsd),
68
+ priceImpactDiffUsd: 0n,
69
+ minCollateralUsd: usd(1),
70
+ minPositionSizeUsd: usd(1),
71
+ userReferralInfo: undefined,
72
+ ...overrides,
73
+ };
74
+ }
75
+ describe("getDecreaseResultingPositionMarginState — partial close", () => {
76
+ // collateral 2 060 with a 2 000 loss leaves 60 of margin: under the 1% regular minimum of the full
77
+ // position (100), above its 0.5% liquidation minimum (50)
78
+ it("rejects a partial close whose remainder stays above max leverage", () => {
79
+ const state = getDecreaseResultingPositionMarginState(params({ closeShare: 0.25, realizedLossUsd: 500 }));
80
+ expect(state?.isLiquidatable).toBe(true);
81
+ expect(state?.reason).toBe(PositionMarginFailureReason.MinCollateralForLeverage);
82
+ expect(state?.remainingCollateralUsd).toBe(usd(60));
83
+ expect(state?.minCollateralUsdForLeverage).toBe(usd(75));
84
+ });
85
+ it("passes when the remaining margin equals the leverage-based minimum", () => {
86
+ const state = getDecreaseResultingPositionMarginState(params({ closeShare: 0.4, realizedLossUsd: 800 }));
87
+ expect(state?.remainingCollateralUsd).toBe(usd(60));
88
+ expect(state?.minCollateralUsdForLeverage).toBe(usd(60));
89
+ expect(state?.isLiquidatable).toBe(false);
90
+ });
91
+ it("passes once a larger part is closed", () => {
92
+ const state = getDecreaseResultingPositionMarginState(params({ closeShare: 0.5, realizedLossUsd: 1000 }));
93
+ expect(state?.isLiquidatable).toBe(false);
94
+ });
95
+ it("never validates a full close", () => {
96
+ expect(getDecreaseResultingPositionMarginState(params({ closeShare: 1, realizedLossUsd: 2000 }))).toBeUndefined();
97
+ });
98
+ it("counts the costs paid out of the collateral against the remainder", () => {
99
+ // closing 50% passes with 60 of margin against a 50 minimum; 10.01 of fees on the closed part tips it over
100
+ const state = getDecreaseResultingPositionMarginState(params({ closeShare: 0.5, realizedLossUsd: 1010.01 }));
101
+ expect(state?.reason).toBe(PositionMarginFailureReason.MinCollateralForLeverage);
102
+ });
103
+ it("charges the closing fee of the remainder", () => {
104
+ // 0.2% of the remaining 5 000 = 10 → 60 - 10 = 50, exactly the minimum; one more cent of loss fails
105
+ const marketInfo = buildMarket({
106
+ positionFeeFactorForBalanceWasImproved: expandDecimals(2, 27),
107
+ positionFeeFactorForBalanceWasNotImproved: expandDecimals(2, 27),
108
+ });
109
+ expect(getDecreaseResultingPositionMarginState(params({ marketInfo, closeShare: 0.5, realizedLossUsd: 1000 }))
110
+ ?.isLiquidatable).toBe(false);
111
+ expect(getDecreaseResultingPositionMarginState(params({ marketInfo, closeShare: 0.5, realizedLossUsd: 1000.01 }))
112
+ ?.reason).toBe(PositionMarginFailureReason.MinCollateralForLeverage);
113
+ });
114
+ it("does not apply the fixed minimum to the remainder", () => {
115
+ // remainder: 60 of margin, 50 leverage minimum; a 61 USD fixed minimum is only checked after an increase
116
+ const state = getDecreaseResultingPositionMarginState(params({
117
+ closeShare: 0.5,
118
+ realizedLossUsd: 1000,
119
+ position: { collateralAmount: usdcAmount(2061) },
120
+ minCollateralUsd: usd(61),
121
+ marketInfo: buildMarket({
122
+ positionFeeFactorForBalanceWasImproved: expandDecimals(2, 26),
123
+ positionFeeFactorForBalanceWasNotImproved: expandDecimals(2, 26),
124
+ }),
125
+ }));
126
+ expect(state?.remainingCollateralUsd).toBe(usd(60));
127
+ expect(state?.isLiquidatable).toBe(false);
128
+ });
129
+ it("returns a non-positive remaining margin as its own reason", () => {
130
+ const state = getDecreaseResultingPositionMarginState(params({ closeShare: 0.25, realizedLossUsd: 500, position: { collateralAmount: usdcAmount(2002) } }));
131
+ // 2 of margin: over the 1 USD fixed minimum, so the contract keeps the close partial
132
+ expect(state?.reason).toBe(PositionMarginFailureReason.MinCollateralForLeverage);
133
+ const underwater = getDecreaseResultingPositionMarginState(params({
134
+ closeShare: 0.25,
135
+ realizedLossUsd: 503,
136
+ position: { collateralAmount: usdcAmount(2002) },
137
+ }));
138
+ expect(underwater?.reason).toBe(PositionMarginFailureReason.NonPositiveRemainingMargin);
139
+ });
140
+ it("validates nothing when the contract turns the order into a full close", () => {
141
+ // estimated remainder: 2 000.5 - 500 of collateral and -1 500 of pnl → 0.5, under the 1 USD fixed minimum
142
+ expect(getDecreaseResultingPositionMarginState(params({ closeShare: 0.25, realizedLossUsd: 500, position: { collateralAmount: usdcAmount(2000.5) } }))).toBeUndefined();
143
+ expect(getDecreaseResultingPositionMarginState(params({ closeShare: 0.5, realizedLossUsd: 1000, minPositionSizeUsd: usd(5001) }))).toBeUndefined();
144
+ });
145
+ });
146
+ describe("getDecreaseResultingPositionMarginState — keep-leverage collateral withdrawal", () => {
147
+ const flat = { sizeInTokens: FLAT, collateralAmount: usdcAmount(200) };
148
+ it("withdraws the collateral when the preliminary gate passes", () => {
149
+ // remaining size 5 000 → 50 required without pnl; 200 - 150 = 50
150
+ const state = getDecreaseResultingPositionMarginState(params({ closeShare: 0.5, position: flat, collateralDeltaAmount: usdcAmount(150) }));
151
+ expect(state?.remainingCollateralUsd).toBe(usd(50));
152
+ expect(state?.isLiquidatable).toBe(false);
153
+ });
154
+ it("keeps the collateral in the position when the preliminary gate fails", () => {
155
+ const state = getDecreaseResultingPositionMarginState(params({ closeShare: 0.5, position: flat, collateralDeltaAmount: usdcAmount(150.01) }));
156
+ expect(state?.remainingCollateralUsd).toBe(usd(200));
157
+ expect(state?.isLiquidatable).toBe(false);
158
+ });
159
+ it("trims the withdrawal by the negative impact past the cap, as the contract does", () => {
160
+ // 30 of the close's negative impact is past the cap: it is paid out of the collateral and the contract
161
+ // withdraws 150 - 30, so 200 - 30 - 120 = 50 stays against the 50 required
162
+ const state = getDecreaseResultingPositionMarginState(params({
163
+ closeShare: 0.5,
164
+ position: flat,
165
+ collateralDeltaAmount: usdcAmount(150),
166
+ payedRemainingCollateralAmount: usdcAmount(30),
167
+ priceImpactDiffUsd: usd(30),
168
+ }));
169
+ expect(state?.remainingCollateralUsd).toBe(usd(50));
170
+ expect(state?.isLiquidatable).toBe(false);
171
+ });
172
+ it("evaluates the open-interest factor on the open interest left after the close", () => {
173
+ // 2% at 1 000 000 of open interest; closing 5 000 leaves 995 000 → 1.99% → 99.5 on the remaining 5 000
174
+ const marketInfo = buildMarket({ minCollateralFactorForOpenInterestLong: expandDecimals(2, 22) });
175
+ expect(getDecreaseResultingPositionMarginState(params({ marketInfo, closeShare: 0.5, position: flat, collateralDeltaAmount: usdcAmount(100.5) }))?.remainingCollateralUsd).toBe(usd(99.5));
176
+ expect(getDecreaseResultingPositionMarginState(params({ marketInfo, closeShare: 0.5, position: flat, collateralDeltaAmount: usdcAmount(100.51) }))?.remainingCollateralUsd).toBe(usd(200));
177
+ });
178
+ });
179
+ describe("getDecreaseResultingPositionMarginState — withdrawal", () => {
180
+ it("passes up to the leverage-based minimum with pnl and fails past it", () => {
181
+ // 2 200 of collateral and a 2 000 loss: 200 of margin against a 100 minimum
182
+ const position = { collateralAmount: usdcAmount(2200) };
183
+ const atThreshold = getDecreaseResultingPositionMarginState(params({ position, collateralDeltaAmount: usdcAmount(100) }));
184
+ const pastThreshold = getDecreaseResultingPositionMarginState(params({ position, collateralDeltaAmount: usdcAmount(100.01) }));
185
+ expect(atThreshold?.remainingCollateralUsd).toBe(usd(100));
186
+ expect(atThreshold?.isLiquidatable).toBe(false);
187
+ expect(pastThreshold?.reason).toBe(PositionMarginFailureReason.MinCollateralForLeverage);
188
+ });
189
+ it("uses the regular factor where the liquidation one would still pass", () => {
190
+ // 60 of margin left: above the 0.5% liquidation minimum (50), under the 1% regular one (100)
191
+ const state = getDecreaseResultingPositionMarginState(params({ position: { collateralAmount: usdcAmount(2200) }, collateralDeltaAmount: usdcAmount(140) }));
192
+ expect(state?.remainingCollateralUsd).toBe(usd(60));
193
+ expect(state?.minCollateralUsdForLeverage).toBe(usd(100));
194
+ expect(state?.isLiquidatable).toBe(true);
195
+ });
196
+ it("settles pending fees out of the collateral before the final validation", () => {
197
+ const state = getDecreaseResultingPositionMarginState(params({
198
+ position: { collateralAmount: usdcAmount(2200) },
199
+ collateralDeltaAmount: usdcAmount(95),
200
+ payedRemainingCollateralAmount: usdcAmount(5.01),
201
+ }));
202
+ expect(state?.reason).toBe(PositionMarginFailureReason.MinCollateralForLeverage);
203
+ });
204
+ it("reverts at the preliminary gate, which ignores pnl", () => {
205
+ // profitable by 2 000, but 150 - 50.01 of collateral is under the 100 the gate requires without pnl
206
+ const position = { sizeInTokens: PROFITABLE_2000, collateralAmount: usdcAmount(150) };
207
+ expect(getDecreaseResultingPositionMarginState(params({ position, collateralDeltaAmount: usdcAmount(50) }))
208
+ ?.isLiquidatable).toBe(false);
209
+ const state = getDecreaseResultingPositionMarginState(params({ position, collateralDeltaAmount: usdcAmount(50.01) }));
210
+ expect(state?.reason).toBe(PositionMarginFailureReason.UnableToWithdrawCollateral);
211
+ expect(state?.remainingCollateralUsd).toBe(usd(99.99));
212
+ expect(state?.minCollateralUsdForLeverage).toBe(usd(100));
213
+ });
214
+ it("reverts at the preliminary gate when collateral with pnl falls under the fixed minimum", () => {
215
+ const state = getDecreaseResultingPositionMarginState(params({
216
+ position: { collateralAmount: usdcAmount(2200) },
217
+ collateralDeltaAmount: usdcAmount(50),
218
+ minCollateralUsd: usd(150.01),
219
+ }));
220
+ expect(state?.reason).toBe(PositionMarginFailureReason.UnableToWithdrawCollateral);
221
+ });
222
+ });
@@ -1,14 +1,18 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import { mockMarketsInfoData, mockTokensData, usdToToken } from "../../../test/mock";
3
- import { applyFactor, expandDecimals, USD_DECIMALS } from "../../numbers";
3
+ import { getMaxAllowedLeverage } from "../../markets";
4
+ import { applyFactor, BASIS_POINTS_DIVISOR_BIGINT, expandDecimals, USD_DECIMALS } from "../../numbers";
4
5
  import { getLiquidationPrice } from "../../positions";
5
6
  import { getMaxWithdrawAmount, getMinRequiredCollateralUsdForPosition } from "../decrease";
7
+ import { getDecreaseResultingPositionMarginState } from "../decreaseMarginCheck";
8
+ import { PositionMarginFailureReason } from "../increaseMarginCheck";
6
9
  describe("getMaxWithdrawAmount", () => {
7
- const ETH_PRICE = expandDecimals(11952, 29); // $1195.20
10
+ const LOSING_ETH_PRICE = expandDecimals(11952, 29); // $1195.20
11
+ const PROFITABLE_ETH_PRICE = expandDecimals(1250, 30);
8
12
  const USDC_PRICE = expandDecimals(1, 30);
9
- function buildScenario() {
13
+ function buildScenario({ ethPrice = LOSING_ETH_PRICE, minCollateralFactorForLiquidation = expandDecimals(4, 27), } = {}) {
10
14
  const tokensData = mockTokensData({
11
- ETH: { prices: { minPrice: ETH_PRICE, maxPrice: ETH_PRICE } },
15
+ ETH: { prices: { minPrice: ethPrice, maxPrice: ethPrice } },
12
16
  USDC: { prices: { minPrice: USDC_PRICE, maxPrice: USDC_PRICE } },
13
17
  });
14
18
  const marketKey = "ETH-ETH-USDC";
@@ -19,7 +23,7 @@ describe("getMaxWithdrawAmount", () => {
19
23
  longInterestInTokens: usdToToken(100000000, tokensData.ETH),
20
24
  shortInterestInTokens: usdToToken(100000000, tokensData.ETH),
21
25
  minCollateralFactor: expandDecimals(5, 27),
22
- minCollateralFactorForLiquidation: expandDecimals(4, 27),
26
+ minCollateralFactorForLiquidation,
23
27
  minCollateralFactorForOpenInterestLong: 0n,
24
28
  minCollateralFactorForOpenInterestShort: 0n,
25
29
  positionFeeFactorForBalanceWasNotImproved: expandDecimals(5, 26),
@@ -34,6 +38,7 @@ describe("getMaxWithdrawAmount", () => {
34
38
  const collateralUsd = expandDecimals(4000, USD_DECIMALS);
35
39
  const sizeInTokens = (sizeInUsd * expandDecimals(1, ethToken.decimals)) / expandDecimals(1200, USD_DECIMALS);
36
40
  const collateralAmount = (collateralUsd * expandDecimals(1, usdcToken.decimals)) / USDC_PRICE;
41
+ const pnl = (sizeInTokens * ethPrice) / expandDecimals(1, ethToken.decimals) - sizeInUsd;
37
42
  const position = {
38
43
  key: "test-position",
39
44
  contractKey: "test-position",
@@ -50,7 +55,7 @@ describe("getMaxWithdrawAmount", () => {
50
55
  fundingFeeAmount: 0n,
51
56
  claimableLongTokenAmount: 0n,
52
57
  claimableShortTokenAmount: 0n,
53
- pnl: -expandDecimals(200, USD_DECIMALS),
58
+ pnl,
54
59
  positionFeeAmount: 0n,
55
60
  traderDiscountAmount: 0n,
56
61
  uiFeeAmount: 0n,
@@ -65,7 +70,7 @@ describe("getMaxWithdrawAmount", () => {
65
70
  poolName: "USDC",
66
71
  collateralToken: usdcToken,
67
72
  pnlToken: usdcToken,
68
- markPrice: ETH_PRICE,
73
+ markPrice: ethPrice,
69
74
  entryPrice: expandDecimals(1200, USD_DECIMALS),
70
75
  liquidationPrice: undefined,
71
76
  collateralUsd,
@@ -73,7 +78,7 @@ describe("getMaxWithdrawAmount", () => {
73
78
  remainingCollateralAmount: collateralAmount,
74
79
  hasLowCollateral: false,
75
80
  pnlPercentage: 0n,
76
- pnlAfterFees: -expandDecimals(200, USD_DECIMALS),
81
+ pnlAfterFees: pnl,
77
82
  pnlAfterFeesPercentage: 0n,
78
83
  pendingFundingFeesUsd: 0n,
79
84
  pendingClaimableFundingFeesUsd: 0n,
@@ -116,8 +121,8 @@ describe("getMaxWithdrawAmount", () => {
116
121
  expect(applyFactor(position.sizeInUsd, position.marketInfo.minCollateralFactorForLiquidation)).toBeGreaterThan(0n);
117
122
  expect(applyFactor(position.sizeInUsd, position.marketInfo.minCollateralFactor)).toBeGreaterThan(0n);
118
123
  });
119
- it("max withdraw equals the collateral above the min required collateral", () => {
120
- const { position, usdcToken } = buildScenario();
124
+ it("max withdraw equals the collateral above the min required collateral where both factors are equal", () => {
125
+ const { position, usdcToken } = buildScenario({ minCollateralFactorForLiquidation: expandDecimals(5, 27) });
121
126
  const minCollateralUsd = expandDecimals(1, USD_DECIMALS);
122
127
  const collateralPrice = usdcToken.prices.minPrice;
123
128
  const minRequiredCollateralUsd = getMinRequiredCollateralUsdForPosition({
@@ -160,4 +165,118 @@ describe("getMaxWithdrawAmount", () => {
160
165
  userReferralInfo: undefined,
161
166
  })).toBe(0n);
162
167
  });
168
+ it("returns zero instead of throwing when the max allowed leverage rounds down to zero", () => {
169
+ const { position, usdcToken } = buildScenario();
170
+ // a 25% min collateral factor allows under 5x, and the max allowed leverage is floored to 5x steps
171
+ const lowLeveragePosition = {
172
+ ...position,
173
+ marketInfo: { ...position.marketInfo, minCollateralFactor: expandDecimals(25, 28) },
174
+ };
175
+ expect(getMaxWithdrawAmount({
176
+ position: lowLeveragePosition,
177
+ minCollateralUsd: expandDecimals(1, USD_DECIMALS),
178
+ collateralPrice: usdcToken.prices.minPrice,
179
+ collateralDecimals: usdcToken.decimals,
180
+ userReferralInfo: undefined,
181
+ })).toBe(0n);
182
+ });
183
+ it("reserves the regular-factor minimum where it is above the liquidation one", () => {
184
+ const { position, usdcToken } = buildScenario();
185
+ const minCollateralUsd = expandDecimals(1, USD_DECIMALS);
186
+ const collateralPrice = usdcToken.prices.minPrice;
187
+ const maxWithdraw = getMaxWithdrawAmount({
188
+ position,
189
+ minCollateralUsd,
190
+ collateralPrice,
191
+ collateralDecimals: usdcToken.decimals,
192
+ userReferralInfo: undefined,
193
+ });
194
+ const maxWithdrawUsd = (maxWithdraw * collateralPrice) / expandDecimals(1, usdcToken.decimals);
195
+ const liquidationBasedMaxUsd = position.collateralUsd -
196
+ getMinRequiredCollateralUsdForPosition({ position, minCollateralUsd, userReferralInfo: undefined });
197
+ const factorGapUsd = applyFactor(position.sizeInUsd, position.marketInfo.minCollateralFactor - position.marketInfo.minCollateralFactorForLiquidation);
198
+ const reservedOnTopUsd = liquidationBasedMaxUsd - maxWithdrawUsd;
199
+ expect(factorGapUsd).toBe(expandDecimals(50, USD_DECIMALS));
200
+ expect(reservedOnTopUsd).toBeGreaterThanOrEqual(factorGapUsd);
201
+ expect(reservedOnTopUsd - factorGapUsd).toBeLessThan(expandDecimals(1, USD_DECIMALS - usdcToken.decimals));
202
+ });
203
+ it.each([
204
+ ["losing", LOSING_ETH_PRICE],
205
+ ["profitable", PROFITABLE_ETH_PRICE],
206
+ ])("is the largest withdrawal the contract check accepts for a %s position", (_name, ethPrice) => {
207
+ const { position, usdcToken } = buildScenario({ ethPrice });
208
+ const minCollateralUsd = expandDecimals(1, USD_DECIMALS);
209
+ const maxWithdraw = getMaxWithdrawAmount({
210
+ position,
211
+ minCollateralUsd,
212
+ collateralPrice: usdcToken.prices.minPrice,
213
+ collateralDecimals: usdcToken.decimals,
214
+ userReferralInfo: undefined,
215
+ });
216
+ const getMarginState = (collateralDeltaAmount) => getDecreaseResultingPositionMarginState({
217
+ marketInfo: position.marketInfo,
218
+ collateralToken: position.collateralToken,
219
+ isLong: position.isLong,
220
+ position,
221
+ sizeDeltaUsd: 0n,
222
+ sizeDeltaInTokens: 0n,
223
+ collateralDeltaAmount,
224
+ payedRemainingCollateralAmount: 0n,
225
+ priceImpactDiffUsd: 0n,
226
+ minCollateralUsd,
227
+ minPositionSizeUsd: expandDecimals(1, USD_DECIMALS),
228
+ userReferralInfo: undefined,
229
+ });
230
+ expect(maxWithdraw).toBeGreaterThan(0n);
231
+ expect(getMarginState(maxWithdraw)?.isLiquidatable).toBe(false);
232
+ });
233
+ it("stops at the contract check for a losing position", () => {
234
+ const { position, usdcToken } = buildScenario();
235
+ const minCollateralUsd = expandDecimals(1, USD_DECIMALS);
236
+ const maxWithdraw = getMaxWithdrawAmount({
237
+ position,
238
+ minCollateralUsd,
239
+ collateralPrice: usdcToken.prices.minPrice,
240
+ collateralDecimals: usdcToken.decimals,
241
+ userReferralInfo: undefined,
242
+ });
243
+ const marginState = getDecreaseResultingPositionMarginState({
244
+ marketInfo: position.marketInfo,
245
+ collateralToken: position.collateralToken,
246
+ isLong: position.isLong,
247
+ position,
248
+ sizeDeltaUsd: 0n,
249
+ sizeDeltaInTokens: 0n,
250
+ collateralDeltaAmount: maxWithdraw + 1n,
251
+ payedRemainingCollateralAmount: 0n,
252
+ priceImpactDiffUsd: 0n,
253
+ minCollateralUsd,
254
+ minPositionSizeUsd: expandDecimals(1, USD_DECIMALS),
255
+ userReferralInfo: undefined,
256
+ });
257
+ expect(marginState?.reason).toBe(PositionMarginFailureReason.MinCollateralForLeverage);
258
+ });
259
+ it("stops at the max allowed leverage for a profitable position", () => {
260
+ const { position, usdcToken } = buildScenario({ ethPrice: PROFITABLE_ETH_PRICE });
261
+ const collateralPrice = usdcToken.prices.minPrice;
262
+ const maxWithdraw = getMaxWithdrawAmount({
263
+ position,
264
+ minCollateralUsd: expandDecimals(1, USD_DECIMALS),
265
+ collateralPrice,
266
+ collateralDecimals: usdcToken.decimals,
267
+ userReferralInfo: undefined,
268
+ });
269
+ const maxAllowedLeverage = BigInt(getMaxAllowedLeverage({
270
+ marketAddress: position.marketInfo.marketTokenAddress,
271
+ minCollateralFactor: position.marketInfo.minCollateralFactor,
272
+ minCollateralFactorForLiquidation: position.marketInfo.minCollateralFactorForLiquidation,
273
+ positionFeeFactorForBalanceWasNotImproved: position.marketInfo.positionFeeFactorForBalanceWasNotImproved,
274
+ }));
275
+ const getNextLeverage = (withdrawAmount) => {
276
+ const withdrawUsd = (withdrawAmount * collateralPrice) / expandDecimals(1, usdcToken.decimals);
277
+ return (position.sizeInUsd * BASIS_POINTS_DIVISOR_BIGINT) / (position.collateralUsd - withdrawUsd);
278
+ };
279
+ expect(getNextLeverage(maxWithdraw)).toBe(maxAllowedLeverage);
280
+ expect(getNextLeverage(maxWithdraw + expandDecimals(1, usdcToken.decimals))).toBeGreaterThan(maxAllowedLeverage);
281
+ });
163
282
  });