@gmx-io/sdk 1.5.0-alpha-18 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/build/cjs/scripts/subsquid-codegen.js +1 -1
  2. package/build/cjs/src/clients/v1/modules/orders/utils.js +1 -1
  3. package/build/cjs/src/clients/v1/modules/trades/trades.js +1 -0
  4. package/build/cjs/src/clients/v2/index.js +44 -40
  5. package/build/cjs/src/codegen/subsquid.js +6 -0
  6. package/build/cjs/src/configs/__tests__/markets.spec.js +11 -0
  7. package/build/cjs/src/configs/api.js +38 -18
  8. package/build/cjs/src/utils/__tests__/objects.spec.js +16 -0
  9. package/build/cjs/src/utils/__tests__/positions.spec.js +163 -0
  10. package/build/cjs/src/utils/__tests__/uiFeeReceiver.spec.js +5 -0
  11. package/build/cjs/src/utils/apy/api.js +1 -1
  12. package/build/cjs/src/utils/balances/api.js +2 -2
  13. package/build/cjs/src/utils/buyback/api.js +1 -1
  14. package/build/cjs/src/utils/express/utils/oracleParamsUtils.js +1 -4
  15. package/build/cjs/src/utils/express/utils/relayParamsUtils.js +0 -1
  16. package/build/cjs/src/utils/gmxAccountApi/api.js +8 -4
  17. package/build/cjs/src/utils/jitLiquidity/api.js +12 -0
  18. package/build/cjs/src/utils/jitLiquidity/index.js +19 -0
  19. package/build/cjs/src/utils/jitLiquidity/types.js +2 -0
  20. package/build/cjs/src/utils/jitLiquidity/utils.js +108 -0
  21. package/build/cjs/src/utils/jitLiquidity/utils.spec.js +133 -0
  22. package/build/cjs/src/utils/markets/api.js +4 -4
  23. package/build/cjs/src/utils/markets/utils.js +4 -2
  24. package/build/cjs/src/utils/numbers/utils.js +1 -1
  25. package/build/cjs/src/utils/objects/utils.js +13 -1
  26. package/build/cjs/src/utils/orderTransactions/api.js +6 -6
  27. package/build/cjs/src/utils/orders/api.js +1 -1
  28. package/build/cjs/src/utils/pairs/api.js +1 -1
  29. package/build/cjs/src/utils/performance/api.js +2 -2
  30. package/build/cjs/src/utils/positions/api.js +1 -1
  31. package/build/cjs/src/utils/positions/utils.js +29 -1
  32. package/build/cjs/src/utils/prices/api.js +1 -1
  33. package/build/cjs/src/utils/rates/api.js +1 -1
  34. package/build/cjs/src/utils/staking/api.js +1 -1
  35. package/build/cjs/src/utils/subaccount/api.js +2 -2
  36. package/build/cjs/src/utils/tokens/api.js +1 -1
  37. package/build/cjs/src/utils/trade/__tests__/getMaxWithdrawAmount.spec.js +121 -0
  38. package/build/cjs/src/utils/trade/decrease.js +60 -3
  39. package/build/cjs/src/utils/trade/decreaseOutputs.js +47 -0
  40. package/build/cjs/src/utils/trade/index.js +1 -0
  41. package/build/cjs/src/utils/tradeHistory/utils.js +1 -0
  42. package/build/cjs/src/utils/trades/api.js +2 -2
  43. package/build/cjs/src/utils/twap/uiFeeReceiver.js +3 -0
  44. package/build/esm/scripts/subsquid-codegen.js +1 -1
  45. package/build/esm/src/clients/v1/modules/orders/utils.js +1 -1
  46. package/build/esm/src/clients/v1/modules/trades/trades.js +1 -0
  47. package/build/esm/src/clients/v2/index.js +4 -0
  48. package/build/esm/src/codegen/subsquid.js +6 -0
  49. package/build/esm/src/configs/__tests__/markets.spec.js +12 -1
  50. package/build/esm/src/configs/api.js +38 -18
  51. package/build/esm/src/utils/__tests__/objects.spec.js +17 -1
  52. package/build/esm/src/utils/__tests__/positions.spec.js +164 -1
  53. package/build/esm/src/utils/__tests__/uiFeeReceiver.spec.js +5 -0
  54. package/build/esm/src/utils/apy/api.js +1 -1
  55. package/build/esm/src/utils/balances/api.js +2 -2
  56. package/build/esm/src/utils/buyback/api.js +1 -1
  57. package/build/esm/src/utils/express/utils/oracleParamsUtils.js +1 -4
  58. package/build/esm/src/utils/express/utils/relayParamsUtils.js +0 -1
  59. package/build/esm/src/utils/gmxAccountApi/api.js +8 -4
  60. package/build/esm/src/utils/jitLiquidity/api.js +8 -0
  61. package/build/esm/src/utils/jitLiquidity/index.js +3 -0
  62. package/build/esm/src/utils/jitLiquidity/types.js +1 -0
  63. package/build/esm/src/utils/jitLiquidity/utils.js +101 -0
  64. package/build/esm/src/utils/jitLiquidity/utils.spec.js +131 -0
  65. package/build/esm/src/utils/markets/api.js +4 -4
  66. package/build/esm/src/utils/markets/utils.js +4 -2
  67. package/build/esm/src/utils/numbers/utils.js +1 -1
  68. package/build/esm/src/utils/objects/utils.js +9 -0
  69. package/build/esm/src/utils/orderTransactions/api.js +6 -6
  70. package/build/esm/src/utils/orders/api.js +1 -1
  71. package/build/esm/src/utils/pairs/api.js +1 -1
  72. package/build/esm/src/utils/performance/api.js +2 -2
  73. package/build/esm/src/utils/positions/api.js +1 -1
  74. package/build/esm/src/utils/positions/utils.js +27 -0
  75. package/build/esm/src/utils/prices/api.js +1 -1
  76. package/build/esm/src/utils/rates/api.js +1 -1
  77. package/build/esm/src/utils/staking/api.js +1 -1
  78. package/build/esm/src/utils/subaccount/api.js +2 -2
  79. package/build/esm/src/utils/tokens/api.js +1 -1
  80. package/build/esm/src/utils/trade/__tests__/getMaxWithdrawAmount.spec.js +119 -0
  81. package/build/esm/src/utils/trade/decrease.js +59 -3
  82. package/build/esm/src/utils/trade/decreaseOutputs.js +40 -0
  83. package/build/esm/src/utils/trade/index.js +1 -0
  84. package/build/esm/src/utils/tradeHistory/utils.js +1 -0
  85. package/build/esm/src/utils/trades/api.js +2 -2
  86. package/build/esm/src/utils/twap/uiFeeReceiver.js +3 -0
  87. package/build/tsconfig.tsbuildinfo +1 -0
  88. package/build/types/src/clients/v2/index.d.ts +3 -0
  89. package/build/types/src/codegen/subsquid.d.ts +16 -0
  90. package/build/types/src/configs/api.d.ts +4 -3
  91. package/build/types/src/utils/express/utils/oracleParamsUtils.d.ts +1 -3
  92. package/build/types/src/utils/jitLiquidity/api.d.ts +5 -0
  93. package/build/types/src/utils/jitLiquidity/index.d.ts +3 -0
  94. package/build/types/src/utils/jitLiquidity/types.d.ts +23 -0
  95. package/build/types/src/utils/jitLiquidity/utils.d.ts +5 -0
  96. package/build/types/src/utils/jitLiquidity/utils.spec.d.ts +1 -0
  97. package/build/types/src/utils/objects/utils.d.ts +3 -0
  98. package/build/types/src/utils/orderTransactions/api.d.ts +1 -0
  99. package/build/types/src/utils/positions/utils.d.ts +10 -0
  100. package/build/types/src/utils/trade/__tests__/getMaxWithdrawAmount.spec.d.ts +1 -0
  101. package/build/types/src/utils/trade/decrease.d.ts +8 -0
  102. package/build/types/src/utils/trade/decreaseOutputs.d.ts +16 -0
  103. package/build/types/src/utils/trade/index.d.ts +1 -0
  104. package/build/types/src/utils/tradeHistory/types.d.ts +1 -0
  105. package/build/types/src/utils/trades/types.d.ts +1 -0
  106. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getOptimalDecreaseAndSwapAmounts = exports.selectBetterDecreaseSwapType = exports.getCollateralToPnlInternalSwapStats = exports.isThirdTokenDecreaseSwap = exports.getDecreaseSwapType = exports.getNextPositionValuesForDecreaseTrade = exports.getTotalFeesUsdForDecrease = exports.estimateCollateralCost = exports.payForCollateralCost = exports.getMinCollateralUsdForLeverage = exports.getIsFullClose = exports.getDecreasePositionAmounts = void 0;
3
+ exports.getOptimalDecreaseAndSwapAmounts = exports.selectBetterDecreaseSwapType = exports.getCollateralToPnlInternalSwapStats = exports.isThirdTokenDecreaseSwap = exports.getDecreaseSwapType = exports.getNextPositionValuesForDecreaseTrade = exports.getTotalFeesUsdForDecrease = exports.estimateCollateralCost = exports.payForCollateralCost = exports.getMaxWithdrawAmount = exports.getMinCollateralUsdForLeverage = exports.getIsFullClose = exports.getDecreasePositionAmounts = void 0;
4
4
  const factors_1 = require("../../configs/factors");
5
5
  const bigmath_1 = require("../bigmath");
6
6
  const fees_1 = require("../fees");
@@ -210,10 +210,14 @@ function getDecreasePositionAmounts(p) {
210
210
  values.payedOutputUsd = (0, tokens_1.convertToUsd)(payedInfo.paidOutputAmount, collateralToken.decimals, values.collateralPrice);
211
211
  values.payedRemainingCollateralAmount = payedInfo.paidRemainingCollateralAmount;
212
212
  values.payedRemainingCollateralUsd = (0, tokens_1.convertToUsd)(payedInfo.paidRemainingCollateralAmount, collateralToken.decimals, values.collateralPrice);
213
+ let netCollateralOutputAmount = 0n;
214
+ let netCollateralOutputUsd = 0n;
213
215
  // Collateral delta
214
216
  if (values.isFullClose) {
215
217
  values.collateralDeltaUsd = estimatedCollateralUsd;
216
218
  values.collateralDeltaAmount = position.collateralAmount;
219
+ netCollateralOutputAmount = payedInfo.remainingCollateralAmount;
220
+ netCollateralOutputUsd = (0, tokens_1.convertToUsd)(netCollateralOutputAmount, collateralToken.decimals, values.collateralPrice);
217
221
  values.receiveTokenAmount = payedInfo.outputAmount + payedInfo.remainingCollateralAmount;
218
222
  }
219
223
  else if (keepLeverage &&
@@ -238,6 +242,8 @@ function getDecreasePositionAmounts(p) {
238
242
  ? remainingCollateralUsd - bigmath_1.bigMath.mulDiv(nextSizeInUsd, numbers_1.BASIS_POINTS_DIVISOR_BIGINT, leverageWithoutPnl)
239
243
  : 0n;
240
244
  values.collateralDeltaAmount = (0, tokens_1.convertToTokenAmount)(values.collateralDeltaUsd, collateralToken.decimals, values.collateralPrice);
245
+ netCollateralOutputAmount = values.collateralDeltaAmount;
246
+ netCollateralOutputUsd = values.collateralDeltaUsd;
241
247
  values.receiveTokenAmount = payedInfo.outputAmount + values.collateralDeltaAmount;
242
248
  }
243
249
  else {
@@ -248,7 +254,21 @@ function getDecreasePositionAmounts(p) {
248
254
  values.receiveUsd = (0, tokens_1.convertToUsd)(values.receiveTokenAmount, collateralToken.decimals, values.collateralPrice);
249
255
  // SwapCollateralTokenToPnlToken → primaryOutput (pnl token), otherwise → secondaryOutput (collateral token)
250
256
  const pnlTokenPrice = pnlToken.prices.minPrice;
251
- if (values.decreaseSwapType === types_1.DecreasePositionSwapType.SwapCollateralTokenToPnlToken) {
257
+ const remainingPnlOutputUsd = (0, tokens_1.convertToUsd)(payedInfo.outputAmount, collateralToken.decimals, values.collateralPrice) ?? 0n;
258
+ if (values.decreaseSwapType === types_1.DecreasePositionSwapType.NoSwap &&
259
+ !(0, tokens_1.getIsEquivalentTokens)(pnlToken, collateralToken)) {
260
+ values.primaryOutput = {
261
+ tokenAddress: pnlToken.address,
262
+ amount: (0, tokens_1.convertToTokenAmount)(remainingPnlOutputUsd, pnlToken.decimals, pnlTokenPrice) ?? 0n,
263
+ usd: remainingPnlOutputUsd,
264
+ };
265
+ values.secondaryOutput = {
266
+ tokenAddress: collateralToken.address,
267
+ amount: netCollateralOutputAmount,
268
+ usd: netCollateralOutputUsd,
269
+ };
270
+ }
271
+ else if (values.decreaseSwapType === types_1.DecreasePositionSwapType.SwapCollateralTokenToPnlToken) {
252
272
  values.primaryOutput = {
253
273
  tokenAddress: pnlToken.address,
254
274
  amount: (0, tokens_1.convertToTokenAmount)(values.receiveUsd, pnlToken.decimals, pnlTokenPrice) ?? 0n,
@@ -308,6 +328,34 @@ function getMinCollateralUsdForLeverage(position, openInterestDelta) {
308
328
  return (0, numbers_1.applyFactor)(position.sizeInUsd, minCollateralFactor);
309
329
  }
310
330
  exports.getMinCollateralUsdForLeverage = getMinCollateralUsdForLeverage;
331
+ function getMaxWithdrawAmount(p) {
332
+ const { position, minCollateralUsd, collateralPrice, collateralDecimals, userReferralInfo } = p;
333
+ const minCollateralUsdForLeverage = getMinCollateralUsdForLeverage(position, 0n);
334
+ let minRequiredNextCollateralUsd = minCollateralUsdForLeverage;
335
+ if (minCollateralUsd !== undefined && minCollateralUsd > minRequiredNextCollateralUsd) {
336
+ minRequiredNextCollateralUsd = minCollateralUsd;
337
+ }
338
+ const minCollateralUsdForLiquidationPrice = (0, positions_1.getMinCollateralUsdForLiquidationPrice)({
339
+ sizeInUsd: position.sizeInUsd,
340
+ sizeInTokens: position.sizeInTokens,
341
+ marketInfo: position.marketInfo,
342
+ pendingImpactAmount: position.pendingImpactAmount,
343
+ minCollateralUsd: minCollateralUsd ?? 0n,
344
+ pnl: position.pnl,
345
+ isLong: position.isLong,
346
+ userReferralInfo,
347
+ });
348
+ if (minCollateralUsdForLiquidationPrice > minRequiredNextCollateralUsd) {
349
+ minRequiredNextCollateralUsd = minCollateralUsdForLiquidationPrice;
350
+ }
351
+ const minRequiredCollateralUsd = minRequiredNextCollateralUsd + (position.pendingBorrowingFeesUsd ?? 0n) + (position.pendingFundingFeesUsd ?? 0n);
352
+ if (position.collateralUsd < minRequiredCollateralUsd) {
353
+ return 0n;
354
+ }
355
+ const maxWithdrawUsd = position.collateralUsd - minRequiredCollateralUsd;
356
+ return (0, tokens_1.convertToTokenAmount)(maxWithdrawUsd, collateralDecimals, collateralPrice) ?? 0n;
357
+ }
358
+ exports.getMaxWithdrawAmount = getMaxWithdrawAmount;
311
359
  function payForCollateralCost(p) {
312
360
  const { initialCostUsd, collateralToken, collateralPrice, outputAmount, remainingCollateralAmount } = p;
313
361
  const values = {
@@ -510,7 +558,7 @@ function selectBetterDecreaseSwapType(p) {
510
558
  }
511
559
  exports.selectBetterDecreaseSwapType = selectBetterDecreaseSwapType;
512
560
  function getOptimalDecreaseAndSwapAmounts(p) {
513
- const { marketInfo, collateralToken, isLong, position, closeSizeUsd, keepLeverage, triggerPrice, fixedAcceptablePriceImpactBps, acceptablePriceImpactBuffer, userReferralInfo, minCollateralUsd, minPositionSizeUsd, uiFeeFactor, triggerOrderType, isSetAcceptablePriceImpactEnabled, receiveToken, findSwapPath, findSwapPathFromPnl, marketsInfoData, chainId, } = p;
561
+ const { marketInfo, collateralToken, isLong, position, closeSizeUsd, keepLeverage, triggerPrice, fixedAcceptablePriceImpactBps, acceptablePriceImpactBuffer, userReferralInfo, minCollateralUsd, minPositionSizeUsd, uiFeeFactor, triggerOrderType, isSetAcceptablePriceImpactEnabled, receiveToken, forceDecreaseSwapType, findSwapPath, findSwapPathFromPnl, marketsInfoData, chainId, } = p;
514
562
  const decreaseBaseParams = {
515
563
  marketInfo,
516
564
  collateralToken,
@@ -529,6 +577,15 @@ function getOptimalDecreaseAndSwapAmounts(p) {
529
577
  isSetAcceptablePriceImpactEnabled,
530
578
  receiveToken,
531
579
  };
580
+ if (forceDecreaseSwapType !== undefined) {
581
+ return {
582
+ decreaseAmounts: getDecreasePositionAmounts({
583
+ ...decreaseBaseParams,
584
+ forceDecreaseSwapType,
585
+ }),
586
+ swapAmounts: undefined,
587
+ };
588
+ }
532
589
  const pathADecrease = getDecreasePositionAmounts(decreaseBaseParams);
533
590
  const pnlToken = isLong ? marketInfo.longToken : marketInfo.shortToken;
534
591
  const shouldSwap = !(0, tokens_1.getIsEquivalentTokens)(collateralToken, receiveToken);
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getIsSplitReceiveAvailable = exports.getHasSplitReceiveOutputs = exports.getCanSplitReceive = exports.getDecreaseReceiveOutputs = void 0;
4
+ const tokens_1 = require("../tokens");
5
+ function getDecreaseReceiveOutputs({ decreaseAmounts, tokensData, }) {
6
+ if (!decreaseAmounts || !tokensData) {
7
+ return [];
8
+ }
9
+ return [
10
+ { type: "primary", output: decreaseAmounts.primaryOutput },
11
+ { type: "secondary", output: decreaseAmounts.secondaryOutput },
12
+ ].reduce((acc, { type, output }) => {
13
+ if (output.amount <= 0n) {
14
+ return acc;
15
+ }
16
+ const token = tokensData[output.tokenAddress];
17
+ if (!token) {
18
+ return acc;
19
+ }
20
+ acc.push({
21
+ type,
22
+ token,
23
+ amount: output.amount,
24
+ usd: output.usd,
25
+ });
26
+ return acc;
27
+ }, []);
28
+ }
29
+ exports.getDecreaseReceiveOutputs = getDecreaseReceiveOutputs;
30
+ function getCanSplitReceive(position) {
31
+ if (!position?.pnlToken || !position.collateralToken) {
32
+ return false;
33
+ }
34
+ return !(0, tokens_1.getIsEquivalentTokens)(position.pnlToken, position.collateralToken);
35
+ }
36
+ exports.getCanSplitReceive = getCanSplitReceive;
37
+ function getHasSplitReceiveOutputs(outputs) {
38
+ if (outputs.length < 2) {
39
+ return false;
40
+ }
41
+ return outputs.some((output) => !(0, tokens_1.getIsEquivalentTokens)(output.token, outputs[0].token));
42
+ }
43
+ exports.getHasSplitReceiveOutputs = getHasSplitReceiveOutputs;
44
+ function getIsSplitReceiveAvailable(position, outputs) {
45
+ return getCanSplitReceive(position) && getHasSplitReceiveOutputs(outputs);
46
+ }
47
+ exports.getIsSplitReceiveAvailable = getIsSplitReceiveAvailable;
@@ -17,4 +17,5 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./types"), exports);
18
18
  __exportStar(require("./increase"), exports);
19
19
  __exportStar(require("./decrease"), exports);
20
+ __exportStar(require("./decreaseOutputs"), exports);
20
21
  __exportStar(require("./trade"), exports);
@@ -120,6 +120,7 @@ function createRawTradeActionTransformer(marketsInfoData, wrappedToken, tokensDa
120
120
  swapImpactUsd: rawAction.swapImpactUsd ? BigInt(rawAction.swapImpactUsd) : undefined,
121
121
  totalImpactUsd: rawAction.totalImpactUsd ? BigInt(rawAction.totalImpactUsd) : undefined,
122
122
  positionFeeAmount: rawAction.positionFeeAmount ? BigInt(rawAction.positionFeeAmount) : undefined,
123
+ traderDiscountAmount: rawAction.traderDiscountAmount ? BigInt(rawAction.traderDiscountAmount) : undefined,
123
124
  borrowingFeeAmount: rawAction.borrowingFeeAmount ? BigInt(rawAction.borrowingFeeAmount) : undefined,
124
125
  fundingFeeAmount: rawAction.fundingFeeAmount ? BigInt(rawAction.fundingFeeAmount) : undefined,
125
126
  swapFeeUsd: rawAction.swapFeeUsd ? BigInt(rawAction.swapFeeUsd) : undefined,
@@ -10,7 +10,7 @@ function parseTradesResponse(raw) {
10
10
  };
11
11
  }
12
12
  async function fetchApiTrades(ctx, params) {
13
- return ctx.api.fetchJson("/trades", {
13
+ return ctx.api.fetchJson("/v1/trades", {
14
14
  query: {
15
15
  address: params.address,
16
16
  symbol: params.symbol,
@@ -26,7 +26,7 @@ async function fetchApiTrades(ctx, params) {
26
26
  }
27
27
  exports.fetchApiTrades = fetchApiTrades;
28
28
  async function searchApiTrades(ctx, params) {
29
- return ctx.api.postJson("/trades/search", params, {
29
+ return ctx.api.postJson("/v1/trades/search", params, {
30
30
  transform: parseTradesResponse,
31
31
  });
32
32
  }
@@ -67,6 +67,9 @@ function getUiFeeReceiverSource(uiFeeReceiver) {
67
67
  }
68
68
  exports.getUiFeeReceiverSource = getUiFeeReceiverSource;
69
69
  function setUiFeeReceiverIsExpress(uiFeeReceiver, isExpress) {
70
+ if (!isValidTwapUiFeeReceiver(uiFeeReceiver)) {
71
+ return uiFeeReceiver;
72
+ }
70
73
  return setUiFeeReceiverByte(uiFeeReceiver, EXPRESS_BYTE_START, EXPRESS_BYTE_END, isExpress);
71
74
  }
72
75
  exports.setUiFeeReceiverIsExpress = setUiFeeReceiverIsExpress;
@@ -1,5 +1,5 @@
1
1
  const config = {
2
- schema: "https://gmx.squids.live/gmx-synthetics-arbitrum@5eaa69/api/graphql",
2
+ schema: "https://gmx.squids.live/gmx-synthetics-arbitrum:prod/api/graphql",
3
3
  overwrite: true,
4
4
  debug: true,
5
5
  generates: {
@@ -50,7 +50,7 @@ export function matchByMarket({ order, nonSwapRelevantDefinedFiltersLowercased,
50
50
  return nonSwapRelevantDefinedFiltersLowercased.some((filter) => {
51
51
  const marketMatch = filter.marketAddress === "any" || filter.marketAddress === order.marketAddress.toLowerCase();
52
52
  const directionMath = filter.direction === "any" || filter.direction === (order.isLong ? "long" : "short");
53
- const initialCollateralAddress = order.initialCollateralTokenAddress.toLowerCase();
53
+ const initialCollateralAddress = order.initialCollateralTokenAddress;
54
54
  let collateralMatch = true;
55
55
  if (!filter.collateralAddress) {
56
56
  collateralMatch = true;
@@ -169,6 +169,7 @@ export async function fetchTradeActions({ sdk, pageIndex, pageSize, marketsDirec
169
169
  swapImpactUsd
170
170
  totalImpactUsd
171
171
  positionFeeAmount
172
+ traderDiscountAmount
172
173
  borrowingFeeAmount
173
174
  fundingFeeAmount
174
175
  swapFeeUsd
@@ -7,6 +7,7 @@ import { fetchApiBuybackWeeklyStats } from "../../utils/buyback/api";
7
7
  import { executeCrossChainDeposit, executeCrossChainWithdraw, getCrossChainWithdrawStatus, prepareCrossChainDeposit, prepareCrossChainWithdraw, signCrossChainWithdrawPrepared, submitCrossChainWithdraw, } from "../../utils/gmxAccountApi";
8
8
  import { HttpClient } from "../../utils/http/http";
9
9
  import { HttpClientWithFallback } from "../../utils/http/httpFallback";
10
+ import { fetchApiJitLiquidityInfo } from "../../utils/jitLiquidity/api";
10
11
  import { fetchApiMarkets, fetchApiMarketsInfo, fetchApiMarketsTickers, fetchApiTokensData } from "../../utils/markets/api";
11
12
  import { buildCrossChainWithdrawBridgeOutParams, buildSameChainDepositTxn, buildSameChainWithdrawBridgeOutParams, buildSameChainWithdrawTxn, executeSameChainDeposit, executeSameChainWithdraw, } from "../../utils/multichain";
12
13
  import { fetchApiOrders } from "../../utils/orders/api";
@@ -101,6 +102,9 @@ export class GmxApiSdk {
101
102
  fetchBuybackWeeklyStats() {
102
103
  return fetchApiBuybackWeeklyStats(this.ctx);
103
104
  }
105
+ fetchJitLiquidityInfo(params) {
106
+ return fetchApiJitLiquidityInfo(this.ctx, params);
107
+ }
104
108
  fetchStakingPower(params) {
105
109
  return fetchApiStakingPower(this.ctx, params);
106
110
  }
@@ -3205,6 +3205,12 @@ export var TradeActionOrderByInput;
3205
3205
  TradeActionOrderByInput["totalImpactUsd_DESC"] = "totalImpactUsd_DESC";
3206
3206
  TradeActionOrderByInput["totalImpactUsd_DESC_NULLS_FIRST"] = "totalImpactUsd_DESC_NULLS_FIRST";
3207
3207
  TradeActionOrderByInput["totalImpactUsd_DESC_NULLS_LAST"] = "totalImpactUsd_DESC_NULLS_LAST";
3208
+ TradeActionOrderByInput["traderDiscountAmount_ASC"] = "traderDiscountAmount_ASC";
3209
+ TradeActionOrderByInput["traderDiscountAmount_ASC_NULLS_FIRST"] = "traderDiscountAmount_ASC_NULLS_FIRST";
3210
+ TradeActionOrderByInput["traderDiscountAmount_ASC_NULLS_LAST"] = "traderDiscountAmount_ASC_NULLS_LAST";
3211
+ TradeActionOrderByInput["traderDiscountAmount_DESC"] = "traderDiscountAmount_DESC";
3212
+ TradeActionOrderByInput["traderDiscountAmount_DESC_NULLS_FIRST"] = "traderDiscountAmount_DESC_NULLS_FIRST";
3213
+ TradeActionOrderByInput["traderDiscountAmount_DESC_NULLS_LAST"] = "traderDiscountAmount_DESC_NULLS_LAST";
3208
3214
  TradeActionOrderByInput["transactionHash_ASC"] = "transactionHash_ASC";
3209
3215
  TradeActionOrderByInput["transactionHash_ASC_NULLS_FIRST"] = "transactionHash_ASC_NULLS_FIRST";
3210
3216
  TradeActionOrderByInput["transactionHash_ASC_NULLS_LAST"] = "transactionHash_ASC_NULLS_LAST";
@@ -1,8 +1,16 @@
1
1
  import { withRetry } from "viem";
2
2
  import { describe, expect, it } from "vitest";
3
- import { CONTRACTS_CHAIN_IDS_DEV } from "../chains";
3
+ import { ARBITRUM, CONTRACTS_CHAIN_IDS_DEV } from "../chains";
4
4
  import { MARKETS } from "../markets";
5
5
  import { getOracleKeeperUrl } from "../oracleKeeper";
6
+ const SKIPPED_KEEPER_MARKETS = {
7
+ [ARBITRUM]: new Set([
8
+ // OM/USD [WBTC-USDC]
9
+ "0x89EB78679921499632fF16B1be3ee48295cfCD91",
10
+ // WELL/USD [WETH-USDC]
11
+ "0x2347EbB8645Cc2EA0Ba92D1EC59704031F2fCCf4",
12
+ ]),
13
+ };
6
14
  const getKeeperMarkets = async (chainId) => {
7
15
  const res = await fetch(`${getOracleKeeperUrl(chainId)}/markets`);
8
16
  const data = (await res.json());
@@ -17,6 +25,9 @@ describe("markets config", () => {
17
25
  retryCount: 2,
18
26
  });
19
27
  Object.entries(MARKETS[chainId]).forEach(([marketAddress, market]) => {
28
+ if (SKIPPED_KEEPER_MARKETS[chainId]?.has(marketAddress)) {
29
+ return;
30
+ }
20
31
  expect(marketAddress).toBe(market.marketTokenAddress);
21
32
  const keeperMarket = keeperMarkets.markets.find((m) => m.marketToken === marketAddress);
22
33
  expect(keeperMarket).toBeDefined();
@@ -1,26 +1,46 @@
1
1
  import { ARBITRUM, ARBITRUM_SEPOLIA, AVALANCHE, AVALANCHE_FUJI, BOTANIX, MEGAETH } from "./chains";
2
2
  const API_URLS = {
3
- [ARBITRUM]: "https://arbitrum.gmxapi.io/v1",
4
- [AVALANCHE]: "https://avalanche.gmxapi.io/v1",
5
- [AVALANCHE_FUJI]: undefined,
6
- [BOTANIX]: "https://botanix.gmxapi.io/v1",
7
- [ARBITRUM_SEPOLIA]: "https://gmx-api-arbitrum-sepolia-yp6pp.ondigitalocean.app/v1",
8
- [MEGAETH]: "https://megaeth.gmxapi.io/v1",
3
+ production: {
4
+ [ARBITRUM]: "https://arbitrum.gmxapi.io",
5
+ [AVALANCHE]: "https://avalanche.gmxapi.io",
6
+ [AVALANCHE_FUJI]: undefined,
7
+ [BOTANIX]: "https://botanix.gmxapi.io",
8
+ [ARBITRUM_SEPOLIA]: "https://gmx-api-arbitrum-sepolia-yp6pp.ondigitalocean.app",
9
+ [MEGAETH]: "https://megaeth.gmxapi.io",
10
+ },
11
+ test: {
12
+ [ARBITRUM]: "https://arbitrum-test.gmxapi.ai",
13
+ [AVALANCHE]: undefined,
14
+ [AVALANCHE_FUJI]: undefined,
15
+ [BOTANIX]: undefined,
16
+ [ARBITRUM_SEPOLIA]: "https://arbitrum-sepolia-test.gmxapi.ai",
17
+ [MEGAETH]: undefined,
18
+ },
9
19
  };
10
20
  const API_FALLBACK_URLS = {
11
- [ARBITRUM]: ["https://arbitrum.gmxapi.ai/v1"],
12
- [AVALANCHE]: ["https://avalanche.gmxapi.ai/v1"],
13
- [AVALANCHE_FUJI]: [],
14
- [BOTANIX]: ["https://botanix.gmxapi.ai/v1"],
15
- [ARBITRUM_SEPOLIA]: [],
16
- [MEGAETH]: ["https://megaeth.gmxapi.ai/v1"],
21
+ production: {
22
+ [ARBITRUM]: [],
23
+ [AVALANCHE]: [],
24
+ [AVALANCHE_FUJI]: [],
25
+ [BOTANIX]: [],
26
+ [ARBITRUM_SEPOLIA]: [],
27
+ [MEGAETH]: [],
28
+ },
29
+ test: {
30
+ [ARBITRUM]: [],
31
+ [AVALANCHE]: [],
32
+ [AVALANCHE_FUJI]: [],
33
+ [BOTANIX]: [],
34
+ [ARBITRUM_SEPOLIA]: [],
35
+ [MEGAETH]: [],
36
+ },
17
37
  };
18
- export function getApiUrl(chainId) {
19
- return API_URLS[chainId];
38
+ export function getApiUrl(chainId, environment = "production") {
39
+ return API_URLS[environment][chainId];
20
40
  }
21
- export function getApiFallbackUrls(chainId) {
22
- return API_FALLBACK_URLS[chainId] ?? [];
41
+ export function getApiFallbackUrls(chainId, environment = "production") {
42
+ return API_FALLBACK_URLS[environment][chainId] ?? [];
23
43
  }
24
- export function isApiSupported(chainId) {
25
- return getApiUrl(chainId) !== undefined;
44
+ export function isApiSupported(chainId, environment = "production") {
45
+ return getApiUrl(chainId, environment) !== undefined;
26
46
  }
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it } from "vitest";
2
- import { setByKey, updateByKey, getByKey, objectKeysDeep } from "../objects";
2
+ import { setByKey, updateByKey, getByKey, getRecord, getString, isRecord, objectKeysDeep } from "../objects";
3
3
  describe("setByKey", () => {
4
4
  it("should set a key in an object", () => {
5
5
  const obj = { a: 1, b: 2 };
@@ -57,6 +57,22 @@ describe("getByKey", () => {
57
57
  expect(getByKey(obj, key)).toEqual(undefined);
58
58
  });
59
59
  });
60
+ describe("record guards", () => {
61
+ it("should identify records", () => {
62
+ expect(isRecord({ a: 1 })).toBe(true);
63
+ expect(isRecord([])).toBe(false);
64
+ expect(isRecord(null)).toBe(false);
65
+ });
66
+ it("should return records only", () => {
67
+ const record = { a: 1 };
68
+ expect(getRecord(record)).toBe(record);
69
+ expect(getRecord([])).toBeUndefined();
70
+ });
71
+ it("should return strings only", () => {
72
+ expect(getString("abc")).toBe("abc");
73
+ expect(getString(1)).toBeUndefined();
74
+ });
75
+ });
60
76
  describe("objectKeysDeep", () => {
61
77
  it("should get all keys from a flat object", () => {
62
78
  const obj = { a: 1, b: 2, c: 3 };
@@ -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, getPositionNetValueAfterAllFees, getPositionPendingFeesUsd, getPositionPnlAfterAllFees, getPositionPnlAfterFees, getPositionPnlUsd, getPositionValueUsd, parsePositionKey, } from "../positions";
6
+ import { getEntryPrice, getLeverage, getLiquidationPrice, getMinCollateralUsdForLiquidationPrice, 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"),
@@ -338,3 +338,166 @@ describe("getLiquidationPrice", () => {
338
338
  expect(result).toBeDefined();
339
339
  });
340
340
  });
341
+ describe("getMinCollateralUsdForLiquidationPrice", () => {
342
+ // Tiny factor magnitudes here round to 0n under PRECISION=1e30 — keeping them this way
343
+ // lets us assert exact integer results. One test below uses realistic factors to lock in
344
+ // that the priceImpact cap also works at scale.
345
+ const marketInfo = {
346
+ indexToken: {
347
+ decimals: 8,
348
+ prices: { minPrice: expandDecimals(1, USD_DECIMALS), maxPrice: expandDecimals(1, USD_DECIMALS) },
349
+ },
350
+ minCollateralFactorForLiquidation: 1000n,
351
+ maxPositionImpactFactorForLiquidations: 500n,
352
+ maxPositionImpactFactorPositive: 1000n,
353
+ maxPositionImpactFactorNegative: 1000n,
354
+ };
355
+ beforeEach(() => {
356
+ getPositionFee.mockReturnValue({ positionFeeUsd: 50n });
357
+ getPriceImpactForPosition.mockReturnValue({ priceImpactDeltaUsd: -100n, balanceWasImproved: false });
358
+ convertToUsd.mockReturnValue(0n);
359
+ });
360
+ it("returns 0 when sizeInUsd <= 0", () => {
361
+ const result = getMinCollateralUsdForLiquidationPrice({
362
+ sizeInUsd: 0n,
363
+ sizeInTokens: 100n,
364
+ marketInfo,
365
+ pendingImpactAmount: 0n,
366
+ minCollateralUsd: 200n,
367
+ pnl: 0n,
368
+ isLong: true,
369
+ userReferralInfo: undefined,
370
+ });
371
+ expect(result).toBe(0n);
372
+ });
373
+ it("returns 0 when sizeInTokens <= 0", () => {
374
+ const result = getMinCollateralUsdForLiquidationPrice({
375
+ sizeInUsd: 1000n,
376
+ sizeInTokens: 0n,
377
+ marketInfo,
378
+ pendingImpactAmount: 0n,
379
+ minCollateralUsd: 200n,
380
+ pnl: 0n,
381
+ isLong: true,
382
+ userReferralInfo: undefined,
383
+ });
384
+ expect(result).toBe(0n);
385
+ });
386
+ it("returns liquidationCollateralUsd - pnl - priceImpactDeltaUsd + closingFeeUsd for a profitable position", () => {
387
+ const result = getMinCollateralUsdForLiquidationPrice({
388
+ sizeInUsd: 1000n,
389
+ sizeInTokens: 100n,
390
+ marketInfo,
391
+ pendingImpactAmount: 0n,
392
+ minCollateralUsd: 200n,
393
+ pnl: 500n,
394
+ isLong: true,
395
+ userReferralInfo: undefined,
396
+ });
397
+ expect(result).toBe(-250n);
398
+ });
399
+ it("returns a larger value for a losing position than a profitable one", () => {
400
+ const losing = getMinCollateralUsdForLiquidationPrice({
401
+ sizeInUsd: 1000n,
402
+ sizeInTokens: 100n,
403
+ marketInfo,
404
+ pendingImpactAmount: 0n,
405
+ minCollateralUsd: 200n,
406
+ pnl: -300n,
407
+ isLong: true,
408
+ userReferralInfo: undefined,
409
+ });
410
+ const profitable = getMinCollateralUsdForLiquidationPrice({
411
+ sizeInUsd: 1000n,
412
+ sizeInTokens: 100n,
413
+ marketInfo,
414
+ pendingImpactAmount: 0n,
415
+ minCollateralUsd: 200n,
416
+ pnl: 300n,
417
+ isLong: true,
418
+ userReferralInfo: undefined,
419
+ });
420
+ expect(losing).toBeGreaterThan(profitable);
421
+ expect(losing).toBe(550n);
422
+ expect(profitable).toBe(-50n);
423
+ });
424
+ it("uses minCollateralUsd when it exceeds the factor-based liquidation collateral", () => {
425
+ const result = getMinCollateralUsdForLiquidationPrice({
426
+ sizeInUsd: 1000n,
427
+ sizeInTokens: 100n,
428
+ marketInfo,
429
+ pendingImpactAmount: 0n,
430
+ minCollateralUsd: 500n,
431
+ pnl: 0n,
432
+ isLong: true,
433
+ userReferralInfo: undefined,
434
+ });
435
+ expect(result).toBe(550n);
436
+ });
437
+ it("includes pendingImpactUsd in priceImpactDeltaUsd", () => {
438
+ convertToUsd.mockReturnValueOnce(-30n);
439
+ const result = getMinCollateralUsdForLiquidationPrice({
440
+ sizeInUsd: 1000n,
441
+ sizeInTokens: 100n,
442
+ marketInfo,
443
+ pendingImpactAmount: -100n,
444
+ minCollateralUsd: 200n,
445
+ pnl: 0n,
446
+ isLong: true,
447
+ userReferralInfo: undefined,
448
+ });
449
+ expect(result).toBe(250n);
450
+ });
451
+ it("uses realistic factors so priceImpactDeltaUsd is not capped to zero", () => {
452
+ const realisticMarketInfo = {
453
+ indexToken: {
454
+ decimals: 8,
455
+ prices: { minPrice: expandDecimals(1, USD_DECIMALS), maxPrice: expandDecimals(1, USD_DECIMALS) },
456
+ },
457
+ minCollateralFactorForLiquidation: 1000n,
458
+ maxPositionImpactFactorForLiquidations: expandDecimals(1, 28),
459
+ maxPositionImpactFactorPositive: 1000n,
460
+ maxPositionImpactFactorNegative: 1000n,
461
+ };
462
+ const sizeInUsd = expandDecimals(1000, USD_DECIMALS);
463
+ getPositionFee.mockReturnValueOnce({ positionFeeUsd: expandDecimals(5, USD_DECIMALS) });
464
+ getPriceImpactForPosition.mockReturnValueOnce({
465
+ priceImpactDeltaUsd: -expandDecimals(20, USD_DECIMALS),
466
+ balanceWasImproved: false,
467
+ });
468
+ const result = getMinCollateralUsdForLiquidationPrice({
469
+ sizeInUsd,
470
+ sizeInTokens: 100n,
471
+ marketInfo: realisticMarketInfo,
472
+ pendingImpactAmount: 0n,
473
+ minCollateralUsd: expandDecimals(100, USD_DECIMALS),
474
+ pnl: expandDecimals(50, USD_DECIMALS),
475
+ isLong: true,
476
+ userReferralInfo: undefined,
477
+ });
478
+ expect(result).toBe(expandDecimals(65, USD_DECIMALS));
479
+ });
480
+ it("works for short positions identically", () => {
481
+ const long = getMinCollateralUsdForLiquidationPrice({
482
+ sizeInUsd: 1000n,
483
+ sizeInTokens: 100n,
484
+ marketInfo,
485
+ pendingImpactAmount: 0n,
486
+ minCollateralUsd: 200n,
487
+ pnl: 200n,
488
+ isLong: true,
489
+ userReferralInfo: undefined,
490
+ });
491
+ const short = getMinCollateralUsdForLiquidationPrice({
492
+ sizeInUsd: 1000n,
493
+ sizeInTokens: 100n,
494
+ marketInfo,
495
+ pendingImpactAmount: 0n,
496
+ minCollateralUsd: 200n,
497
+ pnl: 200n,
498
+ isLong: false,
499
+ userReferralInfo: undefined,
500
+ });
501
+ expect(short).toBe(long);
502
+ });
503
+ });
@@ -81,6 +81,11 @@ describe("uiFeeReceiver", () => {
81
81
  });
82
82
  });
83
83
  describe("setUiFeeReceiverIsExpress", () => {
84
+ it("should preserve regular uiFeeReceiver addresses", () => {
85
+ const uiFeeReceiver = "0x496Ca0b922fd18a2cB9DDEe44969CDdC8D87Bc7F";
86
+ expect(setUiFeeReceiverIsExpress(uiFeeReceiver, true)).toEqual(uiFeeReceiver);
87
+ expect(setUiFeeReceiverIsExpress(uiFeeReceiver, false)).toEqual(uiFeeReceiver);
88
+ });
84
89
  it("should correctly set isExpress for simple uiFeeReceiver", () => {
85
90
  expect(setUiFeeReceiverIsExpress("0xff00000000000000000000000000000000000001", true)).toEqual("0xff00000000000000000000000000000100000001");
86
91
  expect(setUiFeeReceiverIsExpress("0xff00000000000000000000000000000000000001", false)).toEqual("0xff00000000000000000000000000000000000001");
@@ -1,5 +1,5 @@
1
1
  export async function fetchApiApy(ctx, params) {
2
- return ctx.api.fetchJson("/apy", {
2
+ return ctx.api.fetchJson("/v1/apy", {
3
3
  query: {
4
4
  period: params?.period,
5
5
  },
@@ -19,13 +19,13 @@ function parseAllowances(raw) {
19
19
  }));
20
20
  }
21
21
  export async function fetchWalletBalances(ctx, params) {
22
- return ctx.api.fetchJson("/balances/wallet", {
22
+ return ctx.api.fetchJson("/v1/balances/wallet", {
23
23
  query: { address: params.address },
24
24
  transform: parseWalletBalances,
25
25
  });
26
26
  }
27
27
  export async function fetchAllowances(ctx, params) {
28
- return ctx.api.fetchJson("/allowances", {
28
+ return ctx.api.fetchJson("/v1/allowances", {
29
29
  query: { address: params.address, spender: params.spender },
30
30
  transform: parseAllowances,
31
31
  });
@@ -1,3 +1,3 @@
1
1
  export async function fetchApiBuybackWeeklyStats(ctx) {
2
- return ctx.api.fetchJson("/buyback/weekly-stats");
2
+ return ctx.api.fetchJson("/v1/buyback/weekly-stats");
3
3
  }
@@ -12,11 +12,8 @@ function getOracleParams({ chainId, tokenAddresses }) {
12
12
  data: Array(uniqTokenAddresses.length).fill("0x"),
13
13
  };
14
14
  }
15
- export function getOracleParamsForRelayParams({ chainId, gasPaymentTokenAddress, relayerFeeTokenAddress, feeSwapPath, externalCalls, }) {
15
+ export function getOracleParamsForRelayParams({ chainId, gasPaymentTokenAddress, relayerFeeTokenAddress, feeSwapPath, }) {
16
16
  const tokenAddresses = [gasPaymentTokenAddress, relayerFeeTokenAddress];
17
- if (externalCalls) {
18
- tokenAddresses.push(...externalCalls.sendTokens);
19
- }
20
17
  if (feeSwapPath.length) {
21
18
  tokenAddresses.push(...getSwapPathOracleTokens({
22
19
  chainId,
@@ -149,7 +149,6 @@ export function getBestFeeSwapStrategy(internalSwapAmounts, externalSwapQuote) {
149
149
  export function getRawRelayerParams({ chainId, gasPaymentTokenAddress, relayerFeeTokenAddress, feeParams, externalCalls, tokenPermits, }) {
150
150
  const oracleParams = getOracleParamsForRelayParams({
151
151
  chainId,
152
- externalCalls,
153
152
  feeSwapPath: feeParams.feeSwapPath,
154
153
  gasPaymentTokenAddress,
155
154
  relayerFeeTokenAddress,