@gmx-io/sdk 2.9.1 → 2.9.3

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 (112) 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/__tests__/fixtures/nativeMath.json +3171 -0
  7. package/build/cjs/src/utils/gmsol/__tests__/nativeMath.spec.js +213 -0
  8. package/build/cjs/src/utils/gmsol/constants.js +12 -0
  9. package/build/cjs/src/utils/gmsol/fees.js +19 -0
  10. package/build/cjs/src/utils/gmsol/index.js +66 -0
  11. package/build/cjs/src/utils/gmsol/markets.js +206 -0
  12. package/build/cjs/src/utils/gmsol/numbers.js +230 -0
  13. package/build/cjs/src/utils/gmsol/positions.js +152 -0
  14. package/build/cjs/src/utils/gmsol/types.js +2 -0
  15. package/build/cjs/src/utils/http/http.js +3 -4
  16. package/build/cjs/src/utils/http/httpFallback.js +11 -1
  17. package/build/cjs/src/utils/http/solana.js +17 -0
  18. package/build/cjs/src/utils/http/validation.js +21 -1
  19. package/build/cjs/src/utils/http/validation.spec.js +45 -0
  20. package/build/cjs/src/utils/markets/__tests__/api.spec.js +53 -0
  21. package/build/cjs/src/utils/markets/api.js +5 -0
  22. package/build/cjs/src/utils/markets/utils.js +25 -9
  23. package/build/cjs/src/utils/orders/api.js +3 -0
  24. package/build/cjs/src/utils/positions/__tests__/liquidationPrice.spec.js +64 -0
  25. package/build/cjs/src/utils/positions/api.js +3 -0
  26. package/build/cjs/src/utils/positions/utils.js +88 -19
  27. package/build/cjs/src/utils/prices/utils.js +69 -14
  28. package/build/cjs/src/utils/referrals/api.js +41 -0
  29. package/build/cjs/src/utils/swap/swapRouting.js +4 -0
  30. package/build/cjs/src/utils/swap/swapStats.js +6 -1
  31. package/build/cjs/src/utils/trade/__tests__/gmsolTradeMath.spec.js +1012 -0
  32. package/build/cjs/src/utils/trade/decrease.js +266 -56
  33. package/build/cjs/src/utils/trade/decreaseMarginCheck.js +23 -4
  34. package/build/cjs/src/utils/trade/increase.js +86 -28
  35. package/build/cjs/src/utils/trade/increaseMarginCheck.js +51 -9
  36. package/build/cjs/src/utils/trade/twapIncreaseMarginCheck.js +8 -3
  37. package/build/esm/src/clients/v2/index.js +39 -19
  38. package/build/esm/src/clients/v2/solana.spec.js +160 -0
  39. package/build/esm/src/configs/api.js +5 -1
  40. package/build/esm/src/utils/fees/index.js +7 -1
  41. package/build/esm/src/utils/fees/priceImpact.js +111 -12
  42. package/build/esm/src/utils/gmsol/__tests__/fixtures/nativeMath.json +3171 -0
  43. package/build/esm/src/utils/gmsol/__tests__/nativeMath.spec.js +208 -0
  44. package/build/esm/src/utils/gmsol/constants.js +9 -0
  45. package/build/esm/src/utils/gmsol/fees.js +15 -0
  46. package/build/esm/src/utils/gmsol/index.js +46 -0
  47. package/build/esm/src/utils/gmsol/markets.js +193 -0
  48. package/build/esm/src/utils/gmsol/numbers.js +226 -0
  49. package/build/esm/src/utils/gmsol/positions.js +148 -0
  50. package/build/esm/src/utils/gmsol/types.js +1 -0
  51. package/build/esm/src/utils/http/http.js +3 -4
  52. package/build/esm/src/utils/http/httpFallback.js +11 -1
  53. package/build/esm/src/utils/http/solana.js +12 -0
  54. package/build/esm/src/utils/http/validation.js +18 -0
  55. package/build/esm/src/utils/http/validation.spec.js +43 -0
  56. package/build/esm/src/utils/markets/__tests__/api.spec.js +53 -0
  57. package/build/esm/src/utils/markets/api.js +6 -1
  58. package/build/esm/src/utils/markets/utils.js +23 -8
  59. package/build/esm/src/utils/orders/api.js +3 -0
  60. package/build/esm/src/utils/positions/__tests__/liquidationPrice.spec.js +62 -0
  61. package/build/esm/src/utils/positions/api.js +3 -0
  62. package/build/esm/src/utils/positions/utils.js +89 -20
  63. package/build/esm/src/utils/prices/utils.js +70 -15
  64. package/build/esm/src/utils/referrals/api.js +36 -0
  65. package/build/esm/src/utils/swap/swapRouting.js +4 -0
  66. package/build/esm/src/utils/swap/swapStats.js +7 -2
  67. package/build/esm/src/utils/trade/__tests__/gmsolTradeMath.spec.js +1010 -0
  68. package/build/esm/src/utils/trade/decrease.js +266 -56
  69. package/build/esm/src/utils/trade/decreaseMarginCheck.js +23 -4
  70. package/build/esm/src/utils/trade/increase.js +86 -28
  71. package/build/esm/src/utils/trade/increaseMarginCheck.js +53 -11
  72. package/build/esm/src/utils/trade/twapIncreaseMarginCheck.js +8 -3
  73. package/build/tsconfig.tsbuildinfo +1 -1
  74. package/build/types/src/clients/v2/index.d.ts +21 -12
  75. package/build/types/src/clients/v2/solana.spec.d.ts +1 -0
  76. package/build/types/src/utils/fees/index.d.ts +1 -1
  77. package/build/types/src/utils/fees/priceImpact.d.ts +7 -0
  78. package/build/types/src/utils/gmsol/__tests__/nativeMath.spec.d.ts +1 -0
  79. package/build/types/src/utils/gmsol/constants.d.ts +9 -0
  80. package/build/types/src/utils/gmsol/fees.d.ts +6 -0
  81. package/build/types/src/utils/gmsol/index.d.ts +38 -0
  82. package/build/types/src/utils/gmsol/markets.d.ts +49 -0
  83. package/build/types/src/utils/gmsol/numbers.d.ts +11 -0
  84. package/build/types/src/utils/gmsol/positions.d.ts +7 -0
  85. package/build/types/src/utils/gmsol/types.d.ts +105 -0
  86. package/build/types/src/utils/http/http.d.ts +2 -5
  87. package/build/types/src/utils/http/httpFallback.d.ts +2 -5
  88. package/build/types/src/utils/http/solana.d.ts +4 -0
  89. package/build/types/src/utils/http/types.d.ts +17 -4
  90. package/build/types/src/utils/http/validation.d.ts +8 -0
  91. package/build/types/src/utils/http/validation.spec.d.ts +1 -0
  92. package/build/types/src/utils/markets/hashKeys.d.ts +1 -1
  93. package/build/types/src/utils/markets/types.d.ts +3 -2
  94. package/build/types/src/utils/markets/utils.d.ts +6 -2
  95. package/build/types/src/utils/orders/api.d.ts +2 -2
  96. package/build/types/src/utils/positions/__tests__/liquidationPrice.spec.d.ts +1 -0
  97. package/build/types/src/utils/positions/api.d.ts +2 -2
  98. package/build/types/src/utils/positions/types.d.ts +1 -0
  99. package/build/types/src/utils/positions/utils.d.ts +6 -1
  100. package/build/types/src/utils/prices/types.d.ts +16 -0
  101. package/build/types/src/utils/prices/utils.d.ts +3 -11
  102. package/build/types/src/utils/referrals/api.d.ts +8 -0
  103. package/build/types/src/utils/referrals/types.d.ts +5 -0
  104. package/build/types/src/utils/rpc/createViemRpc.d.ts +25 -3
  105. package/build/types/src/utils/trade/__tests__/gmsolTradeMath.spec.d.ts +1 -0
  106. package/build/types/src/utils/trade/decrease.d.ts +5 -0
  107. package/build/types/src/utils/trade/decreaseMarginCheck.d.ts +2 -0
  108. package/build/types/src/utils/trade/increase.d.ts +2 -0
  109. package/build/types/src/utils/trade/increaseMarginCheck.d.ts +2 -0
  110. package/build/types/src/utils/trade/twapIncreaseMarginCheck.d.ts +1 -0
  111. package/build/types/src/utils/trade/types.d.ts +6 -0
  112. package/package.json +10 -1
@@ -0,0 +1,230 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.gmsolMath = 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;
177
+ // gmsol's checked u128 and i128 arithmetic on 20-decimal fixed point: a result outside the type is an error, never a wrapped value
178
+ exports.gmsolMath = {
179
+ toUnsigned(value, what) {
180
+ if (value < 0n || value > constants_1.GMSOL_MAX_UNSIGNED) {
181
+ throw new Error(`u128 overflow in ${what}`);
182
+ }
183
+ return value;
184
+ },
185
+ toSigned(value, what) {
186
+ if (value < -constants_1.GMSOL_MAX_SIGNED - 1n || value > constants_1.GMSOL_MAX_SIGNED) {
187
+ throw new Error(`i128 overflow in ${what}`);
188
+ }
189
+ return value;
190
+ },
191
+ mulDiv(a, b, divisor, what) {
192
+ if (divisor === 0n) {
193
+ throw new Error(`division by zero in ${what}`);
194
+ }
195
+ return exports.gmsolMath.toUnsigned((a * b) / divisor, what);
196
+ },
197
+ mulDivCeil(a, b, divisor, what) {
198
+ if (divisor === 0n) {
199
+ throw new Error(`division by zero in ${what}`);
200
+ }
201
+ return exports.gmsolMath.toUnsigned((a * b + divisor - 1n) / divisor, what);
202
+ },
203
+ // gmsol's checked_round_up_div, whose intermediate sum must fit in u128
204
+ roundUpDiv(value, divisor, what) {
205
+ return (exports.gmsolMath.toUnsigned(value + divisor, what) - 1n) / divisor;
206
+ },
207
+ applyFactor(value, factor, what) {
208
+ return exports.gmsolMath.mulDiv(value, factor, constants_1.GMSOL_PRECISION, what);
209
+ },
210
+ divToFactor(value, divisor, what) {
211
+ return divisor === 0n ? 0n : exports.gmsolMath.mulDiv(value, constants_1.GMSOL_PRECISION, divisor, what);
212
+ },
213
+ // a value below one unit counts as none, as in GMX's applyExponentFactor
214
+ applyExponentFactor(value, exponent, what) {
215
+ if (value < constants_1.GMSOL_PRECISION) {
216
+ return 0n;
217
+ }
218
+ if (value === constants_1.GMSOL_PRECISION || exponent === 0n) {
219
+ return constants_1.GMSOL_PRECISION;
220
+ }
221
+ if (exponent % constants_1.GMSOL_PRECISION !== 0n) {
222
+ return exports.gmsolMath.toUnsigned(getGmsolFractionalPower(value, exponent), what);
223
+ }
224
+ let result = constants_1.GMSOL_PRECISION;
225
+ for (let i = 0n; i < exponent / constants_1.GMSOL_PRECISION; i++) {
226
+ result = exports.gmsolMath.mulDiv(result, value, constants_1.GMSOL_PRECISION, what);
227
+ }
228
+ return result;
229
+ },
230
+ };
@@ -0,0 +1,152 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getGmsolPendingPositionFees = void 0;
4
+ const constants_1 = require("./constants");
5
+ const markets_1 = require("./markets");
6
+ const numbers_1 = require("./numbers");
7
+ // a port of gmsol's pending_borrowing_fee_value and pending_funding_fees (crates/model/src/position.rs at 8af1e70c) on the
8
+ // market advanced to `now` the way the store program's update_fees_state advances it before every order: the borrowing
9
+ // factors, then the funding amounts per size (next_funding_amount_per_size), with the same rounding and checks
10
+ // gmsol-programs' FUNDING_AMOUNT_PER_SIZE_ADJUSTMENT, which the amounts per size carry on top of the factor unit
11
+ const PER_SIZE_UNIT = 10n ** 10n * constants_1.GMSOL_PRECISION;
12
+ function getPerSide(getValue) {
13
+ return [getValue(constants_1.GMSOL_LONG), getValue(constants_1.GMSOL_SHORT)];
14
+ }
15
+ // gmsol's Prices::validate, which both state updates run first
16
+ function validatePrices(prices) {
17
+ for (const { min, max } of [prices.index, prices.long, prices.short]) {
18
+ if (min <= 0n || max <= 0n) {
19
+ throw new Error("invalid prices");
20
+ }
21
+ numbers_1.gmsolMath.toUnsigned(min + max, "prices");
22
+ }
23
+ }
24
+ // MarketMeta::token_side, so a single-token market's collateral is its long token
25
+ function getCollateralSide(market, token) {
26
+ if (token === market.longTokenMint) {
27
+ return constants_1.GMSOL_LONG;
28
+ }
29
+ if (token === market.shortTokenMint) {
30
+ return constants_1.GMSOL_SHORT;
31
+ }
32
+ throw new Error(`${token} is not a collateral token of ${market.name}`);
33
+ }
34
+ function getAmountPerSize({ value, openInterest, price, roundUp, }) {
35
+ if (value === 0n || openInterest === 0n) {
36
+ return 0n;
37
+ }
38
+ if (roundUp) {
39
+ return numbers_1.gmsolMath.roundUpDiv(numbers_1.gmsolMath.mulDivCeil(value, PER_SIZE_UNIT, openInterest, "funding per size"), price, "funding per size");
40
+ }
41
+ return numbers_1.gmsolMath.mulDiv(value, PER_SIZE_UNIT, openInterest, "funding per size") / price;
42
+ }
43
+ // a market's pools are pure exactly when its long and short token are one mint (Market::init); a pure pool keeps one
44
+ // balance that a delta for either collateral moves and that reads back split in half, the long side taking the odd unit
45
+ function addPerSize({ pool, delta, pure }) {
46
+ const long = numbers_1.gmsolMath.toSigned(delta[constants_1.GMSOL_LONG], "funding delta");
47
+ const short = numbers_1.gmsolMath.toSigned(delta[constants_1.GMSOL_SHORT], "funding delta");
48
+ if (!pure) {
49
+ return [
50
+ numbers_1.gmsolMath.toUnsigned(pool[constants_1.GMSOL_LONG] + long, "funding per size"),
51
+ numbers_1.gmsolMath.toUnsigned(pool[constants_1.GMSOL_SHORT] + short, "funding per size"),
52
+ ];
53
+ }
54
+ const balance = numbers_1.gmsolMath.toUnsigned(pool[constants_1.GMSOL_LONG] + pool[constants_1.GMSOL_SHORT] + long + short, "funding per size");
55
+ return [(balance + 1n) / 2n, balance / 2n];
56
+ }
57
+ function replaceSidePool({ pools, side, pool, }) {
58
+ return side === constants_1.GMSOL_LONG ? [pool, pools[constants_1.GMSOL_SHORT]] : [pools[constants_1.GMSOL_LONG], pool];
59
+ }
60
+ function getNextFundingPerSize({ market, prices, now, }) {
61
+ const current = { fee: market.fundingFeeAmountPerSize, claimable: market.claimableFundingAmountPerSize };
62
+ if (market.openInterest[constants_1.GMSOL_LONG] === 0n || market.openInterest[constants_1.GMSOL_SHORT] === 0n) {
63
+ return current;
64
+ }
65
+ const { factor, longsPayShorts } = (0, markets_1.getGmsolNextFunding)(market, now);
66
+ const payer = longsPayShorts ? constants_1.GMSOL_LONG : constants_1.GMSOL_SHORT;
67
+ const receiver = longsPayShorts ? constants_1.GMSOL_SHORT : constants_1.GMSOL_LONG;
68
+ const paying = market.openInterestByCollateral[payer];
69
+ const payerOpenInterest = market.openInterest[payer];
70
+ const duration = BigInt(Math.max(0, now - market.fundingClock));
71
+ const fundingValue = numbers_1.gmsolMath.applyFactor(payerOpenInterest, numbers_1.gmsolMath.toUnsigned(duration * factor, "funding factor"), "funding value");
72
+ const values = getPerSide((collateral) => numbers_1.gmsolMath.mulDiv(fundingValue, paying[collateral], payerOpenInterest, "funding value"));
73
+ const getPrice = (collateral) => (collateral === constants_1.GMSOL_LONG ? prices.long : prices.short).max;
74
+ const fee = getPerSide((collateral) => getAmountPerSize({
75
+ value: values[collateral],
76
+ openInterest: paying[collateral],
77
+ price: getPrice(collateral),
78
+ roundUp: true,
79
+ }));
80
+ const claimable = getPerSide((collateral) => getAmountPerSize({
81
+ value: values[collateral],
82
+ openInterest: market.openInterest[receiver],
83
+ price: getPrice(collateral),
84
+ roundUp: false,
85
+ }));
86
+ const pure = market.longTokenMint === market.shortTokenMint;
87
+ return {
88
+ fee: replaceSidePool({
89
+ pools: current.fee,
90
+ side: payer,
91
+ pool: addPerSize({ pool: current.fee[payer], delta: fee, pure }),
92
+ }),
93
+ claimable: replaceSidePool({
94
+ pools: current.claimable,
95
+ side: receiver,
96
+ pool: addPerSize({ pool: current.claimable[receiver], delta: claimable, pure }),
97
+ }),
98
+ };
99
+ }
100
+ function getFundingAmount({ latest, ofPosition, sizeInUsd, roundUp, what, }) {
101
+ const diff = latest - ofPosition;
102
+ if (diff < 0n) {
103
+ throw new Error(`the position's ${what} per size is ahead of the market's`);
104
+ }
105
+ return roundUp
106
+ ? numbers_1.gmsolMath.mulDivCeil(sizeInUsd, diff, PER_SIZE_UNIT, what)
107
+ : numbers_1.gmsolMath.mulDiv(sizeInUsd, diff, PER_SIZE_UNIT, what);
108
+ }
109
+ function getGmsolPendingPositionFees({ market, prices, now, position, }) {
110
+ if (position.store !== market.store || position.marketToken !== market.marketTokenMint) {
111
+ throw new Error(`the position is not in ${market.name}`);
112
+ }
113
+ const side = position.isLong ? constants_1.GMSOL_LONG : constants_1.GMSOL_SHORT;
114
+ const collateral = getCollateralSide(market, position.collateralToken);
115
+ validatePrices(prices);
116
+ const borrowingFactors = getPerSide((each) => {
117
+ const next = (0, markets_1.getGmsolNextCumulativeBorrowingFactor)({ market, prices, now, side: each });
118
+ numbers_1.gmsolMath.toSigned(next - market.borrowingFactor[each], "borrowing delta");
119
+ return next;
120
+ });
121
+ const funding = getNextFundingPerSize({ market, prices, now });
122
+ const borrowingDiff = borrowingFactors[side] - position.borrowingFactor;
123
+ if (borrowingDiff < 0n) {
124
+ throw new Error("the position's borrowing factor is ahead of the market's");
125
+ }
126
+ const size = position.sizeInUsd;
127
+ return {
128
+ borrowingFeeValue: numbers_1.gmsolMath.applyFactor(size, borrowingDiff, "borrowing fee value"),
129
+ fundingFeeAmount: getFundingAmount({
130
+ latest: funding.fee[side][collateral],
131
+ ofPosition: position.fundingFeeAmountPerSize,
132
+ sizeInUsd: size,
133
+ roundUp: true,
134
+ what: "fee",
135
+ }),
136
+ claimableLongTokenAmount: getFundingAmount({
137
+ latest: funding.claimable[side][constants_1.GMSOL_LONG],
138
+ ofPosition: position.longTokenClaimableFundingAmountPerSize,
139
+ sizeInUsd: size,
140
+ roundUp: false,
141
+ what: "claimable long token",
142
+ }),
143
+ claimableShortTokenAmount: getFundingAmount({
144
+ latest: funding.claimable[side][constants_1.GMSOL_SHORT],
145
+ ofPosition: position.shortTokenClaimableFundingAmountPerSize,
146
+ sizeInUsd: size,
147
+ roundUp: false,
148
+ what: "claimable short token",
149
+ }),
150
+ };
151
+ }
152
+ exports.getGmsolPendingPositionFees = getGmsolPendingPositionFees;
@@ -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
+ });
@@ -1,7 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const vitest_1 = require("vitest");
4
+ const chains_1 = require("../../../configs/chains");
5
+ const tokens_1 = require("../../../configs/tokens");
4
6
  const api_1 = require("../api");
7
+ const utils_1 = require("../utils");
5
8
  const MARKET_ADDRESS = "0x1111111111111111111111111111111111111111";
6
9
  const VIRTUAL_INDEX_TOKEN_ID = "0x2222222222222222222222222222222222222222222222222222222222222222";
7
10
  const CONFIG_FIELD_CASES = [
@@ -102,6 +105,56 @@ function omitField(record, field) {
102
105
  });
103
106
  });
104
107
  (0, vitest_1.describe)("fetchApiMarketsConfig", () => {
108
+ (0, vitest_1.it)("preserves per-market minimums without requiring them from EVM FESOL-52", async () => {
109
+ for (const field of ["minCollateralUsd", "minPositionSizeUsd"]) {
110
+ for (const value of ["0", "50000000000000000000000000000000", 0, 5]) {
111
+ const [market] = await (0, api_1.fetchApiMarketsConfig)({ api: createApi([createMarketConfig({ [field]: value })]) });
112
+ (0, vitest_1.expect)(market[field]).toBe(BigInt(value));
113
+ }
114
+ const [evmMarket] = await (0, api_1.fetchApiMarketsConfig)({ api: createApi([createMarketConfig()]) });
115
+ (0, vitest_1.expect)(evmMarket[field]).toBeUndefined();
116
+ for (const value of [null, true, -1, "-1", "1.5", "invalid"]) {
117
+ await (0, vitest_1.expect)((0, api_1.fetchApiMarketsConfig)({ api: createApi([createMarketConfig({ [field]: value })]) })).rejects.toThrow(field);
118
+ }
119
+ }
120
+ });
121
+ (0, vitest_1.it)("keeps Solana mints and existing EVM native-token hydration FESOL-52", () => {
122
+ const solanaToken = {
123
+ address: "So11111111111111111111111111111111111111112",
124
+ name: "Wrapped SOL",
125
+ symbol: "WSOL",
126
+ decimals: 9,
127
+ };
128
+ for (const chainId of [chains_1.ARBITRUM, chains_1.AVALANCHE, undefined]) {
129
+ const wrappedToken = chainId === undefined ? solanaToken : (0, tokens_1.getWrappedToken)(chainId);
130
+ const indexToken = chainId === undefined ? solanaToken : (0, tokens_1.getNativeToken)(chainId);
131
+ const prices = { minPrice: 1n, maxPrice: 1n };
132
+ const tokensData = {
133
+ [wrappedToken.address]: { ...wrappedToken, prices },
134
+ [indexToken.address]: { ...indexToken, prices },
135
+ };
136
+ const rawMarket = {
137
+ marketTokenAddress: MARKET_ADDRESS,
138
+ indexTokenAddress: wrappedToken.address,
139
+ longTokenAddress: wrappedToken.address,
140
+ shortTokenAddress: wrappedToken.address,
141
+ minCollateralUsd: 5n,
142
+ minPositionSizeUsd: 0n,
143
+ };
144
+ const result = (0, utils_1.composeFullMarketsInfoData)({
145
+ chainId,
146
+ marketsAddresses: [MARKET_ADDRESS],
147
+ rawMarketsInfoData: { [MARKET_ADDRESS]: rawMarket },
148
+ tokensData,
149
+ });
150
+ (0, vitest_1.expect)(result[MARKET_ADDRESS]).toMatchObject({
151
+ ...rawMarket,
152
+ indexToken: tokensData[indexToken.address],
153
+ longToken: tokensData[wrappedToken.address],
154
+ shortToken: tokensData[wrappedToken.address],
155
+ });
156
+ }
157
+ });
105
158
  (0, vitest_1.it)("deserializes required v2.2c bigint fields", async () => {
106
159
  const result = await (0, api_1.fetchApiMarketsConfig)({
107
160
  api: createApi([createMarketConfig()]),
@@ -29,6 +29,11 @@ function parseApiRecords(raw, endpoint, fields) {
29
29
  return raw.map((record, index) => {
30
30
  const parsed = (0, numbers_1.deserializeBigIntsInObject)(record, { handleInts: true });
31
31
  (0, validation_1.assertApiFields)(parsed, fields, endpoint, index);
32
+ for (const name of ["minCollateralUsd", "minPositionSizeUsd"]) {
33
+ if (name in record) {
34
+ parsed[name] = (0, validation_1.readApiUnsignedBigInt)({ record, name, endpoint });
35
+ }
36
+ }
32
37
  return parsed;
33
38
  });
34
39
  }