From 154dd363e181e1eb33d6575783ec0528ccb01eaa Mon Sep 17 00:00:00 2001 From: Chris Duncan Date: Fri, 8 Aug 2025 11:11:17 -0700 Subject: [PATCH] Fix fractional raw handling and allow zero amounts. --- src/lib/tools.ts | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/src/lib/tools.ts b/src/lib/tools.ts index a239994..ea597ea 100644 --- a/src/lib/tools.ts +++ b/src/lib/tools.ts @@ -50,26 +50,28 @@ export function convert (amount: unknown, inputUnit: unknown, outputUnit: unknow let [i, f] = typeof amount === 'string' ? amount.split('.') : amount.toString().split('.') + i = i.replace(/^0*/g, '') + f = f?.replace(/0*$/g, '') - // convert to raw const inUnit = UNITS[inputUnit.toUpperCase()] - i = i.padEnd(i.length + inUnit, '0') - let int = BigInt(i) + const intShift = i.length + inUnit + if (f?.length > inUnit) { + throw new RangeError('Amount contains fractional raw') + } + + // convert to raw + let int = BigInt(i.padEnd(intShift, '0') || '0') if (f != null) { - f = f.padEnd(f.length + inUnit, '0') - let frac = BigInt(f) - const remainder = frac % (10n ** BigInt(inUnit)) - if (remainder > 0n) { - throw new Error('Amount contains fractional raw', { cause: remainder }) - } - frac /= 10n ** BigInt(f.length - inUnit) + const fracShift = f?.length + inUnit + let frac = BigInt(f?.padEnd(fracShift, '0') || '0') + frac /= 10n ** BigInt(f.length) int += frac } if (int > MAX_SUPPLY) { throw new Error('Amount exceeds available supply') } - if (int < 1n) { - throw new Error('Amount must be at least 1 raw') + if (int < 0n) { + throw new Error('Amount must be non-negative') } if (format === 'bigint') { return int -- 2.47.3