@gmx-io/sdk 2.1.2 → 2.2.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 (64) hide show
  1. package/build/cjs/src/abis/TransitStation.js +2222 -0
  2. package/build/cjs/src/abis/index.js +2 -0
  3. package/build/cjs/src/clients/v2/index.js +54 -27
  4. package/build/cjs/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +32 -0
  5. package/build/cjs/src/codegen/prebuilt/hashedMarketConfigKeys.json +272 -0
  6. package/build/cjs/src/codegen/prebuilt/hashedMarketValuesKeys.json +60 -0
  7. package/build/cjs/src/configs/chains.js +9 -1
  8. package/build/cjs/src/configs/markets.js +28 -0
  9. package/build/cjs/src/configs/tokens.js +9 -0
  10. package/build/cjs/src/utils/__tests__/numbers.spec.js +79 -0
  11. package/build/cjs/src/utils/errors/transactionsErrors.js +1 -0
  12. package/build/cjs/src/utils/numbers/index.js +1 -0
  13. package/build/cjs/src/utils/numbers/parts.js +48 -0
  14. package/build/cjs/src/utils/numbers/utils.js +67 -26
  15. package/build/cjs/src/utils/orderTransactions/utils.js +55 -1
  16. package/build/cjs/src/utils/paxos/__tests__/api.spec.js +128 -0
  17. package/build/cjs/src/utils/paxos/api.js +129 -0
  18. package/build/cjs/src/utils/paxos/types.js +2 -0
  19. package/build/cjs/src/utils/usdgBoostApr/api.js +7 -0
  20. package/build/cjs/src/utils/usdgBoostApr/types.js +2 -0
  21. package/build/cjs/src/utils/whitelists/api.js +9 -0
  22. package/build/cjs/src/utils/whitelists/types.js +2 -0
  23. package/build/esm/src/abis/TransitStation.js +2220 -0
  24. package/build/esm/src/abis/index.js +2 -0
  25. package/build/esm/src/clients/v2/index.js +27 -0
  26. package/build/esm/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +32 -0
  27. package/build/esm/src/codegen/prebuilt/hashedMarketConfigKeys.json +272 -0
  28. package/build/esm/src/codegen/prebuilt/hashedMarketValuesKeys.json +60 -0
  29. package/build/esm/src/configs/chains.js +7 -0
  30. package/build/esm/src/configs/markets.js +28 -0
  31. package/build/esm/src/configs/tokens.js +9 -0
  32. package/build/esm/src/utils/__tests__/numbers.spec.js +80 -1
  33. package/build/esm/src/utils/errors/transactionsErrors.js +1 -0
  34. package/build/esm/src/utils/numbers/index.js +1 -0
  35. package/build/esm/src/utils/numbers/parts.js +41 -0
  36. package/build/esm/src/utils/numbers/utils.js +57 -24
  37. package/build/esm/src/utils/orderTransactions/utils.js +53 -1
  38. package/build/esm/src/utils/paxos/__tests__/api.spec.js +126 -0
  39. package/build/esm/src/utils/paxos/api.js +120 -0
  40. package/build/esm/src/utils/paxos/types.js +1 -0
  41. package/build/esm/src/utils/usdgBoostApr/api.js +3 -0
  42. package/build/esm/src/utils/usdgBoostApr/types.js +1 -0
  43. package/build/esm/src/utils/whitelists/api.js +5 -0
  44. package/build/esm/src/utils/whitelists/types.js +1 -0
  45. package/build/tsconfig.tsbuildinfo +1 -1
  46. package/build/types/src/abis/TransitStation.d.ts +1710 -0
  47. package/build/types/src/abis/index.d.ts +1709 -0
  48. package/build/types/src/clients/v2/index.d.ts +20 -0
  49. package/build/types/src/codegen/prebuilt/index.d.ts +364 -0
  50. package/build/types/src/configs/chains.d.ts +1 -0
  51. package/build/types/src/utils/errors/transactionsErrors.d.ts +1 -0
  52. package/build/types/src/utils/numbers/index.d.ts +1 -0
  53. package/build/types/src/utils/numbers/parts.d.ts +12 -0
  54. package/build/types/src/utils/numbers/utils.d.ts +25 -9
  55. package/build/types/src/utils/orderTransactions/utils.d.ts +7 -0
  56. package/build/types/src/utils/paxos/__tests__/api.spec.d.ts +1 -0
  57. package/build/types/src/utils/paxos/api.d.ts +24 -0
  58. package/build/types/src/utils/paxos/types.d.ts +139 -0
  59. package/build/types/src/utils/trade/types.d.ts +2 -0
  60. package/build/types/src/utils/usdgBoostApr/api.d.ts +5 -0
  61. package/build/types/src/utils/usdgBoostApr/types.d.ts +19 -0
  62. package/build/types/src/utils/whitelists/api.d.ts +7 -0
  63. package/build/types/src/utils/whitelists/types.d.ts +6 -0
  64. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import { BASIS_POINTS_DIVISOR_BIGINT, USD_DECIMALS } from "../../configs/factors";
3
- import { applyFactor, basisPointsToFloat, bigintToNumber, BN_NEGATIVE_ONE, BN_ONE, BN_ZERO, expandDecimals, formatAmount, formatAmountHuman, formatBalanceAmount, formatBasisPoints, formatPriceImpactBps, formatFactor, formatNumberHuman, formatPercentage, formatTokenAmount, formatUsdPrice, getBasisPoints, isUint256, MaxUint256, numberToBigint, parseUint256DecimalString, PERCENT_PRECISION_DECIMALS, PRECISION, PRECISION_DECIMALS, parseValue, removeTrailingZeros, trimZeroDecimals, roundWithDecimals, roundUpMagnitudeDivision, roundsToZero, toBigNumberWithDecimals, } from "../numbers";
3
+ import { applyFactor, basisPointsToFloat, bigintToNumber, BN_NEGATIVE_ONE, BN_ONE, BN_ZERO, expandDecimals, formatAmount, formatAmountHuman, formatBalanceAmount, formatBasisPoints, formatPriceImpactBps, formatFactor, formatNumberHuman, formatPercentage, formatTokenAmount, formatUsdPrice, getBasisPoints, isUint256, MaxUint256, numberToBigint, parseUint256DecimalString, PERCENT_PRECISION_DECIMALS, PRECISION, PRECISION_DECIMALS, parseValue, removeTrailingZeros, trimZeroDecimals, roundWithDecimals, roundUpMagnitudeDivision, roundsToZero, toBigNumberWithDecimals, formatUsd, formatUsdParts, formatDeltaUsd, formatDeltaUsdParts, formatBigUsd, formatBigUsdParts, formatUsdPriceParts, formatAmountHumanParts, formatTokenAmountWithUsd, formatTokenAmountWithUsdParts, numberWithCommas, numberWithCommasParts, numberParts, joinNumberParts, isNumberParts, USD_PART, } from "../numbers";
4
4
  const ONE_USD = 1000000000000000000000000000000n;
5
5
  describe("numbers utils", () => {
6
6
  it("constants", () => {
@@ -544,3 +544,82 @@ describe("formatPriceImpactBps", () => {
544
544
  expect(formatPriceImpactBps(-81n, -10000n)).toBeUndefined();
545
545
  });
546
546
  });
547
+ describe("number parts", () => {
548
+ const usd = (amount) => expandDecimals(amount, USD_DECIMALS);
549
+ it("string formatters are the joined parts", () => {
550
+ const cases = [
551
+ [formatUsd(usd(1234)), formatUsdParts(usd(1234))],
552
+ [
553
+ formatUsd(-usd(1), { displayPlus: true, displayDecimals: 4 }),
554
+ formatUsdParts(-usd(1), { displayPlus: true, displayDecimals: 4 }),
555
+ ],
556
+ [formatUsd(usd(2000000000)), formatUsdParts(usd(2000000000))],
557
+ [formatUsd(1n), formatUsdParts(1n)],
558
+ [formatUsd(undefined, { fallbackToZero: true }), formatUsdParts(undefined, { fallbackToZero: true })],
559
+ [formatDeltaUsd(usd(5), expandDecimals(3, 2)), formatDeltaUsdParts(usd(5), expandDecimals(3, 2))],
560
+ [
561
+ formatDeltaUsd(0n, undefined, { showPlusForZero: true }),
562
+ formatDeltaUsdParts(0n, undefined, { showPlusForZero: true }),
563
+ ],
564
+ [formatBigUsd(usd(123456789)), formatBigUsdParts(usd(123456789))],
565
+ [formatUsdPrice(usd(3)), formatUsdPriceParts(usd(3))],
566
+ [formatUsdPrice(-1n), formatUsdPriceParts(-1n)],
567
+ [
568
+ formatAmountHuman(usd(1150000000), USD_DECIMALS, true),
569
+ formatAmountHumanParts(usd(1150000000), USD_DECIMALS, true),
570
+ ],
571
+ [
572
+ formatAmountHuman(-usd(12500), USD_DECIMALS, false, 2),
573
+ formatAmountHumanParts(-usd(12500), USD_DECIMALS, false, 2),
574
+ ],
575
+ [formatAmountHuman(undefined, USD_DECIMALS), formatAmountHumanParts(undefined, USD_DECIMALS)],
576
+ [numberWithCommas("1234.5", { showDollar: true }), numberWithCommasParts("1234.5", { showDollar: true })],
577
+ [
578
+ formatTokenAmountWithUsd(expandDecimals(1, 18), usd(2500), "ETH", 18),
579
+ formatTokenAmountWithUsdParts(expandDecimals(1, 18), usd(2500), "ETH", 18),
580
+ ],
581
+ ];
582
+ for (const [text, parts] of cases) {
583
+ expect(parts && joinNumberParts(parts)).toBe(text);
584
+ }
585
+ });
586
+ it("marks the currency affix and keeps magnitude suffixes as text", () => {
587
+ expect(formatUsdParts(-usd(1234))).toEqual([
588
+ { kind: "text", text: "-" },
589
+ { kind: "currency", text: "$ " },
590
+ { kind: "text", text: "1,234.00" },
591
+ ]);
592
+ expect(formatUsdParts(usd(2000000000))).toEqual([
593
+ { kind: "text", text: "> " },
594
+ { kind: "currency", text: "$ " },
595
+ { kind: "text", text: "1,000,000,000.00" },
596
+ ]);
597
+ expect(formatDeltaUsdParts(usd(5), expandDecimals(3, 2))).toEqual([
598
+ { kind: "text", text: "+" },
599
+ { kind: "currency", text: "$ " },
600
+ { kind: "text", text: "5.00 (+3.00%)" },
601
+ ]);
602
+ expect(formatAmountHumanParts(usd(1150000000), USD_DECIMALS, true)).toEqual([
603
+ { kind: "currency", text: "$ " },
604
+ { kind: "text", text: "1.1b" },
605
+ ]);
606
+ expect(formatAmountHumanParts(expandDecimals(12500, 18), 18)).toEqual([{ kind: "text", text: "12.5k" }]);
607
+ expect(formatAmountHumanParts(usd(999), USD_DECIMALS, true)).toEqual([
608
+ { kind: "currency", text: "$ " },
609
+ { kind: "text", text: "999.0" },
610
+ ]);
611
+ expect(formatUsdPriceParts(-1n)).toEqual([{ kind: "text", text: "NA" }]);
612
+ expect(formatUsdParts(undefined)).toBeUndefined();
613
+ });
614
+ it("numberParts merges adjacent text and skips empty inputs", () => {
615
+ expect(numberParts("> ", undefined, "", "-", USD_PART, "1.00", [{ kind: "multiplier", text: "x" }])).toEqual([
616
+ { kind: "text", text: "> -" },
617
+ { kind: "currency", text: "$ " },
618
+ { kind: "text", text: "1.00" },
619
+ { kind: "multiplier", text: "x" },
620
+ ]);
621
+ expect(isNumberParts(formatUsdParts(usd(1)))).toBe(true);
622
+ expect(isNumberParts(["$ 1.00"])).toBe(false);
623
+ expect(isNumberParts("$ 1.00")).toBe(false);
624
+ });
625
+ });
@@ -62,6 +62,7 @@ export var CustomErrorName;
62
62
  CustomErrorName["DisabledMarket"] = "DisabledMarket";
63
63
  CustomErrorName["EndOfOracleSimulation"] = "EndOfOracleSimulation";
64
64
  CustomErrorName["ExternalCallFailed"] = "ExternalCallFailed";
65
+ CustomErrorName["InsufficientBridgeOutputAmount"] = "InsufficientBridgeOutputAmount";
65
66
  CustomErrorName["InsufficientCollateralAmount"] = "InsufficientCollateralAmount";
66
67
  CustomErrorName["InsufficientCollateralUsd"] = "InsufficientCollateralUsd";
67
68
  CustomErrorName["InsufficientExecutionGas"] = "InsufficientExecutionGas";
@@ -1,2 +1,3 @@
1
1
  export * from "./utils";
2
+ export * from "./parts";
2
3
  export * from "./prbMath";
@@ -0,0 +1,41 @@
1
+ export const USD_SYMBOL = "$ ";
2
+ export const USD_PART = { kind: "currency", text: USD_SYMBOL };
3
+ export function multiplierPart(text) {
4
+ return { kind: "multiplier", text };
5
+ }
6
+ export function numberParts(...inputs) {
7
+ const parts = [];
8
+ const push = (part) => {
9
+ if (!part.text) {
10
+ return;
11
+ }
12
+ const last = parts[parts.length - 1];
13
+ if (part.kind === "text" && last?.kind === "text") {
14
+ parts[parts.length - 1] = { kind: "text", text: last.text + part.text };
15
+ return;
16
+ }
17
+ parts.push(part);
18
+ };
19
+ for (const input of inputs) {
20
+ if (input === undefined) {
21
+ continue;
22
+ }
23
+ if (typeof input === "string") {
24
+ push({ kind: "text", text: input });
25
+ }
26
+ else if (Array.isArray(input)) {
27
+ input.forEach(push);
28
+ }
29
+ else {
30
+ push(input);
31
+ }
32
+ }
33
+ return parts;
34
+ }
35
+ export function joinNumberParts(parts) {
36
+ return parts.map((part) => part.text).join("");
37
+ }
38
+ export function isNumberParts(value) {
39
+ return (Array.isArray(value) &&
40
+ value.every((item) => typeof item === "object" && item !== null && "kind" in item && "text" in item && typeof item.text === "string"));
41
+ }
@@ -1,5 +1,6 @@
1
1
  import { formatUnits, parseUnits } from "viem";
2
2
  import { bigMath } from "../bigmath";
3
+ import { joinNumberParts, numberParts, USD_PART } from "./parts";
3
4
  export const USD_DECIMALS = 30;
4
5
  export const BASIS_POINTS_DIVISOR = 10000;
5
6
  export const BASIS_POINTS_DIVISOR_BIGINT = 10000n;
@@ -154,7 +155,7 @@ export function bigintToNumber(value, decimals) {
154
155
  export function adjustForDecimals(amount, divDecimals, mulDecimals) {
155
156
  return (amount * expandDecimals(1, mulDecimals)) / expandDecimals(1, divDecimals);
156
157
  }
157
- export function formatUsd(usd, opts = {}) {
158
+ export function formatUsdParts(usd, opts = {}) {
158
159
  const { fallbackToZero = false, displayDecimals = 2 } = opts;
159
160
  if (typeof usd !== "bigint") {
160
161
  if (fallbackToZero) {
@@ -180,15 +181,25 @@ export function formatUsd(usd, opts = {}) {
180
181
  const sign = usd < 0n ? "-" : maybePlus;
181
182
  const symbol = exceedingInfo.symbol ? `${exceedingInfo.symbol}\u00a0` : "";
182
183
  const displayUsd = formatAmount(exceedingInfo.value, USD_DECIMALS, displayDecimals, true);
183
- return `${symbol}${sign}$\u200a${displayUsd}`;
184
+ return numberParts(symbol, sign, USD_PART, displayUsd);
185
+ }
186
+ export function formatUsd(usd, opts = {}) {
187
+ const parts = formatUsdParts(usd, opts);
188
+ return parts && joinNumberParts(parts);
189
+ }
190
+ export function formatBigUsdParts(amount, opts = {}) {
191
+ return formatUsdParts(amount, {
192
+ maxThreshold: "9999999999999999999999999",
193
+ displayDecimals: opts.displayDecimals ?? 0,
194
+ });
184
195
  }
185
196
  export function formatBigUsd(amount, opts = {}) {
186
- return formatUsd(amount, { maxThreshold: "9999999999999999999999999", displayDecimals: opts.displayDecimals ?? 0 });
197
+ return joinNumberParts(formatBigUsdParts(amount, opts));
187
198
  }
188
- export function formatDeltaUsd(deltaUsd, percentage, opts = {}) {
199
+ export function formatDeltaUsdParts(deltaUsd, percentage, opts = {}) {
189
200
  if (typeof deltaUsd !== "bigint") {
190
201
  if (opts.fallbackToZero) {
191
- return `${formatUsd(0n)} (${formatAmount(0n, 2, 2)}%)`;
202
+ return numberParts(formatUsdParts(0n), ` (${formatAmount(0n, 2, 2)}%)`);
192
203
  }
193
204
  return undefined;
194
205
  }
@@ -197,7 +208,11 @@ export function formatDeltaUsd(deltaUsd, percentage, opts = {}) {
197
208
  const percentageStr = percentage !== undefined && !opts.hidePercentage ? ` (${sign}${formatPercentage(bigMath.abs(percentage))})` : "";
198
209
  const deltaUsdStr = formatAmount(exceedingInfo.value, USD_DECIMALS, 2, true);
199
210
  const symbol = exceedingInfo.symbol ? `${exceedingInfo.symbol} ` : "";
200
- return `${symbol}${sign}$\u200a${deltaUsdStr}${percentageStr}`;
211
+ return numberParts(symbol, sign, USD_PART, deltaUsdStr, percentageStr);
212
+ }
213
+ export function formatDeltaUsd(deltaUsd, percentage, opts = {}) {
214
+ const parts = formatDeltaUsdParts(deltaUsd, percentage, opts);
215
+ return parts && joinNumberParts(parts);
201
216
  }
202
217
  export function formatPercentage(percentage, opts = {}) {
203
218
  const { fallbackToZero = false, signed = false, displayDecimals = 2, bps = true, showPlus = true, useCommas = false, } = opts;
@@ -246,7 +261,7 @@ export function formatTokenAmount(amount, tokenDecimals, symbol, opts = {}) {
246
261
  }
247
262
  return `${amountStr}${symbolStr}`;
248
263
  }
249
- export function formatTokenAmountWithUsd(tokenAmount, usdAmount, tokenSymbol, tokenDecimals, opts = {}) {
264
+ export function formatTokenAmountWithUsdParts(tokenAmount, usdAmount, tokenSymbol, tokenDecimals, opts = {}) {
250
265
  if (typeof tokenAmount !== "bigint" || typeof usdAmount !== "bigint" || !tokenSymbol || !tokenDecimals) {
251
266
  if (!opts.fallbackToZero) {
252
267
  return undefined;
@@ -257,11 +272,15 @@ export function formatTokenAmountWithUsd(tokenAmount, usdAmount, tokenSymbol, to
257
272
  useCommas: true,
258
273
  displayPlus: opts.displayPlus,
259
274
  });
260
- const usdStr = formatUsd(usdAmount, {
275
+ const usdParts = formatUsdParts(usdAmount, {
261
276
  fallbackToZero: opts.fallbackToZero,
262
277
  displayPlus: opts.displayPlus,
263
278
  });
264
- return `${tokenStr} (${usdStr})`;
279
+ return numberParts(`${tokenStr} (`, usdParts, ")");
280
+ }
281
+ export function formatTokenAmountWithUsd(tokenAmount, usdAmount, tokenSymbol, tokenDecimals, opts = {}) {
282
+ const parts = formatTokenAmountWithUsdParts(tokenAmount, usdAmount, tokenSymbol, tokenDecimals, opts);
283
+ return parts && joinNumberParts(parts);
265
284
  }
266
285
  /**
267
286
  *
@@ -276,51 +295,62 @@ export function formatRatePercentage(rate, opts) {
276
295
  const amount = bigMath.abs(rate * 100n);
277
296
  return `${plurOrMinus}\u200a${formatAmount(amount, 30, opts?.displayDecimals ?? 4)}%`;
278
297
  }
279
- export function formatUsdPrice(price, opts = {}) {
298
+ export function formatUsdPriceParts(price, opts = {}) {
280
299
  if (price === undefined) {
281
300
  return;
282
301
  }
283
302
  if (price < 0n) {
284
- return "NA";
303
+ return numberParts("NA");
285
304
  }
286
305
  const decimals = calculateDisplayDecimals(price, undefined, opts.visualMultiplier);
287
- return formatUsd(price, {
306
+ return formatUsdParts(price, {
288
307
  ...opts,
289
308
  displayDecimals: decimals,
290
309
  });
291
310
  }
311
+ export function formatUsdPrice(price, opts = {}) {
312
+ const parts = formatUsdPriceParts(price, opts);
313
+ return parts && joinNumberParts(parts);
314
+ }
292
315
  export function formatPercentageDisplay(percentage, hideThreshold) {
293
316
  if (hideThreshold && percentage < hideThreshold) {
294
317
  return "";
295
318
  }
296
319
  return `${percentage}%`;
297
320
  }
298
- export function formatNumberHuman(n, showDollar = false, displayDecimals = 1) {
321
+ export function formatNumberHumanParts(n, showDollar = false, displayDecimals = 1) {
299
322
  // For large numbers, we can neglect the decimals to avoid decimals in cases like 9999999.99999
300
323
  if (n >= 1000000) {
301
324
  n = Math.round(n);
302
325
  }
303
326
  const isNegative = n < 0;
304
327
  const absN = Math.abs(n);
305
- const sign = showDollar ? "$\u200a" : "";
328
+ const sign = isNegative ? "-" : "";
329
+ const currency = showDollar ? USD_PART : undefined;
306
330
  // Promote the suffix when the displayed value rounds to 1000 in the smaller unit.
307
331
  if (Number((absN / 1000000).toFixed(displayDecimals)) >= 1000) {
308
- return `${isNegative ? "-" : ""}${sign}${(absN / 1000000000).toFixed(displayDecimals)}b`;
332
+ return numberParts(sign, currency, `${(absN / 1000000000).toFixed(displayDecimals)}b`);
309
333
  }
310
334
  if (Number((absN / 1000).toFixed(displayDecimals)) >= 1000) {
311
- return `${isNegative ? "-" : ""}${sign}${(absN / 1000000).toFixed(displayDecimals)}m`;
335
+ return numberParts(sign, currency, `${(absN / 1000000).toFixed(displayDecimals)}m`);
312
336
  }
313
337
  if (Number(absN.toFixed(displayDecimals)) >= 1000) {
314
- return `${isNegative ? "-" : ""}${sign}${(absN / 1000).toFixed(displayDecimals)}k`;
338
+ return numberParts(sign, currency, `${(absN / 1000).toFixed(displayDecimals)}k`);
315
339
  }
316
- return `${isNegative ? "-" : ""}${sign}${absN.toFixed(displayDecimals)}`;
340
+ return numberParts(sign, currency, absN.toFixed(displayDecimals));
317
341
  }
318
- export function formatAmountHuman(amount, tokenDecimals, showDollar = false, displayDecimals = 1) {
342
+ export function formatNumberHuman(n, showDollar = false, displayDecimals = 1) {
343
+ return joinNumberParts(formatNumberHumanParts(n, showDollar, displayDecimals));
344
+ }
345
+ export function formatAmountHumanParts(amount, tokenDecimals, showDollar = false, displayDecimals = 1) {
319
346
  if (amount === undefined) {
320
- return "...";
347
+ return numberParts("...");
321
348
  }
322
349
  let n = Number(formatAmount(amount, tokenDecimals));
323
- return formatNumberHuman(n, showDollar, displayDecimals);
350
+ return formatNumberHumanParts(n, showDollar, displayDecimals);
351
+ }
352
+ export function formatAmountHuman(amount, tokenDecimals, showDollar = false, displayDecimals = 1) {
353
+ return joinNumberParts(formatAmountHumanParts(amount, tokenDecimals, showDollar, displayDecimals));
324
354
  }
325
355
  export function formatBalanceAmount(amount, tokenDecimals, tokenSymbol, { showZero = false, toExponential = true, isStable = false, signed = false, } = {}) {
326
356
  if (amount === undefined)
@@ -376,13 +406,16 @@ export function formatFactor(factor) {
376
406
  const factorDecimals = Math.max(PRECISION_DECIMALS - trailingZeroes, 0);
377
407
  return formatAmount(factor, PRECISION_DECIMALS, factorDecimals);
378
408
  }
379
- export function numberWithCommas(x, { showDollar = false } = {}) {
409
+ export function numberWithCommasParts(x, { showDollar = false } = {}) {
380
410
  if (x === undefined || x === null) {
381
- return "...";
411
+ return numberParts("...");
382
412
  }
383
413
  const parts = x.toString().split(".");
384
414
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
385
- return `${showDollar ? "$\u200a" : ""}${parts.join(".")}`;
415
+ return numberParts(showDollar ? USD_PART : undefined, parts.join("."));
416
+ }
417
+ export function numberWithCommas(x, opts = {}) {
418
+ return joinNumberParts(numberWithCommasParts(x, opts));
386
419
  }
387
420
  export const formatAmount = (amount, tokenDecimals, displayDecimals, useCommas, defaultValue, visualMultiplier) => {
388
421
  if (defaultValue === undefined || defaultValue === null) {
@@ -3,9 +3,10 @@ import { encodeFunctionData, zeroAddress, zeroHash } from "viem";
3
3
  import ExchangeRouterAbi from "../../abis/ExchangeRouter";
4
4
  import { abis } from "../../abis/index";
5
5
  import ERC20ABI from "../../abis/Token";
6
- import { getExcessiveExecutionFee, getHighExecutionFee } from "../../configs/chains";
6
+ import { getExcessiveExecutionFee, getExecutionFeePriorityFeeAllowance, getHighExecutionFee, } from "../../configs/chains";
7
7
  import { getContract } from "../../configs/contracts";
8
8
  import { convertTokenAddress, getToken, getWrappedToken, NATIVE_TOKEN_ADDRESS } from "../../configs/tokens";
9
+ import { bigMath } from "../bigmath";
9
10
  import { expandDecimals, MaxUint256, USD_DECIMALS } from "../numbers";
10
11
  import { getByKey } from "../objects";
11
12
  import { isIncreaseOrderType, isSwapOrderType } from "../orders";
@@ -315,6 +316,57 @@ export function getBatchTotalExecutionFee({ batchParams, tokensData, chainId, al
315
316
  isFeeVeryHigh,
316
317
  };
317
318
  }
319
+ export function getBatchExecutionFeeEstimates(batchParams) {
320
+ return batchParams.createOrderParams.map((co) => ({
321
+ executionFee: co.orderPayload.numbers.executionFee,
322
+ gasLimit: co.params.executionGasLimit,
323
+ }));
324
+ }
325
+ // Expects wallet-priced params: apply once, right before estimating or signing for the relay
326
+ export function getExpressBatchOrderParams(chainId, batchParams) {
327
+ const allowance = getExecutionFeePriorityFeeAllowance(chainId);
328
+ if (allowance === 0n) {
329
+ return batchParams;
330
+ }
331
+ const orderVaultAddress = getContract(chainId, "OrderVault");
332
+ return {
333
+ ...batchParams,
334
+ updateOrderParams: batchParams.updateOrderParams.map((uo) => {
335
+ const delta = bigMath.min(allowance * (uo.params.executionGasLimit ?? 0n), uo.updatePayload.executionFeeTopUp);
336
+ if (delta === 0n) {
337
+ return uo;
338
+ }
339
+ return {
340
+ ...uo,
341
+ params: { ...uo.params, executionFeeTopUp: uo.params.executionFeeTopUp - delta },
342
+ updatePayload: { ...uo.updatePayload, executionFeeTopUp: uo.updatePayload.executionFeeTopUp - delta },
343
+ };
344
+ }),
345
+ createOrderParams: batchParams.createOrderParams.map((co) => {
346
+ const delta = bigMath.min(allowance * co.params.executionGasLimit, co.orderPayload.numbers.executionFee);
347
+ if (delta === 0n) {
348
+ return co;
349
+ }
350
+ return {
351
+ ...co,
352
+ params: { ...co.params, executionFeeAmount: co.params.executionFeeAmount - delta },
353
+ orderPayload: {
354
+ ...co.orderPayload,
355
+ numbers: { ...co.orderPayload.numbers, executionFee: co.orderPayload.numbers.executionFee - delta },
356
+ },
357
+ tokenTransfersParams: co.tokenTransfersParams
358
+ ? {
359
+ ...co.tokenTransfersParams,
360
+ value: co.tokenTransfersParams.value - delta,
361
+ tokenTransfers: co.tokenTransfersParams.tokenTransfers.map((transfer) => transfer.tokenAddress === NATIVE_TOKEN_ADDRESS && transfer.destination === orderVaultAddress
362
+ ? { ...transfer, amount: transfer.amount - delta }
363
+ : transfer),
364
+ }
365
+ : co.tokenTransfersParams,
366
+ };
367
+ }),
368
+ };
369
+ }
318
370
  export function getBatchTotalPayCollateralAmount(batchParams) {
319
371
  const payAmounts = {};
320
372
  for (const co of batchParams.createOrderParams) {
@@ -0,0 +1,126 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { fetchApiTransitFeeTier, fetchApiTransitOrder, fetchApiTransitOrders, fetchApiTransitQuote, fetchApiTransitRoutes, } from "../api";
3
+ const API_URL = "https://example.test";
4
+ const USER = "0x1111111111111111111111111111111111111111";
5
+ const USDC = "0xaf88d065e77c8cC2239327C5EDb3A432268e5831";
6
+ const USDG = "0x004B506865409877C9fA29bfb1ebA929984B9bbC";
7
+ const ORDER_ID = "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef";
8
+ function createApi(calls, response = {}) {
9
+ return {
10
+ url: API_URL,
11
+ fetchJson: async (path, opts) => {
12
+ calls.push({ path, query: opts?.query });
13
+ return response;
14
+ },
15
+ postJson: async () => {
16
+ throw new Error("Unexpected POST request");
17
+ },
18
+ };
19
+ }
20
+ const RAW_ORDER = {
21
+ id: ORDER_ID,
22
+ offerAsset: USDC,
23
+ wantAsset: USDG,
24
+ amountDue: "50000000",
25
+ remainingAmountDue: "0",
26
+ offerAmount: "50000000",
27
+ receiver: USER,
28
+ distributorCode: "0x",
29
+ destinationChainId: 42161,
30
+ sourceChainId: 42161,
31
+ receiveTime: 1234567890,
32
+ status: "PROCESSED",
33
+ user: USER,
34
+ createdAt: "2026-01-01T00:00:00Z",
35
+ updatedAt: "2026-01-01T00:05:00Z",
36
+ orderExecuteds: [
37
+ { id: "0xab", amount: "50000000", remaining: "0", timestamp: 1234567890, txHash: "0xcd", chainId: 42161 },
38
+ ],
39
+ };
40
+ describe("paxos transit api", () => {
41
+ it("parses routes", async () => {
42
+ const calls = [];
43
+ const api = createApi(calls, {
44
+ routes: [
45
+ {
46
+ sourceChainId: 42161,
47
+ destinationChainId: 42161,
48
+ destinationChainEID: 30110,
49
+ offerAsset: USDC,
50
+ wantAsset: USDG,
51
+ minOrderSize: "10000000",
52
+ },
53
+ ],
54
+ });
55
+ const routes = await fetchApiTransitRoutes({ api });
56
+ expect(calls).toEqual([{ path: "/v1/paxos/transit/routes", query: { filter: undefined } }]);
57
+ expect(routes).toEqual([
58
+ {
59
+ sourceChainId: 42161,
60
+ destinationChainId: 42161,
61
+ destinationChainEID: 30110,
62
+ offerAsset: USDC,
63
+ wantAsset: USDG,
64
+ minOrderSize: 10000000n,
65
+ tokenMetadataMap: {},
66
+ },
67
+ ]);
68
+ });
69
+ it("asks for the routes of a fee tier", async () => {
70
+ const calls = [];
71
+ const api = createApi(calls, { routes: [] });
72
+ await fetchApiTransitRoutes({ api }, { feeTier: "zeroFee" });
73
+ expect(calls).toEqual([{ path: "/v1/paxos/transit/routes", query: { filter: undefined, feeTier: "zeroFee" } }]);
74
+ });
75
+ it("parses fee tier capacity as bigint", async () => {
76
+ const calls = [];
77
+ const api = createApi(calls, { feeTier: "zeroFee", zeroFeeCapacity: "250000000000" });
78
+ const result = await fetchApiTransitFeeTier({ api }, { userAddress: USER });
79
+ expect(calls).toEqual([{ path: "/v1/paxos/transit/fee-tier", query: { userAddress: USER } }]);
80
+ expect(result).toEqual({ feeTier: "zeroFee", zeroFeeCapacity: 250000000000n });
81
+ });
82
+ it("sends quote amounts as strings and parses fees", async () => {
83
+ const calls = [];
84
+ const api = createApi(calls, {
85
+ transaction: { to: "0x22", data: "0x33", value: "1500", functionName: "submitOrder" },
86
+ amountOut: "49990000",
87
+ protocolFee: "10000",
88
+ fillCostFee: "5000",
89
+ conversionRateFee: "5000",
90
+ conversionRateHundredthsBps: 100,
91
+ integratorFee: "0",
92
+ totalFees: "10000",
93
+ });
94
+ const quote = await fetchApiTransitQuote({ api }, {
95
+ userAddress: USER,
96
+ offerAsset: USDC,
97
+ wantAsset: USDG,
98
+ offerAmount: 50000000n,
99
+ sourceChainId: 42161,
100
+ destinationChainId: 42161,
101
+ feeTier: "standardFee",
102
+ });
103
+ expect(calls[0].path).toBe("/v1/paxos/transit/orders/quote");
104
+ expect(calls[0].query).toMatchObject({ offerAmount: "50000000", feeTier: "standardFee" });
105
+ expect(quote.transaction.value).toBe(1500n);
106
+ expect(quote.amountOut).toBe(49990000n);
107
+ expect(quote.totalFees).toBe(10000n);
108
+ expect(quote.estimatedLatencyMs).toBeUndefined();
109
+ });
110
+ it("parses a single order", async () => {
111
+ const calls = [];
112
+ const api = createApi(calls, { order: RAW_ORDER });
113
+ const order = await fetchApiTransitOrder({ api }, { orderId: ORDER_ID });
114
+ expect(calls).toEqual([{ path: `/v1/paxos/transit/orders/${ORDER_ID}`, query: undefined }]);
115
+ expect(order.status).toBe("PROCESSED");
116
+ expect(order.offerAmount).toBe(50000000n);
117
+ expect(order.tokenMetadata).toEqual({});
118
+ expect(order.orderExecuteds[0].amount).toBe(50000000n);
119
+ });
120
+ it("drops an empty next page token", async () => {
121
+ const api = createApi([], { orders: [RAW_ORDER], nextPageToken: "" });
122
+ const result = await fetchApiTransitOrders({ api }, { userAddress: USER });
123
+ expect(result.orders).toHaveLength(1);
124
+ expect(result.nextPageToken).toBeUndefined();
125
+ });
126
+ });
@@ -0,0 +1,120 @@
1
+ export async function fetchApiTransitRoutes(ctx, params) {
2
+ const raw = await ctx.api.fetchJson("/v1/paxos/transit/routes", {
3
+ query: { filter: params?.filter, feeTier: params?.feeTier },
4
+ });
5
+ return (raw.routes ?? []).map(parseRoute);
6
+ }
7
+ export async function fetchApiTransitFeeTier(ctx, params) {
8
+ const raw = await ctx.api.fetchJson("/v1/paxos/transit/fee-tier", {
9
+ query: { userAddress: params.userAddress },
10
+ });
11
+ return {
12
+ feeTier: raw.feeTier,
13
+ zeroFeeCapacity: BigInt(raw.zeroFeeCapacity),
14
+ };
15
+ }
16
+ export async function fetchApiTransitAuthorization(ctx, params) {
17
+ return ctx.api.fetchJson("/v1/paxos/transit/authorization", {
18
+ query: {
19
+ userAddress: params.userAddress,
20
+ tokenAddress: params.tokenAddress,
21
+ spenderAddress: params.spenderAddress,
22
+ amount: params.amount.toString(),
23
+ chainId: params.chainId,
24
+ },
25
+ });
26
+ }
27
+ export async function fetchApiTransitQuote(ctx, params) {
28
+ const raw = await ctx.api.fetchJson("/v1/paxos/transit/orders/quote", {
29
+ query: {
30
+ userAddress: params.userAddress,
31
+ offerAsset: params.offerAsset,
32
+ wantAsset: params.wantAsset,
33
+ offerAmount: params.offerAmount.toString(),
34
+ sourceChainId: params.sourceChainId,
35
+ destinationChainId: params.destinationChainId,
36
+ permitSignature: params.permitSignature,
37
+ permitDeadline: params.permitDeadline,
38
+ responseFormat: params.responseFormat,
39
+ feeTier: params.feeTier,
40
+ },
41
+ });
42
+ return parseQuote(raw);
43
+ }
44
+ export async function fetchApiTransitOrder(ctx, params) {
45
+ const raw = await ctx.api.fetchJson(`/v1/paxos/transit/orders/${encodeURIComponent(params.orderId)}`);
46
+ return parseOrder(raw.order);
47
+ }
48
+ export async function fetchApiTransitOrders(ctx, params) {
49
+ const raw = await ctx.api.fetchJson("/v1/paxos/transit/orders", {
50
+ query: {
51
+ userAddress: params.userAddress,
52
+ pageSize: params.pageSize,
53
+ pageToken: params.pageToken,
54
+ filter: params.filter,
55
+ },
56
+ });
57
+ return {
58
+ orders: (raw.orders ?? []).map(parseOrder),
59
+ nextPageToken: raw.nextPageToken || undefined,
60
+ };
61
+ }
62
+ function parseRoute(raw) {
63
+ return {
64
+ sourceChainId: Number(raw.sourceChainId),
65
+ destinationChainId: Number(raw.destinationChainId),
66
+ destinationChainEID: Number(raw.destinationChainEID),
67
+ offerAsset: raw.offerAsset,
68
+ wantAsset: raw.wantAsset,
69
+ minOrderSize: BigInt(raw.minOrderSize),
70
+ tokenMetadataMap: raw.tokenMetadataMap ?? {},
71
+ };
72
+ }
73
+ function parseQuote(raw) {
74
+ return {
75
+ transaction: {
76
+ to: raw.transaction.to,
77
+ data: raw.transaction.data,
78
+ value: BigInt(raw.transaction.value ?? 0),
79
+ abi: raw.transaction.abi,
80
+ functionName: raw.transaction.functionName,
81
+ args: raw.transaction.args,
82
+ },
83
+ amountOut: BigInt(raw.amountOut),
84
+ protocolFee: BigInt(raw.protocolFee),
85
+ fillCostFee: BigInt(raw.fillCostFee),
86
+ conversionRateFee: BigInt(raw.conversionRateFee),
87
+ conversionRateHundredthsBps: Number(raw.conversionRateHundredthsBps),
88
+ integratorFee: BigInt(raw.integratorFee ?? 0),
89
+ totalFees: BigInt(raw.totalFees),
90
+ estimatedLatencyMs: raw.estimatedLatencyMs === undefined ? undefined : Number(raw.estimatedLatencyMs),
91
+ };
92
+ }
93
+ function parseOrder(raw) {
94
+ return {
95
+ id: raw.id,
96
+ offerAsset: raw.offerAsset,
97
+ wantAsset: raw.wantAsset,
98
+ amountDue: BigInt(raw.amountDue),
99
+ remainingAmountDue: BigInt(raw.remainingAmountDue),
100
+ offerAmount: BigInt(raw.offerAmount),
101
+ receiver: raw.receiver,
102
+ distributorCode: raw.distributorCode,
103
+ destinationChainId: Number(raw.destinationChainId),
104
+ sourceChainId: Number(raw.sourceChainId),
105
+ receiveTime: Number(raw.receiveTime),
106
+ status: raw.status,
107
+ user: raw.user,
108
+ createdAt: raw.createdAt,
109
+ updatedAt: raw.updatedAt,
110
+ tokenMetadata: raw.tokenMetadata ?? {},
111
+ orderExecuteds: (raw.orderExecuteds ?? []).map((execution) => ({
112
+ id: execution.id,
113
+ amount: BigInt(execution.amount),
114
+ remaining: BigInt(execution.remaining),
115
+ timestamp: Number(execution.timestamp),
116
+ txHash: execution.txHash,
117
+ chainId: Number(execution.chainId),
118
+ })),
119
+ };
120
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ export async function fetchApiUsdgBoostApr(ctx) {
2
+ return ctx.api.fetchJson("/v1/incentives/usdg/boost-apr");
3
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,5 @@
1
+ export async function fetchApiWhitelists(ctx, params) {
2
+ return ctx.api.fetchJson("/v1/whitelists", {
3
+ query: { address: params.address },
4
+ });
5
+ }
@@ -0,0 +1 @@
1
+ export {};