|
1 | 1 | /**
|
2 |
| - * Ethereum denominations and conversion utilities |
| 2 | + * Utility functions for handling Ethereum denominations |
| 3 | + * Provides conversion between ETH/tokens and their smallest units (wei/base units) |
3 | 4 | */
|
4 | 5 |
|
5 |
| -// Denomination constants with their values in wei |
6 |
| -export const DENOMINATIONS = { |
7 |
| - wei: '1', |
8 |
| - kwei: '1000', |
9 |
| - mwei: '1000000', |
10 |
| - gwei: '1000000000', |
11 |
| - microether: '1000000000000', |
12 |
| - milliether: '1000000000000000', |
13 |
| - ether: '1000000000000000000', |
14 |
| -} as const; |
| 6 | +// Constants |
| 7 | +const ETHER_DECIMALS = 18; |
15 | 8 |
|
16 |
| -export type EthDenomination = keyof typeof DENOMINATIONS; |
17 |
| - |
18 |
| -// Unit type can be either a predefined denomination or a number representing decimal places |
19 |
| -export type UnitType = EthDenomination | number; |
| 9 | +/** |
| 10 | + * Converts a string or number representing ETH to wei (the smallest unit) |
| 11 | + * @param etherStr - The ETH amount as a string or number |
| 12 | + * @returns The amount in wei as BigInt |
| 13 | + */ |
| 14 | +export function parseEther(etherStr: string | number): bigint { |
| 15 | + return parseUnits(etherStr, ETHER_DECIMALS); |
| 16 | +} |
20 | 17 |
|
21 | 18 | /**
|
22 |
| - * Gets the wei value for a given unit |
23 |
| - * @param unit - The unit (either a predefined denomination or a decimal precision number) |
24 |
| - * @returns The wei value as BigInt |
| 19 | + * Converts wei (the smallest unit) to a string representing ETH |
| 20 | + * @param wei - The amount in wei as BigInt or string |
| 21 | + * @returns The amount in ETH as a decimal string |
25 | 22 | */
|
26 |
| -function getWeiValue(unit: UnitType): bigint { |
27 |
| - if (typeof unit === 'number') { |
28 |
| - return BigInt(10) ** BigInt(unit); |
29 |
| - } |
30 |
| - return BigInt(DENOMINATIONS[unit]); |
| 23 | +export function formatEther(wei: bigint | string): string { |
| 24 | + return formatUnits(wei, ETHER_DECIMALS); |
31 | 25 | }
|
32 | 26 |
|
33 | 27 | /**
|
34 |
| - * Converts from one unit to another |
35 |
| - * @param amount - The amount to convert |
36 |
| - * @param fromUnit - The source unit (denomination name or decimal precision) |
37 |
| - * @param toUnit - The target unit (denomination name or decimal precision) |
38 |
| - * @returns The converted amount as string |
| 28 | + * Converts a human-readable token amount to its smallest unit |
| 29 | + * @param amount - The token amount as a string or number |
| 30 | + * @param decimals - The number of decimals the token uses |
| 31 | + * @returns The amount in the smallest unit as BigInt |
39 | 32 | */
|
40 |
| -export function convert( |
41 |
| - amount: string | number, |
42 |
| - fromUnit: UnitType, |
43 |
| - toUnit: UnitType |
44 |
| -): string { |
45 |
| - const amountStr = typeof amount === 'string' ? amount : amount.toString(); |
46 |
| - |
47 |
| - // Get wei values for each unit |
48 |
| - const fromWei = getWeiValue(fromUnit); |
49 |
| - const toWei = getWeiValue(toUnit); |
50 |
| - |
51 |
| - // Handle decimal points in the input |
52 |
| - let [whole, decimal] = amountStr.split('.'); |
53 |
| - whole = whole || '0'; |
54 |
| - decimal = decimal || ''; |
55 |
| - |
56 |
| - // Calculate base-10 decimals in fromUnit |
57 |
| - const fromDecimals = typeof fromUnit === 'number' |
58 |
| - ? fromUnit |
59 |
| - : DENOMINATIONS[fromUnit].length - 1; |
60 |
| - |
61 |
| - // Convert to BigInt with proper decimal handling |
62 |
| - let valueInSmallestUnit; |
63 |
| - if (decimal) { |
64 |
| - // Scale the decimal part properly |
65 |
| - const scaledDecimal = decimal.padEnd(Number(fromDecimals), '0').slice(0, Number(fromDecimals)); |
66 |
| - // Convert decimal part to equivalent wei value |
67 |
| - const decimalValue = BigInt(scaledDecimal) * BigInt(10) ** BigInt(Math.max(0, Number(fromDecimals) - decimal.length)); |
68 |
| - valueInSmallestUnit = BigInt(whole) * fromWei + decimalValue; |
| 33 | +export function parseUnits(amount: string | number, decimals: number): bigint { |
| 34 | + // Validate inputs |
| 35 | + if (decimals < 0 || !Number.isInteger(decimals)) { |
| 36 | + throw new Error('Decimals must be a non-negative integer'); |
| 37 | + } |
| 38 | + |
| 39 | + // Convert amount to string |
| 40 | + const amountStr = amount.toString(); |
| 41 | + |
| 42 | + // Handle scientific notation if present |
| 43 | + if (amountStr.includes('e')) { |
| 44 | + // Parse scientific notation directly without recursion |
| 45 | + const [mantissa, exponentStr] = amountStr.split('e'); |
| 46 | + const exponent = parseInt(exponentStr); |
| 47 | + |
| 48 | + // Handle the mantissa with its own decimal places |
| 49 | + let [intPart, fracPart = ''] = mantissa.split('.'); |
| 50 | + |
| 51 | + if (exponent >= 0) { |
| 52 | + // Positive exponent - shift decimal point to the right |
| 53 | + if (fracPart.length <= exponent) { |
| 54 | + // Pad with zeros as needed |
| 55 | + const result = intPart + fracPart.padEnd(exponent, '0'); |
| 56 | + return parseUnits(result, decimals); |
| 57 | + } else { |
| 58 | + // Move decimal point within the fraction |
| 59 | + const result = intPart + fracPart.substring(0, exponent) + '.' + fracPart.substring(exponent); |
| 60 | + return parseUnits(result, decimals); |
| 61 | + } |
| 62 | + } else { |
| 63 | + // Negative exponent - shift decimal point to the left |
| 64 | + const absExponent = Math.abs(exponent); |
| 65 | + if (intPart.length <= absExponent) { |
| 66 | + // Result is < 1 |
| 67 | + const padding = '0'.repeat(absExponent - intPart.length); |
| 68 | + const result = '0.' + padding + intPart + fracPart; |
| 69 | + return parseUnits(result, decimals); |
| 70 | + } else { |
| 71 | + // Insert decimal point in the integer part |
| 72 | + const splitPoint = intPart.length - absExponent; |
| 73 | + const result = intPart.substring(0, splitPoint) + '.' + intPart.substring(splitPoint) + fracPart; |
| 74 | + return parseUnits(result, decimals); |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + // Split the decimal string |
| 80 | + let [integerPart, fractionPart = ''] = amountStr.split('.'); |
| 81 | + |
| 82 | + // Remove leading zeros from the integer part (but keep at least one digit) |
| 83 | + integerPart = integerPart.replace(/^0+(?=\d)/, ''); |
| 84 | + if (integerPart === '') integerPart = '0'; |
| 85 | + |
| 86 | + // Pad or truncate the fraction part according to decimals |
| 87 | + if (fractionPart.length > decimals) { |
| 88 | + fractionPart = fractionPart.slice(0, decimals); |
69 | 89 | } else {
|
70 |
| - valueInSmallestUnit = BigInt(whole) * fromWei; |
| 90 | + fractionPart = fractionPart.padEnd(decimals, '0'); |
71 | 91 | }
|
72 | 92 |
|
73 |
| - // Convert to target unit using uniform division |
74 |
| - const result = valueInSmallestUnit / toWei; |
75 |
| - return result.toString(); |
76 |
| -} |
| 93 | + // Combine integer and fraction parts without decimal point |
| 94 | + const result = integerPart + fractionPart; |
77 | 95 |
|
78 |
| -/** |
79 |
| - * Converts from ETH to any unit |
80 |
| - * @param amount - The amount in ETH |
81 |
| - * @param toUnit - The target unit (denomination name or decimal precision) |
82 |
| - * @returns The converted amount as string |
83 |
| - */ |
84 |
| -export function ethToUnit(amount: string | number, toUnit: UnitType): string { |
85 |
| - return convert(amount, 'ether', toUnit); |
| 96 | + // Convert to BigInt - remove leading zeros to prevent octal interpretation |
| 97 | + return BigInt(result.replace(/^0+(?=\d)/, '') || '0'); |
86 | 98 | }
|
87 | 99 |
|
88 | 100 | /**
|
89 |
| - * Converts from any unit to ETH |
90 |
| - * @param amount - The amount in the source unit |
91 |
| - * @param fromUnit - The source unit (denomination name or decimal precision) |
92 |
| - * @returns The amount in ETH as string |
| 101 | + * Converts an amount in smallest units to a human-readable token amount |
| 102 | + * @param amount - The amount in the smallest units as BigInt or string |
| 103 | + * @param decimals - The number of decimals the token uses |
| 104 | + * @returns The human-readable token amount as a decimal string |
93 | 105 | */
|
94 |
| -export function unitToEth(amount: string | number, fromUnit: UnitType): string { |
95 |
| - return convert(amount, fromUnit, 'ether'); |
| 106 | +export function formatUnits(amount: bigint | string, decimals: number): string { |
| 107 | + // Validate inputs |
| 108 | + if (decimals < 0 || !Number.isInteger(decimals)) { |
| 109 | + throw new Error('Decimals must be a non-negative integer'); |
| 110 | + } |
| 111 | + |
| 112 | + // Convert amount to string |
| 113 | + const amountStr = amount.toString(); |
| 114 | + |
| 115 | + // If amount is 0, return "0" |
| 116 | + if (amountStr === '0') return '0'; |
| 117 | + |
| 118 | + // Pad with leading zeros to ensure we have at least 'decimals' digits |
| 119 | + const padded = amountStr.padStart(decimals, '0'); |
| 120 | + |
| 121 | + // Calculate the integer part and fractional part positions |
| 122 | + const integerPartLength = Math.max(0, padded.length - decimals); |
| 123 | + |
| 124 | + // Extract the integer and fraction parts |
| 125 | + const integerPart = integerPartLength > 0 ? padded.slice(0, integerPartLength) : '0'; |
| 126 | + const fractionPart = padded.slice(integerPartLength); |
| 127 | + |
| 128 | + // Trim trailing zeros from fraction part |
| 129 | + const trimmedFraction = fractionPart.replace(/0+$/, ''); |
| 130 | + |
| 131 | + // Combine the parts with a decimal point if necessary |
| 132 | + return trimmedFraction.length > 0 |
| 133 | + ? `${integerPart}.${trimmedFraction}` |
| 134 | + : integerPart; |
96 | 135 | }
|
0 commit comments