@gmx-io/sdk 1.1.1 → 1.2.0

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 (100) hide show
  1. package/build/cjs/src/abis/StBTC.json +1225 -0
  2. package/build/cjs/src/abis/SyntheticsReader.json +480 -19
  3. package/build/cjs/src/configs/__tests__/tokens.spec.js +1 -0
  4. package/build/cjs/src/configs/chains.js +57 -6
  5. package/build/cjs/src/configs/contracts.js +64 -68
  6. package/build/cjs/src/configs/dataStore.js +4 -3
  7. package/build/cjs/src/configs/express.js +2 -1
  8. package/build/cjs/src/configs/factors.js +2 -1
  9. package/build/cjs/src/configs/markets.js +37 -0
  10. package/build/cjs/src/configs/oracleKeeper.js +1 -0
  11. package/build/cjs/src/configs/tokens.js +130 -1
  12. package/build/cjs/src/modules/orders/helpers.js +13 -14
  13. package/build/cjs/src/modules/orders/transactions/createDecreaseOrderTxn.js +1 -1
  14. package/build/cjs/src/modules/orders/transactions/createIncreaseOrderTxn.js +6 -3
  15. package/build/cjs/src/modules/orders/transactions/createSwapOrderTxn.js +1 -1
  16. package/build/cjs/src/modules/positions/positions.js +9 -0
  17. package/build/cjs/src/prebuilt/hashedKinkModelMarketRatesKeys.json +42 -0
  18. package/build/cjs/src/prebuilt/hashedMarketConfigKeys.json +257 -0
  19. package/build/cjs/src/prebuilt/hashedMarketValuesKeys.json +77 -0
  20. package/build/cjs/src/types/subsquid.js +2405 -0
  21. package/build/cjs/src/utils/__tests__/numbers.spec.js +17 -9
  22. package/build/cjs/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +2 -0
  23. package/build/cjs/src/utils/__tests__/orderTransactions/increaseOrders.spec.js +2 -0
  24. package/build/cjs/src/utils/__tests__/orderTransactions/swapOrders.spec.js +1 -0
  25. package/build/cjs/src/utils/__tests__/prices.spec.js +3 -2
  26. package/build/cjs/src/utils/__tests__/uiFeeReceiver.spec.js +9 -0
  27. package/build/cjs/src/utils/errors/transactionsErrors.js +2 -1
  28. package/build/cjs/src/utils/fees/executionFee.js +9 -1
  29. package/build/cjs/src/utils/markets.js +2 -2
  30. package/build/cjs/src/utils/numbers.js +52 -33
  31. package/build/cjs/src/utils/orderTransactions.js +3 -0
  32. package/build/cjs/src/utils/orders.js +8 -2
  33. package/build/cjs/src/utils/prices.js +1 -1
  34. package/build/cjs/src/utils/swap/swapValues.js +40 -0
  35. package/build/cjs/src/utils/tokens.js +10 -1
  36. package/build/cjs/src/utils/tradeHistory.js +4 -4
  37. package/build/cjs/src/utils/twap/uiFeeReceiver.js +26 -6
  38. package/build/esm/src/abis/StBTC.json +1225 -0
  39. package/build/esm/src/abis/SyntheticsReader.json +480 -19
  40. package/build/esm/src/configs/__tests__/tokens.spec.js +2 -1
  41. package/build/esm/src/configs/chains.js +56 -5
  42. package/build/esm/src/configs/contracts.js +65 -69
  43. package/build/esm/src/configs/dataStore.js +1 -0
  44. package/build/esm/src/configs/express.js +4 -3
  45. package/build/esm/src/configs/factors.js +1 -1
  46. package/build/esm/src/configs/markets.js +38 -1
  47. package/build/esm/src/configs/oracleKeeper.js +2 -1
  48. package/build/esm/src/configs/tokens.js +131 -2
  49. package/build/esm/src/modules/orders/helpers.js +13 -14
  50. package/build/esm/src/modules/orders/transactions/createDecreaseOrderTxn.js +1 -1
  51. package/build/esm/src/modules/orders/transactions/createIncreaseOrderTxn.js +6 -3
  52. package/build/esm/src/modules/orders/transactions/createSwapOrderTxn.js +1 -1
  53. package/build/esm/src/modules/positions/positions.js +9 -0
  54. package/build/esm/src/prebuilt/hashedKinkModelMarketRatesKeys.json +42 -0
  55. package/build/esm/src/prebuilt/hashedMarketConfigKeys.json +257 -0
  56. package/build/esm/src/prebuilt/hashedMarketValuesKeys.json +77 -0
  57. package/build/esm/src/types/subsquid.js +2402 -0
  58. package/build/esm/src/utils/__tests__/numbers.spec.js +18 -10
  59. package/build/esm/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +2 -0
  60. package/build/esm/src/utils/__tests__/orderTransactions/increaseOrders.spec.js +2 -0
  61. package/build/esm/src/utils/__tests__/orderTransactions/swapOrders.spec.js +1 -0
  62. package/build/esm/src/utils/__tests__/prices.spec.js +3 -2
  63. package/build/esm/src/utils/__tests__/uiFeeReceiver.spec.js +9 -0
  64. package/build/esm/src/utils/errors/transactionsErrors.js +2 -1
  65. package/build/esm/src/utils/fees/executionFee.js +11 -3
  66. package/build/esm/src/utils/markets.js +2 -2
  67. package/build/esm/src/utils/numbers.js +51 -31
  68. package/build/esm/src/utils/orderTransactions.js +3 -0
  69. package/build/esm/src/utils/orders.js +8 -2
  70. package/build/esm/src/utils/prices.js +1 -1
  71. package/build/esm/src/utils/swap/swapValues.js +41 -1
  72. package/build/esm/src/utils/tokens.js +7 -0
  73. package/build/esm/src/utils/tradeHistory.js +4 -4
  74. package/build/esm/src/utils/twap/uiFeeReceiver.js +24 -5
  75. package/build/types/src/configs/chains.d.ts +20 -37
  76. package/build/types/src/configs/contracts.d.ts +60 -63
  77. package/build/types/src/configs/dataStore.d.ts +1 -0
  78. package/build/types/src/configs/factors.d.ts +1 -1
  79. package/build/types/src/configs/markets.d.ts +2 -1
  80. package/build/types/src/configs/oracleKeeper.d.ts +1 -1
  81. package/build/types/src/configs/tokens.d.ts +1 -0
  82. package/build/types/src/index.d.ts +1 -1
  83. package/build/types/src/modules/base.d.ts +1 -1
  84. package/build/types/src/modules/orders/helpers.d.ts +10 -2
  85. package/build/types/src/modules/orders/orders.d.ts +10 -1
  86. package/build/types/src/types/orders.d.ts +1 -1
  87. package/build/types/src/types/sdk.d.ts +2 -1
  88. package/build/types/src/types/subsquid.d.ts +7304 -0
  89. package/build/types/src/types/tokens.d.ts +1 -0
  90. package/build/types/src/types/trade.d.ts +1 -0
  91. package/build/types/src/types/tradeHistory.d.ts +0 -40
  92. package/build/types/src/utils/markets.d.ts +1 -1
  93. package/build/types/src/utils/multicall.d.ts +1 -1
  94. package/build/types/src/utils/numbers.d.ts +9 -3
  95. package/build/types/src/utils/orderTransactions.d.ts +2 -3
  96. package/build/types/src/utils/prices.d.ts +1 -1
  97. package/build/types/src/utils/tokens.d.ts +2 -0
  98. package/build/types/src/utils/tradeHistory.d.ts +2 -2
  99. package/build/types/src/utils/twap/uiFeeReceiver.d.ts +13 -0
  100. package/package.json +7 -2
@@ -1,7 +1,7 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import { BASIS_POINTS_DIVISOR_BIGINT, USD_DECIMALS } from "../../configs/factors";
3
3
  const ONE_USD = 1000000000000000000000000000000n;
4
- import { applyFactor, basisPointsToFloat, bigintToNumber, BN_NEGATIVE_ONE, BN_ONE, BN_ZERO, expandDecimals, formatAmount, formatAmountHuman, formatBalanceAmount, formatBalanceAmountWithUsd, formatFactor, formatPercentage, formatUsdPrice, getBasisPoints, numberToBigint, PERCENT_PRECISION_DECIMALS, PRECISION, PRECISION_DECIMALS, roundWithDecimals, roundUpMagnitudeDivision, toBigNumberWithDecimals, } from "../numbers";
4
+ import { applyFactor, basisPointsToFloat, bigintToNumber, BN_NEGATIVE_ONE, BN_ONE, BN_ZERO, expandDecimals, formatAmount, formatAmountHuman, formatBalanceAmount, formatFactor, formatPercentage, formatUsdPrice, getBasisPoints, numberToBigint, PERCENT_PRECISION_DECIMALS, PRECISION, PRECISION_DECIMALS, roundWithDecimals, roundUpMagnitudeDivision, toBigNumberWithDecimals, } from "../numbers";
5
5
  describe("numbers utils", () => {
6
6
  it("constants", () => {
7
7
  // Just to confirm they exist and have no unexpected changes
@@ -232,7 +232,7 @@ describe("formatBalanceAmount", () => {
232
232
  it("should display balance amount", () => {
233
233
  expect(formatBalanceAmount(ONE_USD * 1000n, USD_DECIMALS)).toBe("1,000.0000");
234
234
  expect(formatBalanceAmount(0n, USD_DECIMALS)).toBe("-");
235
- expect(formatBalanceAmount(0n, USD_DECIMALS, undefined, true)).toBe("0.0000");
235
+ expect(formatBalanceAmount(0n, USD_DECIMALS, undefined, { showZero: true })).toBe("0.0000");
236
236
  expect(formatBalanceAmount(ONE_USD * 1n, USD_DECIMALS)).toBe("1.0000");
237
237
  expect(formatBalanceAmount(ONE_USD / 10n, USD_DECIMALS)).toBe("0.10000");
238
238
  expect(formatBalanceAmount(ONE_USD / 100n, USD_DECIMALS)).toBe("0.010000");
@@ -248,14 +248,22 @@ describe("formatBalanceAmount", () => {
248
248
  });
249
249
  it("should display balance amount with symbol", () => {
250
250
  expect(formatBalanceAmount(ONE_USD, USD_DECIMALS, "USDC")).toBe("1.0000 USDC");
251
- expect(formatBalanceAmount(0n, USD_DECIMALS, "USDC", true)).toBe("0.0000 USDC");
252
- expect(formatBalanceAmount(0n, USD_DECIMALS, "USDC", false)).toBe("-");
253
- });
254
- it("should display balance amount with usd", () => {
255
- expect(formatBalanceAmountWithUsd(ONE_USD, ONE_USD, USD_DECIMALS)).toBe("1.0000 ($1.00)");
256
- expect(formatBalanceAmountWithUsd(ONE_USD, ONE_USD, USD_DECIMALS, "USDC")).toBe("1.0000 USDC ($1.00)");
257
- expect(formatBalanceAmountWithUsd(0n, 0n, USD_DECIMALS, "USDC")).toBe("-");
258
- expect(formatBalanceAmountWithUsd(0n, 0n, USD_DECIMALS, "USDC", true)).toBe("0.0000 USDC ($0.00)");
251
+ expect(formatBalanceAmount(0n, USD_DECIMALS, "USDC", { showZero: true })).toBe("0.0000 USDC");
252
+ expect(formatBalanceAmount(0n, USD_DECIMALS, "USDC", { showZero: false })).toBe("-");
253
+ });
254
+ it("should display balance of stable token correctly", () => {
255
+ expect(formatBalanceAmount(ONE_USD, USD_DECIMALS, undefined, { isStable: true })).toBe("1.00");
256
+ expect(formatBalanceAmount(ONE_USD / 10n, USD_DECIMALS, undefined, { isStable: true })).toBe("0.100");
257
+ expect(formatBalanceAmount(ONE_USD / 100n, USD_DECIMALS, undefined, { isStable: true })).toBe("0.0100");
258
+ expect(formatBalanceAmount(ONE_USD / 1000n, USD_DECIMALS, undefined, { isStable: true })).toBe("0.00100");
259
+ expect(formatBalanceAmount(ONE_USD / 10000n, USD_DECIMALS, undefined, { isStable: true })).toBe("0.00010000");
260
+ expect(formatBalanceAmount(ONE_USD / 100000n, USD_DECIMALS, undefined, { isStable: true })).toBe("0.00001000");
261
+ expect(formatBalanceAmount(ONE_USD / 1000000n, USD_DECIMALS, undefined, { isStable: true })).toBe("0.00000100");
262
+ expect(formatBalanceAmount(ONE_USD / 10000000n, USD_DECIMALS, undefined, { isStable: true })).toBe("0.00000010");
263
+ expect(formatBalanceAmount(ONE_USD / 100000000n, USD_DECIMALS, undefined, { isStable: true })).toBe("0.00000001");
264
+ expect(formatBalanceAmount(ONE_USD / 1000000000n, USD_DECIMALS, undefined, { isStable: true })).toBe("1.00e-9");
265
+ expect(formatBalanceAmount(0n, USD_DECIMALS, undefined, { isStable: true, showZero: true })).toBe("0.00");
266
+ expect(formatBalanceAmount(0n, USD_DECIMALS, undefined, { isStable: true, showZero: false })).toBe("-");
259
267
  });
260
268
  });
261
269
  describe("formatFactor", () => {
@@ -368,6 +368,7 @@ describe("Decrease Order Payloads", () => {
368
368
  expect(decoded).toEqual({
369
369
  twapId: "8000",
370
370
  numberOfParts: twapParams.numberOfParts,
371
+ isExpress: false,
371
372
  });
372
373
  return {
373
374
  orderPayload: {
@@ -460,6 +461,7 @@ describe("Decrease Order Payloads", () => {
460
461
  const uiFeeReceiver = `0xff00000000000000000000000000000004800001`;
461
462
  const decoded = decodeTwapUiFeeReceiver(uiFeeReceiver);
462
463
  expect(decoded).toEqual({
464
+ isExpress: false,
463
465
  twapId: "8000",
464
466
  numberOfParts: twapParams.numberOfParts,
465
467
  });
@@ -532,6 +532,7 @@ describe("Increase Order Payloads", () => {
532
532
  const uiFeeReceiver = `0xff00000000000000000000000000000004800001`;
533
533
  const decoded = decodeTwapUiFeeReceiver(uiFeeReceiver);
534
534
  expect(decoded).toEqual({
535
+ isExpress: false,
535
536
  twapId: "8000",
536
537
  numberOfParts: twapParams.numberOfParts,
537
538
  });
@@ -626,6 +627,7 @@ describe("Increase Order Payloads", () => {
626
627
  const uiFeeReceiver = `0xff00000000000000000000000000000004800001`;
627
628
  const decoded = decodeTwapUiFeeReceiver(uiFeeReceiver);
628
629
  expect(decoded).toEqual({
630
+ isExpress: false,
629
631
  twapId: "8000",
630
632
  numberOfParts: twapParams.numberOfParts,
631
633
  });
@@ -335,6 +335,7 @@ describe("Swap Order Payloads", () => {
335
335
  expect(decoded).toEqual({
336
336
  twapId: "8000",
337
337
  numberOfParts: twapParams.numberOfParts,
338
+ isExpress: false,
338
339
  });
339
340
  return {
340
341
  orderPayload: {
@@ -61,7 +61,8 @@ describe("getTriggerThresholdType", () => {
61
61
  const result = getOrderThresholdType(OrderType.StopIncrease, false);
62
62
  expect(result).toBe(TriggerThresholdType.Below);
63
63
  });
64
- it("throws error for invalid order type", () => {
65
- expect(() => getOrderThresholdType("SomeInvalidType", true)).toThrow("Invalid trigger order type");
64
+ it("returns undefined for invalid order type", () => {
65
+ const result = getOrderThresholdType("SomeInvalidType", true);
66
+ expect(result).toBeUndefined();
66
67
  });
67
68
  });
@@ -11,12 +11,21 @@ describe("uiFeeReceiver", () => {
11
11
  it("should return undefined if twapId inside is 0000", () => {
12
12
  expect(decodeTwapUiFeeReceiver("0xff00000000000000000000000000000000000001")).toBeUndefined();
13
13
  });
14
+ it("should correctly decode isExpress", () => {
15
+ expect(decodeTwapUiFeeReceiver("0xff0000000000000000000000000000010a123401")).toEqual({
16
+ isExpress: true,
17
+ twapId: "1234",
18
+ numberOfParts: 10,
19
+ });
20
+ });
14
21
  it("should return the twapId and numberOfParts if the uiFeeReceiver is valid twap", () => {
15
22
  expect(decodeTwapUiFeeReceiver("0xff0000000000000000000000000000000a123401")).toEqual({
23
+ isExpress: false,
16
24
  twapId: "1234",
17
25
  numberOfParts: 10,
18
26
  });
19
27
  expect(decodeTwapUiFeeReceiver("0xff000000000000000000000000000000153a4f01")).toEqual({
28
+ isExpress: false,
20
29
  twapId: "3a4f",
21
30
  numberOfParts: 21,
22
31
  });
@@ -16,9 +16,10 @@ const TX_ERROR_PATTERNS = {
16
16
  [TxErrorType.UserDenied]: [
17
17
  { msg: "User denied transaction signature" },
18
18
  { msg: "User rejected" },
19
+ { msg: "User cancelled" },
19
20
  { msg: "user rejected action" },
20
21
  { msg: "ethers-user-denied" },
21
- { msg: "User canceled" },
22
+ { msg: "Action cancelled by user" },
22
23
  { msg: "Signing aborted by user" },
23
24
  ],
24
25
  [TxErrorType.Slippage]: [
@@ -1,9 +1,10 @@
1
- import { getExcessiveExecutionFee, getHighExecutionFee } from "../../configs/chains";
1
+ import { getExcessiveExecutionFee, getHighExecutionFee, MIN_EXECUTION_FEE_USD } from "../../configs/chains";
2
2
  import { USD_DECIMALS } from "../../configs/factors";
3
3
  import { NATIVE_TOKEN_ADDRESS } from "../../configs/tokens";
4
4
  import { DecreasePositionSwapType } from "../../types/orders";
5
+ import { bigMath } from "../bigmath";
5
6
  import { applyFactor, expandDecimals } from "../numbers";
6
- import { convertBetweenTokens, convertToUsd, getTokenData } from "../tokens";
7
+ import { convertBetweenTokens, convertToTokenAmount, convertToUsd, getTokenData } from "../tokens";
7
8
  export function getExecutionFee(chainId, gasLimits,
8
9
  // TODO optimize we only need the native token data
9
10
  tokensData, estimatedGasLimit, gasPrice, oraclePriceCount, numberOfParts) {
@@ -16,7 +17,14 @@ tokensData, estimatedGasLimit, gasPrice, oraclePriceCount, numberOfParts) {
16
17
  const multiplierFactor = gasLimits.estimatedFeeMultiplierFactor;
17
18
  const gasLimit = baseGasLimit + applyFactor(estimatedGasLimit, multiplierFactor);
18
19
  // #endregion
19
- const feeTokenAmount = gasLimit * gasPrice * BigInt(numberOfParts ?? 1);
20
+ // avoid botanix gas spikes when chain is not actively used
21
+ const minGasCostUsd = MIN_EXECUTION_FEE_USD[chainId];
22
+ const minGasCost = convertToTokenAmount(minGasCostUsd, nativeToken.decimals, nativeToken.prices.minPrice);
23
+ let feeTokenAmountPerExecution = gasLimit * gasPrice;
24
+ if (minGasCost) {
25
+ feeTokenAmountPerExecution = bigMath.max(feeTokenAmountPerExecution, minGasCost);
26
+ }
27
+ const feeTokenAmount = feeTokenAmountPerExecution * BigInt(numberOfParts ?? 1);
20
28
  const feeUsd = convertToUsd(feeTokenAmount, nativeToken.decimals, nativeToken.prices.minPrice);
21
29
  const isFeeHigh = feeUsd > expandDecimals(getHighExecutionFee(chainId), USD_DECIMALS);
22
30
  const isFeeVeryHigh = feeUsd > expandDecimals(getExcessiveExecutionFee(chainId), USD_DECIMALS);
@@ -16,9 +16,9 @@ export function getMarketIndexName(p) {
16
16
  const prefix = getTokenVisualMultiplier(firstToken);
17
17
  return `${prefix}${firstToken.baseSymbol || firstToken.symbol}/USD`;
18
18
  }
19
- export function getMarketPoolName(p) {
19
+ export function getMarketPoolName(p, separator = "-") {
20
20
  const { longToken, shortToken } = p;
21
- return `${longToken.symbol}-${shortToken.symbol}`;
21
+ return `${longToken.symbol}${separator}${shortToken.symbol}`;
22
22
  }
23
23
  export function getContractMarketPrices(tokensData, market) {
24
24
  const indexToken = getByKey(tokensData, market.indexTokenAddress);
@@ -3,6 +3,7 @@ import { bigMath } from "./bigmath";
3
3
  export const USD_DECIMALS = 30;
4
4
  export const BASIS_POINTS_DIVISOR = 10000;
5
5
  export const BASIS_POINTS_DIVISOR_BIGINT = 10000n;
6
+ export const BASIS_POINTS_DECIMALS = 4;
6
7
  export const PRECISION_DECIMALS = 30;
7
8
  export const PRECISION = expandDecimals(1, PRECISION_DECIMALS);
8
9
  export const BN_ZERO = 0n;
@@ -126,7 +127,8 @@ export function formatPercentage(percentage, opts = {}) {
126
127
  return `${sign}${formatAmount(bigMath.abs(percentage), bps ? 2 : PERCENT_PRECISION_DECIMALS, displayDecimals)}%`;
127
128
  }
128
129
  export function formatTokenAmount(amount, tokenDecimals, symbol, opts = {}) {
129
- const { displayDecimals = 4, showAllSignificant = false, fallbackToZero = false, useCommas = false, minThreshold = "0", maxThreshold, } = opts;
130
+ const { showAllSignificant = false, fallbackToZero = false, useCommas = false, minThreshold = "0", maxThreshold, } = opts;
131
+ const displayDecimals = opts.displayDecimals ?? (opts.isStable ? 2 : 4);
130
132
  const symbolStr = symbol ? ` ${symbol}` : "";
131
133
  if (typeof amount !== "bigint" || !tokenDecimals) {
132
134
  if (fallbackToZero) {
@@ -146,7 +148,7 @@ export function formatTokenAmount(amount, tokenDecimals, symbol, opts = {}) {
146
148
  else {
147
149
  const exceedingInfo = getLimitedDisplay(amount, tokenDecimals, { maxThreshold, minThreshold });
148
150
  const symbol = exceedingInfo.symbol ? `${exceedingInfo.symbol} ` : "";
149
- amountStr = `${symbol}${sign}${formatAmount(exceedingInfo.value, tokenDecimals, displayDecimals, useCommas)}`;
151
+ amountStr = `${symbol}${sign}${formatAmount(exceedingInfo.value, tokenDecimals, displayDecimals, useCommas, undefined)}`;
150
152
  }
151
153
  return `${amountStr}${symbolStr}`;
152
154
  }
@@ -222,14 +224,20 @@ export function formatAmountHuman(amount, tokenDecimals, showDollar = false, dis
222
224
  }
223
225
  return `${isNegative ? "-" : ""}${sign}${absN.toFixed(displayDecimals)}`;
224
226
  }
225
- export function formatBalanceAmount(amount, tokenDecimals, tokenSymbol, showZero = false, toExponential = true) {
227
+ export function formatBalanceAmount(amount, tokenDecimals, tokenSymbol, { showZero = false, toExponential = true, isStable = false, } = {}) {
226
228
  if (amount === undefined)
227
229
  return "-";
228
230
  if (amount === 0n) {
229
231
  if (showZero === true) {
230
232
  if (tokenSymbol) {
233
+ if (isStable) {
234
+ return `0.00 ${tokenSymbol}`;
235
+ }
231
236
  return `0.0000 ${tokenSymbol}`;
232
237
  }
238
+ if (isStable) {
239
+ return "0.00";
240
+ }
233
241
  return "0.0000";
234
242
  }
235
243
  return "-";
@@ -237,14 +245,15 @@ export function formatBalanceAmount(amount, tokenDecimals, tokenSymbol, showZero
237
245
  const absAmount = bigMath.abs(amount);
238
246
  const absAmountFloat = bigintToNumber(absAmount, tokenDecimals);
239
247
  let value = "";
248
+ const baseDecimals = isStable ? 2 : 4;
240
249
  if (absAmountFloat >= 1)
241
- value = formatAmount(amount, tokenDecimals, 4, true);
250
+ value = formatAmount(amount, tokenDecimals, baseDecimals, true);
242
251
  else if (absAmountFloat >= 0.1)
243
- value = formatAmount(amount, tokenDecimals, 5, true);
252
+ value = formatAmount(amount, tokenDecimals, baseDecimals + 1, true);
244
253
  else if (absAmountFloat >= 0.01)
245
- value = formatAmount(amount, tokenDecimals, 6, true);
254
+ value = formatAmount(amount, tokenDecimals, baseDecimals + 2, true);
246
255
  else if (absAmountFloat >= 0.001)
247
- value = formatAmount(amount, tokenDecimals, 7, true);
256
+ value = formatAmount(amount, tokenDecimals, baseDecimals + 3, true);
248
257
  else if (absAmountFloat >= 1e-8)
249
258
  value = formatAmount(amount, tokenDecimals, 8, true);
250
259
  else {
@@ -261,15 +270,6 @@ export function formatBalanceAmount(amount, tokenDecimals, tokenSymbol, showZero
261
270
  }
262
271
  return value;
263
272
  }
264
- export function formatBalanceAmountWithUsd(amount, amountUsd, tokenDecimals, tokenSymbol, showZero = false) {
265
- if (showZero === false && amount === 0n) {
266
- return "-";
267
- }
268
- const value = formatBalanceAmount(amount, tokenDecimals, tokenSymbol, showZero);
269
- const usd = formatUsd(amountUsd);
270
- // Regular space
271
- return `${value} (${usd})`;
272
- }
273
273
  export function formatFactor(factor) {
274
274
  if (factor == 0n) {
275
275
  return "0";
@@ -541,26 +541,46 @@ export function deserializeBigIntsInObject(obj) {
541
541
  }
542
542
  return result;
543
543
  }
544
- export function calculateDisplayDecimals(price, decimals = USD_DECIMALS, visualMultiplier = 1) {
544
+ export function calculateDisplayDecimals(price, decimals = USD_DECIMALS, visualMultiplier = 1, isStable = false) {
545
545
  if (price === undefined || price === 0n)
546
546
  return 2;
547
547
  const priceNumber = bigintToNumber(bigMath.abs(price) * BigInt(visualMultiplier), decimals);
548
548
  if (isNaN(priceNumber))
549
549
  return 2;
550
- if (priceNumber >= 1000)
551
- return 2;
552
- if (priceNumber >= 100)
553
- return 3;
554
- if (priceNumber >= 1)
555
- return 4;
556
- if (priceNumber >= 0.1)
557
- return 5;
558
- if (priceNumber >= 0.01)
559
- return 6;
560
- if (priceNumber >= 0.0001)
561
- return 7;
562
- if (priceNumber >= 0.00001)
563
- return 8;
550
+ if (isStable) {
551
+ if (priceNumber >= 0.1)
552
+ return 2;
553
+ if (priceNumber >= 0.01)
554
+ return 3;
555
+ if (priceNumber >= 0.001)
556
+ return 4;
557
+ if (priceNumber >= 0.0001)
558
+ return 5;
559
+ if (priceNumber >= 0.00001)
560
+ return 6;
561
+ if (priceNumber >= 0.000001)
562
+ return 7;
563
+ if (priceNumber >= 0.0000001)
564
+ return 8;
565
+ if (priceNumber >= 0.00000001)
566
+ return 9;
567
+ }
568
+ else {
569
+ if (priceNumber >= 1000)
570
+ return 2;
571
+ if (priceNumber >= 100)
572
+ return 3;
573
+ if (priceNumber >= 1)
574
+ return 4;
575
+ if (priceNumber >= 0.1)
576
+ return 5;
577
+ if (priceNumber >= 0.01)
578
+ return 6;
579
+ if (priceNumber >= 0.0001)
580
+ return 7;
581
+ if (priceNumber >= 0.00001)
582
+ return 8;
583
+ }
564
584
  return 9;
565
585
  }
566
586
  export function clamp(value, min, max) {
@@ -171,6 +171,9 @@ export function buildTwapOrdersPayloads(p, twapParams) {
171
171
  referralCode: params.referralCode,
172
172
  autoCancel: params.autoCancel,
173
173
  allowedSlippage: 0,
174
+ ...(params.expectedOutputAmount !== undefined && {
175
+ expectedOutputAmount: params.expectedOutputAmount / BigInt(twapParams.numberOfParts),
176
+ }),
174
177
  payTokenAmount: params.payTokenAmount / BigInt(twapParams.numberOfParts),
175
178
  executionFeeAmount: params.executionFeeAmount / BigInt(twapParams.numberOfParts),
176
179
  validFromTime: getTwapValidFromTime(twapParams.duration, twapParams.numberOfParts, i),
@@ -158,7 +158,10 @@ export function getOrderInfo(p) {
158
158
  shouldApplyPriceImpact: true,
159
159
  isAtomicSwap: false,
160
160
  });
161
- const triggerThresholdType = getOrderThresholdType(order.orderType, order.isLong);
161
+ let triggerThresholdType;
162
+ if (!isMarketOrderType(order.orderType)) {
163
+ triggerThresholdType = getOrderThresholdType(order.orderType, order.isLong);
164
+ }
162
165
  const orderInfo = {
163
166
  ...order,
164
167
  swapPathStats,
@@ -176,7 +179,10 @@ export function getOrderInfo(p) {
176
179
  }
177
180
  }
178
181
  export function isVisibleOrder(orderType) {
179
- return isLimitOrderType(orderType) || isTriggerDecreaseOrderType(orderType) || isLimitSwapOrderType(orderType);
182
+ return (isLimitOrderType(orderType) ||
183
+ isTriggerDecreaseOrderType(orderType) ||
184
+ isLimitSwapOrderType(orderType) ||
185
+ isMarketOrderType(orderType));
180
186
  }
181
187
  export function isOrderForPosition(order, positionKey) {
182
188
  const { account, marketAddress, collateralAddress, isLong } = parsePositionKey(positionKey);
@@ -33,7 +33,7 @@ export function getOrderThresholdType(orderType, isLong) {
33
33
  if (orderType === OrderType.StopLossDecrease) {
34
34
  return isLong ? TriggerThresholdType.Below : TriggerThresholdType.Above;
35
35
  }
36
- throw new Error("Invalid trigger order type");
36
+ return undefined;
37
37
  }
38
38
  export function getAcceptablePriceInfo(p) {
39
39
  const { marketInfo, isIncrease, isLong, indexPrice, sizeDeltaUsd, maxNegativePriceImpactBps } = p;
@@ -2,7 +2,7 @@ import { BASIS_POINTS_DIVISOR_BIGINT } from "../../configs/factors";
2
2
  import { bigMath } from "../bigmath";
3
3
  import { getTotalSwapVolumeFromSwapStats } from "../fees";
4
4
  import { applyFactor } from "../numbers";
5
- import { convertToTokenAmount, convertToUsd, getAmountByRatio, getIsEquivalentTokens } from "../tokens";
5
+ import { convertToTokenAmount, convertToUsd, getAmountByRatio, getIsEquivalentTokens, getIsStake, getIsUnstake, } from "../tokens";
6
6
  export function getSwapAmountsByFromValue(p) {
7
7
  const { tokenIn, tokenOut, amountIn, triggerRatio, isLimit, swapOptimizationOrder, findSwapPath, uiFeeFactor, allowedSwapSlippageBps, } = p;
8
8
  const priceIn = tokenIn.prices.minPrice;
@@ -39,6 +39,9 @@ export function getSwapAmountsByFromValue(p) {
39
39
  swapPathStats: undefined,
40
40
  };
41
41
  }
42
+ if (getIsStake(tokenIn, tokenOut) || getIsUnstake(tokenIn, tokenOut)) {
43
+ return getPlainSwapAmountsByFromToken(tokenIn, tokenOut, amountIn);
44
+ }
42
45
  const swapPathStats = findSwapPath(defaultAmounts.usdIn, { order: swapOptimizationOrder });
43
46
  const totalSwapVolume = getTotalSwapVolumeFromSwapStats(swapPathStats?.swapSteps);
44
47
  const swapUiFeeUsd = applyFactor(totalSwapVolume, uiFeeFactor);
@@ -119,6 +122,9 @@ export function getSwapAmountsByToValue(p) {
119
122
  swapPathStats: undefined,
120
123
  };
121
124
  }
125
+ if (getIsStake(tokenIn, tokenOut) || getIsUnstake(tokenIn, tokenOut)) {
126
+ return getPlainSwapAmountsByToToken(tokenIn, tokenOut, amountOut);
127
+ }
122
128
  const baseUsdIn = usdOut;
123
129
  const swapPathStats = findSwapPath(baseUsdIn, { order: swapOptimizationOrder });
124
130
  if (!swapPathStats) {
@@ -182,3 +188,37 @@ export function getSwapPathComparator(order) {
182
188
  return 0;
183
189
  };
184
190
  }
191
+ function getPlainSwapAmountsByFromToken(tokenIn, tokenOut, amountIn) {
192
+ const usdIn = convertToUsd(amountIn, tokenIn.decimals, tokenIn.prices.minPrice);
193
+ const usdOut = usdIn;
194
+ const amountOut = convertToTokenAmount(usdOut, tokenOut.decimals, tokenOut.prices.maxPrice);
195
+ const priceIn = tokenIn.prices.minPrice;
196
+ const priceOut = tokenOut.prices.maxPrice;
197
+ return {
198
+ amountIn,
199
+ usdIn,
200
+ amountOut,
201
+ usdOut,
202
+ minOutputAmount: amountOut,
203
+ priceIn,
204
+ priceOut,
205
+ swapPathStats: undefined,
206
+ };
207
+ }
208
+ function getPlainSwapAmountsByToToken(tokenIn, tokenOut, amountOut) {
209
+ const priceIn = tokenIn.prices.minPrice;
210
+ const priceOut = tokenOut.prices.maxPrice;
211
+ const usdOut = convertToUsd(amountOut, tokenOut.decimals, priceOut);
212
+ const usdIn = usdOut;
213
+ const amountIn = convertToTokenAmount(usdIn, tokenIn.decimals, priceIn);
214
+ return {
215
+ amountIn,
216
+ usdIn,
217
+ amountOut,
218
+ usdOut,
219
+ minOutputAmount: amountOut,
220
+ priceIn,
221
+ priceOut,
222
+ swapPathStats: undefined,
223
+ };
224
+ }
@@ -132,6 +132,13 @@ export function getIsWrap(token1, token2) {
132
132
  export function getIsUnwrap(token1, token2) {
133
133
  return token1.isWrapped && token2.isNative;
134
134
  }
135
+ export function getIsStake(token1, token2) {
136
+ return (token1.isWrapped || token1.isNative) && token2.isStaking;
137
+ }
138
+ export function getIsUnstake(token1, token2) {
139
+ // can't unstake straight to native token
140
+ return token1.isStaking && token2.isWrapped;
141
+ }
135
142
  export function getTokensRatioByPrice(p) {
136
143
  const { fromToken, toToken, fromPrice, toPrice } = p;
137
144
  const [largestToken, smallestToken, largestPrice, smallestPrice] = fromPrice > toPrice ? [fromToken, toToken, fromPrice, toPrice] : [toToken, fromToken, toPrice, fromPrice];
@@ -38,8 +38,8 @@ export function createRawTradeActionTransformer(marketsInfoData, wrappedToken, t
38
38
  initialCollateralToken,
39
39
  timestamp: rawAction.timestamp,
40
40
  transaction: rawAction.transaction,
41
- reason: rawAction.reason,
42
- reasonBytes: rawAction.reasonBytes,
41
+ reason: rawAction.reason ?? undefined,
42
+ reasonBytes: rawAction.reasonBytes ?? undefined,
43
43
  twapParams: rawAction.twapGroupId && rawAction.numberOfParts
44
44
  ? {
45
45
  twapGroupId: rawAction.twapGroupId,
@@ -112,8 +112,8 @@ export function createRawTradeActionTransformer(marketsInfoData, wrappedToken, t
112
112
  borrowingFeeAmount: rawAction.borrowingFeeAmount ? BigInt(rawAction.borrowingFeeAmount) : undefined,
113
113
  fundingFeeAmount: rawAction.fundingFeeAmount ? BigInt(rawAction.fundingFeeAmount) : undefined,
114
114
  liquidationFeeAmount: rawAction.liquidationFeeAmount ? BigInt(rawAction.liquidationFeeAmount) : undefined,
115
- reason: rawAction.reason,
116
- reasonBytes: rawAction.reasonBytes,
115
+ reason: rawAction.reason ?? undefined,
116
+ reasonBytes: rawAction.reasonBytes ?? undefined,
117
117
  transaction: rawAction.transaction,
118
118
  timestamp: rawAction.timestamp,
119
119
  shouldUnwrapNativeToken: rawAction.shouldUnwrapNativeToken,
@@ -1,6 +1,17 @@
1
1
  import { isAddress } from "viem";
2
2
  const VERSION = "01";
3
- const PREFIX = "0xff";
3
+ const PREFIX = "0xff0000";
4
+ /**
5
+ * Ui fee receiver structure:
6
+ * 0..3 bytes (0..7 chars) - PREFIX
7
+ * 4..16 bytes (8..27 chars) - 12 bytes buffer
8
+ * 17 byte (27..29 chars) - isExpress flag
9
+ * 18 byte (30..32 chars) - numberOfParts (hex encoded)
10
+ * 19..20 bytes (34..38 chars) - twapId
11
+ * 20 byte (38..40 chars) - VERSION
12
+ *
13
+ * Total: 20 bytes (40 hex characters)
14
+ */
4
15
  export function generateTwapId() {
5
16
  return Math.floor(Math.random() * 256 * 256)
6
17
  .toString(16)
@@ -9,16 +20,24 @@ export function generateTwapId() {
9
20
  export function createTwapUiFeeReceiver({ numberOfParts }) {
10
21
  const twapId = generateTwapId();
11
22
  const numberOfPartsInHex = numberOfParts.toString(16).padStart(2, "0");
12
- return `${PREFIX}00${"00".repeat(14)}${numberOfPartsInHex}${twapId}${VERSION}`;
23
+ const isExpressHex = "00";
24
+ const buffer = "00".repeat(12);
25
+ return `${PREFIX}${buffer}${isExpressHex}${numberOfPartsInHex}${twapId}${VERSION}`;
13
26
  }
14
27
  export function decodeTwapUiFeeReceiver(address) {
15
- const twapId = address.slice(36, 40);
28
+ const byteString = address.slice(2);
29
+ const twapId = byteString.slice(34, 38);
30
+ const isExpress = byteString.slice(30, 32) === "01";
16
31
  if (!isValidTwapUiFeeReceiver(address) || twapId === "0000") {
17
32
  return;
18
33
  }
19
- const numberOfParts = parseInt(address.slice(34, 36), 16);
20
- return { twapId, numberOfParts };
34
+ const numberOfParts = parseInt(byteString.slice(32, 34), 16);
35
+ return { twapId, numberOfParts, isExpress };
21
36
  }
22
37
  export function isValidTwapUiFeeReceiver(address) {
23
38
  return isAddress(address) && address.toLowerCase().startsWith(PREFIX.toLowerCase());
24
39
  }
40
+ export function setUiFeeReceiverIsExpress(uiFeeReceiver, isExpress) {
41
+ const isExpressInHex = isExpress ? "01" : "00";
42
+ return `${uiFeeReceiver.slice(0, 27)}${isExpressInHex}${uiFeeReceiver.slice(29)}`;
43
+ }
@@ -2,52 +2,35 @@ import { Chain } from "viem/chains";
2
2
  export declare const AVALANCHE = 43114;
3
3
  export declare const AVALANCHE_FUJI = 43113;
4
4
  export declare const ARBITRUM = 42161;
5
- export declare const BSС_MAINNET = 56;
6
- export declare const BSС_TESTNET = 97;
7
5
  export declare const ETH_MAINNET = 1;
8
- export declare const SUPPORTED_CHAIN_IDS: number[];
9
- export declare const SUPPORTED_CHAIN_IDS_DEV: number[];
10
- export declare const CHAIN_NAMES_MAP: {
11
- 56: string;
12
- 97: string;
13
- 42161: string;
14
- 43114: string;
15
- 43113: string;
16
- };
17
- export declare const HIGH_EXECUTION_FEES_MAP: Record<number, number>;
6
+ export declare const BOTANIX = 3637;
7
+ export declare const SUPPORTED_CHAIN_IDS: UiSupportedChain[];
8
+ export declare const SUPPORTED_CHAIN_IDS_DEV: UiSupportedChain[];
9
+ export type UiContractsChain = typeof ARBITRUM | typeof AVALANCHE | typeof AVALANCHE_FUJI | typeof BOTANIX;
10
+ export type UiSupportedChain = UiContractsChain;
11
+ export declare const CHAIN_NAMES_MAP: Record<UiContractsChain, string>;
12
+ export declare const HIGH_EXECUTION_FEES_MAP: Record<UiContractsChain, number>;
18
13
  export declare const MAX_FEE_PER_GAS_MAP: Record<number, bigint>;
19
14
  export declare const GAS_PRICE_PREMIUM_MAP: Record<number, bigint>;
20
- export declare const MAX_PRIORITY_FEE_PER_GAS_MAP: Record<number, bigint | undefined>;
21
- export declare const EXCESSIVE_EXECUTION_FEES_MAP: Record<number, number>;
15
+ export declare const MAX_PRIORITY_FEE_PER_GAS_MAP: Record<UiSupportedChain, bigint | undefined>;
16
+ export declare const EXCESSIVE_EXECUTION_FEES_MAP: Record<UiSupportedChain, number>;
17
+ export declare const MIN_EXECUTION_FEE_USD: Record<UiSupportedChain, bigint | undefined>;
22
18
  export declare const GAS_PRICE_BUFFER_MAP: Record<number, bigint>;
19
+ export declare const botanix: Chain;
23
20
  export declare function getChainName(chainId: number): any;
24
21
  export declare const getViemChain: (chainId: number) => Chain;
25
- export declare function getHighExecutionFee(chainId: number): number;
26
- export declare function getExcessiveExecutionFee(chainId: number): number;
22
+ export declare function getHighExecutionFee(chainId: number): any;
23
+ export declare function getExcessiveExecutionFee(chainId: number): any;
27
24
  export declare function isSupportedChain(chainId: number, dev?: boolean): boolean;
28
25
  export declare const EXECUTION_FEE_CONFIG_V2: {
29
- [chainId: number]: {
26
+ [chainId in UiSupportedChain]: {
30
27
  shouldUseMaxPriorityFeePerGas: boolean;
31
28
  defaultBufferBps?: number;
32
29
  };
33
30
  };
34
- export declare const GAS_LIMITS_STATIC_CONFIG: {
35
- 42161: {
36
- createOrderGasLimit: bigint;
37
- updateOrderGasLimit: bigint;
38
- cancelOrderGasLimit: bigint;
39
- tokenPermitGasLimit: bigint;
40
- };
41
- 43114: {
42
- createOrderGasLimit: bigint;
43
- updateOrderGasLimit: bigint;
44
- cancelOrderGasLimit: bigint;
45
- tokenPermitGasLimit: bigint;
46
- };
47
- 43113: {
48
- createOrderGasLimit: bigint;
49
- updateOrderGasLimit: bigint;
50
- cancelOrderGasLimit: bigint;
51
- tokenPermitGasLimit: bigint;
52
- };
53
- };
31
+ export declare const GAS_LIMITS_STATIC_CONFIG: Record<UiSupportedChain, {
32
+ createOrderGasLimit: bigint;
33
+ updateOrderGasLimit: bigint;
34
+ cancelOrderGasLimit: bigint;
35
+ tokenPermitGasLimit: bigint;
36
+ }>;