UNPKG

minterjs-util

Version:
97 lines (87 loc) 2.45 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.convert = convert; exports.convertFromPip = convertFromPip; exports.convertToPip = convertToPip; exports.numberToBig = numberToBig; var _bn = _interopRequireDefault(require("bn.js")); var _ethjsUtil = require("ethjs-util"); var _big = _interopRequireDefault(require("./big.js")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /* eslint-disable unicorn/prevent-abbreviations */ var DECIMALS = 18; /** * @param {number|string|Big} num * @param {'pip'|'bip'} to * @param {'hex'} [format] * @return {string} */ function convert(num, to, format) { if (to === 'bip' && format === 'hex') { throw new Error('Converting from pip to hex format doesn\'t supported'); } var numBig = numberToBig(num); var pow = new _big["default"](10).pow(DECIMALS); var result; if (to === 'pip') { result = numBig.times(pow).toFixed(0); if (format === 'hex') { return (0, _ethjsUtil.padToEven)(new _bn["default"](result, 10).toString(16)); } else { return result; } } else if (to === 'bip') { // eslint-disable-next-line unicorn/require-number-to-fixed-digits-argument return numBig.round().div(pow).toFixed(); } else { throw new Error('Unknown type'); } } /** * Multiply value by 10^18 * @param {number|string|Big} num * @param {'hex'} [format] * @return {string} */ function convertToPip(num, format) { return convert(num, 'pip', format); } /** * Multiply value by 10^-18 * @param {number|string|Big} num * @return {string} */ function convertFromPip(num) { return convert(num, 'bip'); } /** * @param {string} str * @return {boolean} */ // function isNumericString(str) { // const NUMERIC = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i; // return NUMERIC.test(str); // } /** * * @param {number|string|Big} num * @return {Big} */ function numberToBig(num) { // if num is prefixed hex string if (typeof num === 'string' && num.indexOf('0x') === 0) { if (num === '0x') { num = '0x0'; } // convert prefixed hex to decimal string num = new _bn["default"](num.slice(2), 16).toString(10); } // `big.js` already throws on invalid numbers // if num is not numeric string // if (typeof num === 'string' && !isNumericString(num)) { // throw new Error('Invalid number'); // } return new _big["default"](num); }