@gmx-io/sdk 1.5.0-alpha-14 → 1.5.0-alpha-15

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 (36) hide show
  1. package/build/cjs/scripts/subsquid-codegen.js +1 -1
  2. package/build/cjs/src/clients/v1/modules/trades/trades.js +4 -0
  3. package/build/cjs/src/codegen/subsquid.js +6 -0
  4. package/build/cjs/src/test/mock.js +1 -0
  5. package/build/cjs/src/utils/__tests__/markets.spec.js +88 -48
  6. package/build/cjs/src/utils/__tests__/positions.spec.js +93 -0
  7. package/build/cjs/src/utils/markets/utils.js +20 -15
  8. package/build/cjs/src/utils/positions/utils.js +34 -2
  9. package/build/cjs/src/utils/prices/utils.js +4 -4
  10. package/build/cjs/src/utils/trade/decrease.js +1 -1
  11. package/build/cjs/src/utils/trade/increase.js +1 -1
  12. package/build/cjs/src/utils/tradeHistory/utils.js +1 -0
  13. package/build/esm/scripts/subsquid-codegen.js +1 -1
  14. package/build/esm/src/clients/v1/modules/trades/trades.js +4 -0
  15. package/build/esm/src/codegen/subsquid.js +6 -0
  16. package/build/esm/src/test/mock.js +1 -0
  17. package/build/esm/src/utils/__tests__/markets.spec.js +90 -50
  18. package/build/esm/src/utils/__tests__/positions.spec.js +94 -1
  19. package/build/esm/src/utils/markets/utils.js +17 -12
  20. package/build/esm/src/utils/positions/utils.js +32 -2
  21. package/build/esm/src/utils/prices/utils.js +4 -4
  22. package/build/esm/src/utils/trade/decrease.js +1 -1
  23. package/build/esm/src/utils/trade/increase.js +1 -1
  24. package/build/esm/src/utils/tradeHistory/utils.js +1 -0
  25. package/build/types/src/codegen/subsquid.d.ts +16 -0
  26. package/build/types/src/utils/markets/utils.d.ts +5 -1
  27. package/build/types/src/utils/positions/types.d.ts +3 -0
  28. package/build/types/src/utils/positions/utils.d.ts +15 -0
  29. package/build/types/src/utils/prices/utils.d.ts +1 -1
  30. package/build/types/src/utils/swap/types.d.ts +1 -1
  31. package/build/types/src/utils/trade/types.d.ts +4 -1
  32. package/build/types/src/utils/tradeHistory/types.d.ts +1 -0
  33. package/package.json +1 -1
  34. package/build/cjs/src/configs/marketHours.js +0 -41
  35. package/build/esm/src/configs/marketHours.js +0 -38
  36. package/build/types/src/configs/marketHours.d.ts +0 -7
@@ -1,9 +1,8 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import { ARBITRUM } from "../../configs/chains";
3
- import { BASIS_POINTS_DIVISOR } from "../../configs/factors";
4
3
  import { TOKENS } from "../../configs/tokens";
5
- import { getMarketFullName, getMarketIndexName, getMarketPoolName, getContractMarketPrices, getTokenPoolType, getPoolUsdWithoutPnl, getCappedPoolPnl, getMaxLeverageByMinCollateralFactor, getMaxAllowedLeverageByMinCollateralFactor, getOppositeCollateral, getAvailableUsdLiquidityForCollateral, getReservedUsd, getMarketDivisor, getMarketPnl, getOpenInterestUsd, getOpenInterestInTokens, getPriceForPnl, } from "../markets";
6
- import { expandDecimals, numberToBigint, PRECISION_DECIMALS } from "../numbers";
4
+ import { getMarketFullName, getMarketIndexName, getMarketPoolName, getContractMarketPrices, getTokenPoolType, getPoolUsdWithoutPnl, getCappedPoolPnl, getMaxLeverageByMinCollateralFactor, getMaxAllowedLeverage, getOppositeCollateral, getAvailableUsdLiquidityForCollateral, getReservedUsd, getMarketDivisor, getMarketPnl, getOpenInterestUsd, getOpenInterestInTokens, getPriceForPnl, } from "../markets";
5
+ import { BASIS_POINTS_DIVISOR, expandDecimals } from "../numbers";
7
6
  function getToken(symbol) {
8
7
  return TOKENS[ARBITRUM].find((token) => token.symbol === symbol);
9
8
  }
@@ -140,53 +139,94 @@ describe("getMaxLeverageByMinCollateralFactor", () => {
140
139
  expect(getMaxLeverageByMinCollateralFactor(1000000000000000000n)).toBe(10000000000000000);
141
140
  });
142
141
  });
143
- describe("getMaxAllowedLeverageByMinCollateralFactor", () => {
144
- const GOLD_MARKET = "0x0Df2BE76F517BCF0000AbfFcB6344B3b2aC4Cc4f";
145
- const SILVER_MARKET = "0x448Fa722717df299ee197E2F6d8EB7911EFF6cEc";
146
- const WTIOIL_MARKET = "0xda81cdd397210C08cFc567f93982E148A3aac8a6";
147
- const BRENTOIL_MARKET = "0x6F287D071800BfA847B4a7a7104BE33F87Ce9E74";
148
- const NATGAS_MARKET = "0x2Ce2bc8B0f9d000f359d756a5816C125474Bb39b";
149
- const NON_MARKET_HOURS_MARKET = "0x1234567890abcdef1234567890abcdef12345678";
150
- it("returns half of max leverage when no market address is provided", () => {
151
- expect(getMaxAllowedLeverageByMinCollateralFactor(1000000000000000000n, undefined)).toBe(5000000000000000);
152
- });
153
- it("returns half of max leverage for a regular market", () => {
154
- expect(getMaxAllowedLeverageByMinCollateralFactor(1000000000000000000n, NON_MARKET_HOURS_MARKET)).toBe(5000000000000000);
155
- });
156
- it("returns 100x for GOLD on on-hours MCF (0.009 → 110x contract max)", () => {
157
- const onHoursFactor = 9n * 10n ** 27n;
158
- expect(getMaxAllowedLeverageByMinCollateralFactor(onHoursFactor, GOLD_MARKET)).toBe(100 * BASIS_POINTS_DIVISOR);
159
- });
160
- it("returns 25x for GOLD on off-hours MCF (0.035 → 30x contract max)", () => {
161
- const offHoursFactor = 35n * 10n ** 27n;
162
- expect(getMaxAllowedLeverageByMinCollateralFactor(offHoursFactor, GOLD_MARKET)).toBe(25 * BASIS_POINTS_DIVISOR);
163
- });
164
- it("returns 100x / 25x for SILVER with the same GOLD MCFs", () => {
165
- expect(getMaxAllowedLeverageByMinCollateralFactor(9n * 10n ** 27n, SILVER_MARKET)).toBe(100 * BASIS_POINTS_DIVISOR);
166
- expect(getMaxAllowedLeverageByMinCollateralFactor(35n * 10n ** 27n, SILVER_MARKET)).toBe(25 * BASIS_POINTS_DIVISOR);
167
- });
168
- it("returns 100x for WTIOIL on-hours MCF and 25x for off-hours MCF", () => {
169
- expect(getMaxAllowedLeverageByMinCollateralFactor(9n * 10n ** 27n, WTIOIL_MARKET)).toBe(100 * BASIS_POINTS_DIVISOR);
170
- expect(getMaxAllowedLeverageByMinCollateralFactor(35n * 10n ** 27n, WTIOIL_MARKET)).toBe(25 * BASIS_POINTS_DIVISOR);
171
- });
172
- it("returns 100x for BRENTOIL on-hours MCF and 25x for off-hours MCF", () => {
173
- expect(getMaxAllowedLeverageByMinCollateralFactor(9n * 10n ** 27n, BRENTOIL_MARKET)).toBe(100 * BASIS_POINTS_DIVISOR);
174
- expect(getMaxAllowedLeverageByMinCollateralFactor(35n * 10n ** 27n, BRENTOIL_MARKET)).toBe(25 * BASIS_POINTS_DIVISOR);
175
- });
176
- it("returns 40x for NATGAS on-hours MCF and 20x for off-hours MCF", () => {
177
- expect(getMaxAllowedLeverageByMinCollateralFactor(22n * 10n ** 27n, NATGAS_MARKET)).toBe(40 * BASIS_POINTS_DIVISOR);
178
- expect(getMaxAllowedLeverageByMinCollateralFactor(40n * 10n ** 27n, NATGAS_MARKET)).toBe(20 * BASIS_POINTS_DIVISOR);
179
- });
180
- it("does not apply market-hours overrides to other markets with same MCF", () => {
181
- const onHoursFactor = 9n * 10n ** 27n;
182
- const offHoursFactor = 35n * 10n ** 27n;
183
- expect(getMaxAllowedLeverageByMinCollateralFactor(onHoursFactor, NON_MARKET_HOURS_MARKET)).toBe(55.5 * BASIS_POINTS_DIVISOR);
184
- expect(getMaxAllowedLeverageByMinCollateralFactor(offHoursFactor, NON_MARKET_HOURS_MARKET)).toBe(14.5 * BASIS_POINTS_DIVISOR);
185
- });
186
- it("rounds allowed leverage to nearest .0 or .5", () => {
187
- expect(getMaxAllowedLeverageByMinCollateralFactor(numberToBigint(1 / 24, PRECISION_DECIMALS), undefined)).toBe(12 * BASIS_POINTS_DIVISOR);
188
- expect(getMaxAllowedLeverageByMinCollateralFactor(numberToBigint(1 / 25, PRECISION_DECIMALS), undefined)).toBe(12.5 * BASIS_POINTS_DIVISOR);
189
- expect(getMaxAllowedLeverageByMinCollateralFactor(numberToBigint(1 / 50, PRECISION_DECIMALS), undefined)).toBe(25 * BASIS_POINTS_DIVISOR);
142
+ describe("getMaxAllowedLeverage", () => {
143
+ // Factors are expressed in PRECISION units (1e30 == 100%).
144
+ const pct = (percent) => expandDecimals(percent * 100, 26); // 0.5% → 5e27
145
+ const bps = (lev) => lev * BASIS_POINTS_DIVISOR;
146
+ it("returns default 100x when any factor is undefined or zero", () => {
147
+ expect(getMaxAllowedLeverage({
148
+ minCollateralFactor: undefined,
149
+ minCollateralFactorForLiquidation: undefined,
150
+ positionFeeFactorForBalanceWasNotImproved: undefined,
151
+ })).toBe(bps(100));
152
+ expect(getMaxAllowedLeverage({
153
+ minCollateralFactor: 0n,
154
+ minCollateralFactorForLiquidation: pct(0.5),
155
+ positionFeeFactorForBalanceWasNotImproved: pct(0.05),
156
+ })).toBe(bps(100));
157
+ expect(getMaxAllowedLeverage({
158
+ minCollateralFactor: pct(0.5),
159
+ minCollateralFactorForLiquidation: 0n,
160
+ positionFeeFactorForBalanceWasNotImproved: pct(0.05),
161
+ })).toBe(bps(100));
162
+ expect(getMaxAllowedLeverage({
163
+ minCollateralFactor: pct(0.5),
164
+ minCollateralFactorForLiquidation: pct(0.5),
165
+ positionFeeFactorForBalanceWasNotImproved: undefined,
166
+ })).toBe(bps(100));
167
+ });
168
+ it("returns 100x for BTC/ETH (equal MCF and liqMCF, liquidation bound dominates)", () => {
169
+ // MCF = liqMCF = 0.5%, fee = 0.05%
170
+ // opening = 1 / (0.005 + 0.001) ≈ 166.67x
171
+ // liquidation = 1 / (2 × 0.005) = 100x
172
+ // min floored to 5x = 100x
173
+ expect(getMaxAllowedLeverage({
174
+ minCollateralFactor: pct(0.5),
175
+ minCollateralFactorForLiquidation: pct(0.5),
176
+ positionFeeFactorForBalanceWasNotImproved: pct(0.05),
177
+ })).toBe(bps(100));
178
+ });
179
+ it("returns 85x for ZEC (opening bound dominates, floors to 5x)", () => {
180
+ // MCF = 1%, liqMCF = 0.5%, fee = 0.06%
181
+ // opening = 1 / (0.01 + 0.0012) ≈ 89.29x
182
+ // liquidation = 1 / (2 × 0.005) = 100x
183
+ // min floored to 5x = 85x
184
+ expect(getMaxAllowedLeverage({
185
+ minCollateralFactor: pct(1),
186
+ minCollateralFactorForLiquidation: pct(0.5),
187
+ positionFeeFactorForBalanceWasNotImproved: pct(0.06),
188
+ })).toBe(bps(85));
189
+ });
190
+ it("returns 100x for GOLD on-hours (split factors)", () => {
191
+ // MCF = 0.9%, liqMCF = 0.5%, fee = 0.05%
192
+ // opening = 1 / (0.009 + 0.001) = 100x
193
+ // liquidation = 1 / (2 × 0.005) = 100x
194
+ expect(getMaxAllowedLeverage({
195
+ minCollateralFactor: 9n * 10n ** 27n,
196
+ minCollateralFactorForLiquidation: pct(0.5),
197
+ positionFeeFactorForBalanceWasNotImproved: pct(0.05),
198
+ })).toBe(bps(100));
199
+ });
200
+ it("returns 25x for GOLD off-hours (split factors, opening bound dominates)", () => {
201
+ // MCF = 3.5%, liqMCF = 1%, fee = 0.05%
202
+ // opening = 1 / (0.035 + 0.001) ≈ 27.78x
203
+ // liquidation = 1 / (2 × 0.01) = 50x
204
+ // min floored to 5x = 25x
205
+ expect(getMaxAllowedLeverage({
206
+ minCollateralFactor: 35n * 10n ** 27n,
207
+ minCollateralFactorForLiquidation: pct(1),
208
+ positionFeeFactorForBalanceWasNotImproved: pct(0.05),
209
+ })).toBe(bps(25));
210
+ });
211
+ it("floors to the nearest 5x", () => {
212
+ // Choose factors so opening = 47.17x exactly, should floor to 45x
213
+ // 1 / (MCF + 2×fee) = 47.17 → MCF + 2×fee ≈ 0.0212
214
+ // MCF = 2%, fee = 0.06% → 0.02 + 0.0012 = 0.0212 → 1/0.0212 ≈ 47.17
215
+ expect(getMaxAllowedLeverage({
216
+ minCollateralFactor: pct(2),
217
+ minCollateralFactorForLiquidation: pct(0.5),
218
+ positionFeeFactorForBalanceWasNotImproved: pct(0.06),
219
+ })).toBe(bps(45));
220
+ });
221
+ it("liquidation bound dominates when MCF-for-liquidation is relatively high", () => {
222
+ // MCF = 0.5%, liqMCF = 2%, fee = 0.05%
223
+ // opening = 1 / (0.005 + 0.001) ≈ 166.67x
224
+ // liquidation = 1 / (2 × 0.02) = 25x → min 25x
225
+ expect(getMaxAllowedLeverage({
226
+ minCollateralFactor: pct(0.5),
227
+ minCollateralFactorForLiquidation: pct(2),
228
+ positionFeeFactorForBalanceWasNotImproved: pct(0.05),
229
+ })).toBe(bps(25));
190
230
  });
191
231
  });
192
232
  describe("getOppositeCollateral", () => {
@@ -3,7 +3,7 @@ import { bigMath } from "../bigmath";
3
3
  import { getPositionFee, getPriceImpactForPosition } from "../fees";
4
4
  import { getCappedPoolPnl, getMarketPnl, getPoolUsdWithoutPnl } from "../markets";
5
5
  import { expandDecimals, USD_DECIMALS } from "../numbers";
6
- import { getEntryPrice, getLeverage, getLiquidationPrice, getPositionKey, getPositionNetValue, getPositionPendingFeesUsd, getPositionPnlAfterFees, getPositionPnlUsd, getPositionValueUsd, parsePositionKey, } from "../positions";
6
+ import { getEntryPrice, getLeverage, getLiquidationPrice, getPositionKey, getPositionNetValue, getPositionNetValueAfterAllFees, getPositionPendingFeesUsd, getPositionPnlAfterAllFees, getPositionPnlAfterFees, getPositionPnlUsd, getPositionValueUsd, parsePositionKey, } from "../positions";
7
7
  import { convertToUsd, getIsEquivalentTokens } from "../tokens";
8
8
  vi.mock("../markets", () => ({
9
9
  ...vi.importActual("../markets"),
@@ -148,6 +148,99 @@ describe("getPositionPnlAfterFees", () => {
148
148
  expect(result).toBe(-70n);
149
149
  });
150
150
  });
151
+ describe("getPositionNetValueAfterAllFees", () => {
152
+ it("subtracts all fees and adds signed price impact (adverse)", () => {
153
+ const result = getPositionNetValueAfterAllFees({
154
+ collateralUsd: 1000n,
155
+ pnl: 200n,
156
+ pendingBorrowingFeesUsd: 15n,
157
+ pendingFundingFeesUsd: 10n,
158
+ netPriceImpactDeltaUsd: -50n,
159
+ closingFeeUsd: 30n,
160
+ });
161
+ // 1000 + 200 - 15 - 10 + (-50) - 30 = 1095
162
+ expect(result).toBe(1095n);
163
+ });
164
+ it("adds favorable price impact", () => {
165
+ const result = getPositionNetValueAfterAllFees({
166
+ collateralUsd: 1000n,
167
+ pnl: 200n,
168
+ pendingBorrowingFeesUsd: 0n,
169
+ pendingFundingFeesUsd: 0n,
170
+ netPriceImpactDeltaUsd: 25n,
171
+ closingFeeUsd: 0n,
172
+ });
173
+ // 1000 + 200 + 25 = 1225
174
+ expect(result).toBe(1225n);
175
+ });
176
+ it("reduces to collateral when pnl, fees, and impact are zero", () => {
177
+ const result = getPositionNetValueAfterAllFees({
178
+ collateralUsd: 500n,
179
+ pnl: 0n,
180
+ pendingBorrowingFeesUsd: 0n,
181
+ pendingFundingFeesUsd: 0n,
182
+ netPriceImpactDeltaUsd: 0n,
183
+ closingFeeUsd: 0n,
184
+ });
185
+ expect(result).toBe(500n);
186
+ });
187
+ it("handles negative pnl with adverse impact", () => {
188
+ const result = getPositionNetValueAfterAllFees({
189
+ collateralUsd: 1000n,
190
+ pnl: -300n,
191
+ pendingBorrowingFeesUsd: 5n,
192
+ pendingFundingFeesUsd: 5n,
193
+ netPriceImpactDeltaUsd: -20n,
194
+ closingFeeUsd: 10n,
195
+ });
196
+ // 1000 - 300 - 5 - 5 - 20 - 10 = 660
197
+ expect(result).toBe(660n);
198
+ });
199
+ });
200
+ describe("getPositionPnlAfterAllFees", () => {
201
+ it("subtracts all fees and adds signed price impact (adverse) from pnl", () => {
202
+ const result = getPositionPnlAfterAllFees({
203
+ pnl: 500n,
204
+ pendingBorrowingFeesUsd: 30n,
205
+ pendingFundingFeesUsd: 20n,
206
+ netPriceImpactDeltaUsd: -40n,
207
+ closingFeeUsd: 50n,
208
+ });
209
+ // 500 - 30 - 20 - 40 - 50 = 360
210
+ expect(result).toBe(360n);
211
+ });
212
+ it("adds favorable price impact to pnl", () => {
213
+ const result = getPositionPnlAfterAllFees({
214
+ pnl: 100n,
215
+ pendingBorrowingFeesUsd: 0n,
216
+ pendingFundingFeesUsd: 0n,
217
+ netPriceImpactDeltaUsd: 50n,
218
+ closingFeeUsd: 0n,
219
+ });
220
+ expect(result).toBe(150n);
221
+ });
222
+ it("returns pnl when fees and impact are zero", () => {
223
+ const result = getPositionPnlAfterAllFees({
224
+ pnl: 200n,
225
+ pendingBorrowingFeesUsd: 0n,
226
+ pendingFundingFeesUsd: 0n,
227
+ netPriceImpactDeltaUsd: 0n,
228
+ closingFeeUsd: 0n,
229
+ });
230
+ expect(result).toBe(200n);
231
+ });
232
+ it("handles negative pnl with adverse impact", () => {
233
+ const result = getPositionPnlAfterAllFees({
234
+ pnl: -100n,
235
+ pendingBorrowingFeesUsd: 10n,
236
+ pendingFundingFeesUsd: 5n,
237
+ netPriceImpactDeltaUsd: -20n,
238
+ closingFeeUsd: 30n,
239
+ });
240
+ // -100 - 10 - 5 - 20 - 30 = -165
241
+ expect(result).toBe(-165n);
242
+ });
243
+ });
151
244
  describe("getLeverage", () => {
152
245
  it("returns undefined if remainingCollateralUsd <= 0", () => {
153
246
  const result = getLeverage({
@@ -1,6 +1,5 @@
1
1
  import { zeroAddress } from "viem";
2
2
  import { BASIS_POINTS_DIVISOR, BASIS_POINTS_DIVISOR_BIGINT } from "../../configs/factors";
3
- import { MARKET_HOURS_MARKETS } from "../../configs/marketHours";
4
3
  import { convertTokenAddress, getTokenVisualMultiplier, NATIVE_TOKEN_ADDRESS } from "../../configs/tokens";
5
4
  import { bigMath } from "../bigmath";
6
5
  import { getBorrowingFactorPerPeriod, getFundingFactorPerPeriod } from "../fees";
@@ -85,7 +84,9 @@ export function getCappedPoolPnl(p) {
85
84
  return poolPnl > maxPnl ? maxPnl : poolPnl;
86
85
  }
87
86
  /**
88
- * Rounds to nearest .0 leverage, so that getMaxAllowedLeverageByMinCollateralFactor can get .0 or .5 leverage.
87
+ * Theoretical max leverage derived purely from minCollateralFactor. Does not account for
88
+ * fees or the liquidation safety buffer. Used by the deposit-collateral path where the
89
+ * user is not opening a new size.
89
90
  */
90
91
  const ROUNDING_VALUE = 10000;
91
92
  export function getMaxLeverageByMinCollateralFactor(minCollateralFactor) {
@@ -97,17 +98,21 @@ export function getMaxLeverageByMinCollateralFactor(minCollateralFactor) {
97
98
  const rounded = Math.round(Number(x) / ROUNDING_VALUE) * ROUNDING_VALUE;
98
99
  return rounded;
99
100
  }
100
- export function getMaxAllowedLeverageByMinCollateralFactor(minCollateralFactor, marketAddress) {
101
- if (marketAddress) {
102
- const cfg = MARKET_HOURS_MARKETS[marketAddress];
103
- if (cfg) {
104
- if (minCollateralFactor === cfg.onHoursMcf)
105
- return cfg.onHoursMaxLeverage * BASIS_POINTS_DIVISOR;
106
- if (minCollateralFactor === cfg.offHoursMcf)
107
- return cfg.offHoursMaxLeverage * BASIS_POINTS_DIVISOR;
108
- }
101
+ const MAX_ALLOWED_LEVERAGE_STEP_BP = 5 * BASIS_POINTS_DIVISOR;
102
+ export function getMaxAllowedLeverage({ minCollateralFactor, minCollateralFactorForLiquidation, positionFeeFactorForBalanceWasNotImproved, }) {
103
+ if (minCollateralFactor === undefined ||
104
+ minCollateralFactor === 0n ||
105
+ minCollateralFactorForLiquidation === undefined ||
106
+ minCollateralFactorForLiquidation === 0n ||
107
+ positionFeeFactorForBalanceWasNotImproved === undefined) {
108
+ return 100 * BASIS_POINTS_DIVISOR;
109
109
  }
110
- return getMaxLeverageByMinCollateralFactor(minCollateralFactor) / 2;
110
+ const openingDenominator = minCollateralFactor + 2n * positionFeeFactorForBalanceWasNotImproved;
111
+ const openingMaxBp = bigMath.mulDiv(PRECISION, BASIS_POINTS_DIVISOR_BIGINT, openingDenominator);
112
+ const liquidationDenominator = 2n * minCollateralFactorForLiquidation;
113
+ const liquidationMaxBp = bigMath.mulDiv(PRECISION, BASIS_POINTS_DIVISOR_BIGINT, liquidationDenominator);
114
+ const rawMaxBp = bigMath.min(openingMaxBp, liquidationMaxBp);
115
+ return Math.floor(Number(rawMaxBp) / MAX_ALLOWED_LEVERAGE_STEP_BP) * MAX_ALLOWED_LEVERAGE_STEP_BP;
111
116
  }
112
117
  export function getOppositeCollateral(marketInfo, tokenAddress) {
113
118
  const poolType = getTokenPoolType(marketInfo, tokenAddress);
@@ -1,7 +1,7 @@
1
1
  import { BASIS_POINTS_DIVISOR_BIGINT } from "../../configs/factors";
2
2
  import { bigMath } from "../bigmath";
3
3
  import { capPositionImpactUsdByMaxImpactPool, capPositionImpactUsdByMaxPriceImpactFactor, getMaxPositionImpactFactors, getPositionFee, getPriceImpactForPosition, getProportionalPendingImpactValues, } from "../fees";
4
- import { getCappedPoolPnl, getMarketIndexName, getMarketPnl, getMarketPoolName, getMaxAllowedLeverageByMinCollateralFactor, getOpenInterestUsd, getPoolUsdWithoutPnl, } from "../markets";
4
+ import { getCappedPoolPnl, getMarketIndexName, getMarketPnl, getMarketPoolName, getMaxAllowedLeverage, getOpenInterestUsd, getPoolUsdWithoutPnl, } from "../markets";
5
5
  import { applyFactor, expandDecimals, FLOAT_PRECISION_SQRT, getBasisPoints, PRECISION } from "../numbers";
6
6
  import { getAcceptablePriceInfo, getMarkPrice } from "../prices";
7
7
  import { convertToTokenAmount, convertToUsd, getIsEquivalentTokens } from "../tokens";
@@ -53,10 +53,17 @@ export function getPositionNetValue(p) {
53
53
  const pendingFeesUsd = getPositionPendingFeesUsd(p);
54
54
  return collateralUsd - pendingFeesUsd + pnl;
55
55
  }
56
+ export function getPositionNetValueAfterAllFees(p) {
57
+ const { collateralUsd, pnl, pendingBorrowingFeesUsd, pendingFundingFeesUsd, netPriceImpactDeltaUsd, closingFeeUsd } = p;
58
+ return collateralUsd + pnl - pendingBorrowingFeesUsd - pendingFundingFeesUsd + netPriceImpactDeltaUsd - closingFeeUsd;
59
+ }
56
60
  export function getPositionPnlAfterFees({ pnl, pendingBorrowingFeesUsd, pendingFundingFeesUsd, }) {
57
61
  const pnlAfterFees = pnl - pendingBorrowingFeesUsd - pendingFundingFeesUsd;
58
62
  return pnlAfterFees;
59
63
  }
64
+ export function getPositionPnlAfterAllFees({ pnl, pendingBorrowingFeesUsd, pendingFundingFeesUsd, netPriceImpactDeltaUsd, closingFeeUsd, }) {
65
+ return pnl - pendingBorrowingFeesUsd - pendingFundingFeesUsd + netPriceImpactDeltaUsd - closingFeeUsd;
66
+ }
60
67
  export function getLeverage(p) {
61
68
  const { pnl, sizeInUsd, collateralUsd, pendingBorrowingFeesUsd, pendingFundingFeesUsd } = p;
62
69
  const totalPendingFeesUsd = getPositionPendingFeesUsd({ pendingFundingFeesUsd, pendingBorrowingFeesUsd });
@@ -308,6 +315,22 @@ export function getPositionInfo(p) {
308
315
  pendingFundingFeesUsd,
309
316
  });
310
317
  const pnlAfterFeesPercentage = collateralUsd !== 0n ? getBasisPoints(pnlAfterFees, collateralUsd) : 0n;
318
+ const netValueAfterAllFees = getPositionNetValueAfterAllFees({
319
+ collateralUsd,
320
+ pnl,
321
+ pendingBorrowingFeesUsd: position.pendingBorrowingFeesUsd,
322
+ pendingFundingFeesUsd,
323
+ netPriceImpactDeltaUsd: netPriceImpactValues.totalImpactDeltaUsd,
324
+ closingFeeUsd,
325
+ });
326
+ const pnlAfterAllFees = getPositionPnlAfterAllFees({
327
+ pnl,
328
+ pendingBorrowingFeesUsd: position.pendingBorrowingFeesUsd,
329
+ pendingFundingFeesUsd,
330
+ netPriceImpactDeltaUsd: netPriceImpactValues.totalImpactDeltaUsd,
331
+ closingFeeUsd,
332
+ });
333
+ const pnlAfterAllFeesPercentage = collateralUsd !== 0n ? getBasisPoints(pnlAfterAllFees, collateralUsd) : 0n;
311
334
  const leverage = getLeverage({
312
335
  sizeInUsd: position.sizeInUsd,
313
336
  collateralUsd,
@@ -329,7 +352,11 @@ export function getPositionInfo(p) {
329
352
  pendingFundingFeesUsd,
330
353
  pnl: undefined,
331
354
  });
332
- const maxAllowedLeverage = getMaxAllowedLeverageByMinCollateralFactor(marketInfo.minCollateralFactor, marketInfo.marketTokenAddress);
355
+ const maxAllowedLeverage = getMaxAllowedLeverage({
356
+ minCollateralFactor: marketInfo.minCollateralFactor,
357
+ minCollateralFactorForLiquidation: marketInfo.minCollateralFactorForLiquidation,
358
+ positionFeeFactorForBalanceWasNotImproved: marketInfo.positionFeeFactorForBalanceWasNotImproved,
359
+ });
333
360
  const hasLowCollateral = (leverage !== undefined && leverage > maxAllowedLeverage) || false;
334
361
  const liquidationPrice = getLiquidationPrice({
335
362
  marketInfo,
@@ -382,6 +409,9 @@ export function getPositionInfo(p) {
382
409
  pnlPercentage,
383
410
  pnlAfterFees,
384
411
  pnlAfterFeesPercentage,
412
+ netValueAfterAllFees,
413
+ pnlAfterAllFees,
414
+ pnlAfterAllFeesPercentage,
385
415
  netValue,
386
416
  netPriceImapctDeltaUsd: netPriceImpactValues.totalImpactDeltaUsd,
387
417
  priceImpactDiffUsd: netPriceImpactValues.priceImpactDiffUsd,
@@ -118,9 +118,9 @@ export function getAcceptablePriceByPriceImpact(p) {
118
118
  };
119
119
  }
120
120
  export function getDefaultAcceptablePriceImpactBps(p) {
121
- const { indexPrice, sizeDeltaUsd, priceImpactDeltaUsd, acceptablePriceImapctBuffer = DEFAULT_ACCEPTABLE_PRICE_IMPACT_BUFFER, } = p;
121
+ const { indexPrice, sizeDeltaUsd, priceImpactDeltaUsd, acceptablePriceImpactBuffer = DEFAULT_ACCEPTABLE_PRICE_IMPACT_BUFFER, } = p;
122
122
  if (priceImpactDeltaUsd > 0) {
123
- return BigInt(acceptablePriceImapctBuffer);
123
+ return BigInt(acceptablePriceImpactBuffer);
124
124
  }
125
125
  const baseAcceptablePriceValues = getAcceptablePriceByPriceImpact({
126
126
  isIncrease: p.isIncrease,
@@ -130,7 +130,7 @@ export function getDefaultAcceptablePriceImpactBps(p) {
130
130
  priceImpactDeltaUsd,
131
131
  });
132
132
  if (baseAcceptablePriceValues.acceptablePriceDeltaBps < 0) {
133
- return bigMath.abs(baseAcceptablePriceValues.acceptablePriceDeltaBps) + BigInt(acceptablePriceImapctBuffer);
133
+ return bigMath.abs(baseAcceptablePriceValues.acceptablePriceDeltaBps) + BigInt(acceptablePriceImpactBuffer);
134
134
  }
135
- return BigInt(acceptablePriceImapctBuffer);
135
+ return BigInt(acceptablePriceImpactBuffer);
136
136
  }
@@ -377,7 +377,7 @@ function applyAcceptablePrice(p) {
377
377
  indexPrice: values.indexPrice,
378
378
  sizeDeltaUsd: values.sizeDeltaUsd,
379
379
  priceImpactDeltaUsd: values.closePriceImpactDeltaUsd,
380
- acceptablePriceImapctBuffer: acceptablePriceImpactBuffer || DEFAULT_ACCEPTABLE_PRICE_IMPACT_BUFFER,
380
+ acceptablePriceImpactBuffer: acceptablePriceImpactBuffer || DEFAULT_ACCEPTABLE_PRICE_IMPACT_BUFFER,
381
381
  });
382
382
  if (maxNegativePriceImpactBps === undefined) {
383
383
  maxNegativePriceImpactBps = values.recommendedAcceptablePriceDeltaBps;
@@ -271,7 +271,7 @@ export function getIncreasePositionAmounts(p) {
271
271
  indexPrice: values.indexPrice,
272
272
  sizeDeltaUsd: values.sizeDeltaUsd,
273
273
  priceImpactDeltaUsd: values.positionPriceImpactDeltaUsd,
274
- acceptablePriceImapctBuffer: acceptablePriceImpactBuffer || DEFAULT_ACCEPTABLE_PRICE_IMPACT_BUFFER,
274
+ acceptablePriceImpactBuffer: acceptablePriceImpactBuffer || DEFAULT_ACCEPTABLE_PRICE_IMPACT_BUFFER,
275
275
  });
276
276
  if (maxNegativePriceImpactBps === undefined) {
277
277
  maxNegativePriceImpactBps = values.recommendedAcceptablePriceDeltaBps;
@@ -114,6 +114,7 @@ export function createRawTradeActionTransformer(marketsInfoData, wrappedToken, t
114
114
  basePnlUsd: rawAction.basePnlUsd ? BigInt(rawAction.basePnlUsd) : undefined,
115
115
  priceImpactDiffUsd: rawAction.priceImpactDiffUsd ? BigInt(rawAction.priceImpactDiffUsd) : undefined,
116
116
  priceImpactUsd: rawAction.priceImpactUsd ? BigInt(rawAction.priceImpactUsd) : undefined,
117
+ swapImpactUsd: rawAction.swapImpactUsd ? BigInt(rawAction.swapImpactUsd) : undefined,
117
118
  totalImpactUsd: rawAction.totalImpactUsd ? BigInt(rawAction.totalImpactUsd) : undefined,
118
119
  positionFeeAmount: rawAction.positionFeeAmount ? BigInt(rawAction.positionFeeAmount) : undefined,
119
120
  borrowingFeeAmount: rawAction.borrowingFeeAmount ? BigInt(rawAction.borrowingFeeAmount) : undefined,
@@ -2987,6 +2987,7 @@ export interface MarketInfo {
2987
2987
  maxShortPoolAmount: Scalars["BigInt"]["output"];
2988
2988
  maxShortPoolUsdForDeposit: Scalars["BigInt"]["output"];
2989
2989
  minCollateralFactor: Scalars["BigInt"]["output"];
2990
+ minCollateralFactorForLiquidation: Scalars["BigInt"]["output"];
2990
2991
  minCollateralFactorForOpenInterestLong: Scalars["BigInt"]["output"];
2991
2992
  minCollateralFactorForOpenInterestShort: Scalars["BigInt"]["output"];
2992
2993
  minFundingFactorPerSecond: Scalars["BigInt"]["output"];
@@ -3317,6 +3318,12 @@ export declare enum MarketInfoOrderByInput {
3317
3318
  maxShortPoolUsdForDeposit_DESC = "maxShortPoolUsdForDeposit_DESC",
3318
3319
  maxShortPoolUsdForDeposit_DESC_NULLS_FIRST = "maxShortPoolUsdForDeposit_DESC_NULLS_FIRST",
3319
3320
  maxShortPoolUsdForDeposit_DESC_NULLS_LAST = "maxShortPoolUsdForDeposit_DESC_NULLS_LAST",
3321
+ minCollateralFactorForLiquidation_ASC = "minCollateralFactorForLiquidation_ASC",
3322
+ minCollateralFactorForLiquidation_ASC_NULLS_FIRST = "minCollateralFactorForLiquidation_ASC_NULLS_FIRST",
3323
+ minCollateralFactorForLiquidation_ASC_NULLS_LAST = "minCollateralFactorForLiquidation_ASC_NULLS_LAST",
3324
+ minCollateralFactorForLiquidation_DESC = "minCollateralFactorForLiquidation_DESC",
3325
+ minCollateralFactorForLiquidation_DESC_NULLS_FIRST = "minCollateralFactorForLiquidation_DESC_NULLS_FIRST",
3326
+ minCollateralFactorForLiquidation_DESC_NULLS_LAST = "minCollateralFactorForLiquidation_DESC_NULLS_LAST",
3320
3327
  minCollateralFactorForOpenInterestLong_ASC = "minCollateralFactorForOpenInterestLong_ASC",
3321
3328
  minCollateralFactorForOpenInterestLong_ASC_NULLS_FIRST = "minCollateralFactorForOpenInterestLong_ASC_NULLS_FIRST",
3322
3329
  minCollateralFactorForOpenInterestLong_ASC_NULLS_LAST = "minCollateralFactorForOpenInterestLong_ASC_NULLS_LAST",
@@ -4043,6 +4050,15 @@ export interface MarketInfoWhereInput {
4043
4050
  maxShortPoolUsdForDeposit_lte?: InputMaybe<Scalars["BigInt"]["input"]>;
4044
4051
  maxShortPoolUsdForDeposit_not_eq?: InputMaybe<Scalars["BigInt"]["input"]>;
4045
4052
  maxShortPoolUsdForDeposit_not_in?: InputMaybe<Array<Scalars["BigInt"]["input"]>>;
4053
+ minCollateralFactorForLiquidation_eq?: InputMaybe<Scalars["BigInt"]["input"]>;
4054
+ minCollateralFactorForLiquidation_gt?: InputMaybe<Scalars["BigInt"]["input"]>;
4055
+ minCollateralFactorForLiquidation_gte?: InputMaybe<Scalars["BigInt"]["input"]>;
4056
+ minCollateralFactorForLiquidation_in?: InputMaybe<Array<Scalars["BigInt"]["input"]>>;
4057
+ minCollateralFactorForLiquidation_isNull?: InputMaybe<Scalars["Boolean"]["input"]>;
4058
+ minCollateralFactorForLiquidation_lt?: InputMaybe<Scalars["BigInt"]["input"]>;
4059
+ minCollateralFactorForLiquidation_lte?: InputMaybe<Scalars["BigInt"]["input"]>;
4060
+ minCollateralFactorForLiquidation_not_eq?: InputMaybe<Scalars["BigInt"]["input"]>;
4061
+ minCollateralFactorForLiquidation_not_in?: InputMaybe<Array<Scalars["BigInt"]["input"]>>;
4046
4062
  minCollateralFactorForOpenInterestLong_eq?: InputMaybe<Scalars["BigInt"]["input"]>;
4047
4063
  minCollateralFactorForOpenInterestLong_gt?: InputMaybe<Scalars["BigInt"]["input"]>;
4048
4064
  minCollateralFactorForOpenInterestLong_gte?: InputMaybe<Scalars["BigInt"]["input"]>;
@@ -43,7 +43,11 @@ export declare function getCappedPoolPnl(p: {
43
43
  isLong: boolean;
44
44
  }): bigint;
45
45
  export declare function getMaxLeverageByMinCollateralFactor(minCollateralFactor: bigint | undefined): number;
46
- export declare function getMaxAllowedLeverageByMinCollateralFactor(minCollateralFactor: bigint | undefined, marketAddress: string | undefined): number;
46
+ export declare function getMaxAllowedLeverage({ minCollateralFactor, minCollateralFactorForLiquidation, positionFeeFactorForBalanceWasNotImproved, }: {
47
+ minCollateralFactor: bigint | undefined;
48
+ minCollateralFactorForLiquidation: bigint | undefined;
49
+ positionFeeFactorForBalanceWasNotImproved: bigint | undefined;
50
+ }): number;
47
51
  export declare function getOppositeCollateral(marketInfo: MarketInfo, tokenAddress: string): import("../tokens").TokenData | undefined;
48
52
  export declare function getOppositeCollateralFromConfig(marketConfig: ConfigMarketConfig, tokenAddress: string): string;
49
53
  export declare function getAvailableUsdLiquidityForCollateral(marketInfo: MarketInfo, isLong: boolean): bigint;
@@ -46,6 +46,9 @@ export type PositionInfo = Position & {
46
46
  pnlPercentage: bigint;
47
47
  pnlAfterFees: bigint;
48
48
  pnlAfterFeesPercentage: bigint;
49
+ netValueAfterAllFees: bigint;
50
+ pnlAfterAllFees: bigint;
51
+ pnlAfterAllFeesPercentage: bigint;
49
52
  netPriceImapctDeltaUsd: bigint;
50
53
  priceImpactDiffUsd: bigint;
51
54
  pendingImpactUsd: bigint;
@@ -36,11 +36,26 @@ export declare function getPositionNetValue(p: {
36
36
  pendingBorrowingFeesUsd: bigint;
37
37
  pnl: bigint;
38
38
  }): bigint;
39
+ export declare function getPositionNetValueAfterAllFees(p: {
40
+ collateralUsd: bigint;
41
+ pnl: bigint;
42
+ pendingBorrowingFeesUsd: bigint;
43
+ pendingFundingFeesUsd: bigint;
44
+ netPriceImpactDeltaUsd: bigint;
45
+ closingFeeUsd: bigint;
46
+ }): bigint;
39
47
  export declare function getPositionPnlAfterFees({ pnl, pendingBorrowingFeesUsd, pendingFundingFeesUsd, }: {
40
48
  pnl: bigint;
41
49
  pendingBorrowingFeesUsd: bigint;
42
50
  pendingFundingFeesUsd: bigint;
43
51
  }): bigint;
52
+ export declare function getPositionPnlAfterAllFees({ pnl, pendingBorrowingFeesUsd, pendingFundingFeesUsd, netPriceImpactDeltaUsd, closingFeeUsd, }: {
53
+ pnl: bigint;
54
+ pendingBorrowingFeesUsd: bigint;
55
+ pendingFundingFeesUsd: bigint;
56
+ netPriceImpactDeltaUsd: bigint;
57
+ closingFeeUsd: bigint;
58
+ }): bigint;
44
59
  export declare function getLeverage(p: {
45
60
  sizeInUsd: bigint;
46
61
  collateralUsd: bigint;
@@ -42,5 +42,5 @@ export declare function getDefaultAcceptablePriceImpactBps(p: {
42
42
  indexPrice: bigint;
43
43
  sizeDeltaUsd: bigint;
44
44
  priceImpactDeltaUsd: bigint;
45
- acceptablePriceImapctBuffer?: number;
45
+ acceptablePriceImpactBuffer?: number;
46
46
  }): bigint;
@@ -29,5 +29,5 @@ export type CombinedSwapStrategy = BaseSwapStrategy & {
29
29
  swapPathStats: SwapPathStats;
30
30
  };
31
31
  export type SwapStrategyForIncreaseOrders = NoSwapStrategy | ExternalSwapStrategy | InternalSwapStrategy | CombinedSwapStrategy;
32
- export type SwapStrategyForSwapOrders = NoSwapStrategy | InternalSwapStrategy | CombinedSwapStrategy;
32
+ export type SwapStrategyForSwapOrders = NoSwapStrategy | ExternalSwapStrategy | InternalSwapStrategy | CombinedSwapStrategy;
33
33
  export {};
@@ -248,7 +248,9 @@ export type ExternalSwapQuote = {
248
248
  priceIn: bigint;
249
249
  priceOut: bigint;
250
250
  feesUsd: bigint;
251
+ slippage?: number;
251
252
  needSpenderApproval?: boolean;
253
+ desiredAmountOut?: bigint;
252
254
  txnData: {
253
255
  to: string;
254
256
  data: string;
@@ -269,7 +271,7 @@ export type ExternalSwapQuoteParams = {
269
271
  tokensData: TokensData | undefined;
270
272
  botanixStakingAssetsPerShare: bigint | undefined;
271
273
  };
272
- export type ExternalSwapCalculationStrategy = "byFromValue" | "leverageBySize";
274
+ export type ExternalSwapCalculationStrategy = "byFromValue" | "byToValue" | "leverageBySize";
273
275
  export type ExternalSwapInputs = {
274
276
  amountIn: bigint;
275
277
  priceIn: bigint;
@@ -277,6 +279,7 @@ export type ExternalSwapInputs = {
277
279
  usdIn: bigint;
278
280
  usdOut: bigint;
279
281
  strategy: ExternalSwapCalculationStrategy;
282
+ desiredAmountOut?: bigint;
280
283
  internalSwapTotalFeesDeltaUsd?: bigint;
281
284
  internalSwapTotalFeeItem?: FeeItem;
282
285
  internalSwapAmounts: SwapAmounts;
@@ -34,6 +34,7 @@ export type PositionTradeAction = {
34
34
  minOutputAmount: bigint;
35
35
  priceImpactUsd?: bigint;
36
36
  priceImpactDiffUsd?: bigint;
37
+ swapImpactUsd?: bigint;
37
38
  swapFeeUsd?: bigint;
38
39
  positionFeeAmount?: bigint;
39
40
  borrowingFeeAmount?: bigint;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gmx-io/sdk",
3
- "version": "1.5.0-alpha-14",
3
+ "version": "1.5.0-alpha-15",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,41 +0,0 @@
1
- "use strict";
2
- // Per-market UI leverage caps keyed off the contract's `minCollateralFactor`.
3
- // The contracts team runs a cron (see Linear ENG-54) that toggles each market's
4
- // MCF between its on-hours and off-hours value. Matching either sentinel here
5
- // lets the UI apply the correct cap without knowing the session schedule.
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.MARKET_HOURS_MARKETS = void 0;
8
- const GOLD_SILVER_CFG = {
9
- onHoursMcf: 9n * 10n ** 27n,
10
- onHoursMaxLeverage: 100,
11
- offHoursMcf: 35n * 10n ** 27n,
12
- offHoursMaxLeverage: 25,
13
- };
14
- exports.MARKET_HOURS_MARKETS = {
15
- // Arbitrum
16
- "0x0Df2BE76F517BCF0000AbfFcB6344B3b2aC4Cc4f": GOLD_SILVER_CFG, // GOLD/USD
17
- "0x448Fa722717df299ee197E2F6d8EB7911EFF6cEc": GOLD_SILVER_CFG, // SILVER/USD
18
- "0xda81cdd397210C08cFc567f93982E148A3aac8a6": GOLD_SILVER_CFG, // WTIOIL/USD
19
- "0x6F287D071800BfA847B4a7a7104BE33F87Ce9E74": GOLD_SILVER_CFG, // BRENTOIL/USD
20
- "0x2Ce2bc8B0f9d000f359d756a5816C125474Bb39b": {
21
- // NATGAS/USD
22
- onHoursMcf: 22n * 10n ** 27n,
23
- onHoursMaxLeverage: 40,
24
- offHoursMcf: 40n * 10n ** 27n,
25
- offHoursMaxLeverage: 20,
26
- },
27
- "0xE26E7b91143f367445f1c0a5dCf4f4aC8EaDcDb1": {
28
- // MegaETH MEGA/USD
29
- onHoursMcf: 22n * 10n ** 27n,
30
- onHoursMaxLeverage: 40,
31
- offHoursMcf: 22n * 10n ** 27n,
32
- offHoursMaxLeverage: 40,
33
- },
34
- "0x1b997cb4841c4cb360E384192fFd7fb26eb10e5f": {
35
- // Arbitrum MEGA/USD
36
- onHoursMcf: 18n * 10n ** 27n,
37
- onHoursMaxLeverage: 50,
38
- offHoursMcf: 18n * 10n ** 27n,
39
- offHoursMaxLeverage: 50,
40
- },
41
- };