@gmx-io/sdk 1.8.0 → 1.9.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 (127) hide show
  1. package/README.md +1 -1
  2. package/build/cjs/scripts/subsquid-codegen.js +1 -1
  3. package/build/cjs/src/abis/ArbSys.js +11 -0
  4. package/build/cjs/src/abis/index.js +2 -0
  5. package/build/cjs/src/clients/v1/testUtil.js +1 -1
  6. package/build/cjs/src/clients/v2/index.js +8 -1
  7. package/build/cjs/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +16 -88
  8. package/build/cjs/src/codegen/prebuilt/hashedMarketConfigKeys.json +136 -748
  9. package/build/cjs/src/codegen/prebuilt/hashedMarketValuesKeys.json +30 -165
  10. package/build/cjs/src/configs/__tests__/markets.spec.js +1 -16
  11. package/build/cjs/src/configs/api.js +10 -1
  12. package/build/cjs/src/configs/contracts.js +2 -0
  13. package/build/cjs/src/configs/dataStore.js +13 -3
  14. package/build/cjs/src/configs/express.js +1 -0
  15. package/build/cjs/src/configs/markets.js +14 -77
  16. package/build/cjs/src/configs/tokens.js +22 -90
  17. package/build/cjs/src/test/fixtures/arbitrumMarkets.json +0 -72
  18. package/build/cjs/src/test/mock.js +12 -1
  19. package/build/cjs/src/utils/__tests__/fees.spec.js +36 -0
  20. package/build/cjs/src/utils/__tests__/markets.spec.js +233 -0
  21. package/build/cjs/src/utils/__tests__/positionPnlCap.spec.js +30 -3
  22. package/build/cjs/src/utils/__tests__/positions.spec.js +5 -5
  23. package/build/cjs/src/utils/__tests__/prices.spec.js +97 -0
  24. package/build/cjs/src/utils/express/utils/gelatoRelayUtils.js +2 -0
  25. package/build/cjs/src/utils/express/utils/gmxRelayUtils.js +145 -0
  26. package/build/cjs/src/utils/express/utils/gmxRelayUtils.spec.js +163 -0
  27. package/build/cjs/src/utils/express/utils/index.js +1 -0
  28. package/build/cjs/src/utils/fees/index.js +8 -5
  29. package/build/cjs/src/utils/fees/priceImpact.js +4 -9
  30. package/build/cjs/src/utils/markets/utils.js +57 -1
  31. package/build/cjs/src/utils/numbers/index.js +1 -0
  32. package/build/cjs/src/utils/numbers/prbMath.js +154 -0
  33. package/build/cjs/src/utils/positions/utils.js +66 -43
  34. package/build/cjs/src/utils/prices/utils.js +28 -1
  35. package/build/cjs/src/utils/stats/__tests__/api.spec.js +100 -0
  36. package/build/cjs/src/utils/stats/api.js +32 -0
  37. package/build/cjs/src/utils/stats/types.js +4 -0
  38. package/build/cjs/src/utils/trade/__tests__/increase.spec.js +580 -0
  39. package/build/cjs/src/utils/trade/__tests__/increaseInvariants.spec.js +258 -0
  40. package/build/cjs/src/utils/trade/__tests__/increaseMarginCheck.spec.js +837 -0
  41. package/build/cjs/src/utils/trade/increase.js +255 -32
  42. package/build/cjs/src/utils/trade/increaseMarginCheck.js +179 -0
  43. package/build/cjs/src/utils/trade/index.js +1 -0
  44. package/build/cjs/src/utils/trade/trade.js +11 -1
  45. package/build/cjs/src/utils/tradeHistory/utils.js +3 -0
  46. package/build/cjs/src/utils/yield/api.js +9 -1
  47. package/build/esm/scripts/subsquid-codegen.js +1 -1
  48. package/build/esm/src/abis/ArbSys.js +9 -0
  49. package/build/esm/src/abis/index.js +2 -0
  50. package/build/esm/src/clients/v1/testUtil.js +1 -1
  51. package/build/esm/src/clients/v2/index.js +5 -1
  52. package/build/esm/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +16 -88
  53. package/build/esm/src/codegen/prebuilt/hashedMarketConfigKeys.json +136 -748
  54. package/build/esm/src/codegen/prebuilt/hashedMarketValuesKeys.json +30 -165
  55. package/build/esm/src/configs/__tests__/markets.spec.js +2 -17
  56. package/build/esm/src/configs/api.js +8 -0
  57. package/build/esm/src/configs/contracts.js +2 -0
  58. package/build/esm/src/configs/dataStore.js +8 -0
  59. package/build/esm/src/configs/express.js +1 -0
  60. package/build/esm/src/configs/markets.js +14 -77
  61. package/build/esm/src/configs/tokens.js +22 -90
  62. package/build/esm/src/test/fixtures/arbitrumMarkets.json +0 -72
  63. package/build/esm/src/test/mock.js +10 -0
  64. package/build/esm/src/utils/__tests__/fees.spec.js +37 -1
  65. package/build/esm/src/utils/__tests__/markets.spec.js +234 -1
  66. package/build/esm/src/utils/__tests__/positionPnlCap.spec.js +30 -3
  67. package/build/esm/src/utils/__tests__/positions.spec.js +5 -5
  68. package/build/esm/src/utils/__tests__/prices.spec.js +98 -1
  69. package/build/esm/src/utils/express/utils/gelatoRelayUtils.js +2 -0
  70. package/build/esm/src/utils/express/utils/gmxRelayUtils.js +137 -0
  71. package/build/esm/src/utils/express/utils/gmxRelayUtils.spec.js +161 -0
  72. package/build/esm/src/utils/express/utils/index.js +1 -0
  73. package/build/esm/src/utils/fees/index.js +8 -5
  74. package/build/esm/src/utils/fees/priceImpact.js +5 -10
  75. package/build/esm/src/utils/markets/utils.js +57 -2
  76. package/build/esm/src/utils/numbers/index.js +1 -0
  77. package/build/esm/src/utils/numbers/prbMath.js +149 -0
  78. package/build/esm/src/utils/positions/utils.js +63 -42
  79. package/build/esm/src/utils/prices/utils.js +25 -0
  80. package/build/esm/src/utils/stats/__tests__/api.spec.js +98 -0
  81. package/build/esm/src/utils/stats/api.js +26 -0
  82. package/build/esm/src/utils/stats/types.js +1 -0
  83. package/build/esm/src/utils/trade/__tests__/increase.spec.js +578 -0
  84. package/build/esm/src/utils/trade/__tests__/increaseInvariants.spec.js +256 -0
  85. package/build/esm/src/utils/trade/__tests__/increaseMarginCheck.spec.js +835 -0
  86. package/build/esm/src/utils/trade/increase.js +243 -20
  87. package/build/esm/src/utils/trade/increaseMarginCheck.js +173 -0
  88. package/build/esm/src/utils/trade/index.js +1 -0
  89. package/build/esm/src/utils/trade/trade.js +10 -1
  90. package/build/esm/src/utils/tradeHistory/utils.js +3 -0
  91. package/build/esm/src/utils/yield/api.js +7 -0
  92. package/build/tsconfig.tsbuildinfo +1 -1
  93. package/build/types/src/abis/ArbSys.d.ts +12 -0
  94. package/build/types/src/abis/index.d.ts +11 -0
  95. package/build/types/src/clients/v2/index.d.ts +6 -3
  96. package/build/types/src/codegen/prebuilt/index.d.ts +170 -989
  97. package/build/types/src/configs/api.d.ts +1 -0
  98. package/build/types/src/configs/contracts.d.ts +2 -0
  99. package/build/types/src/configs/dataStore.d.ts +4 -0
  100. package/build/types/src/configs/express.d.ts +1 -0
  101. package/build/types/src/test/mock.d.ts +2 -0
  102. package/build/types/src/utils/buildUrl/utils.d.ts +1 -1
  103. package/build/types/src/utils/buyback/types.d.ts +7 -0
  104. package/build/types/src/utils/express/utils/gelatoRelayUtils.d.ts +2 -0
  105. package/build/types/src/utils/express/utils/gmxRelayUtils.d.ts +61 -0
  106. package/build/types/src/utils/express/utils/gmxRelayUtils.spec.d.ts +1 -0
  107. package/build/types/src/utils/express/utils/index.d.ts +1 -0
  108. package/build/types/src/utils/fees/index.d.ts +1 -1
  109. package/build/types/src/utils/markets/utils.d.ts +7 -0
  110. package/build/types/src/utils/numbers/index.d.ts +1 -0
  111. package/build/types/src/utils/numbers/prbMath.d.ts +7 -0
  112. package/build/types/src/utils/positions/utils.d.ts +9 -0
  113. package/build/types/src/utils/prices/utils.d.ts +10 -0
  114. package/build/types/src/utils/stats/__tests__/api.spec.d.ts +1 -0
  115. package/build/types/src/utils/stats/api.d.ts +11 -0
  116. package/build/types/src/utils/stats/types.d.ts +106 -0
  117. package/build/types/src/utils/trade/__tests__/increase.spec.d.ts +1 -0
  118. package/build/types/src/utils/trade/__tests__/increaseInvariants.spec.d.ts +1 -0
  119. package/build/types/src/utils/trade/__tests__/increaseMarginCheck.spec.d.ts +1 -0
  120. package/build/types/src/utils/trade/increase.d.ts +3 -0
  121. package/build/types/src/utils/trade/increaseMarginCheck.d.ts +61 -0
  122. package/build/types/src/utils/trade/index.d.ts +1 -0
  123. package/build/types/src/utils/trade/trade.d.ts +2 -0
  124. package/build/types/src/utils/tradeHistory/types.d.ts +2 -1
  125. package/build/types/src/utils/yield/api.d.ts +4 -1
  126. package/build/types/src/utils/yield/types.d.ts +18 -0
  127. package/package.json +3 -3
@@ -0,0 +1,154 @@
1
+ "use strict";
2
+ /**
3
+ * Exact bigint port of the fixed-point math the GMX contracts use for exponentiation:
4
+ * `prb-math@2.4.3` (`PRBMathUD60x18.pow` = `exp2(mulDivFixedPoint(log2(x), y))`) plus the
5
+ * `Precision.applyExponentFactor` wrapper from gmx-synthetics (release-v2.2c).
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.applyExponentFactor = exports.prbPow = void 0;
9
+ const SCALE = 10n ** 18n;
10
+ const HALF_SCALE = 5n * 10n ** 17n;
11
+ const FLOAT_PRECISION = 10n ** 30n;
12
+ const FLOAT_TO_WEI_DIVISOR = 10n ** 12n;
13
+ const EXP2_MAX_INPUT = 192n * SCALE;
14
+ const EXP2_MAGIC = [
15
+ [0x8000000000000000n, 0x16a09e667f3bcc909n],
16
+ [0x4000000000000000n, 0x1306fe0a31b7152dfn],
17
+ [0x2000000000000000n, 0x1172b83c7d517adcen],
18
+ [0x1000000000000000n, 0x10b5586cf9890f62an],
19
+ [0x800000000000000n, 0x1059b0d31585743aen],
20
+ [0x400000000000000n, 0x102c9a3e778060ee7n],
21
+ [0x200000000000000n, 0x10163da9fb33356d8n],
22
+ [0x100000000000000n, 0x100b1afa5abcbed61n],
23
+ [0x80000000000000n, 0x10058c86da1c09ea2n],
24
+ [0x40000000000000n, 0x1002c605e2e8cec50n],
25
+ [0x20000000000000n, 0x100162f3904051fa1n],
26
+ [0x10000000000000n, 0x1000b175effdc76ban],
27
+ [0x8000000000000n, 0x100058ba01fb9f96dn],
28
+ [0x4000000000000n, 0x10002c5cc37da9492n],
29
+ [0x2000000000000n, 0x1000162e525ee0547n],
30
+ [0x1000000000000n, 0x10000b17255775c04n],
31
+ [0x800000000000n, 0x1000058b91b5bc9aen],
32
+ [0x400000000000n, 0x100002c5c89d5ec6dn],
33
+ [0x200000000000n, 0x10000162e43f4f831n],
34
+ [0x100000000000n, 0x100000b1721bcfc9an],
35
+ [0x80000000000n, 0x10000058b90cf1e6en],
36
+ [0x40000000000n, 0x1000002c5c863b73fn],
37
+ [0x20000000000n, 0x100000162e430e5a2n],
38
+ [0x10000000000n, 0x1000000b172183551n],
39
+ [0x8000000000n, 0x100000058b90c0b49n],
40
+ [0x4000000000n, 0x10000002c5c8601ccn],
41
+ [0x2000000000n, 0x1000000162e42fff0n],
42
+ [0x1000000000n, 0x10000000b17217fbbn],
43
+ [0x800000000n, 0x1000000058b90bfcen],
44
+ [0x400000000n, 0x100000002c5c85fe3n],
45
+ [0x200000000n, 0x10000000162e42ff1n],
46
+ [0x100000000n, 0x100000000b17217f8n],
47
+ [0x80000000n, 0x10000000058b90bfcn],
48
+ [0x40000000n, 0x1000000002c5c85fen],
49
+ [0x20000000n, 0x100000000162e42ffn],
50
+ [0x10000000n, 0x1000000000b17217fn],
51
+ [0x8000000n, 0x100000000058b90c0n],
52
+ [0x4000000n, 0x10000000002c5c860n],
53
+ [0x2000000n, 0x1000000000162e430n],
54
+ [0x1000000n, 0x10000000000b17218n],
55
+ [0x800000n, 0x1000000000058b90cn],
56
+ [0x400000n, 0x100000000002c5c86n],
57
+ [0x200000n, 0x10000000000162e43n],
58
+ [0x100000n, 0x100000000000b1721n],
59
+ [0x80000n, 0x10000000000058b91n],
60
+ [0x40000n, 0x1000000000002c5c8n],
61
+ [0x20000n, 0x100000000000162e4n],
62
+ [0x10000n, 0x1000000000000b172n],
63
+ [0x8000n, 0x100000000000058b9n],
64
+ [0x4000n, 0x10000000000002c5dn],
65
+ [0x2000n, 0x1000000000000162en],
66
+ [0x1000n, 0x10000000000000b17n],
67
+ [0x800n, 0x1000000000000058cn],
68
+ [0x400n, 0x100000000000002c6n],
69
+ [0x200n, 0x10000000000000163n],
70
+ [0x100n, 0x100000000000000b1n],
71
+ [0x80n, 0x10000000000000059n],
72
+ [0x40n, 0x1000000000000002cn],
73
+ [0x20n, 0x10000000000000016n],
74
+ [0x10n, 0x1000000000000000bn],
75
+ [0x8n, 0x10000000000000006n],
76
+ [0x4n, 0x10000000000000003n],
77
+ [0x2n, 0x10000000000000001n],
78
+ [0x1n, 0x10000000000000001n],
79
+ ];
80
+ function mulDivFixedPoint(x, y) {
81
+ const prod = x * y;
82
+ return prod / SCALE + (prod % SCALE > 499999999999999999n ? 1n : 0n);
83
+ }
84
+ function mostSignificantBit(x) {
85
+ let n = 0n;
86
+ while (x > 1n) {
87
+ x >>= 1n;
88
+ n += 1n;
89
+ }
90
+ return n;
91
+ }
92
+ function log2(x) {
93
+ if (x < SCALE) {
94
+ throw new Error("prbMath log2: input too small");
95
+ }
96
+ const n = mostSignificantBit(x / SCALE);
97
+ let result = n * SCALE;
98
+ let y = x >> n;
99
+ if (y === SCALE) {
100
+ return result;
101
+ }
102
+ for (let delta = HALF_SCALE; delta > 0n; delta >>= 1n) {
103
+ y = (y * y) / SCALE;
104
+ if (y >= 2n * SCALE) {
105
+ result += delta;
106
+ y >>= 1n;
107
+ }
108
+ }
109
+ return result;
110
+ }
111
+ function exp2(x) {
112
+ if (x >= EXP2_MAX_INPUT) {
113
+ throw new Error("prbMath exp2: input too big");
114
+ }
115
+ const x192x64 = (x << 64n) / SCALE;
116
+ let result = 0x800000000000000000000000000000000000000000000000n;
117
+ for (const [mask, factor] of EXP2_MAGIC) {
118
+ if (x192x64 & mask) {
119
+ result = (result * factor) >> 64n;
120
+ }
121
+ }
122
+ result *= SCALE;
123
+ result >>= 191n - (x192x64 >> 64n);
124
+ return result;
125
+ }
126
+ function prbPow(x, y) {
127
+ if (x === 0n) {
128
+ return y === 0n ? SCALE : 0n;
129
+ }
130
+ return exp2(mulDivFixedPoint(log2(x), y));
131
+ }
132
+ exports.prbPow = prbPow;
133
+ const APPLY_EXPONENT_CACHE_LIMIT = 1024;
134
+ const applyExponentCache = new Map();
135
+ function applyExponentFactor(floatValue, exponentFactor) {
136
+ if (floatValue < FLOAT_PRECISION) {
137
+ return 0n;
138
+ }
139
+ if (exponentFactor === FLOAT_PRECISION) {
140
+ return floatValue;
141
+ }
142
+ const cacheKey = `${floatValue}:${exponentFactor}`;
143
+ const cached = applyExponentCache.get(cacheKey);
144
+ if (cached !== undefined) {
145
+ return cached;
146
+ }
147
+ const result = prbPow(floatValue / FLOAT_TO_WEI_DIVISOR, exponentFactor / FLOAT_TO_WEI_DIVISOR) * FLOAT_TO_WEI_DIVISOR;
148
+ if (applyExponentCache.size >= APPLY_EXPONENT_CACHE_LIMIT) {
149
+ applyExponentCache.delete(applyExponentCache.keys().next().value);
150
+ }
151
+ applyExponentCache.set(cacheKey, result);
152
+ return result;
153
+ }
154
+ exports.applyExponentFactor = applyExponentFactor;
@@ -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.getMinCollateralUsdForLiquidationPrice = 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;
3
+ exports.getPositionInfo = exports.getContractPositionDynamicFees = exports.getMinCollateralFactorForPosition = exports.getPriceImpactDiffUsd = exports.getNetPriceImpactDeltaUsdForDecrease = exports.getIsPositionBelowMinCollateralForLeverage = exports.getMinCollateralUsdForLiquidationPrice = exports.getLiquidationPrice = exports.getLiquidationPriceImpactDeltaUsd = 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");
@@ -32,7 +32,7 @@ function getPositionPnlUsd(p) {
32
32
  if (totalPnl <= 0) {
33
33
  return totalPnl;
34
34
  }
35
- const poolPnl = (0, markets_1.getPositiveMarketPnl)(marketInfo, isLong, true);
35
+ const poolPnl = (0, markets_1.getPositiveMarketPnl)(marketInfo, isLong, false);
36
36
  const poolUsd = (0, markets_1.getPoolUsdWithoutPnl)(marketInfo, isLong, "minPrice");
37
37
  const cappedPnl = (0, markets_1.getCappedPoolPnl)({
38
38
  marketInfo,
@@ -40,9 +40,8 @@ function getPositionPnlUsd(p) {
40
40
  poolPnl,
41
41
  isLong,
42
42
  });
43
- const WEI_PRECISION = (0, numbers_1.expandDecimals)(1, 18);
44
43
  if (cappedPnl !== poolPnl && cappedPnl > 0 && poolPnl > 0) {
45
- totalPnl = bigmath_1.bigMath.mulDiv(totalPnl, cappedPnl / WEI_PRECISION, poolPnl / WEI_PRECISION);
44
+ totalPnl = bigmath_1.bigMath.mulDiv(totalPnl, cappedPnl, poolPnl);
46
45
  }
47
46
  return totalPnl;
48
47
  }
@@ -87,6 +86,30 @@ function getLeverage(p) {
87
86
  return bigmath_1.bigMath.mulDiv(sizeInUsd, factors_1.BASIS_POINTS_DIVISOR_BIGINT, remainingCollateralUsd);
88
87
  }
89
88
  exports.getLeverage = getLeverage;
89
+ function getLiquidationPriceImpactDeltaUsd(p) {
90
+ const { marketInfo, sizeInUsd, sizeInTokens, pendingImpactAmount, isLong, useMaxPriceImpact } = p;
91
+ const maxNegativePriceImpactUsd = -1n * (0, numbers_1.applyFactor)(sizeInUsd, marketInfo.maxPositionImpactFactorForLiquidations);
92
+ if (useMaxPriceImpact) {
93
+ return maxNegativePriceImpactUsd;
94
+ }
95
+ let priceImpactDeltaUsd = (0, fees_1.getPriceImpactForPosition)(marketInfo, -sizeInUsd, isLong, {
96
+ fallbackToZero: true,
97
+ sizeDeltaInTokens: sizeInTokens,
98
+ }).priceImpactDeltaUsd;
99
+ if (priceImpactDeltaUsd > 0) {
100
+ priceImpactDeltaUsd = (0, fees_1.capPositionImpactUsdByMaxPriceImpactFactor)(marketInfo, sizeInUsd, priceImpactDeltaUsd);
101
+ }
102
+ const pendingImpactUsd = (0, tokens_1.convertToUsd)(pendingImpactAmount, marketInfo.indexToken.decimals, pendingImpactAmount > 0 ? marketInfo.indexToken.prices.minPrice : marketInfo.indexToken.prices.maxPrice);
103
+ priceImpactDeltaUsd = priceImpactDeltaUsd + pendingImpactUsd;
104
+ if (priceImpactDeltaUsd > 0) {
105
+ return 0n;
106
+ }
107
+ if (priceImpactDeltaUsd < maxNegativePriceImpactUsd) {
108
+ return maxNegativePriceImpactUsd;
109
+ }
110
+ return priceImpactDeltaUsd;
111
+ }
112
+ exports.getLiquidationPriceImpactDeltaUsd = getLiquidationPriceImpactDeltaUsd;
90
113
  function getLiquidationPrice(p) {
91
114
  const { sizeInUsd, sizeInTokens, collateralUsd, collateralAmount, marketInfo, collateralToken, pendingFundingFeesUsd, pendingBorrowingFeesUsd, pendingImpactAmount, minCollateralUsd, isLong, userReferralInfo, useMaxPriceImpact, } = p;
92
115
  if (sizeInUsd <= 0 || sizeInTokens <= 0) {
@@ -96,29 +119,14 @@ function getLiquidationPrice(p) {
96
119
  const closingFeeUsd = (0, fees_1.getPositionFee)(marketInfo, sizeInUsd, false, userReferralInfo).positionFeeUsd;
97
120
  const totalPendingFeesUsd = getPositionPendingFeesUsd({ pendingFundingFeesUsd, pendingBorrowingFeesUsd });
98
121
  const totalFeesUsd = totalPendingFeesUsd + closingFeeUsd;
99
- const maxNegativePriceImpactUsd = -1n * (0, numbers_1.applyFactor)(sizeInUsd, marketInfo.maxPositionImpactFactorForLiquidations);
100
- let priceImpactDeltaUsd = 0n;
101
- if (useMaxPriceImpact) {
102
- priceImpactDeltaUsd = maxNegativePriceImpactUsd;
103
- }
104
- else {
105
- const priceImpactForPosition = (0, fees_1.getPriceImpactForPosition)(marketInfo, -sizeInUsd, isLong, {
106
- fallbackToZero: true,
107
- sizeDeltaInTokens: sizeInTokens,
108
- });
109
- priceImpactDeltaUsd = priceImpactForPosition.priceImpactDeltaUsd;
110
- if (priceImpactDeltaUsd > 0) {
111
- priceImpactDeltaUsd = (0, fees_1.capPositionImpactUsdByMaxPriceImpactFactor)(marketInfo, sizeInUsd, priceImpactDeltaUsd);
112
- }
113
- const pendingImpactUsd = (0, tokens_1.convertToUsd)(pendingImpactAmount, marketInfo.indexToken.decimals, pendingImpactAmount > 0 ? marketInfo.indexToken.prices.minPrice : marketInfo.indexToken.prices.maxPrice);
114
- priceImpactDeltaUsd = priceImpactDeltaUsd + pendingImpactUsd;
115
- if (priceImpactDeltaUsd > 0) {
116
- priceImpactDeltaUsd = 0n;
117
- }
118
- else if (priceImpactDeltaUsd < maxNegativePriceImpactUsd) {
119
- priceImpactDeltaUsd = maxNegativePriceImpactUsd;
120
- }
121
- }
122
+ const priceImpactDeltaUsd = getLiquidationPriceImpactDeltaUsd({
123
+ marketInfo,
124
+ sizeInUsd,
125
+ sizeInTokens,
126
+ pendingImpactAmount,
127
+ isLong,
128
+ useMaxPriceImpact,
129
+ });
122
130
  let liquidationCollateralUsd = (0, numbers_1.applyFactor)(sizeInUsd, marketInfo.minCollateralFactorForLiquidation);
123
131
  if (liquidationCollateralUsd < minCollateralUsd) {
124
132
  liquidationCollateralUsd = minCollateralUsd;
@@ -172,22 +180,13 @@ function getMinCollateralUsdForLiquidationPrice(p) {
172
180
  return 0n;
173
181
  }
174
182
  const closingFeeUsd = (0, fees_1.getPositionFee)(marketInfo, sizeInUsd, false, userReferralInfo).positionFeeUsd;
175
- const maxNegativePriceImpactUsd = -1n * (0, numbers_1.applyFactor)(sizeInUsd, marketInfo.maxPositionImpactFactorForLiquidations);
176
- let priceImpactDeltaUsd = (0, fees_1.getPriceImpactForPosition)(marketInfo, -sizeInUsd, isLong, {
177
- fallbackToZero: true,
178
- sizeDeltaInTokens: sizeInTokens,
179
- }).priceImpactDeltaUsd;
180
- if (priceImpactDeltaUsd > 0) {
181
- priceImpactDeltaUsd = (0, fees_1.capPositionImpactUsdByMaxPriceImpactFactor)(marketInfo, sizeInUsd, priceImpactDeltaUsd);
182
- }
183
- const pendingImpactUsd = (0, tokens_1.convertToUsd)(pendingImpactAmount, marketInfo.indexToken.decimals, pendingImpactAmount > 0 ? marketInfo.indexToken.prices.minPrice : marketInfo.indexToken.prices.maxPrice);
184
- priceImpactDeltaUsd = priceImpactDeltaUsd + pendingImpactUsd;
185
- if (priceImpactDeltaUsd > 0) {
186
- priceImpactDeltaUsd = 0n;
187
- }
188
- else if (priceImpactDeltaUsd < maxNegativePriceImpactUsd) {
189
- priceImpactDeltaUsd = maxNegativePriceImpactUsd;
190
- }
183
+ const priceImpactDeltaUsd = getLiquidationPriceImpactDeltaUsd({
184
+ marketInfo,
185
+ sizeInUsd,
186
+ sizeInTokens,
187
+ pendingImpactAmount,
188
+ isLong,
189
+ });
191
190
  let liquidationCollateralUsd = (0, numbers_1.applyFactor)(sizeInUsd, marketInfo.minCollateralFactorForLiquidation);
192
191
  if (liquidationCollateralUsd < minCollateralUsd) {
193
192
  liquidationCollateralUsd = minCollateralUsd;
@@ -195,6 +194,30 @@ function getMinCollateralUsdForLiquidationPrice(p) {
195
194
  return liquidationCollateralUsd - pnl - priceImpactDeltaUsd + closingFeeUsd;
196
195
  }
197
196
  exports.getMinCollateralUsdForLiquidationPrice = getMinCollateralUsdForLiquidationPrice;
197
+ function getIsPositionBelowMinCollateralForLeverage(position, collateralDeltaAmount = 0n) {
198
+ const { marketInfo, sizeInUsd, sizeInTokens, isLong, pendingImpactAmount, pnl, closingFeeUsd, remainingCollateralUsd, collateralAmount, collateralToken, } = position;
199
+ if (sizeInUsd <= 0 || sizeInTokens <= 0) {
200
+ return false;
201
+ }
202
+ if (collateralAmount < collateralDeltaAmount) {
203
+ return true;
204
+ }
205
+ const collateralUsdAfterDelta = (0, tokens_1.convertToUsd)(collateralAmount - collateralDeltaAmount, collateralToken.decimals, collateralToken.prices.minPrice);
206
+ if (collateralUsdAfterDelta < (0, numbers_1.applyFactor)(sizeInUsd, getMinCollateralFactorForPosition(position, 0n))) {
207
+ return true;
208
+ }
209
+ const collateralDeltaUsd = (0, tokens_1.convertToUsd)(collateralDeltaAmount, collateralToken.decimals, collateralToken.prices.minPrice);
210
+ const priceImpactDeltaUsd = getLiquidationPriceImpactDeltaUsd({
211
+ marketInfo,
212
+ sizeInUsd,
213
+ sizeInTokens,
214
+ pendingImpactAmount,
215
+ isLong,
216
+ });
217
+ const marginUsd = remainingCollateralUsd - collateralDeltaUsd + pnl + priceImpactDeltaUsd - closingFeeUsd;
218
+ return marginUsd <= 0n || marginUsd < (0, numbers_1.applyFactor)(sizeInUsd, marketInfo.minCollateralFactor);
219
+ }
220
+ exports.getIsPositionBelowMinCollateralForLeverage = getIsPositionBelowMinCollateralForLeverage;
198
221
  function getNetPriceImpactDeltaUsdForDecrease({ marketInfo, sizeInUsd, pendingImpactAmount, priceImpactDeltaUsd, sizeDeltaUsd, }) {
199
222
  const { proportionalPendingImpactDeltaUsd } = (0, fees_1.getProportionalPendingImpactValues)({
200
223
  sizeInUsd,
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getDefaultAcceptablePriceImpactBps = exports.getAcceptablePriceByPriceImpact = exports.getAcceptablePriceInfo = exports.getOrderThresholdType = exports.getShouldUseMaxPrice = exports.getMarkPrice = void 0;
3
+ exports.getDefaultAcceptablePriceImpactBps = exports.getAcceptablePriceByPriceImpact = exports.getAcceptablePriceInfo = exports.getIncreaseEvaluationIndexPrice = exports.getIsIncreaseOrderExecutableNow = exports.getOrderThresholdType = exports.getShouldUseMaxPrice = exports.getMarkPrice = void 0;
4
4
  const factors_1 = require("../../configs/factors");
5
5
  const bigmath_1 = require("../bigmath");
6
6
  const fees_1 = require("../fees");
@@ -38,6 +38,33 @@ function getOrderThresholdType(orderType, isLong) {
38
38
  return undefined;
39
39
  }
40
40
  exports.getOrderThresholdType = getOrderThresholdType;
41
+ function getIsIncreaseOrderExecutableNow(p) {
42
+ const { orderType, isLong, triggerPrice, indexTokenPrices } = p;
43
+ if (orderType === types_1.OrderType.MarketIncrease) {
44
+ return true;
45
+ }
46
+ if (triggerPrice === undefined || triggerPrice <= 0n) {
47
+ return false;
48
+ }
49
+ if (orderType === types_1.OrderType.LimitIncrease) {
50
+ return isLong ? indexTokenPrices.maxPrice <= triggerPrice : indexTokenPrices.minPrice >= triggerPrice;
51
+ }
52
+ if (orderType === types_1.OrderType.StopIncrease) {
53
+ return isLong ? indexTokenPrices.maxPrice >= triggerPrice : indexTokenPrices.minPrice <= triggerPrice;
54
+ }
55
+ return false;
56
+ }
57
+ exports.getIsIncreaseOrderExecutableNow = getIsIncreaseOrderExecutableNow;
58
+ function getIncreaseEvaluationIndexPrice(p) {
59
+ if (p.triggerPrice === undefined ||
60
+ p.triggerPrice <= 0n ||
61
+ p.orderType === undefined ||
62
+ p.orderType === types_1.OrderType.MarketIncrease) {
63
+ return undefined;
64
+ }
65
+ return p.triggerPrice;
66
+ }
67
+ exports.getIncreaseEvaluationIndexPrice = getIncreaseEvaluationIndexPrice;
41
68
  function getAcceptablePriceInfo(p) {
42
69
  const { marketInfo, isIncrease, isLong, indexPrice, sizeDeltaUsd, maxNegativePriceImpactBps } = p;
43
70
  const { indexToken } = marketInfo;
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const vitest_1 = require("vitest");
4
+ const http_1 = require("../../http/http");
5
+ const api_1 = require("../api");
6
+ const { fetchMock } = vitest_1.vi.hoisted(() => ({ fetchMock: vitest_1.vi.fn() }));
7
+ vitest_1.vi.mock("cross-fetch", () => ({ default: fetchMock }));
8
+ const API_URL = "https://example.test";
9
+ const FROM = 1756857600;
10
+ const TO = 1759363200;
11
+ function createApi(calls, response = {}) {
12
+ return {
13
+ url: API_URL,
14
+ fetchJson: async (path, opts) => {
15
+ calls.push({ path, query: opts?.query });
16
+ return response;
17
+ },
18
+ postJson: async () => {
19
+ throw new Error("Unexpected POST request");
20
+ },
21
+ };
22
+ }
23
+ function jsonResponse(body) {
24
+ return new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } });
25
+ }
26
+ function getRequestedUrl() {
27
+ const [url] = fetchMock.mock.calls[0];
28
+ return new URL(url);
29
+ }
30
+ (0, vitest_1.describe)("protocol stats API params", () => {
31
+ (0, vitest_1.it)("passes list filters through as arrays", async () => {
32
+ const calls = [];
33
+ await (0, api_1.fetchApiProtocolStatsSummary)({ api: createApi(calls) }, { networks: ["arbitrum", "solana"], versions: ["v2"] });
34
+ (0, vitest_1.expect)(calls).toEqual([
35
+ { path: "/v1/stats/summary", query: { networks: ["arbitrum", "solana"], versions: ["v2"] } },
36
+ ]);
37
+ });
38
+ (0, vitest_1.it)("drops empty and missing list filters", async () => {
39
+ const calls = [];
40
+ await (0, api_1.fetchApiProtocolStatsSummary)({ api: createApi(calls) }, { networks: [] });
41
+ await (0, api_1.fetchApiProtocolStatsSummary)({ api: createApi(calls) });
42
+ (0, vitest_1.expect)(calls.map((call) => call.query)).toEqual([
43
+ { networks: undefined, versions: undefined },
44
+ { networks: undefined, versions: undefined },
45
+ ]);
46
+ });
47
+ (0, vitest_1.it)("sends the metric, grouping and unix-second bounds of a timeseries", async () => {
48
+ const calls = [];
49
+ await (0, api_1.fetchApiProtocolStatsTimeseries)({ api: createApi(calls) }, { metric: "volume.total", groupBy: "network", from: FROM, to: TO, networks: ["arbitrum"] });
50
+ (0, vitest_1.expect)(calls).toEqual([
51
+ {
52
+ path: "/v1/stats/timeseries",
53
+ query: {
54
+ metric: "volume.total",
55
+ groupBy: "network",
56
+ networks: ["arbitrum"],
57
+ versions: undefined,
58
+ from: FROM,
59
+ to: TO,
60
+ },
61
+ },
62
+ ]);
63
+ });
64
+ (0, vitest_1.it)("requests the sources without params", async () => {
65
+ const calls = [];
66
+ await (0, api_1.fetchApiProtocolStatsSources)({ api: createApi(calls, []) });
67
+ (0, vitest_1.expect)(calls).toEqual([{ path: "/v1/stats/sources", query: undefined }]);
68
+ });
69
+ });
70
+ (0, vitest_1.describe)("protocol stats API query serialization", () => {
71
+ (0, vitest_1.beforeEach)(() => {
72
+ fetchMock.mockReset();
73
+ fetchMock.mockImplementation(async () => jsonResponse({}));
74
+ });
75
+ (0, vitest_1.it)("repeats list filters as separate query params", async () => {
76
+ await (0, api_1.fetchApiProtocolStatsSummary)({ api: new http_1.HttpClient(API_URL) }, { networks: ["arbitrum", "solana"], versions: ["v2"] });
77
+ const url = getRequestedUrl();
78
+ (0, vitest_1.expect)(url.origin + url.pathname).toBe(`${API_URL}/v1/stats/summary`);
79
+ (0, vitest_1.expect)(url.searchParams.getAll("networks")).toEqual(["arbitrum", "solana"]);
80
+ (0, vitest_1.expect)(url.searchParams.getAll("versions")).toEqual(["v2"]);
81
+ (0, vitest_1.expect)(url.search).not.toContain(",");
82
+ });
83
+ (0, vitest_1.it)("omits empty list filters from the query", async () => {
84
+ await (0, api_1.fetchApiProtocolStatsSummary)({ api: new http_1.HttpClient(API_URL) }, { networks: [] });
85
+ const url = getRequestedUrl();
86
+ (0, vitest_1.expect)(url.pathname).toBe("/v1/stats/summary");
87
+ (0, vitest_1.expect)(url.searchParams.has("networks")).toBe(false);
88
+ (0, vitest_1.expect)(url.searchParams.has("versions")).toBe(false);
89
+ });
90
+ (0, vitest_1.it)("serializes timeseries bounds as unix seconds", async () => {
91
+ await (0, api_1.fetchApiProtocolStatsTimeseries)({ api: new http_1.HttpClient(API_URL) }, { metric: "volume.total", groupBy: "network", from: FROM });
92
+ const url = getRequestedUrl();
93
+ (0, vitest_1.expect)(url.pathname).toBe("/v1/stats/timeseries");
94
+ (0, vitest_1.expect)(url.searchParams.get("metric")).toBe("volume.total");
95
+ (0, vitest_1.expect)(url.searchParams.get("groupBy")).toBe("network");
96
+ (0, vitest_1.expect)(url.searchParams.get("from")).toBe(String(FROM));
97
+ (0, vitest_1.expect)(url.searchParams.has("to")).toBe(false);
98
+ (0, vitest_1.expect)(url.searchParams.has("networks")).toBe(false);
99
+ });
100
+ });
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fetchApiProtocolStatsSources = exports.fetchApiProtocolStatsTimeseries = exports.fetchApiProtocolStatsSummary = void 0;
4
+ function toListParam(values) {
5
+ return values && values.length > 0 ? values : undefined;
6
+ }
7
+ async function fetchApiProtocolStatsSummary(ctx, params) {
8
+ return ctx.api.fetchJson("/v1/stats/summary", {
9
+ query: {
10
+ networks: toListParam(params?.networks),
11
+ versions: toListParam(params?.versions),
12
+ },
13
+ });
14
+ }
15
+ exports.fetchApiProtocolStatsSummary = fetchApiProtocolStatsSummary;
16
+ async function fetchApiProtocolStatsTimeseries(ctx, params) {
17
+ return ctx.api.fetchJson("/v1/stats/timeseries", {
18
+ query: {
19
+ metric: params.metric,
20
+ groupBy: params.groupBy,
21
+ networks: toListParam(params.networks),
22
+ versions: toListParam(params.versions),
23
+ from: params.from,
24
+ to: params.to,
25
+ },
26
+ });
27
+ }
28
+ exports.fetchApiProtocolStatsTimeseries = fetchApiProtocolStatsTimeseries;
29
+ async function fetchApiProtocolStatsSources(ctx) {
30
+ return ctx.api.fetchJson("/v1/stats/sources");
31
+ }
32
+ exports.fetchApiProtocolStatsSources = fetchApiProtocolStatsSources;
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PROTOCOL_STATS_NETWORKS = void 0;
4
+ exports.PROTOCOL_STATS_NETWORKS = ["arbitrum", "avalanche", "megaeth", "solana"];