@gmx-io/sdk 1.5.0-alpha-13 → 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 (61) 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/clients/v2/__tests__/decrease.spec.js +12 -12
  4. package/build/cjs/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +16 -0
  5. package/build/cjs/src/codegen/prebuilt/hashedMarketConfigKeys.json +122 -0
  6. package/build/cjs/src/codegen/prebuilt/hashedMarketValuesKeys.json +30 -0
  7. package/build/cjs/src/codegen/subsquid.js +30 -0
  8. package/build/cjs/src/configs/markets.js +14 -0
  9. package/build/cjs/src/configs/tokens.js +18 -0
  10. package/build/cjs/src/test/mock.js +1 -0
  11. package/build/cjs/src/utils/__tests__/markets.spec.js +88 -48
  12. package/build/cjs/src/utils/__tests__/positions.spec.js +93 -0
  13. package/build/cjs/src/utils/markets/utils.js +23 -14
  14. package/build/cjs/src/utils/orderTransactions/utils.js +2 -2
  15. package/build/cjs/src/utils/orderTransactions/validateTypedData.js +3 -3
  16. package/build/cjs/src/utils/positions/utils.js +34 -2
  17. package/build/cjs/src/utils/prices/utils.js +4 -4
  18. package/build/cjs/src/utils/swap/__tests__/swapRouting.spec.js +1 -1
  19. package/build/cjs/src/utils/trade/decrease.js +1 -1
  20. package/build/cjs/src/utils/trade/increase.js +1 -1
  21. package/build/cjs/src/utils/trade/trade.js +0 -7
  22. package/build/cjs/src/utils/tradeHistory/utils.js +2 -0
  23. package/build/cjs/src/utils/twap/index.js +4 -10
  24. package/build/esm/scripts/subsquid-codegen.js +1 -1
  25. package/build/esm/src/clients/v1/modules/trades/trades.js +4 -0
  26. package/build/esm/src/clients/v2/__tests__/decrease.spec.js +12 -12
  27. package/build/esm/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +16 -0
  28. package/build/esm/src/codegen/prebuilt/hashedMarketConfigKeys.json +122 -0
  29. package/build/esm/src/codegen/prebuilt/hashedMarketValuesKeys.json +30 -0
  30. package/build/esm/src/codegen/subsquid.js +30 -0
  31. package/build/esm/src/configs/markets.js +14 -0
  32. package/build/esm/src/configs/tokens.js +18 -0
  33. package/build/esm/src/test/mock.js +1 -0
  34. package/build/esm/src/utils/__tests__/markets.spec.js +90 -50
  35. package/build/esm/src/utils/__tests__/positions.spec.js +94 -1
  36. package/build/esm/src/utils/markets/utils.js +21 -13
  37. package/build/esm/src/utils/orderTransactions/utils.js +2 -2
  38. package/build/esm/src/utils/orderTransactions/validateTypedData.js +3 -3
  39. package/build/esm/src/utils/positions/utils.js +32 -2
  40. package/build/esm/src/utils/prices/utils.js +4 -4
  41. package/build/esm/src/utils/subaccount/index.js +2 -2
  42. package/build/esm/src/utils/swap/__tests__/swapRouting.spec.js +1 -1
  43. package/build/esm/src/utils/trade/decrease.js +1 -1
  44. package/build/esm/src/utils/trade/increase.js +1 -1
  45. package/build/esm/src/utils/trade/trade.js +0 -7
  46. package/build/esm/src/utils/tradeHistory/utils.js +2 -0
  47. package/build/esm/src/utils/twap/index.js +4 -10
  48. package/build/types/src/codegen/prebuilt/index.d.ts +168 -0
  49. package/build/types/src/codegen/subsquid.d.ts +77 -0
  50. package/build/types/src/utils/markets/utils.d.ts +6 -1
  51. package/build/types/src/utils/positions/types.d.ts +3 -0
  52. package/build/types/src/utils/positions/utils.d.ts +15 -0
  53. package/build/types/src/utils/prices/utils.d.ts +1 -1
  54. package/build/types/src/utils/subaccount/index.d.ts +2 -2
  55. package/build/types/src/utils/swap/types.d.ts +1 -1
  56. package/build/types/src/utils/trade/types.d.ts +4 -1
  57. package/build/types/src/utils/tradeHistory/types.d.ts +2 -0
  58. package/package.json +1 -1
  59. package/build/cjs/src/configs/marketHours.js +0 -27
  60. package/build/esm/src/configs/marketHours.js +0 -24
  61. package/build/types/src/configs/marketHours.d.ts +0 -7
@@ -150,6 +150,99 @@ vitest_1.vi.mock("../fees", () => ({
150
150
  (0, vitest_1.expect)(result).toBe(-70n);
151
151
  });
152
152
  });
153
+ (0, vitest_1.describe)("getPositionNetValueAfterAllFees", () => {
154
+ (0, vitest_1.it)("subtracts all fees and adds signed price impact (adverse)", () => {
155
+ const result = (0, positions_1.getPositionNetValueAfterAllFees)({
156
+ collateralUsd: 1000n,
157
+ pnl: 200n,
158
+ pendingBorrowingFeesUsd: 15n,
159
+ pendingFundingFeesUsd: 10n,
160
+ netPriceImpactDeltaUsd: -50n,
161
+ closingFeeUsd: 30n,
162
+ });
163
+ // 1000 + 200 - 15 - 10 + (-50) - 30 = 1095
164
+ (0, vitest_1.expect)(result).toBe(1095n);
165
+ });
166
+ (0, vitest_1.it)("adds favorable price impact", () => {
167
+ const result = (0, positions_1.getPositionNetValueAfterAllFees)({
168
+ collateralUsd: 1000n,
169
+ pnl: 200n,
170
+ pendingBorrowingFeesUsd: 0n,
171
+ pendingFundingFeesUsd: 0n,
172
+ netPriceImpactDeltaUsd: 25n,
173
+ closingFeeUsd: 0n,
174
+ });
175
+ // 1000 + 200 + 25 = 1225
176
+ (0, vitest_1.expect)(result).toBe(1225n);
177
+ });
178
+ (0, vitest_1.it)("reduces to collateral when pnl, fees, and impact are zero", () => {
179
+ const result = (0, positions_1.getPositionNetValueAfterAllFees)({
180
+ collateralUsd: 500n,
181
+ pnl: 0n,
182
+ pendingBorrowingFeesUsd: 0n,
183
+ pendingFundingFeesUsd: 0n,
184
+ netPriceImpactDeltaUsd: 0n,
185
+ closingFeeUsd: 0n,
186
+ });
187
+ (0, vitest_1.expect)(result).toBe(500n);
188
+ });
189
+ (0, vitest_1.it)("handles negative pnl with adverse impact", () => {
190
+ const result = (0, positions_1.getPositionNetValueAfterAllFees)({
191
+ collateralUsd: 1000n,
192
+ pnl: -300n,
193
+ pendingBorrowingFeesUsd: 5n,
194
+ pendingFundingFeesUsd: 5n,
195
+ netPriceImpactDeltaUsd: -20n,
196
+ closingFeeUsd: 10n,
197
+ });
198
+ // 1000 - 300 - 5 - 5 - 20 - 10 = 660
199
+ (0, vitest_1.expect)(result).toBe(660n);
200
+ });
201
+ });
202
+ (0, vitest_1.describe)("getPositionPnlAfterAllFees", () => {
203
+ (0, vitest_1.it)("subtracts all fees and adds signed price impact (adverse) from pnl", () => {
204
+ const result = (0, positions_1.getPositionPnlAfterAllFees)({
205
+ pnl: 500n,
206
+ pendingBorrowingFeesUsd: 30n,
207
+ pendingFundingFeesUsd: 20n,
208
+ netPriceImpactDeltaUsd: -40n,
209
+ closingFeeUsd: 50n,
210
+ });
211
+ // 500 - 30 - 20 - 40 - 50 = 360
212
+ (0, vitest_1.expect)(result).toBe(360n);
213
+ });
214
+ (0, vitest_1.it)("adds favorable price impact to pnl", () => {
215
+ const result = (0, positions_1.getPositionPnlAfterAllFees)({
216
+ pnl: 100n,
217
+ pendingBorrowingFeesUsd: 0n,
218
+ pendingFundingFeesUsd: 0n,
219
+ netPriceImpactDeltaUsd: 50n,
220
+ closingFeeUsd: 0n,
221
+ });
222
+ (0, vitest_1.expect)(result).toBe(150n);
223
+ });
224
+ (0, vitest_1.it)("returns pnl when fees and impact are zero", () => {
225
+ const result = (0, positions_1.getPositionPnlAfterAllFees)({
226
+ pnl: 200n,
227
+ pendingBorrowingFeesUsd: 0n,
228
+ pendingFundingFeesUsd: 0n,
229
+ netPriceImpactDeltaUsd: 0n,
230
+ closingFeeUsd: 0n,
231
+ });
232
+ (0, vitest_1.expect)(result).toBe(200n);
233
+ });
234
+ (0, vitest_1.it)("handles negative pnl with adverse impact", () => {
235
+ const result = (0, positions_1.getPositionPnlAfterAllFees)({
236
+ pnl: -100n,
237
+ pendingBorrowingFeesUsd: 10n,
238
+ pendingFundingFeesUsd: 5n,
239
+ netPriceImpactDeltaUsd: -20n,
240
+ closingFeeUsd: 30n,
241
+ });
242
+ // -100 - 10 - 5 - 20 - 30 = -165
243
+ (0, vitest_1.expect)(result).toBe(-165n);
244
+ });
245
+ });
153
246
  (0, vitest_1.describe)("getLeverage", () => {
154
247
  (0, vitest_1.it)("returns undefined if remainingCollateralUsd <= 0", () => {
155
248
  const result = (0, positions_1.getLeverage)({
@@ -1,9 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getMarketAddressByName = exports.getMarketWithTiers = exports.composeFullMarketsInfoData = exports.hydrateMarketInfo = exports.composeRawMarketsInfoData = exports.composeRawMarketInfo = exports.getMarketTicker = exports.getMarket24Stats = exports.getIsMarketAvailableForExpressSwaps = exports.getPriceForPnl = exports.getOpenInterestForBalance = exports.getOpenInterestInTokens = exports.getOpenInterestUsd = exports.getMarketPnl = exports.getOiInTokensFromRawValues = exports.getOiUsdFromRawValues = exports.getMarketDivisor = exports.getReservedUsd = exports.getAvailableUsdLiquidityForCollateral = exports.getOppositeCollateralFromConfig = exports.getOppositeCollateral = exports.getMaxAllowedLeverageByMinCollateralFactor = exports.getMaxLeverageByMinCollateralFactor = exports.getCappedPoolPnl = exports.getPoolUsdWithoutPnl = exports.getTokenPoolType = exports.getContractMarketPrices = exports.getMarketPoolName = exports.getMarketBaseName = exports.getMarketIndexName = exports.getMarketFullName = void 0;
3
+ exports.getMarketAddressByName = exports.getMarketWithTiers = exports.composeFullMarketsInfoData = exports.hydrateMarketInfo = exports.composeRawMarketsInfoData = exports.composeRawMarketInfo = exports.getMarketTicker = exports.getMarket24Stats = exports.getIsMarketDeprecated = exports.getIsMarketAvailableForExpressSwaps = exports.getPriceForPnl = exports.getOpenInterestForBalance = exports.getOpenInterestInTokens = exports.getOpenInterestUsd = exports.getMarketPnl = exports.getOiInTokensFromRawValues = exports.getOiUsdFromRawValues = exports.getMarketDivisor = exports.getReservedUsd = exports.getAvailableUsdLiquidityForCollateral = exports.getOppositeCollateralFromConfig = exports.getOppositeCollateral = exports.getMaxAllowedLeverage = exports.getMaxLeverageByMinCollateralFactor = exports.getCappedPoolPnl = exports.getPoolUsdWithoutPnl = exports.getTokenPoolType = exports.getContractMarketPrices = exports.getMarketPoolName = exports.getMarketBaseName = exports.getMarketIndexName = exports.getMarketFullName = void 0;
4
4
  const viem_1 = require("viem");
5
5
  const factors_1 = require("../../configs/factors");
6
- const marketHours_1 = require("../../configs/marketHours");
7
6
  const tokens_1 = require("../../configs/tokens");
8
7
  const bigmath_1 = require("../bigmath");
9
8
  const fees_1 = require("../fees");
@@ -96,7 +95,9 @@ function getCappedPoolPnl(p) {
96
95
  }
97
96
  exports.getCappedPoolPnl = getCappedPoolPnl;
98
97
  /**
99
- * Rounds to nearest .0 leverage, so that getMaxAllowedLeverageByMinCollateralFactor can get .0 or .5 leverage.
98
+ * Theoretical max leverage derived purely from minCollateralFactor. Does not account for
99
+ * fees or the liquidation safety buffer. Used by the deposit-collateral path where the
100
+ * user is not opening a new size.
100
101
  */
101
102
  const ROUNDING_VALUE = 10000;
102
103
  function getMaxLeverageByMinCollateralFactor(minCollateralFactor) {
@@ -109,19 +110,23 @@ function getMaxLeverageByMinCollateralFactor(minCollateralFactor) {
109
110
  return rounded;
110
111
  }
111
112
  exports.getMaxLeverageByMinCollateralFactor = getMaxLeverageByMinCollateralFactor;
112
- function getMaxAllowedLeverageByMinCollateralFactor(minCollateralFactor, marketAddress) {
113
- if (marketAddress) {
114
- const cfg = marketHours_1.MARKET_HOURS_MARKETS[marketAddress];
115
- if (cfg) {
116
- if (minCollateralFactor === cfg.onHoursMcf)
117
- return cfg.onHoursMaxLeverage * factors_1.BASIS_POINTS_DIVISOR;
118
- if (minCollateralFactor === cfg.offHoursMcf)
119
- return cfg.offHoursMaxLeverage * factors_1.BASIS_POINTS_DIVISOR;
120
- }
113
+ const MAX_ALLOWED_LEVERAGE_STEP_BP = 5 * factors_1.BASIS_POINTS_DIVISOR;
114
+ function getMaxAllowedLeverage({ minCollateralFactor, minCollateralFactorForLiquidation, positionFeeFactorForBalanceWasNotImproved, }) {
115
+ if (minCollateralFactor === undefined ||
116
+ minCollateralFactor === 0n ||
117
+ minCollateralFactorForLiquidation === undefined ||
118
+ minCollateralFactorForLiquidation === 0n ||
119
+ positionFeeFactorForBalanceWasNotImproved === undefined) {
120
+ return 100 * factors_1.BASIS_POINTS_DIVISOR;
121
121
  }
122
- return getMaxLeverageByMinCollateralFactor(minCollateralFactor) / 2;
122
+ const openingDenominator = minCollateralFactor + 2n * positionFeeFactorForBalanceWasNotImproved;
123
+ const openingMaxBp = bigmath_1.bigMath.mulDiv(numbers_1.PRECISION, factors_1.BASIS_POINTS_DIVISOR_BIGINT, openingDenominator);
124
+ const liquidationDenominator = 2n * minCollateralFactorForLiquidation;
125
+ const liquidationMaxBp = bigmath_1.bigMath.mulDiv(numbers_1.PRECISION, factors_1.BASIS_POINTS_DIVISOR_BIGINT, liquidationDenominator);
126
+ const rawMaxBp = bigmath_1.bigMath.min(openingMaxBp, liquidationMaxBp);
127
+ return Math.floor(Number(rawMaxBp) / MAX_ALLOWED_LEVERAGE_STEP_BP) * MAX_ALLOWED_LEVERAGE_STEP_BP;
123
128
  }
124
- exports.getMaxAllowedLeverageByMinCollateralFactor = getMaxAllowedLeverageByMinCollateralFactor;
129
+ exports.getMaxAllowedLeverage = getMaxAllowedLeverage;
125
130
  function getOppositeCollateral(marketInfo, tokenAddress) {
126
131
  const poolType = getTokenPoolType(marketInfo, tokenAddress);
127
132
  if (poolType === "long") {
@@ -231,6 +236,10 @@ function getIsMarketAvailableForExpressSwaps(marketInfo) {
231
236
  return [marketInfo.indexToken, marketInfo.longToken, marketInfo.shortToken].every((token) => token.hasPriceFeedProvider);
232
237
  }
233
238
  exports.getIsMarketAvailableForExpressSwaps = getIsMarketAvailableForExpressSwaps;
239
+ function getIsMarketDeprecated(marketInfo) {
240
+ return marketInfo.maxOpenInterestLong <= (0, numbers_1.expandDecimals)(1n, 30) && marketInfo.maxOpenInterestShort <= (0, numbers_1.expandDecimals)(1n, 30);
241
+ }
242
+ exports.getIsMarketDeprecated = getIsMarketDeprecated;
234
243
  function getMarket24Stats(dayPriceCandle) {
235
244
  const open24h = dayPriceCandle.open;
236
245
  const high24h = dayPriceCandle.high;
@@ -167,8 +167,8 @@ function buildDecreaseOrderPayload(p) {
167
167
  }
168
168
  exports.buildDecreaseOrderPayload = buildDecreaseOrderPayload;
169
169
  function buildTwapOrdersPayloads(p, twapParams) {
170
- if (!twapParams.numberOfParts || twapParams.numberOfParts < 2) {
171
- throw new Error(`TWAP numberOfParts must be >= 2, got ${twapParams.numberOfParts}`);
170
+ if (!twapParams.numberOfParts || twapParams.numberOfParts <= 0) {
171
+ throw new Error(`TWAP numberOfParts must be > 0, got ${twapParams.numberOfParts}`);
172
172
  }
173
173
  const uiFeeReceiver = (0, uiFeeReceiver_1.createTwapUiFeeReceiver)({ numberOfParts: twapParams.numberOfParts, source: twapParams.source });
174
174
  if ((0, orders_1.isSwapOrderType)(p.orderType)) {
@@ -73,7 +73,8 @@ accountAddress) {
73
73
  const cancellationReceiver = order?.addresses?.cancellationReceiver;
74
74
  if (cancellationReceiver) {
75
75
  const checksummedCancellationReceiver = (0, viem_1.getAddress)(cancellationReceiver);
76
- if (checksummedCancellationReceiver !== ZERO_ADDRESS && !allowedReceivers.has(checksummedCancellationReceiver)) {
76
+ if (checksummedCancellationReceiver !== ZERO_ADDRESS &&
77
+ !allowedReceivers.has(checksummedCancellationReceiver)) {
77
78
  throw new Error(`Order cancellationReceiver "${cancellationReceiver}" does not match signer "${signerAddress}". Possible malicious typed data.`);
78
79
  }
79
80
  }
@@ -88,8 +89,7 @@ function validateSubaccountApprovalTypedData(domain, message, chainId, signerAdd
88
89
  if (message.account && (0, viem_1.getAddress)(message.account) !== checksummedSigner) {
89
90
  throw new Error(`Subaccount approval account "${message.account}" does not match signer "${signerAddress}"`);
90
91
  }
91
- if (message.subaccount &&
92
- (0, viem_1.getAddress)(message.subaccount) !== (0, viem_1.getAddress)(expectedSubaccountAddress)) {
92
+ if (message.subaccount && (0, viem_1.getAddress)(message.subaccount) !== (0, viem_1.getAddress)(expectedSubaccountAddress)) {
93
93
  throw new Error(`Subaccount address "${message.subaccount}" does not match expected "${expectedSubaccountAddress}"`);
94
94
  }
95
95
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getPositionInfo = exports.getContractPositionDynamicFees = exports.getMinCollateralFactorForPosition = exports.getPriceImpactDiffUsd = exports.getNetPriceImpactDeltaUsdForDecrease = exports.getLiquidationPrice = exports.getLeverage = exports.getPositionPnlAfterFees = exports.getPositionNetValue = exports.getPositionPendingFeesUsd = exports.getPositionValueUsd = exports.getPositionPnlUsd = exports.getEntryPrice = exports.parsePositionKey = exports.getPositionKey = void 0;
3
+ exports.getPositionInfo = exports.getContractPositionDynamicFees = exports.getMinCollateralFactorForPosition = exports.getPriceImpactDiffUsd = exports.getNetPriceImpactDeltaUsdForDecrease = exports.getLiquidationPrice = exports.getLeverage = exports.getPositionPnlAfterAllFees = exports.getPositionPnlAfterFees = exports.getPositionNetValueAfterAllFees = exports.getPositionNetValue = exports.getPositionPendingFeesUsd = exports.getPositionValueUsd = exports.getPositionPnlUsd = exports.getEntryPrice = exports.parsePositionKey = exports.getPositionKey = void 0;
4
4
  const factors_1 = require("../../configs/factors");
5
5
  const bigmath_1 = require("../bigmath");
6
6
  const fees_1 = require("../fees");
@@ -63,11 +63,20 @@ function getPositionNetValue(p) {
63
63
  return collateralUsd - pendingFeesUsd + pnl;
64
64
  }
65
65
  exports.getPositionNetValue = getPositionNetValue;
66
+ function getPositionNetValueAfterAllFees(p) {
67
+ const { collateralUsd, pnl, pendingBorrowingFeesUsd, pendingFundingFeesUsd, netPriceImpactDeltaUsd, closingFeeUsd } = p;
68
+ return collateralUsd + pnl - pendingBorrowingFeesUsd - pendingFundingFeesUsd + netPriceImpactDeltaUsd - closingFeeUsd;
69
+ }
70
+ exports.getPositionNetValueAfterAllFees = getPositionNetValueAfterAllFees;
66
71
  function getPositionPnlAfterFees({ pnl, pendingBorrowingFeesUsd, pendingFundingFeesUsd, }) {
67
72
  const pnlAfterFees = pnl - pendingBorrowingFeesUsd - pendingFundingFeesUsd;
68
73
  return pnlAfterFees;
69
74
  }
70
75
  exports.getPositionPnlAfterFees = getPositionPnlAfterFees;
76
+ function getPositionPnlAfterAllFees({ pnl, pendingBorrowingFeesUsd, pendingFundingFeesUsd, netPriceImpactDeltaUsd, closingFeeUsd, }) {
77
+ return pnl - pendingBorrowingFeesUsd - pendingFundingFeesUsd + netPriceImpactDeltaUsd - closingFeeUsd;
78
+ }
79
+ exports.getPositionPnlAfterAllFees = getPositionPnlAfterAllFees;
71
80
  function getLeverage(p) {
72
81
  const { pnl, sizeInUsd, collateralUsd, pendingBorrowingFeesUsd, pendingFundingFeesUsd } = p;
73
82
  const totalPendingFeesUsd = getPositionPendingFeesUsd({ pendingFundingFeesUsd, pendingBorrowingFeesUsd });
@@ -325,6 +334,22 @@ function getPositionInfo(p) {
325
334
  pendingFundingFeesUsd,
326
335
  });
327
336
  const pnlAfterFeesPercentage = collateralUsd !== 0n ? (0, numbers_1.getBasisPoints)(pnlAfterFees, collateralUsd) : 0n;
337
+ const netValueAfterAllFees = getPositionNetValueAfterAllFees({
338
+ collateralUsd,
339
+ pnl,
340
+ pendingBorrowingFeesUsd: position.pendingBorrowingFeesUsd,
341
+ pendingFundingFeesUsd,
342
+ netPriceImpactDeltaUsd: netPriceImpactValues.totalImpactDeltaUsd,
343
+ closingFeeUsd,
344
+ });
345
+ const pnlAfterAllFees = getPositionPnlAfterAllFees({
346
+ pnl,
347
+ pendingBorrowingFeesUsd: position.pendingBorrowingFeesUsd,
348
+ pendingFundingFeesUsd,
349
+ netPriceImpactDeltaUsd: netPriceImpactValues.totalImpactDeltaUsd,
350
+ closingFeeUsd,
351
+ });
352
+ const pnlAfterAllFeesPercentage = collateralUsd !== 0n ? (0, numbers_1.getBasisPoints)(pnlAfterAllFees, collateralUsd) : 0n;
328
353
  const leverage = getLeverage({
329
354
  sizeInUsd: position.sizeInUsd,
330
355
  collateralUsd,
@@ -346,7 +371,11 @@ function getPositionInfo(p) {
346
371
  pendingFundingFeesUsd,
347
372
  pnl: undefined,
348
373
  });
349
- const maxAllowedLeverage = (0, markets_1.getMaxAllowedLeverageByMinCollateralFactor)(marketInfo.minCollateralFactor, marketInfo.marketTokenAddress);
374
+ const maxAllowedLeverage = (0, markets_1.getMaxAllowedLeverage)({
375
+ minCollateralFactor: marketInfo.minCollateralFactor,
376
+ minCollateralFactorForLiquidation: marketInfo.minCollateralFactorForLiquidation,
377
+ positionFeeFactorForBalanceWasNotImproved: marketInfo.positionFeeFactorForBalanceWasNotImproved,
378
+ });
350
379
  const hasLowCollateral = (leverage !== undefined && leverage > maxAllowedLeverage) || false;
351
380
  const liquidationPrice = getLiquidationPrice({
352
381
  marketInfo,
@@ -399,6 +428,9 @@ function getPositionInfo(p) {
399
428
  pnlPercentage,
400
429
  pnlAfterFees,
401
430
  pnlAfterFeesPercentage,
431
+ netValueAfterAllFees,
432
+ pnlAfterAllFees,
433
+ pnlAfterAllFeesPercentage,
402
434
  netValue,
403
435
  netPriceImapctDeltaUsd: netPriceImpactValues.totalImpactDeltaUsd,
404
436
  priceImpactDiffUsd: netPriceImpactValues.priceImpactDiffUsd,
@@ -126,9 +126,9 @@ function getAcceptablePriceByPriceImpact(p) {
126
126
  }
127
127
  exports.getAcceptablePriceByPriceImpact = getAcceptablePriceByPriceImpact;
128
128
  function getDefaultAcceptablePriceImpactBps(p) {
129
- const { indexPrice, sizeDeltaUsd, priceImpactDeltaUsd, acceptablePriceImapctBuffer = factors_1.DEFAULT_ACCEPTABLE_PRICE_IMPACT_BUFFER, } = p;
129
+ const { indexPrice, sizeDeltaUsd, priceImpactDeltaUsd, acceptablePriceImpactBuffer = factors_1.DEFAULT_ACCEPTABLE_PRICE_IMPACT_BUFFER, } = p;
130
130
  if (priceImpactDeltaUsd > 0) {
131
- return BigInt(acceptablePriceImapctBuffer);
131
+ return BigInt(acceptablePriceImpactBuffer);
132
132
  }
133
133
  const baseAcceptablePriceValues = getAcceptablePriceByPriceImpact({
134
134
  isIncrease: p.isIncrease,
@@ -138,8 +138,8 @@ function getDefaultAcceptablePriceImpactBps(p) {
138
138
  priceImpactDeltaUsd,
139
139
  });
140
140
  if (baseAcceptablePriceValues.acceptablePriceDeltaBps < 0) {
141
- return bigmath_1.bigMath.abs(baseAcceptablePriceValues.acceptablePriceDeltaBps) + BigInt(acceptablePriceImapctBuffer);
141
+ return bigmath_1.bigMath.abs(baseAcceptablePriceValues.acceptablePriceDeltaBps) + BigInt(acceptablePriceImpactBuffer);
142
142
  }
143
- return BigInt(acceptablePriceImapctBuffer);
143
+ return BigInt(acceptablePriceImpactBuffer);
144
144
  }
145
145
  exports.getDefaultAcceptablePriceImpactBps = getDefaultAcceptablePriceImpactBps;
@@ -295,7 +295,7 @@ const dollar = 10n ** BigInt(factors_1.USD_DECIMALS);
295
295
  (0, vitest_1.it)("should handle routes with zero output", () => {
296
296
  const routes = createTestRoutes();
297
297
  const result = (0, swapRouting_1.getBestSwapPath)({ routes, usdIn: 100n * dollar, estimator: () => ({ usdOut: 0n }) });
298
- (0, vitest_1.expect)(result).toBeUndefined();
298
+ (0, vitest_1.expect)(result).toEqual(routes[0]);
299
299
  });
300
300
  (0, vitest_1.it)("should skip routes that throw errors", () => {
301
301
  const routes = createTestRoutes();
@@ -384,7 +384,7 @@ function applyAcceptablePrice(p) {
384
384
  indexPrice: values.indexPrice,
385
385
  sizeDeltaUsd: values.sizeDeltaUsd,
386
386
  priceImpactDeltaUsd: values.closePriceImpactDeltaUsd,
387
- acceptablePriceImapctBuffer: acceptablePriceImpactBuffer || factors_1.DEFAULT_ACCEPTABLE_PRICE_IMPACT_BUFFER,
387
+ acceptablePriceImpactBuffer: acceptablePriceImpactBuffer || factors_1.DEFAULT_ACCEPTABLE_PRICE_IMPACT_BUFFER,
388
388
  });
389
389
  if (maxNegativePriceImpactBps === undefined) {
390
390
  maxNegativePriceImpactBps = values.recommendedAcceptablePriceDeltaBps;
@@ -274,7 +274,7 @@ function getIncreasePositionAmounts(p) {
274
274
  indexPrice: values.indexPrice,
275
275
  sizeDeltaUsd: values.sizeDeltaUsd,
276
276
  priceImpactDeltaUsd: values.positionPriceImpactDeltaUsd,
277
- acceptablePriceImapctBuffer: acceptablePriceImpactBuffer || factors_1.DEFAULT_ACCEPTABLE_PRICE_IMPACT_BUFFER,
277
+ acceptablePriceImpactBuffer: acceptablePriceImpactBuffer || factors_1.DEFAULT_ACCEPTABLE_PRICE_IMPACT_BUFFER,
278
278
  });
279
279
  if (maxNegativePriceImpactBps === undefined) {
280
280
  maxNegativePriceImpactBps = values.recommendedAcceptablePriceDeltaBps;
@@ -6,11 +6,7 @@ const bigmath_1 = require("../bigmath");
6
6
  const types_1 = require("../orders/types");
7
7
  const prices_1 = require("../prices");
8
8
  const types_2 = require("./types");
9
- const MAX_ALLOWED_SLIPPAGE = 5000; // 50%
10
9
  function applySlippageToPrice(allowedSlippage, price, isIncrease, isLong) {
11
- if (allowedSlippage < 0 || allowedSlippage > MAX_ALLOWED_SLIPPAGE) {
12
- throw new Error(`allowedSlippage must be between 0 and ${MAX_ALLOWED_SLIPPAGE} bps, got ${allowedSlippage}`);
13
- }
14
10
  const shouldIncreasePrice = (0, prices_1.getShouldUseMaxPrice)(isIncrease, isLong);
15
11
  const slippageBasisPoints = shouldIncreasePrice
16
12
  ? factors_1.BASIS_POINTS_DIVISOR + allowedSlippage
@@ -19,9 +15,6 @@ function applySlippageToPrice(allowedSlippage, price, isIncrease, isLong) {
19
15
  }
20
16
  exports.applySlippageToPrice = applySlippageToPrice;
21
17
  function applySlippageToMinOut(allowedSlippage, minOutputAmount) {
22
- if (allowedSlippage < 0 || allowedSlippage > MAX_ALLOWED_SLIPPAGE) {
23
- throw new Error(`allowedSlippage must be between 0 and ${MAX_ALLOWED_SLIPPAGE} bps, got ${allowedSlippage}`);
24
- }
25
18
  const slippageBasisPoints = factors_1.BASIS_POINTS_DIVISOR - allowedSlippage;
26
19
  return bigmath_1.bigMath.mulDiv(minOutputAmount, BigInt(slippageBasisPoints), factors_1.BASIS_POINTS_DIVISOR_BIGINT);
27
20
  }
@@ -117,10 +117,12 @@ function createRawTradeActionTransformer(marketsInfoData, wrappedToken, tokensDa
117
117
  basePnlUsd: rawAction.basePnlUsd ? BigInt(rawAction.basePnlUsd) : undefined,
118
118
  priceImpactDiffUsd: rawAction.priceImpactDiffUsd ? BigInt(rawAction.priceImpactDiffUsd) : undefined,
119
119
  priceImpactUsd: rawAction.priceImpactUsd ? BigInt(rawAction.priceImpactUsd) : undefined,
120
+ swapImpactUsd: rawAction.swapImpactUsd ? BigInt(rawAction.swapImpactUsd) : undefined,
120
121
  totalImpactUsd: rawAction.totalImpactUsd ? BigInt(rawAction.totalImpactUsd) : undefined,
121
122
  positionFeeAmount: rawAction.positionFeeAmount ? BigInt(rawAction.positionFeeAmount) : undefined,
122
123
  borrowingFeeAmount: rawAction.borrowingFeeAmount ? BigInt(rawAction.borrowingFeeAmount) : undefined,
123
124
  fundingFeeAmount: rawAction.fundingFeeAmount ? BigInt(rawAction.fundingFeeAmount) : undefined,
125
+ swapFeeUsd: rawAction.swapFeeUsd ? BigInt(rawAction.swapFeeUsd) : undefined,
124
126
  liquidationFeeAmount: rawAction.liquidationFeeAmount ? BigInt(rawAction.liquidationFeeAmount) : undefined,
125
127
  reason: rawAction.reason ?? undefined,
126
128
  reasonBytes: rawAction.reasonBytes ?? undefined,
@@ -33,13 +33,10 @@ function getTwapDurationInSeconds(duration) {
33
33
  }
34
34
  exports.getTwapDurationInSeconds = getTwapDurationInSeconds;
35
35
  function getTwapValidFromTime(duration, numberOfParts, partIndex) {
36
- if (numberOfParts < 2) {
37
- throw new Error(`TWAP numberOfParts must be >= 2, got ${numberOfParts}`);
38
- }
39
36
  const durationMinutes = duration.hours * 60 + duration.minutes;
40
- const durationSeconds = durationMinutes * 60;
37
+ const durationMs = durationMinutes * 60;
41
38
  const startTime = Math.ceil(Date.now() / 1000);
42
- return BigInt(Math.floor(startTime + (durationSeconds / (numberOfParts - 1)) * partIndex));
39
+ return BigInt(Math.floor(startTime + (durationMs / (numberOfParts - 1)) * partIndex));
43
40
  }
44
41
  exports.getTwapValidFromTime = getTwapValidFromTime;
45
42
  function changeTwapNumberOfPartsValue(value) {
@@ -64,14 +61,11 @@ function getTwapOrderKey({ twapId, orderType, pool, isLong, collateralTokenSymbo
64
61
  }
65
62
  exports.getTwapOrderKey = getTwapOrderKey;
66
63
  function makeTwapValidFromTimeGetter(duration, numberOfParts) {
67
- if (numberOfParts < 2) {
68
- throw new Error(`TWAP numberOfParts must be >= 2, got ${numberOfParts}`);
69
- }
70
64
  const durationMinutes = duration.hours * 60 + duration.minutes;
71
- const durationSeconds = durationMinutes * 60;
65
+ const durationMs = durationMinutes * 60;
72
66
  const startTime = Math.ceil(Date.now() / 1000);
73
67
  return (part) => {
74
- return BigInt(Math.floor(startTime + (durationSeconds / (numberOfParts - 1)) * part));
68
+ return BigInt(Math.floor(startTime + (durationMs / (numberOfParts - 1)) * part));
75
69
  };
76
70
  }
77
71
  exports.makeTwapValidFromTimeGetter = makeTwapValidFromTimeGetter;
@@ -1,5 +1,5 @@
1
1
  const config = {
2
- schema: "https://gmx.squids.live/gmx-synthetics-arbitrum@24678a/api/graphql",
2
+ schema: "https://gmx.squids.live/gmx-synthetics-arbitrum@5eaa69/api/graphql",
3
3
  overwrite: true,
4
4
  debug: true,
5
5
  generates: {
@@ -166,9 +166,13 @@ export async function fetchTradeActions({ sdk, pageIndex, pageSize, marketsDirec
166
166
 
167
167
  priceImpactUsd
168
168
  priceImpactDiffUsd
169
+ swapImpactUsd
170
+ totalImpactUsd
169
171
  positionFeeAmount
170
172
  borrowingFeeAmount
171
173
  fundingFeeAmount
174
+ swapFeeUsd
175
+ liquidationFeeAmount
172
176
  pnlUsd
173
177
  basePnlUsd
174
178
 
@@ -93,7 +93,7 @@ describe("decrease orders", () => {
93
93
  const pos = await ensureLongPosition();
94
94
  const sizeBefore = BigInt(pos.sizeInUsd);
95
95
  const collateralBefore = BigInt(pos.collateralUsd);
96
- const leverageBefore = sizeBefore * 10000n / collateralBefore;
96
+ const leverageBefore = (sizeBefore * 10000n) / collateralBefore;
97
97
  const decreaseSize = sizeBefore / 5n;
98
98
  const { submitted } = await expressFlow(sdk, signer, {
99
99
  kind: "decrease",
@@ -117,12 +117,10 @@ describe("decrease orders", () => {
117
117
  expect(posAfter).toBeDefined();
118
118
  const sizeAfter = BigInt(posAfter.sizeInUsd);
119
119
  const collateralAfter = BigInt(posAfter.collateralUsd);
120
- const leverageAfter = sizeAfter * 10000n / collateralAfter;
120
+ const leverageAfter = (sizeAfter * 10000n) / collateralAfter;
121
121
  // Leverage preserved within 5% tolerance
122
- const diff = leverageAfter > leverageBefore
123
- ? leverageAfter - leverageBefore
124
- : leverageBefore - leverageAfter;
125
- expect(diff * 100n / leverageBefore).toBeLessThanOrEqual(5n);
122
+ const diff = leverageAfter > leverageBefore ? leverageAfter - leverageBefore : leverageBefore - leverageAfter;
123
+ expect((diff * 100n) / leverageBefore).toBeLessThanOrEqual(5n);
126
124
  // Collateral also removed proportionally
127
125
  expect(collateralAfter).toBeLessThan(collateralBefore);
128
126
  });
@@ -153,10 +151,8 @@ describe("decrease orders", () => {
153
151
  expect(posAfter).toBeDefined();
154
152
  const collateralAfter = BigInt(posAfter.collateralUsd);
155
153
  // Collateral stays roughly the same (may change slightly due to fees)
156
- const collateralDiff = collateralAfter > collateralBefore
157
- ? collateralAfter - collateralBefore
158
- : collateralBefore - collateralAfter;
159
- expect(collateralDiff * 100n / collateralBefore).toBeLessThanOrEqual(10n);
154
+ const collateralDiff = collateralAfter > collateralBefore ? collateralAfter - collateralBefore : collateralBefore - collateralAfter;
155
+ expect((collateralDiff * 100n) / collateralBefore).toBeLessThanOrEqual(10n);
160
156
  });
161
157
  });
162
158
  describe("receiveToken", () => {
@@ -210,7 +206,9 @@ describe("decrease orders", () => {
210
206
  },
211
207
  });
212
208
  }
213
- catch { /* cleanup */ }
209
+ catch {
210
+ /* cleanup */
211
+ }
214
212
  });
215
213
  it("TWAP market decrease — partial close split into parts", async () => {
216
214
  const pos = await ensureLongPosition();
@@ -300,7 +298,9 @@ describe("decrease orders", () => {
300
298
  },
301
299
  });
302
300
  }
303
- catch { /* cleanup */ }
301
+ catch {
302
+ /* cleanup */
303
+ }
304
304
  });
305
305
  it("stop-loss: estimates present", async () => {
306
306
  await ensureLongPosition();
@@ -50,6 +50,14 @@
50
50
  "aboveOptimalUsageBorrowingFactorLong": "0x7a6c2c5606edbf4ad6d99540c5788fc9bdc10e90e63a84e11c4129a2f04c8cf9",
51
51
  "aboveOptimalUsageBorrowingFactorShort": "0xc6f8f13437ac5a034a7a93a8a4bfa46e8d83b49c61b45c01240003e491de9d72"
52
52
  },
53
+ "0x1b997cb4841c4cb360E384192fFd7fb26eb10e5f": {
54
+ "optimalUsageFactorLong": "0x4d65f516c890bfdc01bfaf9ef1fe05bc6a78d2a4015d14de0837219c887d7098",
55
+ "optimalUsageFactorShort": "0x42250297858b187815cfd16f31654b887069a6ae5a174f5e8764ef61e68a550e",
56
+ "baseBorrowingFactorLong": "0x64e7d45b8a6b5b607d007c813ac753232dda12a3ba6953a7abdc9ec1495663f4",
57
+ "baseBorrowingFactorShort": "0x2a8628640685fef975df5c0e898fc5d0796e46b0c11cc7f1fcb30ccfcf03900a",
58
+ "aboveOptimalUsageBorrowingFactorLong": "0xcd5fef2dcde9921645b4f25cc06658e4a232efdc005a237a71b5db4aa1795cad",
59
+ "aboveOptimalUsageBorrowingFactorShort": "0x02bf1759ac43e1a8ce374831520870154c462dc29fca7a2a19bac560c4a6ae87"
60
+ },
53
61
  "0xc5c9B5E23810565763De41144741477eeCB25e2e": {
54
62
  "optimalUsageFactorLong": "0x009bc89771e196346b3d41cf47c8234c6843f977392651e5a122511445fdc304",
55
63
  "optimalUsageFactorShort": "0x522a6a2270cc21374e753b06f2df5dabe018d2135aa58d75bd64ab43b16dc98f",
@@ -1115,6 +1123,14 @@
1115
1123
  "baseBorrowingFactorShort": "0x85a4a75fcc2ced632df6a9dadbc46b5d4171f166572e298ac8e0f5dc0a713818",
1116
1124
  "aboveOptimalUsageBorrowingFactorLong": "0xfdc145dc5c86925a834513f0c78ef57f8da0f095253e561506b6367106d5caac",
1117
1125
  "aboveOptimalUsageBorrowingFactorShort": "0xc961a42b4a07b7f63f14fbd2a3c14c41643eb80dd5a8fdcde32ad1365bcb51a7"
1126
+ },
1127
+ "0xE26E7b91143f367445f1c0a5dCf4f4aC8EaDcDb1": {
1128
+ "optimalUsageFactorLong": "0x7dd92ed8d2f972a0bedc134931f1ce1257fdc1ba4ebc043c270e81880efee700",
1129
+ "optimalUsageFactorShort": "0xec58abc0c1c902e8df7ed4f6968dbfd88228e741bfd63bf3efc635e0d7c9bb9d",
1130
+ "baseBorrowingFactorLong": "0x0df8b0065fbf53780b168beeff39d576cca7b15e1f341b4041d7b485a8ef4ec6",
1131
+ "baseBorrowingFactorShort": "0x7d507d9ca2d236ab9c89efaeb23488e5e23a215bd060a72d159eaa1f2fd0b604",
1132
+ "aboveOptimalUsageBorrowingFactorLong": "0x337fd48d8d99cf5949ebc95f32f43bfd55a3bdc9ba8c5ed407f7d6985d3bf30e",
1133
+ "aboveOptimalUsageBorrowingFactorShort": "0x580ab973f5bd7e0ab5f89478b225d431776863715a24acce5ee7fa1bd82ae9b0"
1118
1134
  }
1119
1135
  },
1120
1136
  "43113": {