@gmx-io/sdk 1.4.0 → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/build/cjs/src/abis/GlvReader.js +940 -940
  2. package/build/cjs/src/abis/IStargate.js +603 -0
  3. package/build/cjs/src/abis/LayerZeroProvider.js +273 -46
  4. package/build/cjs/src/abis/index.js +2 -2
  5. package/build/cjs/src/configs/batch.js +29 -103
  6. package/build/cjs/src/configs/chainIds.js +2 -2
  7. package/build/cjs/src/configs/chains.js +230 -151
  8. package/build/cjs/src/configs/contracts.js +1 -5
  9. package/build/cjs/src/configs/dataStore.js +5 -4
  10. package/build/cjs/src/configs/express.js +1 -1
  11. package/build/cjs/src/configs/gasLimits.js +41 -0
  12. package/build/cjs/src/configs/markets.js +102 -1
  13. package/build/cjs/src/configs/multichain.js +1 -0
  14. package/build/cjs/src/configs/oracleKeeper.js +18 -20
  15. package/build/cjs/src/configs/tokens.js +98 -180
  16. package/build/cjs/src/modules/markets/index.js +6 -2
  17. package/build/cjs/src/modules/markets/markets.spec.js +5 -5
  18. package/build/cjs/src/modules/markets/query-builders.js +8 -0
  19. package/build/cjs/src/modules/orders/helpers.js +4 -2
  20. package/build/cjs/src/modules/orders/helpers.spec.js +1 -1
  21. package/build/cjs/src/modules/orders/orders.spec.js +1 -1
  22. package/build/cjs/src/modules/positions/positions.spec.js +2 -2
  23. package/build/cjs/src/modules/tokens/tokens.spec.js +2 -2
  24. package/build/cjs/src/modules/trades/trades.spec.js +1 -1
  25. package/build/cjs/src/modules/utils/utils.js +7 -6
  26. package/build/cjs/src/prebuilt/hashedKinkModelMarketRatesKeys.json +64 -0
  27. package/build/cjs/src/prebuilt/hashedMarketConfigKeys.json +780 -0
  28. package/build/cjs/src/prebuilt/hashedMarketValuesKeys.json +120 -0
  29. package/build/cjs/src/test/mock.js +2 -0
  30. package/build/cjs/src/types/chains.js +2 -0
  31. package/build/cjs/src/types/orders.js +8 -2
  32. package/build/cjs/src/types/subsquid.js +241 -1
  33. package/build/cjs/src/types/tokens.js +7 -0
  34. package/build/cjs/src/utils/__tests__/abort.spec.js +122 -0
  35. package/build/cjs/src/utils/__tests__/numbers.spec.js +94 -14
  36. package/build/cjs/src/utils/abort.js +31 -0
  37. package/build/cjs/src/utils/callContract.js +4 -4
  38. package/build/cjs/src/utils/fees/executionFee.js +14 -11
  39. package/build/cjs/src/utils/fees/index.js +8 -2
  40. package/build/cjs/src/utils/marketKeysAndConfigs.js +8 -0
  41. package/build/cjs/src/utils/markets.js +7 -1
  42. package/build/cjs/src/utils/multicall.js +54 -17
  43. package/build/cjs/src/utils/numbers.js +25 -14
  44. package/build/cjs/src/utils/orders.js +2 -2
  45. package/build/cjs/src/utils/swap/__tests__/findSwapPathsBetweenTokens.spec.js +22 -0
  46. package/build/cjs/src/utils/swap/__tests__/mockRouting.spec.js +264 -6
  47. package/build/cjs/src/utils/swap/__tests__/swapRouting.spec.js +5 -4
  48. package/build/cjs/src/utils/swap/__tests__/swapStats.spec.js +10 -9
  49. package/build/cjs/src/utils/swap/buildSwapStrategy.js +20 -11
  50. package/build/cjs/src/utils/swap/findSwapPathsBetweenTokens.js +8 -4
  51. package/build/cjs/src/utils/swap/swapPath.js +6 -6
  52. package/build/cjs/src/utils/swap/swapRouting.js +8 -4
  53. package/build/cjs/src/utils/swap/swapStats.js +6 -6
  54. package/build/cjs/src/utils/swap/swapValues.js +17 -6
  55. package/build/cjs/src/utils/tokens.js +17 -1
  56. package/build/cjs/src/utils/trade/decrease.js +1 -1
  57. package/build/cjs/src/utils/trade/increase.js +3 -0
  58. package/build/esm/src/abis/GlvReader.js +940 -940
  59. package/build/esm/src/abis/IStargate.js +601 -0
  60. package/build/esm/src/abis/LayerZeroProvider.js +273 -46
  61. package/build/esm/src/abis/index.js +2 -2
  62. package/build/esm/src/configs/batch.js +30 -104
  63. package/build/esm/src/configs/chainIds.js +1 -1
  64. package/build/esm/src/configs/chains.js +212 -147
  65. package/build/esm/src/configs/contracts.js +1 -5
  66. package/build/esm/src/configs/dataStore.js +1 -0
  67. package/build/esm/src/configs/express.js +1 -1
  68. package/build/esm/src/configs/gasLimits.js +38 -0
  69. package/build/esm/src/configs/markets.js +95 -1
  70. package/build/esm/src/configs/multichain.js +2 -1
  71. package/build/esm/src/configs/oracleKeeper.js +17 -19
  72. package/build/esm/src/configs/tokens.js +97 -179
  73. package/build/esm/src/modules/markets/index.js +6 -2
  74. package/build/esm/src/modules/markets/markets.spec.js +5 -5
  75. package/build/esm/src/modules/markets/query-builders.js +8 -0
  76. package/build/esm/src/modules/orders/helpers.js +5 -3
  77. package/build/esm/src/modules/orders/helpers.spec.js +1 -1
  78. package/build/esm/src/modules/orders/orders.spec.js +1 -1
  79. package/build/esm/src/modules/positions/positions.spec.js +2 -2
  80. package/build/esm/src/modules/tokens/tokens.spec.js +2 -2
  81. package/build/esm/src/modules/trades/trades.spec.js +1 -1
  82. package/build/esm/src/modules/utils/utils.js +7 -6
  83. package/build/esm/src/prebuilt/hashedKinkModelMarketRatesKeys.json +64 -0
  84. package/build/esm/src/prebuilt/hashedMarketConfigKeys.json +780 -0
  85. package/build/esm/src/prebuilt/hashedMarketValuesKeys.json +120 -0
  86. package/build/esm/src/test/mock.js +2 -0
  87. package/build/esm/src/types/chains.js +1 -0
  88. package/build/esm/src/types/orders.js +8 -2
  89. package/build/esm/src/types/subsquid.js +240 -0
  90. package/build/esm/src/types/tokens.js +6 -1
  91. package/build/esm/src/utils/__tests__/abort.spec.js +120 -0
  92. package/build/esm/src/utils/__tests__/numbers.spec.js +95 -15
  93. package/build/esm/src/utils/abort.js +27 -0
  94. package/build/esm/src/utils/callContract.js +5 -5
  95. package/build/esm/src/utils/fees/executionFee.js +15 -12
  96. package/build/esm/src/utils/fees/index.js +8 -2
  97. package/build/esm/src/utils/marketKeysAndConfigs.js +9 -1
  98. package/build/esm/src/utils/markets.js +5 -0
  99. package/build/esm/src/utils/multicall.js +53 -16
  100. package/build/esm/src/utils/numbers.js +21 -12
  101. package/build/esm/src/utils/orders.js +3 -3
  102. package/build/esm/src/utils/swap/__tests__/findSwapPathsBetweenTokens.spec.js +22 -0
  103. package/build/esm/src/utils/swap/__tests__/mockRouting.spec.js +264 -6
  104. package/build/esm/src/utils/swap/__tests__/swapRouting.spec.js +5 -4
  105. package/build/esm/src/utils/swap/__tests__/swapStats.spec.js +10 -9
  106. package/build/esm/src/utils/swap/buildSwapStrategy.js +21 -12
  107. package/build/esm/src/utils/swap/findSwapPathsBetweenTokens.js +8 -4
  108. package/build/esm/src/utils/swap/swapPath.js +6 -6
  109. package/build/esm/src/utils/swap/swapRouting.js +8 -4
  110. package/build/esm/src/utils/swap/swapStats.js +6 -6
  111. package/build/esm/src/utils/swap/swapValues.js +18 -7
  112. package/build/esm/src/utils/tokens.js +15 -1
  113. package/build/esm/src/utils/trade/decrease.js +2 -2
  114. package/build/esm/src/utils/trade/increase.js +3 -0
  115. package/build/types/src/abis/IStargate.d.ts +464 -0
  116. package/build/types/src/abis/LayerZeroProvider.d.ts +12 -0
  117. package/build/types/src/abis/index.d.ts +475 -99
  118. package/build/types/src/configs/chainIds.d.ts +1 -1
  119. package/build/types/src/configs/chains.d.ts +170 -27
  120. package/build/types/src/configs/contracts.d.ts +0 -4
  121. package/build/types/src/configs/dataStore.d.ts +1 -0
  122. package/build/types/src/configs/express.d.ts +1 -1
  123. package/build/types/src/configs/gasLimits.d.ts +4 -0
  124. package/build/types/src/configs/markets.d.ts +10 -1
  125. package/build/types/src/configs/oracleKeeper.d.ts +13 -0
  126. package/build/types/src/configs/tokens.d.ts +3 -0
  127. package/build/types/src/index.d.ts +1 -1
  128. package/build/types/src/modules/base.d.ts +1 -1
  129. package/build/types/src/modules/markets/index.d.ts +2 -0
  130. package/build/types/src/modules/markets/query-builders.d.ts +1 -1
  131. package/build/types/src/modules/markets/types.d.ts +2 -2
  132. package/build/types/src/modules/utils/utils.d.ts +2 -3
  133. package/build/types/src/types/chains.d.ts +57 -0
  134. package/build/types/src/types/markets.d.ts +2 -0
  135. package/build/types/src/types/orders.d.ts +8 -2
  136. package/build/types/src/types/subsquid.d.ts +5987 -5172
  137. package/build/types/src/types/tokens.d.ts +11 -6
  138. package/build/types/src/types/trade.d.ts +5 -0
  139. package/build/types/src/utils/__tests__/abort.spec.d.ts +1 -0
  140. package/build/types/src/utils/abort.d.ts +1 -0
  141. package/build/types/src/utils/fees/estimateOraclePriceCount.d.ts +2 -2
  142. package/build/types/src/utils/fees/executionFee.d.ts +6 -6
  143. package/build/types/src/utils/fees/index.d.ts +2 -1
  144. package/build/types/src/utils/marketKeysAndConfigs.d.ts +2 -0
  145. package/build/types/src/utils/markets.d.ts +4 -2
  146. package/build/types/src/utils/multicall.d.ts +4 -2
  147. package/build/types/src/utils/numbers.d.ts +8 -1
  148. package/build/types/src/utils/swap/buildSwapStrategy.d.ts +8 -3
  149. package/build/types/src/utils/swap/swapPath.d.ts +2 -1
  150. package/build/types/src/utils/swap/swapRouting.d.ts +7 -2
  151. package/build/types/src/utils/swap/swapStats.d.ts +3 -2
  152. package/build/types/src/utils/swap/swapValues.d.ts +3 -1
  153. package/build/types/src/utils/tokens.d.ts +3 -0
  154. package/package.json +17 -5
  155. package/build/cjs/src/abis/MultichainUtils.js +0 -133
  156. package/build/esm/src/abis/MultichainUtils.js +0 -131
  157. package/build/types/src/abis/MultichainUtils.d.ts +0 -100
@@ -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, 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, formatTokenAmount, 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
@@ -229,38 +229,39 @@ describe("formatAmountHuman", () => {
229
229
  });
230
230
  });
231
231
  describe("formatBalanceAmount", () => {
232
+ const NBSP = "\u00a0";
232
233
  it("should display balance amount", () => {
233
- expect(formatBalanceAmount(ONE_USD * 1000n, USD_DECIMALS)).toBe("1,000.0000");
234
+ expect(formatBalanceAmount(ONE_USD * 1000n, USD_DECIMALS)).toBe("1,000.00");
234
235
  expect(formatBalanceAmount(0n, USD_DECIMALS)).toBe("-");
235
236
  expect(formatBalanceAmount(0n, USD_DECIMALS, undefined, { showZero: true })).toBe("0.0000");
236
237
  expect(formatBalanceAmount(ONE_USD * 1n, USD_DECIMALS)).toBe("1.0000");
237
238
  expect(formatBalanceAmount(ONE_USD / 10n, USD_DECIMALS)).toBe("0.10000");
238
239
  expect(formatBalanceAmount(ONE_USD / 100n, USD_DECIMALS)).toBe("0.010000");
239
240
  expect(formatBalanceAmount(ONE_USD / 1000n, USD_DECIMALS)).toBe("0.0010000");
240
- expect(formatBalanceAmount(ONE_USD / 10000n, USD_DECIMALS)).toBe("0.00010000");
241
+ expect(formatBalanceAmount(ONE_USD / 10000n, USD_DECIMALS)).toBe("0.0001000");
241
242
  expect(formatBalanceAmount(ONE_USD / 100000n, USD_DECIMALS)).toBe("0.00001000");
242
- expect(formatBalanceAmount(ONE_USD / 1000000n, USD_DECIMALS)).toBe("0.00000100");
243
- expect(formatBalanceAmount(ONE_USD / 10000000n, USD_DECIMALS)).toBe("0.00000010");
244
- expect(formatBalanceAmount(ONE_USD / 100000000n, USD_DECIMALS)).toBe("0.00000001");
243
+ expect(formatBalanceAmount(ONE_USD / 1000000n, USD_DECIMALS)).toBe("0.000001000");
244
+ expect(formatBalanceAmount(ONE_USD / 10000000n, USD_DECIMALS)).toBe("0.000000100");
245
+ expect(formatBalanceAmount(ONE_USD / 100000000n, USD_DECIMALS)).toBe("0.000000010");
245
246
  expect(formatBalanceAmount(ONE_USD / 1000000000n, USD_DECIMALS)).toBe("1.00e-9");
246
247
  expect(formatBalanceAmount(ONE_USD / 1000000000000n, USD_DECIMALS)).toBe("1.00e-12");
247
248
  expect(formatBalanceAmount(ONE_USD * -1n, USD_DECIMALS)).toBe("-1.0000");
248
249
  });
249
250
  it("should display balance amount with symbol", () => {
250
- expect(formatBalanceAmount(ONE_USD, USD_DECIMALS, "USDC")).toBe("1.0000 USDC");
251
- expect(formatBalanceAmount(0n, USD_DECIMALS, "USDC", { showZero: true })).toBe("0.0000 USDC");
251
+ expect(formatBalanceAmount(ONE_USD, USD_DECIMALS, "USDC")).toBe(`1.0000${NBSP}USDC`);
252
+ expect(formatBalanceAmount(0n, USD_DECIMALS, "USDC", { showZero: true })).toBe(`0.0000${NBSP}USDC`);
252
253
  expect(formatBalanceAmount(0n, USD_DECIMALS, "USDC", { showZero: false })).toBe("-");
253
254
  });
254
255
  it("should display balance of stable token correctly", () => {
255
256
  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");
257
+ expect(formatBalanceAmount(ONE_USD / 10n, USD_DECIMALS, undefined, { isStable: true })).toBe("0.10");
258
+ expect(formatBalanceAmount(ONE_USD / 100n, USD_DECIMALS, undefined, { isStable: true })).toBe("0.010");
259
+ expect(formatBalanceAmount(ONE_USD / 1000n, USD_DECIMALS, undefined, { isStable: true })).toBe("0.0010");
260
+ expect(formatBalanceAmount(ONE_USD / 10000n, USD_DECIMALS, undefined, { isStable: true })).toBe("0.00010");
261
+ expect(formatBalanceAmount(ONE_USD / 100000n, USD_DECIMALS, undefined, { isStable: true })).toBe("0.000010");
262
+ expect(formatBalanceAmount(ONE_USD / 1000000n, USD_DECIMALS, undefined, { isStable: true })).toBe("0.0000010");
262
263
  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 / 100000000n, USD_DECIMALS, undefined, { isStable: true })).toBe("0.000000010");
264
265
  expect(formatBalanceAmount(ONE_USD / 1000000000n, USD_DECIMALS, undefined, { isStable: true })).toBe("1.00e-9");
265
266
  expect(formatBalanceAmount(0n, USD_DECIMALS, undefined, { isStable: true, showZero: true })).toBe("0.00");
266
267
  expect(formatBalanceAmount(ONE_USD, USD_DECIMALS, undefined, { isStable: true, signed: true })).toBe("+1.00");
@@ -306,3 +307,82 @@ describe("formatPercentage", () => {
306
307
  expect(formatPercentage(toBigNumberWithDecimals("0.999", PERCENT_PRECISION_DECIMALS), { bps: false, displayDecimals: 5 })).toBe("0.99900%");
307
308
  });
308
309
  });
310
+ describe("formatTokenAmount", () => {
311
+ const TOKEN_DECIMALS = 18;
312
+ const ONE_TOKEN = expandDecimals(1, TOKEN_DECIMALS);
313
+ const NBSP = "\u00a0";
314
+ it("should return undefined for undefined amount without fallbackToZero", () => {
315
+ expect(formatTokenAmount(undefined, TOKEN_DECIMALS)).toBeUndefined();
316
+ expect(formatTokenAmount(undefined, TOKEN_DECIMALS, "ETH")).toBeUndefined();
317
+ });
318
+ it("should return zero with fallbackToZero", () => {
319
+ expect(formatTokenAmount(undefined, TOKEN_DECIMALS, undefined, { fallbackToZero: true })).toBe("0.0000");
320
+ expect(formatTokenAmount(undefined, TOKEN_DECIMALS, "ETH", { fallbackToZero: true })).toBe(`0.0000${NBSP}ETH`);
321
+ });
322
+ it("should format token amount with symbol", () => {
323
+ expect(formatTokenAmount(ONE_TOKEN, TOKEN_DECIMALS, "ETH")).toBe(`1.0000${NBSP}ETH`);
324
+ expect(formatTokenAmount(ONE_TOKEN * 100n, TOKEN_DECIMALS, "ETH")).toBe(`100.000${NBSP}ETH`);
325
+ });
326
+ it("should format token amount without symbol", () => {
327
+ expect(formatTokenAmount(ONE_TOKEN, TOKEN_DECIMALS)).toBe("1.0000");
328
+ expect(formatTokenAmount(ONE_TOKEN * 1000n, TOKEN_DECIMALS)).toBe("1000.00");
329
+ });
330
+ it("should adjust decimals based on amount magnitude (non-stable)", () => {
331
+ expect(formatTokenAmount(ONE_TOKEN * 1000n, TOKEN_DECIMALS)).toBe("1000.00");
332
+ expect(formatTokenAmount(ONE_TOKEN * 100n, TOKEN_DECIMALS)).toBe("100.000");
333
+ expect(formatTokenAmount(ONE_TOKEN * 10n, TOKEN_DECIMALS)).toBe("10.0000");
334
+ expect(formatTokenAmount(ONE_TOKEN, TOKEN_DECIMALS)).toBe("1.0000");
335
+ expect(formatTokenAmount(ONE_TOKEN / 10n, TOKEN_DECIMALS)).toBe("0.10000");
336
+ expect(formatTokenAmount(ONE_TOKEN / 100n, TOKEN_DECIMALS)).toBe("0.010000");
337
+ expect(formatTokenAmount(ONE_TOKEN / 1000n, TOKEN_DECIMALS)).toBe("0.0010000");
338
+ expect(formatTokenAmount(ONE_TOKEN / 10000n, TOKEN_DECIMALS)).toBe("0.0001000");
339
+ });
340
+ it("should adjust decimals based on amount magnitude (stable)", () => {
341
+ expect(formatTokenAmount(ONE_TOKEN * 1000n, TOKEN_DECIMALS, undefined, { isStable: true })).toBe("1000.00");
342
+ expect(formatTokenAmount(ONE_TOKEN * 100n, TOKEN_DECIMALS, undefined, { isStable: true })).toBe("100.00");
343
+ expect(formatTokenAmount(ONE_TOKEN * 10n, TOKEN_DECIMALS, undefined, { isStable: true })).toBe("10.00");
344
+ expect(formatTokenAmount(ONE_TOKEN, TOKEN_DECIMALS, undefined, { isStable: true })).toBe("1.00");
345
+ expect(formatTokenAmount(ONE_TOKEN / 10n, TOKEN_DECIMALS, undefined, { isStable: true })).toBe("0.10");
346
+ expect(formatTokenAmount(ONE_TOKEN / 100n, TOKEN_DECIMALS, undefined, { isStable: true })).toBe("0.010");
347
+ expect(formatTokenAmount(ONE_TOKEN / 1000n, TOKEN_DECIMALS, undefined, { isStable: true })).toBe("0.0010");
348
+ expect(formatTokenAmount(ONE_TOKEN / 10000n, TOKEN_DECIMALS, undefined, { isStable: true })).toBe("0.00010");
349
+ });
350
+ it("should respect explicit displayDecimals override", () => {
351
+ expect(formatTokenAmount(ONE_TOKEN, TOKEN_DECIMALS, undefined, { displayDecimals: 2 })).toBe("1.00");
352
+ expect(formatTokenAmount(ONE_TOKEN, TOKEN_DECIMALS, undefined, { displayDecimals: 6 })).toBe("1.000000");
353
+ expect(formatTokenAmount(ONE_TOKEN / 10n, TOKEN_DECIMALS, undefined, { displayDecimals: 2 })).toBe("0.10");
354
+ });
355
+ it("should format with commas when useCommas is true", () => {
356
+ expect(formatTokenAmount(ONE_TOKEN * 1000000n, TOKEN_DECIMALS, undefined, { useCommas: true })).toBe("1,000,000.00");
357
+ expect(formatTokenAmount(ONE_TOKEN * 123456n, TOKEN_DECIMALS, "ETH", { useCommas: true })).toBe(`123,456.00${NBSP}ETH`);
358
+ });
359
+ it("should show all significant digits with showAllSignificant", () => {
360
+ const preciseAmount = ONE_TOKEN + ONE_TOKEN / 123456789n;
361
+ expect(formatTokenAmount(preciseAmount, TOKEN_DECIMALS, undefined, { showAllSignificant: true })).not.toContain("...");
362
+ });
363
+ it("should display plus sign for positive values with displayPlus", () => {
364
+ expect(formatTokenAmount(ONE_TOKEN, TOKEN_DECIMALS, undefined, { displayPlus: true })).toBe("+1.0000");
365
+ expect(formatTokenAmount(-ONE_TOKEN, TOKEN_DECIMALS, undefined, { displayPlus: true })).toBe("-1.0000");
366
+ });
367
+ it("should handle negative amounts", () => {
368
+ expect(formatTokenAmount(-ONE_TOKEN, TOKEN_DECIMALS)).toBe("-1.0000");
369
+ expect(formatTokenAmount(-ONE_TOKEN * 100n, TOKEN_DECIMALS, "ETH")).toBe(`-100.000${NBSP}ETH`);
370
+ });
371
+ it("should handle zero amount", () => {
372
+ expect(formatTokenAmount(0n, TOKEN_DECIMALS)).toBe("0.00");
373
+ expect(formatTokenAmount(0n, TOKEN_DECIMALS, "ETH")).toBe(`0.00${NBSP}ETH`);
374
+ expect(formatTokenAmount(0n, TOKEN_DECIMALS, undefined, { isStable: true })).toBe("0.00");
375
+ });
376
+ it("should handle maxThreshold", () => {
377
+ const result = formatTokenAmount(ONE_TOKEN * 10000000000n, TOKEN_DECIMALS, undefined, {
378
+ maxThreshold: "1000000000",
379
+ });
380
+ expect(result).toContain(">");
381
+ });
382
+ it("should handle minThreshold", () => {
383
+ const result = formatTokenAmount(ONE_TOKEN / 1000000000n, TOKEN_DECIMALS, undefined, {
384
+ minThreshold: "0.00000001",
385
+ });
386
+ expect(result).toContain("<");
387
+ });
388
+ });
@@ -0,0 +1,27 @@
1
+ export function combineAbortSignals(...signals) {
2
+ const controller = new AbortController();
3
+ const abortHandler = () => {
4
+ for (const signal of signals) {
5
+ signal.removeEventListener("abort", abortHandler);
6
+ }
7
+ controller.abort();
8
+ };
9
+ const signalsWithListeners = [];
10
+ for (const signal of signals) {
11
+ if (signal.aborted) {
12
+ for (const signalWithListener of signalsWithListeners) {
13
+ signalWithListener.removeEventListener("abort", abortHandler);
14
+ }
15
+ controller.abort();
16
+ return controller;
17
+ }
18
+ signal.addEventListener("abort", abortHandler);
19
+ signalsWithListeners.push(signal);
20
+ }
21
+ controller.signal.addEventListener("abort", () => {
22
+ for (const signal of signals) {
23
+ signal.removeEventListener("abort", abortHandler);
24
+ }
25
+ });
26
+ return controller;
27
+ }
@@ -1,10 +1,10 @@
1
1
  import { encodeFunctionData, withRetry } from "viem";
2
- import { GAS_PRICE_BUFFER_MAP, GAS_PRICE_PREMIUM_MAP, getViemChain, MAX_FEE_PER_GAS_MAP, MAX_PRIORITY_FEE_PER_GAS_MAP, } from "../configs/chains";
2
+ import { getGasPriceBuffer, getGasPricePremium, getMaxFeePerGas, getMaxPriorityFeePerGas, getViemChain, } from "../configs/chains";
3
3
  import { BASIS_POINTS_DIVISOR_BIGINT } from "../configs/factors";
4
4
  import { bigMath } from "./bigmath";
5
5
  export async function getGasPrice(client, chainId) {
6
- let maxFeePerGas = MAX_FEE_PER_GAS_MAP[chainId];
7
- const premium = GAS_PRICE_PREMIUM_MAP[chainId] || 0n;
6
+ let maxFeePerGas = getMaxFeePerGas(chainId);
7
+ const premium = getGasPricePremium(chainId) || 0n;
8
8
  const feeData = await withRetry(() => client.estimateFeesPerGas({
9
9
  type: "legacy",
10
10
  chain: getViemChain(chainId),
@@ -25,7 +25,7 @@ export async function getGasPrice(client, chainId) {
25
25
  const block = await client.getBlock({ blockTag: "pending" });
26
26
  if (block.baseFeePerGas !== undefined && block.baseFeePerGas !== null) {
27
27
  const baseFeePerGas = block.baseFeePerGas;
28
- const maxPriorityFeePerGas = bigMath.max(MAX_PRIORITY_FEE_PER_GAS_MAP[chainId] ?? 0n, premium);
28
+ const maxPriorityFeePerGas = bigMath.max(getMaxPriorityFeePerGas(chainId) || 0n, premium);
29
29
  // Calculate maxFeePerGas
30
30
  const calculatedMaxFeePerGas = baseFeePerGas + maxPriorityFeePerGas + premium;
31
31
  return {
@@ -37,7 +37,7 @@ export async function getGasPrice(client, chainId) {
37
37
  if (gasPrice === null || gasPrice === undefined) {
38
38
  throw new Error("Can't fetch gas price");
39
39
  }
40
- const bufferBps = GAS_PRICE_BUFFER_MAP[chainId] || 0n;
40
+ const bufferBps = getGasPriceBuffer(chainId) || 0n;
41
41
  const buffer = bigMath.mulDiv(gasPrice, bufferBps, BASIS_POINTS_DIVISOR_BIGINT);
42
42
  return {
43
43
  gasPrice: gasPrice + buffer + premium,
@@ -1,4 +1,4 @@
1
- import { getExcessiveExecutionFee, getHighExecutionFee, MIN_EXECUTION_FEE_USD } from "../../configs/chains";
1
+ import { getExcessiveExecutionFee, getHighExecutionFee, getMinExecutionFeeUsd } 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";
@@ -18,7 +18,7 @@ tokensData, estimatedGasLimit, gasPrice, oraclePriceCount, numberOfParts) {
18
18
  const gasLimit = baseGasLimit + applyFactor(estimatedGasLimit, multiplierFactor);
19
19
  // #endregion
20
20
  // avoid botanix gas spikes when chain is not actively used
21
- const minGasCostUsd = MIN_EXECUTION_FEE_USD[chainId];
21
+ const minGasCostUsd = getMinExecutionFeeUsd(chainId);
22
22
  const minGasCost = convertToTokenAmount(minGasCostUsd, nativeToken.decimals, nativeToken.prices.minPrice);
23
23
  let feeTokenAmountPerExecution = gasLimit * gasPrice;
24
24
  if (minGasCost) {
@@ -117,11 +117,11 @@ export function estimateExecuteSwapOrderGasLimit(gasLimits, order) {
117
117
  */
118
118
  export function estimateExecuteDepositGasLimit(gasLimits, deposit) {
119
119
  const gasPerSwap = gasLimits.singleSwap;
120
- const swapsCount = BigInt((deposit.longTokenSwapsCount ?? 0) + (deposit.shortTokenSwapsCount ?? 0));
120
+ const swapsCount = BigInt(deposit.swapsCount ?? 0);
121
121
  const gasForSwaps = swapsCount * gasPerSwap;
122
122
  return gasLimits.depositToken + (deposit.callbackGasLimit ?? 0n) + gasForSwaps;
123
123
  }
124
- export function estimateExecuteGlvDepositGasLimit(gasLimits, { marketsCount, isMarketTokenDeposit, }) {
124
+ export function estimateExecuteGlvDepositGasLimit(gasLimits, { marketsCount, isMarketTokenDeposit, swapsCount, }) {
125
125
  const gasPerGlvPerMarket = gasLimits.glvPerMarketGasLimit;
126
126
  const gasForGlvMarkets = gasPerGlvPerMarket * marketsCount;
127
127
  const glvDepositGasLimit = gasLimits.glvDepositGasLimit;
@@ -129,14 +129,18 @@ export function estimateExecuteGlvDepositGasLimit(gasLimits, { marketsCount, isM
129
129
  if (isMarketTokenDeposit) {
130
130
  return gasLimit;
131
131
  }
132
- return gasLimit + gasLimits.depositToken;
132
+ const gasPerSwap = gasLimits.singleSwap;
133
+ const gasForSwaps = swapsCount * gasPerSwap;
134
+ return gasLimit + gasLimits.depositToken + gasForSwaps;
133
135
  }
134
- export function estimateExecuteGlvWithdrawalGasLimit(gasLimits, { marketsCount, }) {
136
+ export function estimateExecuteGlvWithdrawalGasLimit(gasLimits, { marketsCount, swapsCount, }) {
135
137
  const gasPerGlvPerMarket = gasLimits.glvPerMarketGasLimit;
136
138
  const gasForGlvMarkets = gasPerGlvPerMarket * marketsCount;
137
139
  const glvWithdrawalGasLimit = gasLimits.glvWithdrawalGasLimit;
138
140
  const gasLimit = glvWithdrawalGasLimit + gasForGlvMarkets;
139
- return gasLimit + gasLimits.withdrawalMultiToken;
141
+ const gasPerSwap = gasLimits.singleSwap;
142
+ const gasForSwaps = swapsCount * gasPerSwap;
143
+ return gasLimit + gasLimits.withdrawalMultiToken + gasForSwaps;
140
144
  }
141
145
  /**
142
146
  * Only GM withdrawals. Do not confuse with decrease with zero delta size.
@@ -144,11 +148,10 @@ export function estimateExecuteGlvWithdrawalGasLimit(gasLimits, { marketsCount,
144
148
  * Copy from contract: `estimateExecuteWithdrawalGasLimit`
145
149
  */
146
150
  export function estimateExecuteWithdrawalGasLimit(gasLimits, withdrawal) {
147
- // Swap is not used but supported in the contract.
148
- // const gasPerSwap = gasLimits.singleSwap;
149
- // const swapsCount = 0n;
150
- // const gasForSwaps = swapsCount * gasPerSwap;
151
- return gasLimits.withdrawalMultiToken + (withdrawal.callbackGasLimit ?? 0n);
151
+ const gasPerSwap = gasLimits.singleSwap;
152
+ const swapsCount = withdrawal.swapsCount ?? 0n;
153
+ const gasForSwaps = swapsCount * gasPerSwap;
154
+ return gasLimits.withdrawalMultiToken + (withdrawal.callbackGasLimit ?? 0n) + gasForSwaps;
152
155
  }
153
156
  /**
154
157
  * Copy from contract: `estimateExecuteShiftGasLimit`
@@ -1,15 +1,21 @@
1
1
  import { HIGH_PRICE_IMPACT_BPS } from "../../configs/factors";
2
+ import { SwapPricingType } from "../../types/orders";
2
3
  import { bigMath } from "../bigmath";
3
4
  import { getOpenInterestForBalance } from "../markets";
4
5
  import { applyFactor, getBasisPoints, PRECISION } from "../numbers";
5
6
  export * from "./estimateOraclePriceCount";
6
7
  export * from "./executionFee";
7
8
  export * from "./priceImpact";
8
- export function getSwapFee(marketInfo, swapAmount, balanceWasImproved, isAtomicSwap) {
9
+ export function getSwapFee(marketInfo, swapAmount, balanceWasImproved, swapPricingType) {
9
10
  let factor;
10
- if (isAtomicSwap) {
11
+ if (swapPricingType === SwapPricingType.AtomicSwap) {
11
12
  factor = marketInfo.atomicSwapFeeFactor;
12
13
  }
14
+ else if (swapPricingType === SwapPricingType.Withdrawal) {
15
+ factor = balanceWasImproved
16
+ ? marketInfo.withdrawalFeeFactorBalanceWasImproved ?? marketInfo.swapFeeFactorForBalanceWasImproved
17
+ : marketInfo.withdrawalFeeFactorBalanceWasNotImproved ?? marketInfo.swapFeeFactorForBalanceWasNotImproved;
18
+ }
13
19
  else {
14
20
  factor = balanceWasImproved
15
21
  ? marketInfo.swapFeeFactorForBalanceWasImproved
@@ -1,4 +1,4 @@
1
- import { ATOMIC_SWAP_FEE_FACTOR_KEY, BORROWING_EXPONENT_FACTOR_KEY, BORROWING_FACTOR_KEY, FUNDING_DECREASE_FACTOR_PER_SECOND, FUNDING_EXPONENT_FACTOR_KEY, FUNDING_FACTOR_KEY, FUNDING_INCREASE_FACTOR_PER_SECOND, IS_MARKET_DISABLED_KEY, LENT_POSITION_IMPACT_POOL_AMOUNT_KEY, MAX_FUNDING_FACTOR_PER_SECOND, MAX_LENDABLE_IMPACT_FACTOR_FOR_WITHDRAWALS_KEY, MAX_LENDABLE_IMPACT_FACTOR_KEY, MAX_LENDABLE_IMPACT_USD_KEY, MAX_OPEN_INTEREST_KEY, MAX_PNL_FACTOR_FOR_TRADERS_KEY, MAX_PNL_FACTOR_KEY, MAX_POOL_AMOUNT_KEY, MAX_POOL_USD_FOR_DEPOSIT_KEY, MAX_POSITION_IMPACT_FACTOR_FOR_LIQUIDATIONS_KEY, MAX_POSITION_IMPACT_FACTOR_KEY, MIN_COLLATERAL_FACTOR_FOR_LIQUIDATION_KEY, MIN_COLLATERAL_FACTOR_FOR_OPEN_INTEREST_MULTIPLIER_KEY, MIN_COLLATERAL_FACTOR_KEY, MIN_FUNDING_FACTOR_PER_SECOND, MIN_POSITION_IMPACT_POOL_AMOUNT_KEY, OPEN_INTEREST_IN_TOKENS_KEY, OPEN_INTEREST_KEY, OPEN_INTEREST_RESERVE_FACTOR_KEY, POOL_AMOUNT_KEY, POSITION_FEE_FACTOR_KEY, POSITION_IMPACT_EXPONENT_FACTOR_KEY, POSITION_IMPACT_FACTOR_KEY, POSITION_IMPACT_POOL_AMOUNT_KEY, POSITION_IMPACT_POOL_DISTRIBUTION_RATE_KEY, RESERVE_FACTOR_KEY, SWAP_FEE_FACTOR_KEY, SWAP_IMPACT_EXPONENT_FACTOR_KEY, SWAP_IMPACT_FACTOR_KEY, SWAP_IMPACT_POOL_AMOUNT_KEY, THRESHOLD_FOR_DECREASE_FUNDING, THRESHOLD_FOR_STABLE_FUNDING, VIRTUAL_MARKET_ID_KEY, VIRTUAL_TOKEN_ID_KEY, } from "../configs/dataStore";
1
+ import { ATOMIC_SWAP_FEE_FACTOR_KEY, BORROWING_EXPONENT_FACTOR_KEY, BORROWING_FACTOR_KEY, FUNDING_DECREASE_FACTOR_PER_SECOND, FUNDING_EXPONENT_FACTOR_KEY, FUNDING_FACTOR_KEY, FUNDING_INCREASE_FACTOR_PER_SECOND, IS_MARKET_DISABLED_KEY, LENT_POSITION_IMPACT_POOL_AMOUNT_KEY, MAX_FUNDING_FACTOR_PER_SECOND, MAX_LENDABLE_IMPACT_FACTOR_FOR_WITHDRAWALS_KEY, MAX_LENDABLE_IMPACT_FACTOR_KEY, MAX_LENDABLE_IMPACT_USD_KEY, MAX_OPEN_INTEREST_KEY, MAX_PNL_FACTOR_FOR_TRADERS_KEY, MAX_PNL_FACTOR_KEY, MAX_POOL_AMOUNT_KEY, MAX_POOL_USD_FOR_DEPOSIT_KEY, MAX_POSITION_IMPACT_FACTOR_FOR_LIQUIDATIONS_KEY, MAX_POSITION_IMPACT_FACTOR_KEY, MIN_COLLATERAL_FACTOR_FOR_LIQUIDATION_KEY, MIN_COLLATERAL_FACTOR_FOR_OPEN_INTEREST_MULTIPLIER_KEY, MIN_COLLATERAL_FACTOR_KEY, MIN_FUNDING_FACTOR_PER_SECOND, MIN_POSITION_IMPACT_POOL_AMOUNT_KEY, OPEN_INTEREST_IN_TOKENS_KEY, OPEN_INTEREST_KEY, OPEN_INTEREST_RESERVE_FACTOR_KEY, POOL_AMOUNT_KEY, POSITION_FEE_FACTOR_KEY, POSITION_IMPACT_EXPONENT_FACTOR_KEY, POSITION_IMPACT_FACTOR_KEY, POSITION_IMPACT_POOL_AMOUNT_KEY, POSITION_IMPACT_POOL_DISTRIBUTION_RATE_KEY, RESERVE_FACTOR_KEY, SWAP_FEE_FACTOR_KEY, SWAP_IMPACT_EXPONENT_FACTOR_KEY, SWAP_IMPACT_FACTOR_KEY, SWAP_IMPACT_POOL_AMOUNT_KEY, THRESHOLD_FOR_DECREASE_FUNDING, THRESHOLD_FOR_STABLE_FUNDING, VIRTUAL_MARKET_ID_KEY, VIRTUAL_TOKEN_ID_KEY, WITHDRAWAL_FEE_FACTOR_KEY, } from "../configs/dataStore";
2
2
  import { hashDataMap } from "./hash";
3
3
  export function hashMarketConfigKeys(market) {
4
4
  const marketAddress = market.marketTokenAddress;
@@ -203,6 +203,14 @@ export function hashMarketConfigKeys(market) {
203
203
  ["bytes32", "address"],
204
204
  [SWAP_IMPACT_EXPONENT_FACTOR_KEY, marketAddress],
205
205
  ],
206
+ withdrawalFeeFactorBalanceWasImproved: [
207
+ ["bytes32", "address", "bool"],
208
+ [WITHDRAWAL_FEE_FACTOR_KEY, marketAddress, true],
209
+ ],
210
+ withdrawalFeeFactorBalanceWasNotImproved: [
211
+ ["bytes32", "address", "bool"],
212
+ [WITHDRAWAL_FEE_FACTOR_KEY, marketAddress, false],
213
+ ],
206
214
  virtualMarketId: [
207
215
  ["bytes32", "address"],
208
216
  [VIRTUAL_MARKET_ID_KEY, marketAddress],
@@ -101,6 +101,11 @@ export function getOppositeCollateral(marketInfo, tokenAddress) {
101
101
  }
102
102
  return undefined;
103
103
  }
104
+ export function getOppositeCollateralFromConfig(marketConfig, tokenAddress) {
105
+ return marketConfig.shortTokenAddress === tokenAddress
106
+ ? marketConfig.longTokenAddress
107
+ : marketConfig.shortTokenAddress;
108
+ }
104
109
  export function getAvailableUsdLiquidityForCollateral(marketInfo, isLong) {
105
110
  const poolUsd = getPoolUsdWithoutPnl(marketInfo, isLong, "minPrice");
106
111
  if (marketInfo.isSpotOnly) {
@@ -1,6 +1,8 @@
1
1
  import { abis as allAbis } from "../abis";
2
2
  import { sleep } from "./common";
3
- export const MAX_TIMEOUT = 20000;
3
+ export const MAX_TIMEOUT = 40000;
4
+ export const MAX_CALLS_PER_BATCH = 1000;
5
+ export const MAX_CONCURRENT_BATCHES = 1;
4
6
  export class Multicall {
5
7
  static async getInstance(sdk) {
6
8
  const chainId = sdk.chainId;
@@ -95,21 +97,56 @@ export class Multicall {
95
97
  return multicallResult;
96
98
  };
97
99
  const timeoutController = new AbortController();
98
- const result = await Promise.race([
99
- client.multicall({ contracts: encodedPayload }),
100
- sleep(maxTimeout, timeoutController.signal).then(() => Promise.reject(new Error("multicall timeout"))),
101
- ])
102
- .then((response) => {
103
- timeoutController.abort();
104
- return processResponse(response);
105
- })
106
- .catch((_viemError) => {
107
- timeoutController.abort();
108
- const e = new Error(_viemError.message.slice(0, 150));
109
- /* eslint-disable-next-line */
110
- console.error(e);
111
- throw e;
112
- });
100
+ const payloadSize = encodedPayload.length;
101
+ let result;
102
+ if (payloadSize > MAX_CALLS_PER_BATCH) {
103
+ const batches = [];
104
+ for (let i = 0; i < encodedPayload.length; i += MAX_CALLS_PER_BATCH) {
105
+ batches.push(encodedPayload.slice(i, i + MAX_CALLS_PER_BATCH));
106
+ }
107
+ const batchResults = [];
108
+ for (let i = 0; i < batches.length; i += MAX_CONCURRENT_BATCHES) {
109
+ const batchGroup = batches.slice(i, i + MAX_CONCURRENT_BATCHES);
110
+ const groupResults = await Promise.all(batchGroup.map(async (batch) => {
111
+ const batchTimeoutController = new AbortController();
112
+ try {
113
+ const response = await Promise.race([
114
+ client.multicall({ contracts: batch }),
115
+ sleep(maxTimeout, batchTimeoutController.signal).then(() => Promise.reject(new Error("multicall timeout"))),
116
+ ]);
117
+ batchTimeoutController.abort();
118
+ return response;
119
+ }
120
+ catch (error) {
121
+ batchTimeoutController.abort();
122
+ const e = new Error((error instanceof Error ? error.message : String(error)).slice(0, 150));
123
+ /* eslint-disable-next-line */
124
+ console.error(e);
125
+ throw e;
126
+ }
127
+ }));
128
+ batchResults.push(...groupResults);
129
+ }
130
+ const combinedResponse = batchResults.flat();
131
+ result = processResponse(combinedResponse);
132
+ }
133
+ else {
134
+ result = await Promise.race([
135
+ client.multicall({ contracts: encodedPayload }),
136
+ sleep(maxTimeout, timeoutController.signal).then(() => Promise.reject(new Error("multicall timeout"))),
137
+ ])
138
+ .then((response) => {
139
+ timeoutController.abort();
140
+ return processResponse(response);
141
+ })
142
+ .catch((_viemError) => {
143
+ timeoutController.abort();
144
+ const e = new Error(_viemError.message.slice(0, 150));
145
+ /* eslint-disable-next-line */
146
+ console.error(e);
147
+ throw e;
148
+ });
149
+ }
113
150
  if (result.success) {
114
151
  return result;
115
152
  }
@@ -10,11 +10,18 @@ export const BN_ZERO = 0n;
10
10
  export const BN_ONE = 1n;
11
11
  export const BN_NEGATIVE_ONE = -1n;
12
12
  export const MaxUint256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
13
+ export const MaxInt256 = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
13
14
  export const PERCENT_PRECISION_DECIMALS = PRECISION_DECIMALS - 2;
14
15
  const MAX_EXCEEDING_THRESHOLD = "1000000000";
15
16
  const MIN_EXCEEDING_THRESHOLD = "0.01";
16
17
  export const TRIGGER_PREFIX_ABOVE = ">";
17
18
  export const TRIGGER_PREFIX_BELOW = "<";
19
+ export function isNonZero(value) {
20
+ return value !== 0 && value !== 0n;
21
+ }
22
+ export function safeDivide(a, b) {
23
+ return (a / b);
24
+ }
18
25
  export function expandDecimals(n, decimals) {
19
26
  return BigInt(n) * 10n ** BigInt(decimals);
20
27
  }
@@ -132,7 +139,16 @@ export function formatPercentage(percentage, opts = {}) {
132
139
  }
133
140
  export function formatTokenAmount(amount, tokenDecimals, symbol, opts = {}) {
134
141
  const { showAllSignificant = false, fallbackToZero = false, useCommas = false, minThreshold = "0", maxThreshold, } = opts;
135
- const displayDecimals = opts.displayDecimals ?? (opts.isStable ? 2 : 4);
142
+ let displayDecimals;
143
+ if (opts.displayDecimals !== undefined) {
144
+ displayDecimals = opts.displayDecimals;
145
+ }
146
+ else if (typeof amount === "bigint" && tokenDecimals) {
147
+ displayDecimals = calculateDisplayDecimals(amount, tokenDecimals, 1, opts.isStable);
148
+ }
149
+ else {
150
+ displayDecimals = opts.isStable ? 2 : 4;
151
+ }
136
152
  const symbolStr = symbol ? ` ${symbol}` : "";
137
153
  if (typeof amount !== "bigint" || !tokenDecimals) {
138
154
  if (fallbackToZero) {
@@ -250,17 +266,10 @@ export function formatBalanceAmount(amount, tokenDecimals, tokenSymbol, { showZe
250
266
  const absAmount = bigMath.abs(amount);
251
267
  const absAmountFloat = bigintToNumber(absAmount, tokenDecimals);
252
268
  let value = "";
253
- const baseDecimals = isStable ? 2 : 4;
254
- if (absAmountFloat >= 1)
255
- value = formatAmount(absAmount, tokenDecimals, baseDecimals, true);
256
- else if (absAmountFloat >= 0.1)
257
- value = formatAmount(absAmount, tokenDecimals, baseDecimals + 1, true);
258
- else if (absAmountFloat >= 0.01)
259
- value = formatAmount(absAmount, tokenDecimals, baseDecimals + 2, true);
260
- else if (absAmountFloat >= 0.001)
261
- value = formatAmount(absAmount, tokenDecimals, baseDecimals + 3, true);
262
- else if (absAmountFloat >= 1e-8)
263
- value = formatAmount(absAmount, tokenDecimals, 8, true);
269
+ if (absAmountFloat >= 1e-8) {
270
+ const displayDecimals = calculateDisplayDecimals(absAmount, tokenDecimals, 1, isStable);
271
+ value = formatAmount(absAmount, tokenDecimals, displayDecimals, true);
272
+ }
264
273
  else {
265
274
  if (toExponential) {
266
275
  value = bigintToNumber(absAmount, tokenDecimals).toExponential(2);
@@ -1,5 +1,5 @@
1
1
  import { BASIS_POINTS_DIVISOR_BIGINT, DEFAULT_ALLOWED_SWAP_SLIPPAGE_BPS } from "../configs/factors";
2
- import { OrderType, } from "../types/orders";
2
+ import { OrderType, SwapPricingType, } from "../types/orders";
3
3
  import { getSwapPathOutputAddresses, getSwapPathStats } from "./swap/swapStats";
4
4
  import { bigMath } from "./bigmath";
5
5
  import { getByKey } from "./objects";
@@ -84,7 +84,7 @@ export function getOrderInfo(p) {
84
84
  usdIn: convertToUsd(order.initialCollateralDeltaAmount, initialCollateralToken.decimals, initialCollateralToken.prices.minPrice),
85
85
  shouldUnwrapNativeToken: order.shouldUnwrapNativeToken,
86
86
  shouldApplyPriceImpact: true,
87
- isAtomicSwap: false,
87
+ swapPricingType: SwapPricingType.Swap,
88
88
  });
89
89
  const priceImpactAmount = convertToTokenAmount(swapPathStats?.totalSwapPriceImpactDeltaUsd, targetCollateralToken.decimals, targetCollateralToken.prices.minPrice);
90
90
  const swapFeeAmount = convertToTokenAmount(swapPathStats?.totalSwapFeeUsd, targetCollateralToken.decimals, targetCollateralToken.prices.minPrice);
@@ -157,7 +157,7 @@ export function getOrderInfo(p) {
157
157
  usdIn: convertToUsd(order.initialCollateralDeltaAmount, initialCollateralToken.decimals, initialCollateralToken.prices.minPrice),
158
158
  shouldUnwrapNativeToken: order.shouldUnwrapNativeToken,
159
159
  shouldApplyPriceImpact: true,
160
- isAtomicSwap: false,
160
+ swapPricingType: SwapPricingType.Swap,
161
161
  });
162
162
  let triggerThresholdType;
163
163
  if (!isMarketOrderType(order.orderType)) {
@@ -35,12 +35,26 @@ describe("findSwapPathsBetweenTokens", () => {
35
35
  const result = findSwapPathsBetweenTokens(graph);
36
36
  expect(result).toEqual({
37
37
  BTC: {
38
+ BTC: [
39
+ ["ETH", "USDC"],
40
+ ["USDC", "ETH"],
41
+ ],
38
42
  ETH: [[], ["USDC"]],
39
43
  USDC: [[], ["ETH"]],
40
44
  },
41
45
  ETH: {
46
+ ETH: [
47
+ ["USDC", "BTC"],
48
+ ["BTC", "USDC"],
49
+ ],
42
50
  USDC: [[], ["BTC"]],
43
51
  },
52
+ USDC: {
53
+ USDC: [
54
+ ["ETH", "BTC"],
55
+ ["BTC", "ETH"],
56
+ ],
57
+ },
44
58
  });
45
59
  });
46
60
  it("should handle multiple markets between same tokens", () => {
@@ -55,8 +69,12 @@ describe("findSwapPathsBetweenTokens", () => {
55
69
  const result = findSwapPathsBetweenTokens(graph);
56
70
  expect(result).toEqual({
57
71
  ETH: {
72
+ ETH: [["USDC"]],
58
73
  USDC: [[], ["USDC", "ETH"]],
59
74
  },
75
+ USDC: {
76
+ USDC: [["ETH"]],
77
+ },
60
78
  });
61
79
  });
62
80
  it("should not include self-loops", () => {
@@ -137,12 +155,16 @@ describe("findSwapPathsBetweenTokens", () => {
137
155
  const result = findSwapPathsBetweenTokens(graph);
138
156
  expect(result).toEqual({
139
157
  A: {
158
+ A: [["USDC"]],
140
159
  B: [["USDC"]],
141
160
  USDC: [[], ["USDC", "A"]],
142
161
  },
143
162
  B: {
144
163
  USDC: [[], ["USDC", "A"]],
145
164
  },
165
+ USDC: {
166
+ USDC: [["A"]],
167
+ },
146
168
  });
147
169
  });
148
170
  });