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