(text: string | number | bigint)
| 91 | } |
| 92 | |
| 93 | static parseAmount(text: string | number | bigint): number { |
| 94 | if (typeof text !== 'string') { |
| 95 | text = text.toString(); |
| 96 | } |
| 97 | |
| 98 | const regex = '^(\\d*(\\.\\d{0,8})?)\\s*(' + Object.keys(Constants.UNITS2).join('|') + ')?$'; |
| 99 | const match = new RegExp(regex, 'i').exec(text.trim()); |
| 100 | |
| 101 | if (!match || match.length === 0) { |
| 102 | // Die since this is likely a system error |
| 103 | Utils.die('Invalid amount: ' + text); |
| 104 | } |
| 105 | |
| 106 | const amount = parseFloat(match[1]); |
| 107 | if (isNaN(amount)) { |
| 108 | // Don't die as this is likely a user input error that can be corrected |
| 109 | throw new Error('Invalid amount'); |
| 110 | } |
| 111 | |
| 112 | const unit = (match[3] || 'sat').toLowerCase(); |
| 113 | const rate = Constants.UNITS2[unit]; |
| 114 | if (!rate) { |
| 115 | Utils.die('Invalid unit: ' + unit); |
| 116 | } |
| 117 | |
| 118 | const amountSat = parseFloat((amount * rate).toPrecision(12)); |
| 119 | if (amountSat != Math.round(amountSat)) { |
| 120 | Utils.die('Invalid amount: ' + amount + ' ' + unit); |
| 121 | } |
| 122 | |
| 123 | return amountSat; |
| 124 | }; |
| 125 | |
| 126 | static renderAmount(currency: string, satoshis: number | bigint | string, opts?: ITokenObj): string { |
| 127 | return Utils.amountFromSats(currency, Number(satoshis), opts) + ' ' + currency.toUpperCase(); |
no test coverage detected