@gmx-io/sdk 2.9.1 → 2.9.2

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 (98) hide show
  1. package/build/cjs/src/clients/v2/index.js +61 -41
  2. package/build/cjs/src/clients/v2/solana.spec.js +188 -0
  3. package/build/cjs/src/configs/api.js +4 -0
  4. package/build/cjs/src/utils/fees/index.js +7 -1
  5. package/build/cjs/src/utils/fees/priceImpact.js +118 -18
  6. package/build/cjs/src/utils/gmsol/constants.js +9 -0
  7. package/build/cjs/src/utils/gmsol/index.js +53 -0
  8. package/build/cjs/src/utils/gmsol/numbers.js +176 -0
  9. package/build/cjs/src/utils/gmsol/types.js +2 -0
  10. package/build/cjs/src/utils/http/http.js +3 -4
  11. package/build/cjs/src/utils/http/httpFallback.js +11 -1
  12. package/build/cjs/src/utils/http/solana.js +17 -0
  13. package/build/cjs/src/utils/http/validation.js +21 -1
  14. package/build/cjs/src/utils/http/validation.spec.js +45 -0
  15. package/build/cjs/src/utils/markets/__tests__/api.spec.js +53 -0
  16. package/build/cjs/src/utils/markets/api.js +5 -0
  17. package/build/cjs/src/utils/markets/utils.js +25 -9
  18. package/build/cjs/src/utils/orders/api.js +3 -0
  19. package/build/cjs/src/utils/positions/__tests__/liquidationPrice.spec.js +64 -0
  20. package/build/cjs/src/utils/positions/api.js +3 -0
  21. package/build/cjs/src/utils/positions/utils.js +88 -19
  22. package/build/cjs/src/utils/prices/utils.js +69 -14
  23. package/build/cjs/src/utils/referrals/api.js +41 -0
  24. package/build/cjs/src/utils/swap/swapRouting.js +4 -0
  25. package/build/cjs/src/utils/swap/swapStats.js +6 -1
  26. package/build/cjs/src/utils/trade/__tests__/gmsolTradeMath.spec.js +1012 -0
  27. package/build/cjs/src/utils/trade/decrease.js +266 -56
  28. package/build/cjs/src/utils/trade/decreaseMarginCheck.js +23 -4
  29. package/build/cjs/src/utils/trade/increase.js +86 -28
  30. package/build/cjs/src/utils/trade/increaseMarginCheck.js +51 -9
  31. package/build/cjs/src/utils/trade/twapIncreaseMarginCheck.js +8 -3
  32. package/build/esm/src/clients/v2/index.js +39 -19
  33. package/build/esm/src/clients/v2/solana.spec.js +160 -0
  34. package/build/esm/src/configs/api.js +5 -1
  35. package/build/esm/src/utils/fees/index.js +7 -1
  36. package/build/esm/src/utils/fees/priceImpact.js +111 -12
  37. package/build/esm/src/utils/gmsol/constants.js +6 -0
  38. package/build/esm/src/utils/gmsol/index.js +43 -0
  39. package/build/esm/src/utils/gmsol/numbers.js +172 -0
  40. package/build/esm/src/utils/gmsol/types.js +1 -0
  41. package/build/esm/src/utils/http/http.js +3 -4
  42. package/build/esm/src/utils/http/httpFallback.js +11 -1
  43. package/build/esm/src/utils/http/solana.js +12 -0
  44. package/build/esm/src/utils/http/validation.js +18 -0
  45. package/build/esm/src/utils/http/validation.spec.js +43 -0
  46. package/build/esm/src/utils/markets/__tests__/api.spec.js +53 -0
  47. package/build/esm/src/utils/markets/api.js +6 -1
  48. package/build/esm/src/utils/markets/utils.js +23 -8
  49. package/build/esm/src/utils/orders/api.js +3 -0
  50. package/build/esm/src/utils/positions/__tests__/liquidationPrice.spec.js +62 -0
  51. package/build/esm/src/utils/positions/api.js +3 -0
  52. package/build/esm/src/utils/positions/utils.js +89 -20
  53. package/build/esm/src/utils/prices/utils.js +70 -15
  54. package/build/esm/src/utils/referrals/api.js +36 -0
  55. package/build/esm/src/utils/swap/swapRouting.js +4 -0
  56. package/build/esm/src/utils/swap/swapStats.js +7 -2
  57. package/build/esm/src/utils/trade/__tests__/gmsolTradeMath.spec.js +1010 -0
  58. package/build/esm/src/utils/trade/decrease.js +266 -56
  59. package/build/esm/src/utils/trade/decreaseMarginCheck.js +23 -4
  60. package/build/esm/src/utils/trade/increase.js +86 -28
  61. package/build/esm/src/utils/trade/increaseMarginCheck.js +53 -11
  62. package/build/esm/src/utils/trade/twapIncreaseMarginCheck.js +8 -3
  63. package/build/tsconfig.tsbuildinfo +1 -1
  64. package/build/types/src/clients/v2/index.d.ts +21 -12
  65. package/build/types/src/clients/v2/solana.spec.d.ts +1 -0
  66. package/build/types/src/utils/fees/index.d.ts +1 -1
  67. package/build/types/src/utils/fees/priceImpact.d.ts +7 -0
  68. package/build/types/src/utils/gmsol/constants.d.ts +5 -0
  69. package/build/types/src/utils/gmsol/index.d.ts +35 -0
  70. package/build/types/src/utils/gmsol/numbers.d.ts +1 -0
  71. package/build/types/src/utils/gmsol/types.d.ts +9 -0
  72. package/build/types/src/utils/http/http.d.ts +2 -5
  73. package/build/types/src/utils/http/httpFallback.d.ts +2 -5
  74. package/build/types/src/utils/http/solana.d.ts +4 -0
  75. package/build/types/src/utils/http/types.d.ts +17 -4
  76. package/build/types/src/utils/http/validation.d.ts +8 -0
  77. package/build/types/src/utils/http/validation.spec.d.ts +1 -0
  78. package/build/types/src/utils/markets/hashKeys.d.ts +1 -1
  79. package/build/types/src/utils/markets/types.d.ts +3 -2
  80. package/build/types/src/utils/markets/utils.d.ts +6 -2
  81. package/build/types/src/utils/orders/api.d.ts +2 -2
  82. package/build/types/src/utils/positions/__tests__/liquidationPrice.spec.d.ts +1 -0
  83. package/build/types/src/utils/positions/api.d.ts +2 -2
  84. package/build/types/src/utils/positions/types.d.ts +1 -0
  85. package/build/types/src/utils/positions/utils.d.ts +6 -1
  86. package/build/types/src/utils/prices/types.d.ts +16 -0
  87. package/build/types/src/utils/prices/utils.d.ts +3 -11
  88. package/build/types/src/utils/referrals/api.d.ts +8 -0
  89. package/build/types/src/utils/referrals/types.d.ts +5 -0
  90. package/build/types/src/utils/rpc/createViemRpc.d.ts +25 -3
  91. package/build/types/src/utils/trade/__tests__/gmsolTradeMath.spec.d.ts +1 -0
  92. package/build/types/src/utils/trade/decrease.d.ts +5 -0
  93. package/build/types/src/utils/trade/decreaseMarginCheck.d.ts +2 -0
  94. package/build/types/src/utils/trade/increase.d.ts +2 -0
  95. package/build/types/src/utils/trade/increaseMarginCheck.d.ts +2 -0
  96. package/build/types/src/utils/trade/twapIncreaseMarginCheck.d.ts +1 -0
  97. package/build/types/src/utils/trade/types.d.ts +6 -0
  98. package/package.json +10 -1
@@ -1,16 +1,26 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getMaxNegativeImpactBps = exports.getCappedPriceImpactPercentageFromFees = exports.applyImpactFactor = exports.calculateImpactForCrossoverRebalance = exports.calculateImpactForSameSideRebalance = exports.getPriceImpactUsd = exports.getNextPoolAmountsParams = exports.getPriceImpactForSwap = exports.getProportionalPendingImpactValues = exports.getPriceImpactForPosition = exports.getMaxPositionImpactFactors = exports.capPositionImpactUsdByMaxPriceImpactFactor = exports.capPositionImpactUsdByMaxImpactPool = exports.getCappedPositionImpactUsd = exports.applySwapImpactWithCap = exports.getPriceImpactByAcceptablePrice = void 0;
3
+ exports.getMaxNegativeImpactBps = exports.getCappedPriceImpactPercentageFromFees = exports.applyImpactFactor = exports.calculateImpactForCrossoverRebalance = exports.calculateImpactForSameSideRebalance = exports.getPriceImpactUsd = exports.getNextPoolAmountsParams = exports.getPriceImpactForSwap = exports.getProportionalPendingImpactValues = exports.getPriceImpactForPosition = exports.getMaxPositionImpactFactors = exports.capPositionImpactUsdByMaxPriceImpactFactor = exports.capPositionImpactUsdByMaxImpactPool = exports.getCappedPositionImpactUsd = exports.applySwapImpactWithCap = exports.getPriceImpactByAcceptablePrice = exports.GmsolPriceImpactError = void 0;
4
4
  const viem_1 = require("viem");
5
5
  const bigmath_1 = require("../bigmath");
6
+ const gmsol_1 = require("../gmsol");
7
+ const constants_1 = require("../gmsol/constants");
8
+ const numbers_1 = require("../gmsol/numbers");
6
9
  const markets_1 = require("../markets");
7
- const numbers_1 = require("../numbers");
10
+ const numbers_2 = require("../numbers");
8
11
  const utils_1 = require("../tokens/utils");
12
+ class GmsolPriceImpactError extends Error {
13
+ constructor() {
14
+ super(...arguments);
15
+ this.name = "GmsolPriceImpactError";
16
+ }
17
+ }
18
+ exports.GmsolPriceImpactError = GmsolPriceImpactError;
9
19
  function getPriceImpactByAcceptablePrice(p) {
10
20
  const { sizeDeltaUsd, acceptablePrice, indexPrice: markPrice, isLong, isIncrease } = p;
11
21
  const shouldFlipPriceDiff = isIncrease ? !isLong : isLong;
12
22
  const priceDelta = (markPrice - acceptablePrice) * (shouldFlipPriceDiff ? -1n : 1n);
13
- const acceptablePriceDeltaBps = markPrice === 0n ? 0n : (0, numbers_1.getBasisPoints)(priceDelta, markPrice);
23
+ const acceptablePriceDeltaBps = markPrice === 0n ? 0n : (0, numbers_2.getBasisPoints)(priceDelta, markPrice);
14
24
  const priceImpactDeltaUsd = acceptablePrice === 0n ? 0n : (sizeDeltaUsd * priceDelta) / acceptablePrice;
15
25
  const priceImpactDeltaAmount = markPrice === 0n ? 0n : priceImpactDeltaUsd / markPrice;
16
26
  return {
@@ -37,24 +47,30 @@ function applySwapImpactWithCap(marketInfo, token, priceImpactDeltaUsd) {
37
47
  ? marketInfo.swapImpactPoolAmountLong
38
48
  : marketInfo.swapImpactPoolAmountShort;
39
49
  if (impactDeltaAmount > maxImpactAmount) {
40
- cappedDiffUsd = bigmath_1.bigMath.mulDiv(impactDeltaAmount - maxImpactAmount, price, (0, numbers_1.expandDecimals)(1, token.decimals));
50
+ cappedDiffUsd = bigmath_1.bigMath.mulDiv(impactDeltaAmount - maxImpactAmount, price, (0, numbers_2.expandDecimals)(1, token.decimals));
41
51
  impactDeltaAmount = maxImpactAmount;
42
52
  }
43
53
  }
44
54
  else {
45
55
  // round negative impactAmount up, this will be deducted from the user
46
- impactDeltaAmount = (0, numbers_1.roundUpMagnitudeDivision)(priceImpactDeltaUsd * (0, numbers_1.expandDecimals)(1, token.decimals), price);
56
+ impactDeltaAmount = (0, numbers_2.roundUpMagnitudeDivision)(priceImpactDeltaUsd * (0, numbers_2.expandDecimals)(1, token.decimals), price);
47
57
  }
48
58
  return { impactDeltaAmount, cappedDiffUsd };
49
59
  }
50
60
  exports.applySwapImpactWithCap = applySwapImpactWithCap;
51
61
  function getCappedPositionImpactUsd(marketInfo, sizeDeltaUsd, isLong, isIncrease, opts = {}) {
62
+ if (marketInfo.tradeMath === "gmsol") {
63
+ sizeDeltaUsd = (0, gmsol_1.getGmsolUsdAmount)(sizeDeltaUsd);
64
+ }
52
65
  sizeDeltaUsd = isIncrease ? sizeDeltaUsd : sizeDeltaUsd * -1n;
53
66
  const { priceImpactDeltaUsd, balanceWasImproved } = getPriceImpactForPosition(marketInfo, sizeDeltaUsd, isLong, opts);
54
67
  if (priceImpactDeltaUsd < 0 && !opts.shouldCapNegativeImpact) {
55
68
  return { priceImpactDeltaUsd, balanceWasImproved };
56
69
  }
57
- const cappedImpactUsd = capPositionImpactUsdByMaxPriceImpactFactor(marketInfo, sizeDeltaUsd, priceImpactDeltaUsd);
70
+ let cappedImpactUsd = capPositionImpactUsdByMaxPriceImpactFactor(marketInfo, sizeDeltaUsd, priceImpactDeltaUsd);
71
+ if (marketInfo.tradeMath === "gmsol") {
72
+ cappedImpactUsd = capPositionImpactUsdByMaxImpactPool(marketInfo, cappedImpactUsd);
73
+ }
58
74
  return {
59
75
  priceImpactDeltaUsd: cappedImpactUsd,
60
76
  balanceWasImproved,
@@ -77,7 +93,8 @@ exports.capPositionImpactUsdByMaxImpactPool = capPositionImpactUsdByMaxImpactPoo
77
93
  function capPositionImpactUsdByMaxPriceImpactFactor(marketInfo, sizeDeltaUsd, positionImpactDeltaUsd) {
78
94
  const { maxPositiveImpactFactor, maxNegativeImpactFactor } = getMaxPositionImpactFactors(marketInfo);
79
95
  const maxPriceImapctFactor = positionImpactDeltaUsd > 0 ? maxPositiveImpactFactor : maxNegativeImpactFactor;
80
- const maxPriceImpactUsdBasedOnMaxPriceImpactFactor = (0, numbers_1.applyFactor)(bigmath_1.bigMath.abs(sizeDeltaUsd), maxPriceImapctFactor);
96
+ const maxImpactUsd = (0, numbers_2.applyFactor)(bigmath_1.bigMath.abs(sizeDeltaUsd), maxPriceImapctFactor);
97
+ const maxPriceImpactUsdBasedOnMaxPriceImpactFactor = marketInfo.tradeMath === "gmsol" ? (0, gmsol_1.getGmsolUsdAmount)(maxImpactUsd) : maxImpactUsd;
81
98
  if (bigmath_1.bigMath.abs(positionImpactDeltaUsd) > maxPriceImpactUsdBasedOnMaxPriceImpactFactor) {
82
99
  positionImpactDeltaUsd = maxPriceImpactUsdBasedOnMaxPriceImpactFactor * (positionImpactDeltaUsd > 0 ? 1n : -1n);
83
100
  }
@@ -87,17 +104,20 @@ exports.capPositionImpactUsdByMaxPriceImpactFactor = capPositionImpactUsdByMaxPr
87
104
  function getMaxPositionImpactFactors(marketInfo) {
88
105
  let maxPositiveImpactFactor = marketInfo.maxPositionImpactFactorPositive;
89
106
  const maxNegativeImpactFactor = marketInfo.maxPositionImpactFactorNegative;
90
- if (maxPositiveImpactFactor > maxNegativeImpactFactor) {
107
+ if (marketInfo.tradeMath !== "gmsol" && maxPositiveImpactFactor > maxNegativeImpactFactor) {
91
108
  maxPositiveImpactFactor = maxNegativeImpactFactor;
92
109
  }
93
110
  return { maxPositiveImpactFactor, maxNegativeImpactFactor };
94
111
  }
95
112
  exports.getMaxPositionImpactFactors = getMaxPositionImpactFactors;
96
113
  function getPriceImpactForPosition(marketInfo, sizeDeltaUsd, isLong, opts = {}) {
114
+ if (marketInfo.tradeMath === "gmsol") {
115
+ sizeDeltaUsd = (0, gmsol_1.getGmsolUsdAmount)(sizeDeltaUsd);
116
+ }
97
117
  const longInterestUsd = (0, markets_1.getOpenInterestForBalance)(marketInfo, true);
98
118
  const shortInterestUsd = (0, markets_1.getOpenInterestForBalance)(marketInfo, false);
99
119
  let effectiveUsdDelta = sizeDeltaUsd;
100
- if (marketInfo.useOpenInterestInTokensForBalance) {
120
+ if (marketInfo.tradeMath !== "gmsol" && marketInfo.useOpenInterestInTokensForBalance) {
101
121
  if (sizeDeltaUsd < 0n && opts.sizeDeltaInTokens === undefined) {
102
122
  throw new Error(`Missing sizeDeltaInTokens for token-OI decrease market ${marketInfo.marketTokenAddress}`);
103
123
  }
@@ -130,6 +150,7 @@ function getPriceImpactForPosition(marketInfo, sizeDeltaUsd, isLong, opts = {})
130
150
  exponentFactorPositive: marketInfo.positionImpactExponentFactorPositive,
131
151
  exponentFactorNegative: marketInfo.positionImpactExponentFactorNegative,
132
152
  fallbackToZero: opts.fallbackToZero,
153
+ tradeMath: marketInfo.tradeMath,
133
154
  });
134
155
  if (priceImpactDeltaUsd >= 0n) {
135
156
  return {
@@ -159,6 +180,7 @@ function getPriceImpactForPosition(marketInfo, sizeDeltaUsd, isLong, opts = {})
159
180
  exponentFactorPositive: marketInfo.positionImpactExponentFactorPositive,
160
181
  exponentFactorNegative: marketInfo.positionImpactExponentFactorNegative,
161
182
  fallbackToZero: opts.fallbackToZero,
183
+ tradeMath: marketInfo.tradeMath,
162
184
  });
163
185
  if (priceImpactUsdForVirtualInventory < priceImpactDeltaUsd) {
164
186
  return {
@@ -178,7 +200,7 @@ function getVirtualInventoryForPositionImpact(marketInfo) {
178
200
  return { hasVirtualInventory: false, virtualInventory: 0n };
179
201
  }
180
202
  let virtualInventory = marketInfo.virtualInventoryForPositions;
181
- if (marketInfo.useOpenInterestInTokensForBalance) {
203
+ if (marketInfo.tradeMath !== "gmsol" && marketInfo.useOpenInterestInTokensForBalance) {
182
204
  if (typeof marketInfo.virtualInventoryForPositionsInTokens !== "bigint") {
183
205
  throw new Error(`Missing virtualInventoryForPositionsInTokens for token-OI market ${marketInfo.marketTokenAddress}`);
184
206
  }
@@ -214,6 +236,7 @@ function getPriceImpactForSwap(marketInfo, tokenA, tokenB, usdDeltaTokenA, usdDe
214
236
  shortPoolAmount: marketInfo.shortPoolAmount,
215
237
  longDeltaUsd,
216
238
  shortDeltaUsd,
239
+ tradeMath: marketInfo.tradeMath,
217
240
  });
218
241
  const { priceImpactDeltaUsd, balanceWasImproved } = getPriceImpactUsd({
219
242
  currentLongUsd: longPoolUsd,
@@ -225,6 +248,7 @@ function getPriceImpactForSwap(marketInfo, tokenA, tokenB, usdDeltaTokenA, usdDe
225
248
  exponentFactorPositive: marketInfo.swapImpactExponentFactor,
226
249
  exponentFactorNegative: marketInfo.swapImpactExponentFactor,
227
250
  fallbackToZero: opts.fallbackToZero,
251
+ tradeMath: marketInfo.tradeMath,
228
252
  });
229
253
  if (priceImpactDeltaUsd > 0) {
230
254
  return {
@@ -247,6 +271,7 @@ function getPriceImpactForSwap(marketInfo, tokenA, tokenB, usdDeltaTokenA, usdDe
247
271
  shortPoolAmount: virtualInventoryShort,
248
272
  longDeltaUsd,
249
273
  shortDeltaUsd,
274
+ tradeMath: marketInfo.tradeMath,
250
275
  });
251
276
  const { priceImpactDeltaUsd: priceImpactUsdForVirtualInventory } = getPriceImpactUsd({
252
277
  currentLongUsd: virtualInventoryParams.longPoolUsd,
@@ -258,6 +283,7 @@ function getPriceImpactForSwap(marketInfo, tokenA, tokenB, usdDeltaTokenA, usdDe
258
283
  exponentFactorPositive: marketInfo.swapImpactExponentFactor,
259
284
  exponentFactorNegative: marketInfo.swapImpactExponentFactor,
260
285
  fallbackToZero: opts.fallbackToZero,
286
+ tradeMath: marketInfo.tradeMath,
261
287
  });
262
288
  return {
263
289
  priceImpactDeltaUsd: priceImpactUsdForVirtualInventory < priceImpactDeltaUsd
@@ -308,8 +334,8 @@ function getNextOpenInterestParams(p) {
308
334
  }
309
335
  function getNextPoolAmountsParams(p) {
310
336
  const { longToken, shortToken, longPoolAmount, shortPoolAmount, longDeltaUsd, shortDeltaUsd } = p;
311
- const longPrice = (0, utils_1.getMidPrice)(longToken.prices);
312
- const shortPrice = (0, utils_1.getMidPrice)(shortToken.prices);
337
+ const longPrice = p.tradeMath === "gmsol" ? (0, gmsol_1.getGmsolMidPrice)(longToken) : (0, utils_1.getMidPrice)(longToken.prices);
338
+ const shortPrice = p.tradeMath === "gmsol" ? (0, gmsol_1.getGmsolMidPrice)(shortToken) : (0, utils_1.getMidPrice)(shortToken.prices);
313
339
  const longPoolUsd = (0, utils_1.convertToUsd)(longPoolAmount, longToken.decimals, longPrice);
314
340
  const shortPoolUsd = (0, utils_1.convertToUsd)(shortPoolAmount, shortToken.decimals, shortPrice);
315
341
  const nextLongPoolUsd = longPoolUsd + longDeltaUsd;
@@ -353,6 +379,7 @@ function getPriceImpactUsd(p) {
353
379
  hasPositiveImpact,
354
380
  factor,
355
381
  exponentFactor,
382
+ tradeMath: p.tradeMath,
356
383
  });
357
384
  }
358
385
  else {
@@ -363,6 +390,7 @@ function getPriceImpactUsd(p) {
363
390
  factorNegative: p.factorNegative,
364
391
  exponentFactorPositive: p.exponentFactorPositive,
365
392
  exponentFactorNegative: p.exponentFactorNegative,
393
+ tradeMath: p.tradeMath,
366
394
  });
367
395
  }
368
396
  return {
@@ -376,9 +404,22 @@ exports.getPriceImpactUsd = getPriceImpactUsd;
376
404
  */
377
405
  function calculateImpactForSameSideRebalance(p) {
378
406
  const { currentDiff, nextDiff, hasPositiveImpact, factor, exponentFactor } = p;
379
- const currentImpact = applyImpactFactor(currentDiff, factor, exponentFactor);
380
- const nextImpact = applyImpactFactor(nextDiff, factor, exponentFactor);
407
+ const currentImpact = applyMarketImpactFactor({
408
+ diff: currentDiff,
409
+ factor,
410
+ exponent: exponentFactor,
411
+ tradeMath: p.tradeMath,
412
+ });
413
+ const nextImpact = applyMarketImpactFactor({
414
+ diff: nextDiff,
415
+ factor,
416
+ exponent: exponentFactor,
417
+ tradeMath: p.tradeMath,
418
+ });
381
419
  const deltaDiff = bigmath_1.bigMath.abs(currentImpact - nextImpact);
420
+ if (p.tradeMath === "gmsol" && deltaDiff > constants_1.GMSOL_MAX_SIGNED * constants_1.GMSOL_PRECISION_SCALE) {
421
+ throw new GmsolPriceImpactError("Solana price impact exceeds native signed range");
422
+ }
382
423
  return hasPositiveImpact ? deltaDiff : -deltaDiff;
383
424
  }
384
425
  exports.calculateImpactForSameSideRebalance = calculateImpactForSameSideRebalance;
@@ -387,15 +428,74 @@ exports.calculateImpactForSameSideRebalance = calculateImpactForSameSideRebalanc
387
428
  */
388
429
  function calculateImpactForCrossoverRebalance(p) {
389
430
  const { currentDiff, nextDiff, factorNegative, factorPositive, exponentFactorPositive, exponentFactorNegative } = p;
390
- const positiveImpact = applyImpactFactor(currentDiff, factorPositive, exponentFactorPositive);
391
- const negativeImpactUsd = applyImpactFactor(nextDiff, factorNegative, exponentFactorNegative);
431
+ const positiveImpact = applyMarketImpactFactor({
432
+ diff: currentDiff,
433
+ factor: factorPositive,
434
+ exponent: exponentFactorPositive,
435
+ tradeMath: p.tradeMath,
436
+ });
437
+ const negativeImpactUsd = applyMarketImpactFactor({
438
+ diff: nextDiff,
439
+ factor: factorNegative,
440
+ exponent: exponentFactorNegative,
441
+ tradeMath: p.tradeMath,
442
+ });
392
443
  const deltaDiffUsd = bigmath_1.bigMath.abs(positiveImpact - negativeImpactUsd);
444
+ if (p.tradeMath === "gmsol" && deltaDiffUsd > constants_1.GMSOL_MAX_SIGNED * constants_1.GMSOL_PRECISION_SCALE) {
445
+ throw new GmsolPriceImpactError("Solana price impact exceeds native signed range");
446
+ }
393
447
  return positiveImpact > negativeImpactUsd ? deltaDiffUsd : -deltaDiffUsd;
394
448
  }
395
449
  exports.calculateImpactForCrossoverRebalance = calculateImpactForCrossoverRebalance;
450
+ function applyMarketImpactFactor(p) {
451
+ if (p.tradeMath !== "gmsol") {
452
+ return applyImpactFactor(p.diff, p.factor, p.exponent);
453
+ }
454
+ for (const value of [p.diff, p.factor, p.exponent]) {
455
+ if (value < 0n || value % constants_1.GMSOL_PRECISION_SCALE !== 0n || value > constants_1.GMSOL_MAX_UNSIGNED * constants_1.GMSOL_PRECISION_SCALE) {
456
+ throw new GmsolPriceImpactError("Solana impact input is outside native precision or range");
457
+ }
458
+ }
459
+ const base = bigmath_1.bigMath.mulDiv(p.diff, 1n, constants_1.GMSOL_PRECISION_SCALE);
460
+ const factor = bigmath_1.bigMath.mulDiv(p.factor, 1n, constants_1.GMSOL_PRECISION_SCALE);
461
+ const power = getGmsolImpactPower(base, p.exponent);
462
+ const impact = bigmath_1.bigMath.mulDiv(power, factor, constants_1.GMSOL_PRECISION);
463
+ if (impact > constants_1.GMSOL_MAX_UNSIGNED) {
464
+ throw new GmsolPriceImpactError("Solana impact factor exceeds native range");
465
+ }
466
+ return impact * constants_1.GMSOL_PRECISION_SCALE;
467
+ }
468
+ function getGmsolImpactPower(base, exponent) {
469
+ if (base < constants_1.GMSOL_PRECISION) {
470
+ return 0n;
471
+ }
472
+ if (base === constants_1.GMSOL_PRECISION || exponent === 0n) {
473
+ return constants_1.GMSOL_PRECISION;
474
+ }
475
+ const hasFractionalExponent = exponent % numbers_2.PRECISION !== 0n;
476
+ if (hasFractionalExponent) {
477
+ try {
478
+ return (0, numbers_1.getGmsolFractionalPower)(base, exponent / constants_1.GMSOL_PRECISION_SCALE);
479
+ }
480
+ catch (error) {
481
+ throw new GmsolPriceImpactError(error instanceof Error ? error.message : "Solana fractional power failed");
482
+ }
483
+ }
484
+ if (exponent > constants_1.GMSOL_MAX_IMPACT_EXPONENT) {
485
+ throw new GmsolPriceImpactError("Solana impact exponent is unsupported for exact calculation");
486
+ }
487
+ let power = constants_1.GMSOL_PRECISION;
488
+ for (let remaining = exponent; remaining > 0n; remaining -= numbers_2.PRECISION) {
489
+ power = bigmath_1.bigMath.mulDiv(power, base, constants_1.GMSOL_PRECISION);
490
+ if (power > constants_1.GMSOL_MAX_UNSIGNED) {
491
+ throw new GmsolPriceImpactError("Solana impact power exceeds native range");
492
+ }
493
+ }
494
+ return power;
495
+ }
396
496
  function applyImpactFactor(diff, factor, exponent) {
397
497
  try {
398
- return (0, numbers_1.applyFactor)((0, numbers_1.applyExponentFactor)(diff, exponent), factor);
498
+ return (0, numbers_2.applyFactor)((0, numbers_2.applyExponentFactor)(diff, exponent), factor);
399
499
  }
400
500
  catch {
401
501
  return 0n;
@@ -411,6 +511,6 @@ function getCappedPriceImpactPercentageFromFees({ fees, isSwap, }) {
411
511
  exports.getCappedPriceImpactPercentageFromFees = getCappedPriceImpactPercentageFromFees;
412
512
  function getMaxNegativeImpactBps(marketInfo) {
413
513
  const factor = marketInfo.maxPositionImpactFactorNegative;
414
- return factor / (0, numbers_1.expandDecimals)(1, numbers_1.PRECISION_DECIMALS - numbers_1.BASIS_POINTS_DECIMALS);
514
+ return factor / (0, numbers_2.expandDecimals)(1, numbers_2.PRECISION_DECIMALS - numbers_2.BASIS_POINTS_DECIMALS);
415
515
  }
416
516
  exports.getMaxNegativeImpactBps = getMaxNegativeImpactBps;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GMSOL_MAX_IMPACT_EXPONENT = exports.GMSOL_MAX_SIGNED = exports.GMSOL_MAX_UNSIGNED = exports.GMSOL_PRECISION_SCALE = exports.GMSOL_PRECISION = void 0;
4
+ const numbers_1 = require("../numbers");
5
+ exports.GMSOL_PRECISION = 10n ** 20n;
6
+ exports.GMSOL_PRECISION_SCALE = numbers_1.PRECISION / exports.GMSOL_PRECISION;
7
+ exports.GMSOL_MAX_UNSIGNED = (1n << 128n) - 1n;
8
+ exports.GMSOL_MAX_SIGNED = (1n << 127n) - 1n;
9
+ exports.GMSOL_MAX_IMPACT_EXPONENT = 128n * numbers_1.PRECISION;
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getGmsolExecutionFeeRefund = exports.getGmsolExecutionFee = exports.getGmsolIncreaseSizeDeltaInTokens = exports.getGmsolMidPrice = exports.getGmsolUsdAmount = exports.getGmsolFractionalPower = exports.GMSOL_PRECISION_SCALE = void 0;
4
+ const bigmath_1 = require("../bigmath");
5
+ const numbers_1 = require("../numbers");
6
+ const constants_1 = require("./constants");
7
+ var constants_2 = require("./constants");
8
+ Object.defineProperty(exports, "GMSOL_PRECISION_SCALE", { enumerable: true, get: function () { return constants_2.GMSOL_PRECISION_SCALE; } });
9
+ var numbers_2 = require("./numbers");
10
+ Object.defineProperty(exports, "getGmsolFractionalPower", { enumerable: true, get: function () { return numbers_2.getGmsolFractionalPower; } });
11
+ function getGmsolUsdAmount(value) {
12
+ return bigmath_1.bigMath.mulDiv(value, 1n, constants_1.GMSOL_PRECISION_SCALE) * constants_1.GMSOL_PRECISION_SCALE;
13
+ }
14
+ exports.getGmsolUsdAmount = getGmsolUsdAmount;
15
+ function getGmsolMidPrice(token) {
16
+ const scale = (0, numbers_1.expandDecimals)(1, token.decimals) * constants_1.GMSOL_PRECISION_SCALE;
17
+ return bigmath_1.bigMath.mulDiv(token.prices.minPrice + token.prices.maxPrice, 1n, 2n * scale) * scale;
18
+ }
19
+ exports.getGmsolMidPrice = getGmsolMidPrice;
20
+ /** The impact is settled in the entry size; it never becomes pending collateral. 0 means the order fills no tokens. */
21
+ function getGmsolIncreaseSizeDeltaInTokens(p) {
22
+ const { baseSizeDeltaInTokens, priceImpactDeltaUsd, indexToken, isLong } = p;
23
+ const unit = (0, numbers_1.expandDecimals)(1, indexToken.decimals);
24
+ const impactAmount = priceImpactDeltaUsd > 0n
25
+ ? bigmath_1.bigMath.mulDiv(priceImpactDeltaUsd, unit, indexToken.prices.maxPrice)
26
+ : (0, numbers_1.roundUpMagnitudeDivision)(priceImpactDeltaUsd * unit, indexToken.prices.minPrice);
27
+ return bigmath_1.bigMath.max(baseSizeDeltaInTokens + (isLong ? impactAmount : -impactAmount), 0n);
28
+ }
29
+ exports.getGmsolIncreaseSizeDeltaInTokens = getGmsolIncreaseSizeDeltaInTokens;
30
+ /** Rent is a refundable deposit. The maximum keeper fee can be spent even on a cancelled execution. */
31
+ function getGmsolExecutionFee(p) {
32
+ const { maxExecutionLamports, orderRentLamports, escrowRentLamports, solPrice } = p;
33
+ if ([maxExecutionLamports, orderRentLamports, escrowRentLamports, solPrice].some((value) => value < 0n)) {
34
+ throw new Error("Execution fee inputs must be nonnegative");
35
+ }
36
+ const keeperFeeLamports = bigmath_1.bigMath.max(300000n, maxExecutionLamports);
37
+ const refundableRentLamports = orderRentLamports + escrowRentLamports;
38
+ return {
39
+ keeperFeeLamports,
40
+ keeperFeeUsd: bigmath_1.bigMath.mulDiv(keeperFeeLamports, solPrice, 1000000000n),
41
+ refundableRentLamports,
42
+ refundableRentUsd: bigmath_1.bigMath.mulDiv(refundableRentLamports, solPrice, 1000000000n),
43
+ requiredLamports: keeperFeeLamports + refundableRentLamports,
44
+ };
45
+ }
46
+ exports.getGmsolExecutionFee = getGmsolExecutionFee;
47
+ function getGmsolExecutionFeeRefund(p) {
48
+ const spent = p.ownerCancelledBeforeExecution
49
+ ? 0n
50
+ : bigmath_1.bigMath.min(p.keeperFeeLamports, bigmath_1.bigMath.max(0n, p.executionLamportsSpent));
51
+ return { keeperCostLamports: spent, refundLamports: p.refundableRentLamports + p.keeperFeeLamports - spent };
52
+ }
53
+ exports.getGmsolExecutionFeeRefund = getGmsolExecutionFeeRefund;
@@ -0,0 +1,176 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getGmsolFractionalPower = void 0;
4
+ const constants_1 = require("./constants");
5
+ const MAX_COEFFICIENT = (1n << 96n) - 1n;
6
+ const MAX_U64 = (1n << 64n) - 1n;
7
+ const MAX_I64 = (1n << 63n) - 1n;
8
+ const UNIT = 1000000000n;
9
+ const INPUT_SCALE = constants_1.GMSOL_PRECISION / UNIT;
10
+ const ONE = { coefficient: 1n, scale: 0 };
11
+ const E = { coefficient: 27182818284590452353602874714n, scale: 28 };
12
+ const INVERSE_E = { coefficient: 3678794411714423215955237702n, scale: 28 };
13
+ function roundEven(numerator, denominator) {
14
+ const quotient = numerator / denominator;
15
+ const twiceRemainder = (numerator % denominator) * 2n;
16
+ return (quotient + (twiceRemainder > denominator || (twiceRemainder === denominator && quotient % 2n !== 0n) ? 1n : 0n));
17
+ }
18
+ function fit(coefficient, scale) {
19
+ const sign = coefficient < 0n ? -1n : 1n;
20
+ let magnitude = coefficient * sign;
21
+ let removed = Math.max(0, scale - 28);
22
+ while (magnitude / 10n ** BigInt(removed) > MAX_COEFFICIENT) {
23
+ removed++;
24
+ }
25
+ if (removed > scale) {
26
+ throw new Error("Solana decimal overflow");
27
+ }
28
+ magnitude = roundEven(magnitude, 10n ** BigInt(removed));
29
+ scale -= removed;
30
+ if (magnitude > MAX_COEFFICIENT) {
31
+ if (scale === 0)
32
+ throw new Error("Solana decimal overflow");
33
+ magnitude = roundEven(magnitude, 10n);
34
+ scale--;
35
+ }
36
+ return { coefficient: magnitude * sign, scale };
37
+ }
38
+ function add(left, right) {
39
+ if (left.coefficient === 0n)
40
+ return right;
41
+ if (right.coefficient === 0n)
42
+ return left;
43
+ const scale = Math.max(left.scale, right.scale);
44
+ return fit(left.coefficient * 10n ** BigInt(scale - left.scale) + right.coefficient * 10n ** BigInt(scale - right.scale), scale);
45
+ }
46
+ function subtract(left, right) {
47
+ return add(left, { coefficient: -right.coefficient, scale: right.scale });
48
+ }
49
+ function multiply(left, right) {
50
+ return fit(left.coefficient * right.coefficient, left.scale + right.scale);
51
+ }
52
+ function compare(left, right) {
53
+ const scale = Math.max(left.scale, right.scale);
54
+ const difference = left.coefficient * 10n ** BigInt(scale - left.scale) - right.coefficient * 10n ** BigInt(scale - right.scale);
55
+ return difference < 0n ? -1 : difference > 0n ? 1 : 0;
56
+ }
57
+ function divideByInteger(value, divisor) {
58
+ let scale = value.scale;
59
+ let coefficient = value.coefficient / divisor;
60
+ let remainder = value.coefficient % divisor;
61
+ const fractional = remainder !== 0n;
62
+ while (remainder !== 0n && scale < 28 && coefficient * 10n <= MAX_COEFFICIENT) {
63
+ let digits = Math.min(9, 28 - scale);
64
+ while (coefficient * 10n ** BigInt(digits) > MAX_COEFFICIENT)
65
+ digits--;
66
+ const multiplier = 10n ** BigInt(digits);
67
+ coefficient = coefficient * multiplier + (remainder * multiplier) / divisor;
68
+ remainder = (remainder * multiplier) % divisor;
69
+ scale += digits;
70
+ if (coefficient > MAX_COEFFICIENT) {
71
+ const lastDigit = coefficient % 10n;
72
+ coefficient /= 10n;
73
+ if (lastDigit > 5n || (lastDigit === 5n && (remainder !== 0n || coefficient % 2n !== 0n)))
74
+ coefficient++;
75
+ scale--;
76
+ remainder = 0n;
77
+ }
78
+ }
79
+ if (remainder !== 0n) {
80
+ coefficient = roundEven(coefficient * divisor + remainder, divisor);
81
+ }
82
+ const result = fit(coefficient, scale);
83
+ if (fractional) {
84
+ while (result.scale >= 8 && (result.coefficient & 0xffffffffn) === 0n && result.coefficient % 100000000n === 0n) {
85
+ result.coefficient /= 100000000n;
86
+ result.scale -= 8;
87
+ }
88
+ for (const digits of [4, 2, 1]) {
89
+ const divisor = 10n ** BigInt(digits);
90
+ if (result.scale >= digits && result.coefficient % divisor === 0n) {
91
+ result.coefficient /= divisor;
92
+ result.scale -= digits;
93
+ }
94
+ }
95
+ }
96
+ return result;
97
+ }
98
+ function logarithm(value) {
99
+ let x = value;
100
+ let count = 0n;
101
+ while (compare(x, ONE) >= 0) {
102
+ x = multiply(x, INVERSE_E);
103
+ count++;
104
+ }
105
+ while (compare(x, INVERSE_E) <= 0) {
106
+ x = multiply(x, E);
107
+ count--;
108
+ }
109
+ x = subtract(ONE, x);
110
+ let result = { coefficient: 0n, scale: 0 };
111
+ let term = ONE;
112
+ for (let iteration = 1n; iteration <= 100n; iteration++) {
113
+ term = multiply(term, x);
114
+ const next = add(result, divideByInteger(term, iteration));
115
+ if (compare(next, result) === 0)
116
+ break;
117
+ result = next;
118
+ }
119
+ return subtract({ coefficient: count, scale: 0 }, result);
120
+ }
121
+ function exponential(value) {
122
+ let term = value;
123
+ let result = add(value, ONE);
124
+ let factorial = 1n;
125
+ for (let iteration = 2n; iteration <= 27n; iteration++) {
126
+ factorial *= iteration;
127
+ term = multiply(value, term);
128
+ const next = add(result, divideByInteger(term, factorial));
129
+ const difference = subtract(next, result);
130
+ result = next;
131
+ if (compare(difference, { coefficient: 2n, scale: 7 }) <= 0)
132
+ break;
133
+ }
134
+ return result;
135
+ }
136
+ function getGmsolFractionalPower(base20, exponent20) {
137
+ const base = base20 / INPUT_SCALE;
138
+ const exponent = exponent20 / INPUT_SCALE;
139
+ if (base < UNIT || base > MAX_U64 || exponent < 0n || exponent > MAX_U64) {
140
+ throw new Error("Solana fractional power input exceeds native range");
141
+ }
142
+ let result;
143
+ if (exponent % UNIT === 0n) {
144
+ result = UNIT;
145
+ if (base !== UNIT) {
146
+ if (exponent > 128n * UNIT)
147
+ throw new Error("Solana impact exponent exceeds calculation limit");
148
+ for (let remaining = exponent; remaining > 0n; remaining -= UNIT) {
149
+ result = (result * base) / UNIT;
150
+ if (result > MAX_U64)
151
+ throw new Error("Solana fractional power exceeds native range");
152
+ }
153
+ }
154
+ }
155
+ else {
156
+ if (base > MAX_I64 || exponent > MAX_I64) {
157
+ throw new Error("Solana decimal input exceeds native range");
158
+ }
159
+ const power = base === UNIT
160
+ ? ONE
161
+ : exponential(multiply(logarithm({ coefficient: base, scale: 9 }), { coefficient: exponent, scale: 9 }));
162
+ if (power.scale > 9) {
163
+ const divisor = 10n ** BigInt(power.scale - 9);
164
+ result = power.coefficient / divisor + ((power.coefficient % divisor) * 2n >= divisor ? 1n : 0n);
165
+ }
166
+ else {
167
+ result = power.coefficient;
168
+ for (let scale = power.scale; scale < 9 && result * 10n <= MAX_COEFFICIENT; scale++)
169
+ result *= 10n;
170
+ }
171
+ if (result < 0n || result > MAX_U64)
172
+ throw new Error("Solana fractional power exceeds native range");
173
+ }
174
+ return result * INPUT_SCALE;
175
+ }
176
+ exports.getGmsolFractionalPower = getGmsolFractionalPower;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -59,10 +59,9 @@ class HttpClient {
59
59
  throwHttpError(response.status, response.statusText, errorBody);
60
60
  }
61
61
  const json = await response.json();
62
- if (opts?.transform) {
63
- return opts.transform(json);
64
- }
65
- return json;
62
+ const result = opts?.transform ? opts.transform(json) : json;
63
+ opts?.onResponse?.({ headers: response.headers });
64
+ return result;
66
65
  }
67
66
  finally {
68
67
  clearTimeout(timeoutId);
@@ -23,7 +23,17 @@ class HttpClientWithFallback {
23
23
  return this.clients[this.primaryIndex].url;
24
24
  }
25
25
  async fetchJson(path, opts) {
26
- return this.withFallback((client) => client.fetchJson(path, opts));
26
+ let metadata;
27
+ const result = await this.withFallback((client) => client.fetchJson(path, {
28
+ ...opts,
29
+ onResponse: (response) => {
30
+ metadata = response;
31
+ },
32
+ }));
33
+ if (metadata) {
34
+ opts?.onResponse?.(metadata);
35
+ }
36
+ return result;
27
37
  }
28
38
  async postJson(path, body, opts) {
29
39
  return (await this.postJsonWith(path, body, opts)).result;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getSolanaResponseHandler = exports.parseSolanaSlotHeader = void 0;
4
+ function parseSolanaSlotHeader(value) {
5
+ if (value === null || value.trim() === "") {
6
+ return undefined;
7
+ }
8
+ const slot = Number(value);
9
+ return Number.isSafeInteger(slot) && slot >= 0 ? slot : undefined;
10
+ }
11
+ exports.parseSolanaSlotHeader = parseSolanaSlotHeader;
12
+ function getSolanaResponseHandler(onResponse) {
13
+ return onResponse
14
+ ? ({ headers }) => onResponse({ slot: parseSolanaSlotHeader(headers.get("x-solana-slot")) })
15
+ : undefined;
16
+ }
17
+ exports.getSolanaResponseHandler = getSolanaResponseHandler;
@@ -1,6 +1,26 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.assertApiFields = exports.assertApiRecords = void 0;
3
+ exports.assertApiFields = exports.assertApiRecords = exports.readApiUnsignedBigInt = exports.readApiString = void 0;
4
+ const objects_1 = require("../objects");
5
+ function readApiString({ record, name, endpoint }) {
6
+ const value = (0, objects_1.getString)(record[name]);
7
+ if (value === undefined) {
8
+ throw new Error(`${endpoint}: expected string field "${name}"`);
9
+ }
10
+ return value;
11
+ }
12
+ exports.readApiString = readApiString;
13
+ function readApiUnsignedBigInt({ record, name, endpoint }) {
14
+ const value = record[name];
15
+ if (typeof value === "string" && /^\d+$/.test(value)) {
16
+ return BigInt(value);
17
+ }
18
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) {
19
+ return BigInt(value);
20
+ }
21
+ throw new Error(`${endpoint}: expected bigint field "${name}"`);
22
+ }
23
+ exports.readApiUnsignedBigInt = readApiUnsignedBigInt;
4
24
  function assertApiRecords(value, endpoint) {
5
25
  if (!Array.isArray(value)) {
6
26
  throw new Error(`Invalid ${endpoint} response: expected an array`);
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const vitest_1 = require("vitest");
4
+ const validation_1 = require("./validation");
5
+ (0, vitest_1.it)("reads unsigned API amounts without losing precision or accepting coercible values", () => {
6
+ const name = "amount";
7
+ const endpoint = "/v1/example";
8
+ const largeAmount = 1n << 256n;
9
+ const accepted = [
10
+ ["0", 0n],
11
+ ["000123", 123n],
12
+ [largeAmount.toString(), largeAmount],
13
+ [0, 0n],
14
+ [-0, 0n],
15
+ [Number.MAX_SAFE_INTEGER, BigInt(Number.MAX_SAFE_INTEGER)],
16
+ ];
17
+ for (const [value, expected] of accepted) {
18
+ (0, vitest_1.expect)((0, validation_1.readApiUnsignedBigInt)({ record: { amount: value }, name, endpoint })).toBe(expected);
19
+ }
20
+ for (const value of [
21
+ undefined,
22
+ null,
23
+ true,
24
+ false,
25
+ "",
26
+ " ",
27
+ " 1",
28
+ "1 ",
29
+ "+1",
30
+ "-1",
31
+ "1.0",
32
+ "1e3",
33
+ "0x10",
34
+ -1,
35
+ 1.5,
36
+ NaN,
37
+ Infinity,
38
+ Number.MAX_SAFE_INTEGER + 1,
39
+ 0n,
40
+ [],
41
+ {},
42
+ ]) {
43
+ (0, vitest_1.expect)(() => (0, validation_1.readApiUnsignedBigInt)({ record: { amount: value }, name, endpoint })).toThrow('/v1/example: expected bigint field "amount"');
44
+ }
45
+ });