@gmx-io/sdk 1.0.4 → 1.1.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 (190) hide show
  1. package/build/cjs/src/abis/ArbitrumNodeInterface.json +105 -0
  2. package/build/cjs/src/abis/CustomErrors.json +613 -16
  3. package/build/cjs/src/abis/ERC20PermitInterface.json +118 -0
  4. package/build/cjs/src/abis/GelatoRelayRouter.json +1426 -0
  5. package/build/cjs/src/abis/RelayParams.json +110 -0
  6. package/build/cjs/src/abis/SubaccountApproval.json +17 -0
  7. package/build/cjs/src/abis/SubaccountGelatoRelayRouter.json +1885 -0
  8. package/build/cjs/src/abis/SyntheticsReader.json +1 -131
  9. package/build/cjs/src/abis/__tests__/abis.spec.js +40 -0
  10. package/build/cjs/src/abis/index.js +8 -0
  11. package/build/cjs/src/configs/__tests__/permits.spec.js +109 -0
  12. package/build/cjs/src/configs/__tests__/tokens.spec.js +1 -1
  13. package/build/cjs/src/configs/chains.js +36 -5
  14. package/build/cjs/src/configs/contracts.js +15 -3
  15. package/build/cjs/src/configs/dataStore.js +26 -4
  16. package/build/cjs/src/configs/express.js +35 -0
  17. package/build/cjs/src/configs/factors.js +4 -3
  18. package/build/cjs/src/configs/markets.js +28 -0
  19. package/build/cjs/src/configs/tokens.js +90 -0
  20. package/build/cjs/src/configs/twap.js +10 -0
  21. package/build/cjs/src/index.js +3 -3
  22. package/build/cjs/src/modules/markets/index.js +1 -0
  23. package/build/cjs/src/modules/markets/query-builders.js +4 -0
  24. package/build/cjs/src/modules/orders/helpers.js +2 -0
  25. package/build/cjs/src/modules/orders/orders.js +4 -3
  26. package/build/cjs/src/modules/utils/utils.js +11 -1
  27. package/build/cjs/src/prebuilt/hashedKinkModelMarketRatesKeys.json +32 -0
  28. package/build/cjs/src/prebuilt/hashedMarketConfigKeys.json +323 -0
  29. package/build/cjs/src/prebuilt/hashedMarketValuesKeys.json +60 -0
  30. package/build/cjs/src/test/mock.js +30 -1
  31. package/build/cjs/src/types/twap.js +2 -0
  32. package/build/cjs/src/utils/__tests__/numbers.spec.js +217 -0
  33. package/build/cjs/src/utils/__tests__/orderTransactions/batchUtils.spec.js +241 -0
  34. package/build/cjs/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +595 -0
  35. package/build/cjs/src/utils/__tests__/orderTransactions/exchangeRouterMulticall.spec.js +296 -0
  36. package/build/cjs/src/utils/__tests__/orderTransactions/externalCalls.spec.js +118 -0
  37. package/build/cjs/src/utils/__tests__/orderTransactions/increaseOrders.spec.js +762 -0
  38. package/build/cjs/src/utils/__tests__/orderTransactions/swapOrders.spec.js +469 -0
  39. package/build/cjs/src/utils/__tests__/orderTransactions/updateOrder.spec.js +80 -0
  40. package/build/cjs/src/utils/__tests__/parseError.spec.js +263 -0
  41. package/build/cjs/src/utils/__tests__/uiFeeReceiver.spec.js +45 -0
  42. package/build/cjs/src/utils/bigmath.js +3 -0
  43. package/build/cjs/src/utils/callContract.js +2 -2
  44. package/build/cjs/src/utils/errors/index.js +18 -0
  45. package/build/cjs/src/utils/errors/parseError.js +150 -0
  46. package/build/cjs/src/utils/{contracts.js → errors/transactionsErrors.js} +35 -3
  47. package/build/cjs/src/utils/fees/executionFee.js +52 -1
  48. package/build/cjs/src/utils/fees/index.js +8 -4
  49. package/build/cjs/src/utils/gelatoRelay.js +5 -0
  50. package/build/cjs/src/utils/hash.js +6 -1
  51. package/build/cjs/src/utils/marketKeysAndConfigs.js +4 -0
  52. package/build/cjs/src/utils/markets.js +5 -1
  53. package/build/cjs/src/utils/numbers.js +559 -5
  54. package/build/cjs/src/utils/orderTransactions.js +638 -0
  55. package/build/cjs/src/utils/orders.js +7 -1
  56. package/build/cjs/src/utils/simulateExecuteOrder.js +6 -2
  57. package/build/cjs/src/utils/swap/__tests__/mockRouting.spec.js +11 -6
  58. package/build/cjs/src/utils/swap/__tests__/swapRouting.spec.js +4 -4
  59. package/build/cjs/src/utils/swap/__tests__/swapStats.spec.js +9 -0
  60. package/build/cjs/src/utils/swap/swapPath.js +30 -13
  61. package/build/cjs/src/utils/swap/swapRouting.js +4 -2
  62. package/build/cjs/src/utils/swap/swapStats.js +6 -5
  63. package/build/cjs/src/utils/testUtil.js +1 -1
  64. package/build/cjs/src/utils/time.js +30 -0
  65. package/build/cjs/src/utils/tokens.js +16 -2
  66. package/build/cjs/src/utils/twap/index.js +53 -0
  67. package/build/cjs/src/utils/twap/uiFeeReceiver.js +31 -0
  68. package/build/cjs/src/utils/types.js +13 -0
  69. package/build/esm/src/abis/ArbitrumNodeInterface.json +105 -0
  70. package/build/esm/src/abis/CustomErrors.json +613 -16
  71. package/build/esm/src/abis/ERC20PermitInterface.json +118 -0
  72. package/build/esm/src/abis/GelatoRelayRouter.json +1426 -0
  73. package/build/esm/src/abis/RelayParams.json +110 -0
  74. package/build/esm/src/abis/SubaccountApproval.json +17 -0
  75. package/build/esm/src/abis/SubaccountGelatoRelayRouter.json +1885 -0
  76. package/build/esm/src/abis/SyntheticsReader.json +1 -131
  77. package/build/esm/src/abis/__tests__/abis.spec.js +35 -0
  78. package/build/esm/src/abis/index.js +8 -0
  79. package/build/esm/src/configs/__tests__/permits.spec.js +107 -0
  80. package/build/esm/src/configs/__tests__/tokens.spec.js +3 -3
  81. package/build/esm/src/configs/chains.js +33 -3
  82. package/build/esm/src/configs/contracts.js +15 -3
  83. package/build/esm/src/configs/dataStore.js +19 -1
  84. package/build/esm/src/configs/express.js +29 -0
  85. package/build/esm/src/configs/factors.js +1 -3
  86. package/build/esm/src/configs/markets.js +28 -0
  87. package/build/esm/src/configs/tokens.js +90 -0
  88. package/build/esm/src/configs/twap.js +7 -0
  89. package/build/esm/src/index.js +4 -4
  90. package/build/esm/src/modules/markets/index.js +1 -0
  91. package/build/esm/src/modules/markets/query-builders.js +4 -0
  92. package/build/esm/src/modules/orders/helpers.js +2 -0
  93. package/build/esm/src/modules/orders/orders.js +4 -3
  94. package/build/esm/src/modules/utils/utils.js +13 -3
  95. package/build/esm/src/prebuilt/hashedKinkModelMarketRatesKeys.json +32 -0
  96. package/build/esm/src/prebuilt/hashedMarketConfigKeys.json +323 -0
  97. package/build/esm/src/prebuilt/hashedMarketValuesKeys.json +60 -0
  98. package/build/esm/src/test/mock.js +28 -0
  99. package/build/esm/src/types/twap.js +1 -0
  100. package/build/esm/src/utils/__tests__/numbers.spec.js +219 -2
  101. package/build/esm/src/utils/__tests__/orderTransactions/batchUtils.spec.js +239 -0
  102. package/build/esm/src/utils/__tests__/orderTransactions/decreaseOrders.spec.js +593 -0
  103. package/build/esm/src/utils/__tests__/orderTransactions/exchangeRouterMulticall.spec.js +294 -0
  104. package/build/esm/src/utils/__tests__/orderTransactions/externalCalls.spec.js +116 -0
  105. package/build/esm/src/utils/__tests__/orderTransactions/increaseOrders.spec.js +760 -0
  106. package/build/esm/src/utils/__tests__/orderTransactions/swapOrders.spec.js +467 -0
  107. package/build/esm/src/utils/__tests__/orderTransactions/updateOrder.spec.js +78 -0
  108. package/build/esm/src/utils/__tests__/parseError.spec.js +261 -0
  109. package/build/esm/src/utils/__tests__/uiFeeReceiver.spec.js +43 -0
  110. package/build/esm/src/utils/bigmath.js +3 -0
  111. package/build/esm/src/utils/callContract.js +3 -3
  112. package/build/esm/src/utils/errors/index.js +2 -0
  113. package/build/esm/src/utils/errors/parseError.js +141 -0
  114. package/build/esm/src/utils/{contracts.js → errors/transactionsErrors.js} +30 -1
  115. package/build/esm/src/utils/fees/executionFee.js +48 -1
  116. package/build/esm/src/utils/fees/index.js +8 -4
  117. package/build/esm/src/utils/gelatoRelay.js +2 -0
  118. package/build/esm/src/utils/hash.js +5 -1
  119. package/build/esm/src/utils/marketKeysAndConfigs.js +5 -1
  120. package/build/esm/src/utils/markets.js +3 -0
  121. package/build/esm/src/utils/numbers.js +516 -1
  122. package/build/esm/src/utils/orderTransactions.js +607 -0
  123. package/build/esm/src/utils/orders.js +5 -0
  124. package/build/esm/src/utils/simulateExecuteOrder.js +6 -2
  125. package/build/esm/src/utils/swap/__tests__/mockRouting.spec.js +11 -6
  126. package/build/esm/src/utils/swap/__tests__/swapRouting.spec.js +4 -4
  127. package/build/esm/src/utils/swap/__tests__/swapStats.spec.js +9 -0
  128. package/build/esm/src/utils/swap/swapPath.js +30 -13
  129. package/build/esm/src/utils/swap/swapRouting.js +4 -2
  130. package/build/esm/src/utils/swap/swapStats.js +6 -5
  131. package/build/esm/src/utils/testUtil.js +2 -2
  132. package/build/esm/src/utils/time.js +23 -0
  133. package/build/esm/src/utils/tokens.js +14 -1
  134. package/build/esm/src/utils/twap/index.js +44 -0
  135. package/build/esm/src/utils/twap/uiFeeReceiver.js +24 -0
  136. package/build/esm/src/utils/types.js +8 -0
  137. package/build/types/src/abis/__tests__/abis.spec.d.ts +1 -0
  138. package/build/types/src/abis/index.d.ts +1 -1
  139. package/build/types/src/configs/__tests__/permits.spec.d.ts +1 -0
  140. package/build/types/src/configs/chains.d.ts +29 -1
  141. package/build/types/src/configs/contracts.d.ts +238 -1
  142. package/build/types/src/configs/dataStore.d.ts +10 -0
  143. package/build/types/src/configs/express.d.ts +12 -0
  144. package/build/types/src/configs/factors.d.ts +1 -3
  145. package/build/types/src/configs/tokens.d.ts +2 -2
  146. package/build/types/src/configs/twap.d.ts +7 -0
  147. package/build/types/src/modules/markets/query-builders.d.ts +1 -1
  148. package/build/types/src/modules/markets/types.d.ts +2 -2
  149. package/build/types/src/modules/orders/orders.d.ts +2 -1
  150. package/build/types/src/modules/orders/transactions/createIncreaseOrderTxn.d.ts +1 -1
  151. package/build/types/src/test/mock.d.ts +16 -1
  152. package/build/types/src/types/fees.d.ts +9 -0
  153. package/build/types/src/types/markets.d.ts +1 -0
  154. package/build/types/src/types/orders.d.ts +3 -0
  155. package/build/types/src/types/tokens.d.ts +27 -0
  156. package/build/types/src/types/trade.d.ts +2 -19
  157. package/build/types/src/types/twap.d.ts +11 -0
  158. package/build/types/src/utils/__tests__/orderTransactions/batchUtils.spec.d.ts +1 -0
  159. package/build/types/src/utils/__tests__/orderTransactions/decreaseOrders.spec.d.ts +1 -0
  160. package/build/types/src/utils/__tests__/orderTransactions/exchangeRouterMulticall.spec.d.ts +1 -0
  161. package/build/types/src/utils/__tests__/orderTransactions/externalCalls.spec.d.ts +1 -0
  162. package/build/types/src/utils/__tests__/orderTransactions/increaseOrders.spec.d.ts +1 -0
  163. package/build/types/src/utils/__tests__/orderTransactions/swapOrders.spec.d.ts +1 -0
  164. package/build/types/src/utils/__tests__/orderTransactions/updateOrder.spec.d.ts +1 -0
  165. package/build/types/src/utils/__tests__/parseError.spec.d.ts +1 -0
  166. package/build/types/src/utils/__tests__/uiFeeReceiver.spec.d.ts +1 -0
  167. package/build/types/src/utils/bigmath.d.ts +1 -0
  168. package/build/types/src/utils/errors/index.d.ts +2 -0
  169. package/build/types/src/utils/errors/parseError.d.ts +50 -0
  170. package/build/types/src/utils/errors/transactionsErrors.d.ts +34 -0
  171. package/build/types/src/utils/fees/executionFee.d.ts +35 -2
  172. package/build/types/src/utils/fees/index.d.ts +1 -1
  173. package/build/types/src/utils/gelatoRelay.d.ts +2 -0
  174. package/build/types/src/utils/hash.d.ts +2 -0
  175. package/build/types/src/utils/marketKeysAndConfigs.d.ts +1 -0
  176. package/build/types/src/utils/markets.d.ts +1 -0
  177. package/build/types/src/utils/numbers.d.ts +110 -1
  178. package/build/types/src/utils/orderTransactions.d.ts +231 -0
  179. package/build/types/src/utils/orders.d.ts +2 -1
  180. package/build/types/src/utils/simulateExecuteOrder.d.ts +4 -0
  181. package/build/types/src/utils/swap/swapPath.d.ts +5 -5
  182. package/build/types/src/utils/swap/swapRouting.d.ts +2 -2
  183. package/build/types/src/utils/swap/swapStats.d.ts +2 -0
  184. package/build/types/src/utils/time.d.ts +14 -0
  185. package/build/types/src/utils/tokens.d.ts +6 -5
  186. package/build/types/src/utils/twap/index.d.ts +17 -0
  187. package/build/types/src/utils/twap/uiFeeReceiver.d.ts +9 -0
  188. package/build/types/src/utils/types.d.ts +5 -0
  189. package/package.json +3 -1
  190. package/build/types/src/utils/contracts.d.ts +0 -19
@@ -1,9 +1,19 @@
1
- import { BASIS_POINTS_DIVISOR_BIGINT } from "../configs/factors";
1
+ import { formatUnits, parseUnits } from "viem";
2
+ import { bigMath } from "./bigmath";
3
+ export const USD_DECIMALS = 30;
4
+ export const BASIS_POINTS_DIVISOR = 10000;
5
+ export const BASIS_POINTS_DIVISOR_BIGINT = 10000n;
2
6
  export const PRECISION_DECIMALS = 30;
3
7
  export const PRECISION = expandDecimals(1, PRECISION_DECIMALS);
4
8
  export const BN_ZERO = 0n;
5
9
  export const BN_ONE = 1n;
6
10
  export const BN_NEGATIVE_ONE = -1n;
11
+ export const MaxUint256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
12
+ export const PERCENT_PRECISION_DECIMALS = PRECISION_DECIMALS - 2;
13
+ const MAX_EXCEEDING_THRESHOLD = "1000000000";
14
+ const MIN_EXCEEDING_THRESHOLD = "0.01";
15
+ export const TRIGGER_PREFIX_ABOVE = ">";
16
+ export const TRIGGER_PREFIX_BELOW = "<";
7
17
  export function expandDecimals(n, decimals) {
8
18
  return BigInt(n) * 10n ** BigInt(decimals);
9
19
  }
@@ -47,6 +57,12 @@ export function numberToBigint(value, decimals) {
47
57
  }
48
58
  return negative ? -res : res;
49
59
  }
60
+ export const trimZeroDecimals = (amount) => {
61
+ if (parseFloat(amount) === parseInt(amount)) {
62
+ return parseInt(amount).toString();
63
+ }
64
+ return amount;
65
+ };
50
66
  export function bigintToNumber(value, decimals) {
51
67
  const negative = value < 0;
52
68
  if (negative)
@@ -60,3 +76,502 @@ export function bigintToNumber(value, decimals) {
60
76
  export function adjustForDecimals(amount, divDecimals, mulDecimals) {
61
77
  return (amount * expandDecimals(1, mulDecimals)) / expandDecimals(1, divDecimals);
62
78
  }
79
+ export function formatUsd(usd, opts = {}) {
80
+ const { fallbackToZero = false, displayDecimals = 2 } = opts;
81
+ if (typeof usd !== "bigint") {
82
+ if (fallbackToZero) {
83
+ usd = 0n;
84
+ }
85
+ else {
86
+ return undefined;
87
+ }
88
+ }
89
+ if (opts.visualMultiplier) {
90
+ usd *= BigInt(opts.visualMultiplier);
91
+ }
92
+ const defaultMinThreshold = displayDecimals > 1 ? "0." + "0".repeat(displayDecimals - 1) + "1" : undefined;
93
+ const exceedingInfo = getLimitedDisplay(usd, USD_DECIMALS, {
94
+ maxThreshold: opts.maxThreshold,
95
+ minThreshold: opts.minThreshold ?? defaultMinThreshold,
96
+ });
97
+ const maybePlus = opts.displayPlus ? "+" : "";
98
+ const sign = usd < 0n ? "-" : maybePlus;
99
+ const symbol = exceedingInfo.symbol ? `${exceedingInfo.symbol} ` : "";
100
+ const displayUsd = formatAmount(exceedingInfo.value, USD_DECIMALS, displayDecimals, true);
101
+ return `${symbol}${sign}$${displayUsd}`;
102
+ }
103
+ export function formatDeltaUsd(deltaUsd, percentage, opts = {}) {
104
+ if (typeof deltaUsd !== "bigint") {
105
+ if (opts.fallbackToZero) {
106
+ return `${formatUsd(0n)} (${formatAmount(0n, 2, 2)}%)`;
107
+ }
108
+ return undefined;
109
+ }
110
+ const sign = getPlusOrMinusSymbol(deltaUsd, { showPlusForZero: opts.showPlusForZero });
111
+ const exceedingInfo = getLimitedDisplay(deltaUsd, USD_DECIMALS);
112
+ const percentageStr = percentage !== undefined ? ` (${sign}${formatPercentage(bigMath.abs(percentage))})` : "";
113
+ const deltaUsdStr = formatAmount(exceedingInfo.value, USD_DECIMALS, 2, true);
114
+ const symbol = exceedingInfo.symbol ? `${exceedingInfo.symbol} ` : "";
115
+ return `${symbol}${sign}$${deltaUsdStr}${percentageStr}`;
116
+ }
117
+ export function formatPercentage(percentage, opts = {}) {
118
+ const { fallbackToZero = false, signed = false, displayDecimals = 2, bps = true } = opts;
119
+ if (percentage === undefined) {
120
+ if (fallbackToZero) {
121
+ return `${formatAmount(0n, PERCENT_PRECISION_DECIMALS, displayDecimals)}%`;
122
+ }
123
+ return undefined;
124
+ }
125
+ const sign = signed ? getPlusOrMinusSymbol(percentage) : "";
126
+ return `${sign}${formatAmount(bigMath.abs(percentage), bps ? 2 : PERCENT_PRECISION_DECIMALS, displayDecimals)}%`;
127
+ }
128
+ export function formatTokenAmount(amount, tokenDecimals, symbol, opts = {}) {
129
+ const { displayDecimals = 4, showAllSignificant = false, fallbackToZero = false, useCommas = false, minThreshold = "0", maxThreshold, } = opts;
130
+ const symbolStr = symbol ? ` ${symbol}` : "";
131
+ if (typeof amount !== "bigint" || !tokenDecimals) {
132
+ if (fallbackToZero) {
133
+ amount = 0n;
134
+ tokenDecimals = displayDecimals;
135
+ }
136
+ else {
137
+ return undefined;
138
+ }
139
+ }
140
+ let amountStr;
141
+ const maybePlus = opts.displayPlus ? "+" : "";
142
+ const sign = amount < 0n ? "-" : maybePlus;
143
+ if (showAllSignificant) {
144
+ amountStr = formatAmountFree(amount, tokenDecimals, tokenDecimals);
145
+ }
146
+ else {
147
+ const exceedingInfo = getLimitedDisplay(amount, tokenDecimals, { maxThreshold, minThreshold });
148
+ const symbol = exceedingInfo.symbol ? `${exceedingInfo.symbol} ` : "";
149
+ amountStr = `${symbol}${sign}${formatAmount(exceedingInfo.value, tokenDecimals, displayDecimals, useCommas)}`;
150
+ }
151
+ return `${amountStr}${symbolStr}`;
152
+ }
153
+ export function formatTokenAmountWithUsd(tokenAmount, usdAmount, tokenSymbol, tokenDecimals, opts = {}) {
154
+ if (typeof tokenAmount !== "bigint" || typeof usdAmount !== "bigint" || !tokenSymbol || !tokenDecimals) {
155
+ if (!opts.fallbackToZero) {
156
+ return undefined;
157
+ }
158
+ }
159
+ const tokenStr = formatTokenAmount(tokenAmount, tokenDecimals, tokenSymbol, {
160
+ ...opts,
161
+ useCommas: true,
162
+ displayPlus: opts.displayPlus,
163
+ });
164
+ const usdStr = formatUsd(usdAmount, {
165
+ fallbackToZero: opts.fallbackToZero,
166
+ displayPlus: opts.displayPlus,
167
+ });
168
+ return `${tokenStr} (${usdStr})`;
169
+ }
170
+ /**
171
+ *
172
+ * @param opts.signed - Default `true`. whether to display a `+` or `-` sign for all non-zero values.
173
+ */
174
+ export function formatRatePercentage(rate, opts) {
175
+ if (typeof rate !== "bigint") {
176
+ return "-";
177
+ }
178
+ const signed = opts?.signed ?? true;
179
+ const plurOrMinus = signed ? getPlusOrMinusSymbol(rate) : "";
180
+ const amount = bigMath.abs(rate * 100n);
181
+ return `${plurOrMinus}${formatAmount(amount, 30, opts?.displayDecimals ?? 4)}%`;
182
+ }
183
+ export function formatUsdPrice(price, opts = {}) {
184
+ if (price === undefined) {
185
+ return;
186
+ }
187
+ if (price < 0n) {
188
+ return "NA";
189
+ }
190
+ const decimals = calculateDisplayDecimals(price, undefined, opts.visualMultiplier);
191
+ return formatUsd(price, {
192
+ ...opts,
193
+ displayDecimals: decimals,
194
+ });
195
+ }
196
+ export function formatPercentageDisplay(percentage, hideThreshold) {
197
+ if (hideThreshold && percentage < hideThreshold) {
198
+ return "";
199
+ }
200
+ return `${percentage}%`;
201
+ }
202
+ export function formatAmountHuman(amount, tokenDecimals, showDollar = false, displayDecimals = 1) {
203
+ if (amount === undefined) {
204
+ return "...";
205
+ }
206
+ let n = Number(formatAmount(amount, tokenDecimals));
207
+ // For large numbers, we can neglect the decimals to avoid decimals in cases like 9999999.99999
208
+ if (n >= 1000000) {
209
+ n = Math.round(n);
210
+ }
211
+ const isNegative = n < 0;
212
+ const absN = Math.abs(n);
213
+ const sign = showDollar ? "$" : "";
214
+ if (absN >= 1000000000) {
215
+ return `${isNegative ? "-" : ""}${sign}${(absN / 1000000000).toFixed(displayDecimals)}b`;
216
+ }
217
+ if (absN >= 1000000) {
218
+ return `${isNegative ? "-" : ""}${sign}${(absN / 1000000).toFixed(displayDecimals)}m`;
219
+ }
220
+ if (absN >= 1000) {
221
+ return `${isNegative ? "-" : ""}${sign}${(absN / 1000).toFixed(displayDecimals)}k`;
222
+ }
223
+ return `${isNegative ? "-" : ""}${sign}${absN.toFixed(displayDecimals)}`;
224
+ }
225
+ export function formatBalanceAmount(amount, tokenDecimals, tokenSymbol, showZero = false, toExponential = true) {
226
+ if (amount === undefined)
227
+ return "-";
228
+ if (amount === 0n) {
229
+ if (showZero === true) {
230
+ if (tokenSymbol) {
231
+ return `0.0000 ${tokenSymbol}`;
232
+ }
233
+ return "0.0000";
234
+ }
235
+ return "-";
236
+ }
237
+ const absAmount = bigMath.abs(amount);
238
+ const absAmountFloat = bigintToNumber(absAmount, tokenDecimals);
239
+ let value = "";
240
+ if (absAmountFloat >= 1)
241
+ value = formatAmount(amount, tokenDecimals, 4, true);
242
+ else if (absAmountFloat >= 0.1)
243
+ value = formatAmount(amount, tokenDecimals, 5, true);
244
+ else if (absAmountFloat >= 0.01)
245
+ value = formatAmount(amount, tokenDecimals, 6, true);
246
+ else if (absAmountFloat >= 0.001)
247
+ value = formatAmount(amount, tokenDecimals, 7, true);
248
+ else if (absAmountFloat >= 1e-8)
249
+ value = formatAmount(amount, tokenDecimals, 8, true);
250
+ else {
251
+ if (toExponential) {
252
+ value = bigintToNumber(amount, tokenDecimals).toExponential(2);
253
+ }
254
+ else {
255
+ value = bigintToNumber(amount, tokenDecimals).toFixed(8);
256
+ }
257
+ }
258
+ if (tokenSymbol) {
259
+ // Non-breaking space
260
+ return `${value} ${tokenSymbol}`;
261
+ }
262
+ return value;
263
+ }
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
+ export function formatFactor(factor) {
274
+ if (factor == 0n) {
275
+ return "0";
276
+ }
277
+ if (bigMath.abs(factor) > PRECISION * 1000n) {
278
+ return (factor / PRECISION).toString();
279
+ }
280
+ const trailingZeroes = bigMath
281
+ .abs(factor)
282
+ .toString()
283
+ .match(/^(.+?)(?<zeroes>0*)$/)?.groups?.zeroes?.length || 0;
284
+ const factorDecimals = 30 - trailingZeroes;
285
+ return formatAmount(factor, 30, factorDecimals);
286
+ }
287
+ export function numberWithCommas(x) {
288
+ if (x === undefined || x === null) {
289
+ return "...";
290
+ }
291
+ const parts = x.toString().split(".");
292
+ parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
293
+ return parts.join(".");
294
+ }
295
+ export const formatAmount = (amount, tokenDecimals, displayDecimals, useCommas, defaultValue, visualMultiplier) => {
296
+ if (defaultValue === undefined || defaultValue === null) {
297
+ defaultValue = "...";
298
+ }
299
+ if (amount === undefined || amount === null || amount === "") {
300
+ return defaultValue;
301
+ }
302
+ if (displayDecimals === undefined) {
303
+ displayDecimals = 4;
304
+ }
305
+ const amountBigInt = roundWithDecimals(BigInt(amount) * BigInt(visualMultiplier ?? 1), {
306
+ displayDecimals,
307
+ decimals: tokenDecimals,
308
+ });
309
+ let amountStr = formatUnits(amountBigInt, tokenDecimals);
310
+ amountStr = limitDecimals(amountStr, displayDecimals);
311
+ if (displayDecimals !== 0) {
312
+ amountStr = padDecimals(amountStr, displayDecimals);
313
+ }
314
+ if (useCommas) {
315
+ return numberWithCommas(amountStr);
316
+ }
317
+ return amountStr;
318
+ };
319
+ export const formatKeyAmount = (map, key, tokenDecimals, displayDecimals, useCommas) => {
320
+ const value = map ? map[key] ?? undefined : undefined;
321
+ if (value === undefined || value === null) {
322
+ return "...";
323
+ }
324
+ return formatAmount(value, tokenDecimals, displayDecimals, useCommas);
325
+ };
326
+ export const formatArrayAmount = (arr, index, tokenDecimals, displayDecimals, useCommas) => {
327
+ if (!arr || arr[index] === undefined || arr[index] === null) {
328
+ return "...";
329
+ }
330
+ return formatAmount(arr[index], tokenDecimals, displayDecimals, useCommas);
331
+ };
332
+ export const formatAmountFree = (amount, tokenDecimals, displayDecimals) => {
333
+ if (amount === undefined || amount === null) {
334
+ return "...";
335
+ }
336
+ amount = BigInt(amount);
337
+ let amountStr = formatUnits(amount, tokenDecimals);
338
+ amountStr = limitDecimals(amountStr, displayDecimals);
339
+ return trimZeroDecimals(amountStr);
340
+ };
341
+ export function getLimitedDisplay(amount, tokenDecimals, opts = {}) {
342
+ const { maxThreshold = MAX_EXCEEDING_THRESHOLD, minThreshold = MIN_EXCEEDING_THRESHOLD } = opts;
343
+ const max = maxThreshold === null ? null : expandDecimals(BigInt(maxThreshold), tokenDecimals);
344
+ const min = parseUnits(minThreshold.toString(), tokenDecimals);
345
+ const absAmount = bigMath.abs(amount);
346
+ if (absAmount == 0n) {
347
+ return {
348
+ symbol: "",
349
+ value: absAmount,
350
+ };
351
+ }
352
+ const symbol = max !== null && absAmount > max ? TRIGGER_PREFIX_ABOVE : absAmount < min ? TRIGGER_PREFIX_BELOW : "";
353
+ const value = max !== null && absAmount > max ? max : absAmount < min ? min : absAmount;
354
+ return {
355
+ symbol,
356
+ value,
357
+ };
358
+ }
359
+ export const limitDecimals = (amount, maxDecimals) => {
360
+ let amountStr = amount.toString();
361
+ if (maxDecimals === undefined) {
362
+ return amountStr;
363
+ }
364
+ if (maxDecimals === 0) {
365
+ return amountStr.split(".")[0];
366
+ }
367
+ const dotIndex = amountStr.indexOf(".");
368
+ if (dotIndex !== -1) {
369
+ let decimals = amountStr.length - dotIndex - 1;
370
+ if (decimals > maxDecimals) {
371
+ amountStr = amountStr.substr(0, amountStr.length - (decimals - maxDecimals));
372
+ }
373
+ }
374
+ return amountStr;
375
+ };
376
+ export const padDecimals = (amount, minDecimals) => {
377
+ let amountStr = amount.toString();
378
+ const dotIndex = amountStr.indexOf(".");
379
+ if (dotIndex !== -1) {
380
+ const decimals = amountStr.length - dotIndex - 1;
381
+ if (decimals < minDecimals) {
382
+ amountStr = amountStr.padEnd(amountStr.length + (minDecimals - decimals), "0");
383
+ }
384
+ }
385
+ else {
386
+ amountStr = amountStr + "." + "0".repeat(minDecimals);
387
+ }
388
+ return amountStr;
389
+ };
390
+ export function getPlusOrMinusSymbol(value, opts = {}) {
391
+ if (value === undefined) {
392
+ return "";
393
+ }
394
+ const { showPlusForZero = false } = opts;
395
+ return value === 0n ? (showPlusForZero ? "+" : "") : value < 0n ? "-" : "+";
396
+ }
397
+ export function roundWithDecimals(value, opts) {
398
+ if (opts.displayDecimals === opts.decimals) {
399
+ return BigInt(value);
400
+ }
401
+ let valueString = value.toString();
402
+ let isNegative = false;
403
+ if (valueString[0] === "-") {
404
+ valueString = valueString.slice(1);
405
+ isNegative = true;
406
+ }
407
+ if (valueString.length < opts.decimals) {
408
+ valueString = valueString.padStart(opts.decimals, "0");
409
+ }
410
+ const mainPart = valueString.slice(0, valueString.length - opts.decimals + opts.displayDecimals);
411
+ const partToRound = valueString.slice(valueString.length - opts.decimals + opts.displayDecimals);
412
+ let mainPartBigInt = BigInt(mainPart);
413
+ let returnValue = mainPartBigInt;
414
+ if (partToRound.length !== 0) {
415
+ if (Number(partToRound[0]) >= 5) {
416
+ mainPartBigInt += 1n;
417
+ }
418
+ returnValue = BigInt(mainPartBigInt.toString() + new Array(partToRound.length).fill("0").join(""));
419
+ }
420
+ return isNegative ? returnValue * -1n : returnValue;
421
+ }
422
+ // TODO: Remove this function
423
+ export function toBigNumberWithDecimals(value, decimals) {
424
+ if (!value)
425
+ return BN_ZERO;
426
+ const parts = value.split(".");
427
+ const integerPart = parts[0];
428
+ const decimalPart = parts.length > 1 ? parts[1] : "";
429
+ const paddingZeros = decimals - decimalPart.length;
430
+ if (paddingZeros >= 0) {
431
+ const result = integerPart + decimalPart + "0".repeat(paddingZeros);
432
+ return BigInt(result);
433
+ }
434
+ else {
435
+ const result = integerPart + decimalPart.substring(0, decimals);
436
+ return BigInt(result);
437
+ }
438
+ }
439
+ /**
440
+ *
441
+ * @deprecated Use BigInt instead
442
+ */
443
+ export function bigNumberify(n) {
444
+ try {
445
+ if (n === undefined)
446
+ throw new Error("n is undefined");
447
+ if (n === null)
448
+ throw new Error("n is null");
449
+ return BigInt(n);
450
+ }
451
+ catch (e) {
452
+ // eslint-disable-next-line no-console
453
+ console.error("bigNumberify error", e);
454
+ return undefined;
455
+ }
456
+ }
457
+ export const parseValue = (value, tokenDecimals) => {
458
+ const pValue = parseFloat(value);
459
+ if (isNaN(pValue)) {
460
+ return undefined;
461
+ }
462
+ value = limitDecimals(value, tokenDecimals);
463
+ const amount = parseUnits(value, tokenDecimals);
464
+ return bigNumberify(amount);
465
+ };
466
+ export function roundUpDivision(a, b) {
467
+ return (a + b - 1n) / b;
468
+ }
469
+ export function roundToTwoDecimals(n) {
470
+ return Math.round(n * 100) / 100;
471
+ }
472
+ export function roundToOrder(n, significantDigits = 1) {
473
+ const decimals = Math.max(n.toString().length - significantDigits, 0);
474
+ return (n / expandDecimals(1, decimals)) * expandDecimals(1, decimals);
475
+ }
476
+ export function roundBigIntToDecimals(value, tokenDecimals, roundToDecimals) {
477
+ const excessDecimals = tokenDecimals - roundToDecimals;
478
+ const divisor = BigInt(10 ** excessDecimals);
479
+ const scaledValue = value / divisor;
480
+ const remainder = scaledValue % 10n;
481
+ const roundedValue = remainder >= 5n ? scaledValue + 10n - remainder : scaledValue - remainder;
482
+ return roundedValue * divisor;
483
+ }
484
+ export function minBigNumber(...args) {
485
+ if (!args.length)
486
+ return undefined;
487
+ return args.reduce((acc, num) => (num < acc ? num : acc), args[0]);
488
+ }
489
+ export function maxbigint(...args) {
490
+ if (!args.length)
491
+ return undefined;
492
+ return args.reduce((acc, num) => (num > acc ? num : acc), args[0]);
493
+ }
494
+ export function removeTrailingZeros(amount) {
495
+ const amountWithoutZeros = Number(amount);
496
+ if (!amountWithoutZeros)
497
+ return amount;
498
+ return amountWithoutZeros;
499
+ }
500
+ export function serializeBigIntsInObject(obj) {
501
+ const result = Array.isArray(obj) ? [] : {};
502
+ for (const key in obj) {
503
+ const value = obj[key];
504
+ if (typeof value === "bigint") {
505
+ result[key] = { type: "bigint", value: String(value) };
506
+ }
507
+ else if (value && typeof value === "object") {
508
+ result[key] = serializeBigIntsInObject(value);
509
+ }
510
+ else {
511
+ result[key] = value;
512
+ }
513
+ }
514
+ return result;
515
+ }
516
+ export function deserializeBigIntsInObject(obj) {
517
+ const result = Array.isArray(obj) ? [] : {};
518
+ for (const key in obj) {
519
+ const value = obj[key];
520
+ if (typeof value === "object" &&
521
+ value !== null &&
522
+ (("type" in value && value.type === "bigint") || ("_type" in value && value._type === "BigNumber"))) {
523
+ if ("value" in value && typeof value.value === "string") {
524
+ result[key] = BigInt(value.value);
525
+ }
526
+ else if ("hex" in value && typeof value.hex === "string") {
527
+ if (value.hex.startsWith("-")) {
528
+ result[key] = BigInt(value.hex.slice(1)) * -1n;
529
+ }
530
+ else {
531
+ result[key] = BigInt(value.hex);
532
+ }
533
+ }
534
+ }
535
+ else if (value && typeof value === "object") {
536
+ result[key] = deserializeBigIntsInObject(value);
537
+ }
538
+ else {
539
+ result[key] = value;
540
+ }
541
+ }
542
+ return result;
543
+ }
544
+ export function calculateDisplayDecimals(price, decimals = USD_DECIMALS, visualMultiplier = 1) {
545
+ if (price === undefined || price === 0n)
546
+ return 2;
547
+ const priceNumber = bigintToNumber(bigMath.abs(price) * BigInt(visualMultiplier), decimals);
548
+ if (isNaN(priceNumber))
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;
564
+ return 9;
565
+ }
566
+ export function clamp(value, min, max) {
567
+ return Math.max(min, Math.min(value, max));
568
+ }
569
+ export function absDiffBps(value, base) {
570
+ if ((value === 0n && base !== 0n) || (value !== 0n && base === 0n)) {
571
+ return BASIS_POINTS_DIVISOR_BIGINT;
572
+ }
573
+ if (value === 0n && base === 0n) {
574
+ return 0n;
575
+ }
576
+ return bigMath.mulDiv(bigMath.abs(value - base), BASIS_POINTS_DIVISOR_BIGINT, base);
577
+ }