@mezo-org/passport 0.5.4-dev.2 → 0.5.4-dev.21

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 (54) hide show
  1. package/dist/src/api/portal.d.ts +1 -1
  2. package/dist/src/api/portal.d.ts.map +1 -1
  3. package/dist/src/components/Dropdown/Root/AccountBalance.d.ts.map +1 -1
  4. package/dist/src/components/Dropdown/Root/AccountBalance.js +1 -0
  5. package/dist/src/components/Dropdown/Root/AccountBalance.js.map +1 -1
  6. package/dist/src/components/Dropdown/Root/AccountBtcListing.d.ts.map +1 -1
  7. package/dist/src/components/Dropdown/Root/AccountBtcListing.js +4 -3
  8. package/dist/src/components/Dropdown/Root/AccountBtcListing.js.map +1 -1
  9. package/dist/src/components/Dropdown/Root/AccountMusdListing.js +3 -3
  10. package/dist/src/components/Dropdown/Root/AccountMusdListing.js.map +1 -1
  11. package/dist/src/components/Dropdown/Root/AccountOtherAssets.js +3 -3
  12. package/dist/src/components/Dropdown/Root/AccountOtherAssets.js.map +1 -1
  13. package/dist/src/hooks/index.d.ts +1 -1
  14. package/dist/src/hooks/index.d.ts.map +1 -1
  15. package/dist/src/hooks/index.js +1 -1
  16. package/dist/src/hooks/index.js.map +1 -1
  17. package/dist/src/hooks/useAssetsConversionRates.d.ts.map +1 -1
  18. package/dist/src/hooks/useAssetsConversionRates.js +15 -3
  19. package/dist/src/hooks/useAssetsConversionRates.js.map +1 -1
  20. package/dist/src/hooks/useBorrowData.d.ts.map +1 -1
  21. package/dist/src/hooks/useBorrowData.js +5 -6
  22. package/dist/src/hooks/useBorrowData.js.map +1 -1
  23. package/dist/src/hooks/useCollateralPrice.d.ts.map +1 -1
  24. package/dist/src/hooks/useCollateralPrice.js +3 -1
  25. package/dist/src/hooks/useCollateralPrice.js.map +1 -1
  26. package/dist/src/hooks/useTokensBalances.d.ts.map +1 -1
  27. package/dist/src/hooks/useTokensBalances.js +10 -13
  28. package/dist/src/hooks/useTokensBalances.js.map +1 -1
  29. package/dist/src/provider.d.ts +14 -3
  30. package/dist/src/provider.d.ts.map +1 -1
  31. package/dist/src/provider.js +3 -1
  32. package/dist/src/provider.js.map +1 -1
  33. package/package.json +1 -1
  34. package/src/api/portal.ts +1 -1
  35. package/src/components/Dropdown/Root/AccountBalance.tsx +1 -0
  36. package/src/components/Dropdown/Root/AccountBtcListing.tsx +5 -4
  37. package/src/components/Dropdown/Root/AccountMusdListing.tsx +4 -4
  38. package/src/components/Dropdown/Root/AccountOtherAssets.tsx +4 -4
  39. package/src/hooks/index.ts +1 -0
  40. package/src/hooks/useAssetsConversionRates.ts +17 -3
  41. package/src/hooks/useBorrowData.ts +6 -7
  42. package/src/hooks/useCollateralPrice.ts +4 -1
  43. package/src/hooks/useTokensBalances.ts +13 -16
  44. package/src/provider.ts +19 -4
  45. package/dist/src/utils/number2.d.ts +0 -106
  46. package/dist/src/utils/number2.d.ts.map +0 -1
  47. package/dist/src/utils/number2.js +0 -289
  48. package/dist/src/utils/number2.js.map +0 -1
  49. package/dist/src/utils/number2.test.d.ts +0 -2
  50. package/dist/src/utils/number2.test.d.ts.map +0 -1
  51. package/dist/src/utils/number2.test.js +0 -223
  52. package/dist/src/utils/number2.test.js.map +0 -1
  53. package/src/utils/number2.test.ts +0 -309
  54. package/src/utils/number2.ts +0 -419
@@ -18,6 +18,7 @@ export * from "./useSignInWithWallet"
18
18
  export * from "./useSignOut"
19
19
  export * from "./useSignUpWithWallet"
20
20
  export {
21
+ useTokensBalances,
21
22
  useInvalidateTokensBalances,
22
23
  useResetTokensBalances,
23
24
  } from "./useTokensBalances"
@@ -3,6 +3,7 @@ import { parseUnits } from "viem"
3
3
  import { ONE_SECOND_MS } from "../utils/time"
4
4
  import { usePortalApiClient } from "./usePortalApiClient"
5
5
  import { useCollateralPrice } from "./useCollateralPrice"
6
+ import { PortalStatistics } from "../api"
6
7
 
7
8
  export const CONVERSION_RATE_DECIMALS = 18
8
9
 
@@ -27,9 +28,22 @@ export function useAssetsConversionRates() {
27
28
 
28
29
  return useQuery({
29
30
  queryKey: [QUERY_KEY, collateralPrice],
30
- queryFn: async () => Promise.all([portalApiClient.getPortalStatistics()]),
31
+ queryFn: () => {
32
+ if (!collateralPriceData) {
33
+ throw new Error("Collateral price is not available.")
34
+ }
35
+
36
+ return Promise.all([
37
+ new Promise((resolve) => {
38
+ resolve(portalApiClient.getPortalStatistics())
39
+ }) as Promise<PortalStatistics>,
40
+ new Promise((resolve) => {
41
+ resolve(collateralPriceData)
42
+ }) as Promise<typeof collateralPriceData>,
43
+ ])
44
+ },
31
45
  enabled: !!collateralPrice,
32
- select: ([portalStatistics]) => {
46
+ select: ([portalStatistics, btcPrice]) => {
33
47
  const tTokenConversionRate = portalStatistics.tTokenPrice
34
48
 
35
49
  const tPrice = parseUnits(
@@ -40,7 +54,7 @@ export function useAssetsConversionRates() {
40
54
  return {
41
55
  rates: {
42
56
  mT: tPrice,
43
- BTC: BigInt(collateralPrice!),
57
+ BTC: btcPrice,
44
58
  },
45
59
  decimals: CONVERSION_RATE_DECIMALS,
46
60
  }
@@ -2,7 +2,6 @@ import { useReadContracts } from "wagmi"
2
2
  import { useCallback, useMemo } from "react"
3
3
  import { useQueryClient } from "@tanstack/react-query"
4
4
  import { formatUnits } from "viem"
5
- import { ONE_MINUTE_MS } from "../utils/time"
6
5
  import {
7
6
  mainnetBorrowContracts,
8
7
  testnetBorrowContracts,
@@ -92,12 +91,11 @@ const BORROWER_OPERATIONS_ABI = [
92
91
  * @param queryOptions Query options passed to the underlying `useQuery` hook.
93
92
  */
94
93
  export function useBorrowData(queryOptions = {}) {
95
- const { environment = "mainnet" } = usePassportContext()
94
+ const { environment = "mainnet", borrowDataRefetchInterval } =
95
+ usePassportContext()
96
96
  const walletAccount = useWalletAccount()
97
97
 
98
- const { data: collateralPriceData } = useCollateralPrice()
99
-
100
- const collateralPrice = collateralPriceData?.toString()
98
+ const { data: collateralPrice } = useCollateralPrice()
101
99
 
102
100
  const contractAddress = useMemo(() => {
103
101
  if (environment === "mainnet") {
@@ -134,7 +132,6 @@ export function useBorrowData(queryOptions = {}) {
134
132
  ],
135
133
  query: {
136
134
  enabled: !!walletAccount.accountAddress && !!collateralPrice,
137
- staleTime: 5 * ONE_MINUTE_MS,
138
135
  retry: 1,
139
136
  select: (data) => {
140
137
  if (!data || data.some((item) => !item.result))
@@ -155,7 +152,7 @@ export function useBorrowData(queryOptions = {}) {
155
152
  usd: convertToUsd(
156
153
  rawCollateral,
157
154
  DEBT_AND_COLL_PRECISION,
158
- BigInt(collateralPrice),
155
+ collateralPrice,
159
156
  DEBT_AND_COLL_PRECISION,
160
157
  ),
161
158
  }
@@ -182,6 +179,8 @@ export function useBorrowData(queryOptions = {}) {
182
179
  debtInUsd,
183
180
  }
184
181
  },
182
+ staleTime: borrowDataRefetchInterval,
183
+ refetchInterval: borrowDataRefetchInterval,
185
184
  ...queryOptions,
186
185
  },
187
186
  })
@@ -36,7 +36,8 @@ const PRICE_FEED_ABI = [
36
36
  * @param queryOptions Query options passed to the underlying `useQuery` hook.
37
37
  */
38
38
  export function useCollateralPrice(queryOptions = {}) {
39
- const { environment = "mainnet" } = usePassportContext()
39
+ const { environment = "mainnet", borrowDataRefetchInterval } =
40
+ usePassportContext()
40
41
  const walletAccount = useWalletAccount()
41
42
 
42
43
  const priceFeedContractAddress = useMemo(() => {
@@ -55,6 +56,8 @@ export function useCollateralPrice(queryOptions = {}) {
55
56
  chainId,
56
57
  query: {
57
58
  enabled: !!walletAccount.accountAddress,
59
+ staleTime: borrowDataRefetchInterval,
60
+ refetchInterval: borrowDataRefetchInterval,
58
61
  retry: 1,
59
62
  ...queryOptions,
60
63
  },
@@ -1,6 +1,7 @@
1
1
  import { useConfig } from "wagmi"
2
2
  import { Abi, formatUnits } from "viem"
3
3
  import {
4
+ keepPreviousData,
4
5
  useQuery,
5
6
  useQueryClient,
6
7
  UseQueryOptions,
@@ -124,20 +125,16 @@ export function useTokensBalances<T extends MezoChainToken[]>(
124
125
  walletAccount?.accountAddress,
125
126
  options.tokens,
126
127
  chainId,
127
- conversionRatesData?.decimals,
128
- conversionRatesData?.rates.BTC.toString(),
129
- conversionRatesData?.rates.mT.toString(),
130
128
  ],
131
129
  enabled: !!walletAccount?.accountAddress && !!conversionRatesData,
130
+ placeholderData: keepPreviousData,
132
131
  queryFn: async () => {
133
132
  const isMainnet = chainId === CHAIN_ID.mainnet
134
133
  const contractsMap = isMainnet
135
134
  ? mainnetTokenContracts
136
135
  : testnetTokenContracts
137
136
 
138
- const accountAddress = walletAccount?.accountAddress
139
-
140
- if (!accountAddress) {
137
+ if (!walletAccount?.accountAddress) {
141
138
  throw new Error("Account address is not available.")
142
139
  }
143
140
 
@@ -147,7 +144,7 @@ export function useTokensBalances<T extends MezoChainToken[]>(
147
144
  address,
148
145
  abi: BALANCE_OF_ABI,
149
146
  functionName: "balanceOf" as const,
150
- args: [accountAddress],
147
+ args: [walletAccount?.accountAddress],
151
148
  chainId,
152
149
  }
153
150
  })
@@ -157,7 +154,7 @@ export function useTokensBalances<T extends MezoChainToken[]>(
157
154
  }
158
155
 
159
156
  return Promise.all([
160
- getBalance(config, { address: accountAddress }),
157
+ getBalance(config, { address: walletAccount?.accountAddress, chainId }),
161
158
  readContracts(config, {
162
159
  contracts: tokenContracts,
163
160
  }),
@@ -167,7 +164,7 @@ export function useTokensBalances<T extends MezoChainToken[]>(
167
164
  ])
168
165
  },
169
166
  select: (data) => {
170
- const [btcBalance, tokensBalancesData, conversions] = data
167
+ const [btcBalance, tokensBalancesData, conversion] = data
171
168
 
172
169
  const parsedBtcBalance = {
173
170
  ...btcBalance,
@@ -175,8 +172,8 @@ export function useTokensBalances<T extends MezoChainToken[]>(
175
172
  usd: convertToUsd(
176
173
  btcBalance.value,
177
174
  btcBalance.decimals,
178
- conversions.rates.BTC,
179
- conversions.decimals,
175
+ conversion.rates.BTC,
176
+ conversion.decimals,
180
177
  ),
181
178
  }
182
179
 
@@ -201,7 +198,7 @@ export function useTokensBalances<T extends MezoChainToken[]>(
201
198
  value: normalizePrecision(
202
199
  tokenBalance.value,
203
200
  tokenBalance.decimals,
204
- conversions.decimals,
201
+ conversion.decimals,
205
202
  ),
206
203
  formatted: formatUnits(tokenBalance.value, tokenBalance.decimals),
207
204
  }
@@ -209,16 +206,16 @@ export function useTokensBalances<T extends MezoChainToken[]>(
209
206
  usd = convertToUsd(
210
207
  tokenBalance.value,
211
208
  tokenBalance.decimals,
212
- conversions.rates.BTC,
213
- conversions.decimals,
209
+ conversion.rates.BTC,
210
+ conversion.decimals,
214
211
  )
215
212
  }
216
213
  if (isTTokenCryptoAsset(tokenBalance.symbol)) {
217
214
  usd = convertToUsd(
218
215
  tokenBalance.value,
219
216
  tokenBalance.decimals,
220
- conversions.rates.mT,
221
- conversions.decimals,
217
+ conversion.rates.mT,
218
+ conversion.decimals,
222
219
  )
223
220
  }
224
221
 
package/src/provider.ts CHANGED
@@ -8,6 +8,8 @@ export interface PassportContextValue {
8
8
  environment?: Environment
9
9
  accountDataRefetchInterval: number
10
10
  nativeBalanceRefetchInterval: number
11
+ nativePriceRefetchInterval: number
12
+ borrowDataRefetchInterval: number
11
13
  }
12
14
 
13
15
  export const PassportContext = createContext<PassportContextValue | undefined>(
@@ -21,10 +23,19 @@ type PassportProviderProps = {
21
23
  environment?: Environment
22
24
  authApiUrl?: string
23
25
  portalApiUrl?: string
24
- /** Time in milliseconds after which account data (like mats or mezo id) in dropdown should be re-fetched. Default is 90000 (90 secs) */
26
+ /** Time in milliseconds after which account data (like mats or mezo id) in
27
+ * dropdown should be re-fetched. Default is 60000 (60 secs) */
25
28
  accountDataRefetchInterval?: number
26
- /** Time in milliseconds after which native balance in dropdown should be re-fetched. Default is 90000 (90 secs) */
29
+ /** Time in milliseconds after which native token balance in dropdown should
30
+ * be re-fetched. Default is 60000 (60 secs). */
27
31
  nativeBalanceRefetchInterval?: number
32
+ /** Time in milliseconds after which native token price in dropdown should be
33
+ * re-fetched. Default is 60000 (60 secs). */
34
+ nativePriceRefetchInterval?: number
35
+ /** Time in milliseconds after which borrow data in dropdown should be
36
+ * re-fetched. Default is 60000 (60 secs)
37
+ * price. */
38
+ borrowDataRefetchInterval?: number
28
39
  }
29
40
 
30
41
  export function PassportProvider({
@@ -32,8 +43,10 @@ export function PassportProvider({
32
43
  authApiUrl,
33
44
  portalApiUrl,
34
45
  children,
35
- accountDataRefetchInterval = 90 * ONE_SECOND_MS,
36
- nativeBalanceRefetchInterval = 90 * ONE_SECOND_MS,
46
+ accountDataRefetchInterval = 60 * ONE_SECOND_MS,
47
+ nativeBalanceRefetchInterval = 60 * ONE_SECOND_MS,
48
+ nativePriceRefetchInterval = 60 * ONE_SECOND_MS,
49
+ borrowDataRefetchInterval = 60 * ONE_SECOND_MS,
37
50
  }: PassportProviderProps) {
38
51
  if (environment && !["mainnet", "testnet"].includes(environment)) {
39
52
  throw new Error("Wrong environment passed to PassportProvider.")
@@ -51,6 +64,8 @@ export function PassportProvider({
51
64
  environment,
52
65
  accountDataRefetchInterval,
53
66
  nativeBalanceRefetchInterval,
67
+ nativePriceRefetchInterval,
68
+ borrowDataRefetchInterval,
54
69
  },
55
70
  },
56
71
  children,
@@ -1,106 +0,0 @@
1
- export declare const FLOATING_POINT_REGEX: RegExp;
2
- /** PUBLIC HELPER FUNCTIONS for calculations */
3
- /**
4
- * Multiplies a bigint with a decimal number, taking into account the decimal places.
5
- *
6
- * @param bigint - The bigint value to multiply.
7
- * @param number - The decimal number to multiply with.
8
- * @returns The result of the multiplication as a bigint.
9
- */
10
- export declare const multiplyBigIntWithDecimal: (bigint: bigint, number: number) => bigint;
11
- /**
12
- * Converts a fixed-point number to another fixed-point number with a different decimal precision.
13
- * @param args The arguments for the conversion.
14
- * - amount: required, the fixed-point number to convert.
15
- * - decimals: required, the current decimal precision of the number.
16
- * - targetDecimals: required, the target decimal precision for the conversion.
17
- * @returns The converted fixed-point number.
18
- */
19
- export declare const convertDecimals: ({ amount, decimals, targetDecimals, }: {
20
- amount: bigint;
21
- decimals: number;
22
- targetDecimals: number;
23
- }) => bigint;
24
- /** Helper functions for input components */
25
- /**
26
- * Trims decimal places to a specified precision - NO ROUNDING!
27
- * @param value The value to trim
28
- * @param precision The number of decimal places to keep
29
- * @returns The trimmed value
30
- */
31
- export declare const trimDecimals: (value: string, precision: number) => string;
32
- /**
33
- * Trims integer part to a specified length - NO ROUNDING!
34
- * @param value The value to trim
35
- * @param precision The number of integer places to keep
36
- * @returns The trimmed value
37
- * @deprecated just compare the value to the max allowed value in the input component
38
- */
39
- export declare const trimBeforeDecimals: (value: string, precision: number) => string;
40
- /**
41
- * Normalizes a decimal number input by removing invalid characters and preventing multiple dots.
42
- * @param value The value to normalize
43
- * @returns The normalized value
44
- */
45
- export declare const normalizeDecimalNumber: (value: string) => string;
46
- /**
47
- * CONVERSION FUNCTIONS
48
- * These functions convert between floating-point numbers and big integers as well as
49
- * provide human-readable formats.
50
- *
51
- * They are used to ensure that numbers are correctly formatted for display and calculations
52
- * and should be used in the UI and business logic to ensure correct number formatting.
53
- */
54
- /** Basic conversion bigint <-> float */
55
- /**
56
- * Converts a floating-point number to a big integer representation.
57
- * @param args The arguments for the conversion.
58
- * - amount: required, the floating-point number to convert.
59
- * - decimals: optional, the number of decimal places to consider.
60
- * @returns The big integer representation of the floating-point number.
61
- */
62
- export declare const floatToBigInt: ({ amount, decimals, }: {
63
- amount: string | number;
64
- decimals?: number;
65
- }) => bigint;
66
- /**
67
- * Converts a big integer representation to a floating-point number.
68
- * @param args The arguments for the conversion.
69
- * - amount: required, the big integer representation to convert.
70
- * - decimals: optional, the number of decimal places to consider.
71
- * - desiredDecimals: optional, the desired number of decimal places for the output.
72
- * @returns The floating-point representation of the big integer.
73
- */
74
- export declare const bigIntToFloat: ({ amount, decimals, desiredDecimals, }: {
75
- amount: bigint;
76
- decimals?: number;
77
- desiredDecimals?: number;
78
- }) => string;
79
- /** Human-readable formats */
80
- type AmountAsHumanReadableArguments<T extends number | string | bigint> = {
81
- amount: T;
82
- desiredDecimals?: number;
83
- minDecimals?: number;
84
- decimals?: number;
85
- };
86
- /**
87
- * Helpers for setting correct arguments and getting unified human-readable
88
- * formats across the app with _toHumanReadableFormat functions.
89
- */
90
- export declare const amountAsUSD: <T extends number | string | bigint>(args: AmountAsHumanReadableArguments<T>) => AmountAsHumanReadableArguments<T>;
91
- export declare const amountAsToken: <T extends number | string | bigint>(args: AmountAsHumanReadableArguments<T>) => AmountAsHumanReadableArguments<T>;
92
- export declare const amountAsMusd: <T extends number | string | bigint>(args: AmountAsHumanReadableArguments<T>) => AmountAsHumanReadableArguments<T>;
93
- export declare const amountAsMats: <T extends number | string | bigint>(args: AmountAsHumanReadableArguments<T>) => AmountAsHumanReadableArguments<T>;
94
- /**
95
- * Converts a floating-point number to a human-readable format - with thousands
96
- * separators and specified decimal places.
97
- * @param args The arguments for the conversion.
98
- * - amount: required, the floating-point number to convert.
99
- * - desiredDecimals: optional, the desired number of decimal places for the output.
100
- * - minDecimals: optional, the minimum number of decimal places.
101
- * @returns The human-readable format of the floating-point number.
102
- */
103
- export declare const floatToHumanReadableFormat: ({ amount, desiredDecimals, minDecimals, }: AmountAsHumanReadableArguments<number | string>) => string;
104
- export declare const bigIntToHumanReadableFormat: ({ amount, decimals, desiredDecimals, minDecimals, }: AmountAsHumanReadableArguments<bigint>) => string;
105
- export {};
106
- //# sourceMappingURL=number2.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"number2.d.ts","sourceRoot":"","sources":["../../../src/utils/number2.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,oBAAoB,QAAsC,CAAA;AAuFvE,+CAA+C;AAE/C;;;;;;GAMG;AACH,eAAO,MAAM,yBAAyB,GACpC,QAAQ,MAAM,EACd,QAAQ,MAAM,KACb,MAqBF,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,eAAe,GAAI,uCAI7B;IACD,MAAM,EAAE,MAAM,CAAA;IACd,QAAQ,EAAE,MAAM,CAAA;IAChB,cAAc,EAAE,MAAM,CAAA;CACvB,KAAG,MAMH,CAAA;AAED,4CAA4C;AAE5C;;;;;GAKG;AACH,eAAO,MAAM,YAAY,GAAI,OAAO,MAAM,EAAE,WAAW,MAAM,KAAG,MAK/D,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,GAC7B,OAAO,MAAM,EACb,WAAW,MAAM,KAChB,MAMF,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,GAAI,OAAO,MAAM,WACM,CAAA;AAE1D;;;;;;;GAOG;AAEH,yCAAyC;AAEzC;;;;;;GAMG;AACH,eAAO,MAAM,aAAa,GAAI,uBAG3B;IACD,MAAM,EAAE,MAAM,GAAG,MAAM,CAAA;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB,KAAG,MAeH,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,aAAa,GAAI,wCAI3B;IACD,MAAM,EAAE,MAAM,CAAA;IACd,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,eAAe,CAAC,EAAE,MAAM,CAAA;CACzB,KAAG,MAqEH,CAAA;AAED,8BAA8B;AAE9B,KAAK,8BAA8B,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,GAAG,MAAM,IAAI;IACxE,MAAM,EAAE,CAAC,CAAA;IACT,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB,CAAA;AAED;;;GAGG;AAEH,eAAO,MAAM,WAAW,GAAI,CAAC,SAAS,MAAM,GAAG,MAAM,GAAG,MAAM,EAC5D,MAAM,8BAA8B,CAAC,CAAC,CAAC,KACtC,8BAA8B,CAAC,CAAC,CAIjC,CAAA;AAEF,eAAO,MAAM,aAAa,GAAI,CAAC,SAAS,MAAM,GAAG,MAAM,GAAG,MAAM,EAC9D,MAAM,8BAA8B,CAAC,CAAC,CAAC,KACtC,8BAA8B,CAAC,CAAC,CAIjC,CAAA;AAEF,eAAO,MAAM,YAAY,GAAI,CAAC,SAAS,MAAM,GAAG,MAAM,GAAG,MAAM,EAC7D,MAAM,8BAA8B,CAAC,CAAC,CAAC,KACtC,8BAA8B,CAAC,CAAC,CAKjC,CAAA;AAEF,eAAO,MAAM,YAAY,GAAI,CAAC,SAAS,MAAM,GAAG,MAAM,GAAG,MAAM,EAC7D,MAAM,8BAA8B,CAAC,CAAC,CAAC,KACtC,8BAA8B,CAAC,CAAC,CAIjC,CAAA;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,0BAA0B,GAAI,2CAIxC,8BAA8B,CAAC,MAAM,GAAG,MAAM,CAAC,KAAG,MACa,CAAA;AAElE,eAAO,MAAM,2BAA2B,GAAI,qDAKzC,8BAA8B,CAAC,MAAM,CAAC,KAAG,MAkC3C,CAAA"}
@@ -1,289 +0,0 @@
1
- // Matches floating point numbers with optional thousands separators
2
- export const FLOATING_POINT_REGEX = /^[^0-9]*([0-9,]+)(?:\.([0-9]*))?$/;
3
- const FRIENDLY_DECIMALS_AMOUNT = 6;
4
- /**
5
- * HELPER FUNCTIONS
6
- * These functions are used to convert between floating-point numbers and fixed-point numbers.
7
- * They handle parsing, conversion, and formatting of numbers with specific decimal places.
8
- * They shouldn't be used directly in the UI or business logic.
9
- */
10
- /**
11
- * Parses a floating-point string into a fixed-point number representation.
12
- * @param floatingPointString The floating-point string to parse.
13
- * @returns The fixed-point number representation or undefined if parsing fails.
14
- */
15
- const parseToFixedPointNumber = (floatingPointString) => {
16
- if (!floatingPointString.match(FLOATING_POINT_REGEX)) {
17
- return undefined;
18
- }
19
- const [whole, decimals, ...extra] = floatingPointString.split(".");
20
- // Only one `.` supported.
21
- if (extra.length > 0) {
22
- return undefined;
23
- }
24
- const noThousandsSeparatorWhole = whole.replace(",", "");
25
- const setDecimals = decimals ?? "";
26
- try {
27
- return {
28
- amount: BigInt([noThousandsSeparatorWhole, setDecimals].join("")),
29
- decimals: setDecimals.length,
30
- };
31
- }
32
- catch (error) {
33
- return undefined;
34
- }
35
- };
36
- /**
37
- * Separates thousands in a number with commas.
38
- * @param value The value to format.
39
- * @param minDecimals The minimum number of decimal places.
40
- * @param maxDecimals The maximum number of decimal places.
41
- * @returns The formatted value with thousands separators.
42
- */
43
- const separateThousandsWithComma = (value, minDecimals = 0, maxDecimals = 2) => {
44
- let adjustedValue = value;
45
- let adjustedMaxDecimals = maxDecimals;
46
- // If passed value is not numeric we should return 0
47
- if (Number.isNaN(+value.toString())) {
48
- adjustedValue = 0;
49
- }
50
- if (typeof adjustedValue === "string") {
51
- adjustedValue = +adjustedValue;
52
- }
53
- if (minDecimals > maxDecimals) {
54
- adjustedMaxDecimals = minDecimals;
55
- }
56
- // Ensure maximumFractionDigits is within allowed range [0, 20]
57
- const safeMaxDecimals = Math.max(0, Math.min(adjustedMaxDecimals, 20));
58
- // @ts-expect-error - `maximumFractionDigits` wants to get number less than 21,
59
- // but as the tokens have 18 decimals have, we can safely pass a parameter
60
- return adjustedValue.toLocaleString("en-US", {
61
- minimumFractionDigits: minDecimals,
62
- maximumFractionDigits: safeMaxDecimals,
63
- roundingMode: "halfExpand",
64
- });
65
- };
66
- /** PUBLIC HELPER FUNCTIONS for calculations */
67
- /**
68
- * Multiplies a bigint with a decimal number, taking into account the decimal places.
69
- *
70
- * @param bigint - The bigint value to multiply.
71
- * @param number - The decimal number to multiply with.
72
- * @returns The result of the multiplication as a bigint.
73
- */
74
- export const multiplyBigIntWithDecimal = (bigint, number) => {
75
- const numberString = number.toString();
76
- const scientificMatch = /^1e-(\d+)$/.exec(numberString);
77
- // Ensure we can correctly deal with scientific number expression
78
- if (scientificMatch) {
79
- const exponent = parseInt(scientificMatch[1], 10);
80
- const scale = BigInt(10 ** exponent);
81
- return (bigint * 1n) / scale;
82
- }
83
- const decimalsPart = number.toString().split(".")[1];
84
- const decimalsCount = decimalsPart ? decimalsPart.length : 0;
85
- if (!decimalsCount)
86
- return bigint * BigInt(number);
87
- const scale = BigInt(10 ** decimalsCount);
88
- const scaledNumber = BigInt(Math.round(number * Number(scale)));
89
- return (bigint * scaledNumber) / scale;
90
- };
91
- /**
92
- * Converts a fixed-point number to another fixed-point number with a different decimal precision.
93
- * @param args The arguments for the conversion.
94
- * - amount: required, the fixed-point number to convert.
95
- * - decimals: required, the current decimal precision of the number.
96
- * - targetDecimals: required, the target decimal precision for the conversion.
97
- * @returns The converted fixed-point number.
98
- */
99
- export const convertDecimals = ({ amount, decimals, targetDecimals, }) => {
100
- if (decimals >= targetDecimals) {
101
- return amount / 10n ** BigInt(decimals - targetDecimals);
102
- }
103
- return amount * 10n ** BigInt(targetDecimals - decimals);
104
- };
105
- /** Helper functions for input components */
106
- /**
107
- * Trims decimal places to a specified precision - NO ROUNDING!
108
- * @param value The value to trim
109
- * @param precision The number of decimal places to keep
110
- * @returns The trimmed value
111
- */
112
- export const trimDecimals = (value, precision) => {
113
- const [integerPart, decimalPart = ""] = value.split(".");
114
- return decimalPart.length > precision
115
- ? `${integerPart}.${decimalPart.slice(0, precision)}`
116
- : value;
117
- };
118
- /**
119
- * Trims integer part to a specified length - NO ROUNDING!
120
- * @param value The value to trim
121
- * @param precision The number of integer places to keep
122
- * @returns The trimmed value
123
- * @deprecated just compare the value to the max allowed value in the input component
124
- */
125
- export const trimBeforeDecimals = (value, precision) => {
126
- const [integerPart, decimalPart = ""] = value.split(".");
127
- return integerPart.length > precision
128
- ? `${integerPart.slice(0, precision)}.${decimalPart}`
129
- : value;
130
- };
131
- /**
132
- * Normalizes a decimal number input by removing invalid characters and preventing multiple dots.
133
- * @param value The value to normalize
134
- * @returns The normalized value
135
- */
136
- export const normalizeDecimalNumber = (value) => value.replace(/[^0-9.]/g, "").replace(/\.(?=.*\.)/g, ""); // Remove all dots except the first one
137
- /**
138
- * CONVERSION FUNCTIONS
139
- * These functions convert between floating-point numbers and big integers as well as
140
- * provide human-readable formats.
141
- *
142
- * They are used to ensure that numbers are correctly formatted for display and calculations
143
- * and should be used in the UI and business logic to ensure correct number formatting.
144
- */
145
- /** Basic conversion bigint <-> float */
146
- /**
147
- * Converts a floating-point number to a big integer representation.
148
- * @param args The arguments for the conversion.
149
- * - amount: required, the floating-point number to convert.
150
- * - decimals: optional, the number of decimal places to consider.
151
- * @returns The big integer representation of the floating-point number.
152
- */
153
- export const floatToBigInt = ({ amount, decimals = 18, }) => {
154
- const parsedAmount = amount.toString();
155
- const fixedPointAmount = parseToFixedPointNumber(parsedAmount);
156
- if (typeof fixedPointAmount === "undefined") {
157
- return 0n;
158
- }
159
- const bigIntAmount = convertDecimals({
160
- amount: fixedPointAmount.amount,
161
- decimals: fixedPointAmount.decimals,
162
- targetDecimals: decimals,
163
- });
164
- return bigIntAmount;
165
- };
166
- /**
167
- * Converts a big integer representation to a floating-point number.
168
- * @param args The arguments for the conversion.
169
- * - amount: required, the big integer representation to convert.
170
- * - decimals: optional, the number of decimal places to consider.
171
- * - desiredDecimals: optional, the desired number of decimal places for the output.
172
- * @returns The floating-point representation of the big integer.
173
- */
174
- export const bigIntToFloat = ({ amount, decimals = 18, desiredDecimals = decimals, }) => {
175
- let isNegative = false;
176
- let normalizedAmount = amount;
177
- if (amount < 0n) {
178
- normalizedAmount = -amount;
179
- isNegative = true;
180
- }
181
- const desiredDecimalsAmount = normalizedAmount / 10n ** BigInt(Math.max(0, decimals - desiredDecimals));
182
- // Desired decimals amount with additional decimal to check if number
183
- // should be rounded up
184
- const desiredDecimalsAmountWithAdditionalDecimal = normalizedAmount /
185
- 10n ** BigInt(Math.max(0, decimals - desiredDecimals - 1));
186
- // We are getting the first value that has been cut off
187
- const firstDecimalAfterCutOff = desiredDecimalsAmountWithAdditionalDecimal
188
- .toString()
189
- .at(-1);
190
- // Padding amount when its length is smaller than desired
191
- const parsedDesiredAmount = desiredDecimalsAmount
192
- .toString()
193
- .padStart(desiredDecimals + 1, "0");
194
- const integersPart = parsedDesiredAmount.slice(0, -desiredDecimals);
195
- const decimalsPart = parsedDesiredAmount.slice(-desiredDecimals);
196
- // If number is above or equal to 5 we should round up the number
197
- const shouldIncreaseDecimalsPart = Number(firstDecimalAfterCutOff) >= 5 && desiredDecimals !== decimals;
198
- // If above is true we add 1 to the decimals value and convert it back to string
199
- const adjustedDecimalsPart = shouldIncreaseDecimalsPart
200
- ? (Number(decimalsPart) + 1).toString().padStart(desiredDecimals, "0")
201
- : decimalsPart;
202
- // Determining whether integer part needs to be increased due to rounding up
203
- const shouldIncreaseIntegerPart = (decimalsPart === "0" && adjustedDecimalsPart !== decimalsPart) ||
204
- adjustedDecimalsPart.length > decimalsPart.length;
205
- // If above is true we add 1 to the integers value and convert it back to string
206
- // and set first value of decimals part to 0
207
- const adjustedIntegersPart = shouldIncreaseIntegerPart
208
- ? (Number(integersPart) + 1).toString()
209
- : integersPart;
210
- const decimalsPartAfterIntegersAdjustments = shouldIncreaseIntegerPart
211
- ? `0${adjustedDecimalsPart.slice(1)}`
212
- : adjustedDecimalsPart;
213
- // Inserting "." to separate integers part from decimal part
214
- const desiredAmount = [
215
- ...adjustedIntegersPart,
216
- ".",
217
- ...decimalsPartAfterIntegersAdjustments,
218
- ].join("");
219
- // Remove trailing zeros and the trailing decimal point (if exists)
220
- const trimmedDesiredAmount = desiredAmount.replace(/(?:\.0*|(\.\d+?)0+)$/, "$1");
221
- return isNegative ? `-${trimmedDesiredAmount}` : trimmedDesiredAmount;
222
- };
223
- /**
224
- * Helpers for setting correct arguments and getting unified human-readable
225
- * formats across the app with _toHumanReadableFormat functions.
226
- */
227
- export const amountAsUSD = (args) => ({
228
- desiredDecimals: 2,
229
- minDecimals: 2,
230
- ...args,
231
- });
232
- export const amountAsToken = (args) => ({
233
- desiredDecimals: FRIENDLY_DECIMALS_AMOUNT,
234
- minDecimals: 0,
235
- ...args,
236
- });
237
- export const amountAsMusd = (args) => ({
238
- desiredDecimals: 2,
239
- minDecimals: 2,
240
- decimals: 18, // MUSD has 18 decimals
241
- ...args,
242
- });
243
- export const amountAsMats = (args) => ({
244
- desiredDecimals: 0,
245
- minDecimals: 0,
246
- ...args,
247
- });
248
- /**
249
- * Converts a floating-point number to a human-readable format - with thousands
250
- * separators and specified decimal places.
251
- * @param args The arguments for the conversion.
252
- * - amount: required, the floating-point number to convert.
253
- * - desiredDecimals: optional, the desired number of decimal places for the output.
254
- * - minDecimals: optional, the minimum number of decimal places.
255
- * @returns The human-readable format of the floating-point number.
256
- */
257
- export const floatToHumanReadableFormat = ({ amount, desiredDecimals = 2, // treat is as an USD amount by default
258
- minDecimals = 0, }) => separateThousandsWithComma(amount, minDecimals, desiredDecimals);
259
- export const bigIntToHumanReadableFormat = ({ amount, decimals = 18, desiredDecimals = FRIENDLY_DECIMALS_AMOUNT, // treat is as a token by default
260
- minDecimals = 0, }) => {
261
- let isNegative = false;
262
- let normalizedAmount = amount;
263
- let adjustedDesiredDecimals = desiredDecimals;
264
- if (minDecimals > desiredDecimals) {
265
- adjustedDesiredDecimals = minDecimals;
266
- }
267
- if (normalizedAmount < 0n) {
268
- normalizedAmount = -normalizedAmount;
269
- isNegative = true;
270
- }
271
- const trimmedDesiredAmount = bigIntToFloat({
272
- amount: normalizedAmount,
273
- decimals,
274
- desiredDecimals: adjustedDesiredDecimals,
275
- });
276
- if (trimmedDesiredAmount === "0" && normalizedAmount !== 0n) {
277
- const decimalsString = "1".padStart(adjustedDesiredDecimals, "0");
278
- return `<0.${decimalsString}`;
279
- }
280
- const desiredValue = isNegative
281
- ? `-${trimmedDesiredAmount}`
282
- : trimmedDesiredAmount;
283
- return floatToHumanReadableFormat({
284
- amount: desiredValue,
285
- desiredDecimals: adjustedDesiredDecimals,
286
- minDecimals,
287
- });
288
- };
289
- //# sourceMappingURL=number2.js.map