From: Chris Duncan Date: Fri, 8 Aug 2025 18:11:17 +0000 (-0700) Subject: Fix fractional raw handling and allow zero amounts. X-Git-Tag: v0.10.5~43^2~21 X-Git-Url: https://git.codecow.com/?a=commitdiff_plain;h=154dd363e181e1eb33d6575783ec0528ccb01eaa;p=libnemo.git Fix fractional raw handling and allow zero amounts. --- 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