]> git.codecow.com Git - libnemo.git/commitdiff
Fix fractional raw handling and allow zero amounts.
authorChris Duncan <chris@zoso.dev>
Fri, 8 Aug 2025 18:11:17 +0000 (11:11 -0700)
committerChris Duncan <chris@zoso.dev>
Fri, 8 Aug 2025 18:11:17 +0000 (11:11 -0700)
src/lib/tools.ts

index a2399949829cf1f5bb86aa03a9279297e17b046f..ea597eaf71b239b2f87b631e40c87f105a5045f4 100644 (file)
@@ -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