@tempus-labs/utils
Version:
Tempus utility helpers
70 lines • 2.77 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.toEth = exports.fromRay = exports.toRay = exports.fromWei = exports.toWei = exports.formatDecimal = exports.parseDecimal = exports.MAX_UINT256 = exports.MAX_NUMBER_DIGITS = void 0;
const Decimal_1 = require("./Decimal");
/**
* double has limited digits of accuracy, so any decimal
* beyond this # of digits will be converted to a string
* example: 50.09823182711198 --> 50.09823182711198
* 50.09823182711198117 --> '50.09823182711198117'
*/
exports.MAX_NUMBER_DIGITS = 17;
/**
* Maximum value for uint256
*/
exports.MAX_UINT256 = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
/**
* Converts a decimal number into a scaled bigint
* @example let wei = parseDecimal("0.000001", 18);
* @param decimal Decimal such as 1.25 or "12.1234777777"
* @param decimalBase Base precision of the decimal, for wei=18, for ray=27
* @returns Scaled bigint for use in solidity contracts
*/
function parseDecimal(decimal, decimalBase) {
// need this special case to support MAX_UINT256, ignoring decimalBase
if (typeof (decimal) === "bigint" && decimal === exports.MAX_UINT256) {
return decimal;
}
return Decimal_1.Decimal.toScaledBigInt(decimal, decimalBase);
}
exports.parseDecimal = parseDecimal;
/**
* Formats a big decimal into a Number or String which is representable in TypeScript
* @param scaledBigInt Scaled BigInt decimal from an ERC20-like contract
* @param decimalBase Base precision of the decimal, for wei=18, for ray=27
* @returns Number for simple decimals like 2.5, string for long decimals "0.00000000000001"
*/
function formatDecimal(scaledBigInt, decimalBase) {
const decimal = new Decimal_1.Decimal(scaledBigInt, decimalBase);
const str = decimal.toRounded(-1);
if (str.length <= exports.MAX_NUMBER_DIGITS)
return Number(str);
return str;
}
exports.formatDecimal = formatDecimal;
/** @return WEI Scaled BigInt from an ETH decimal */
function toWei(eth) {
return parseDecimal(eth, 18);
}
exports.toWei = toWei;
/** @return Decimal from a WEI Scaled BigInt */
function fromWei(wei) {
return formatDecimal(wei, 18);
}
exports.fromWei = fromWei;
/** @return RAY Scaled BigInt from a decimal number */
function toRay(decimal) {
return parseDecimal(decimal, 27);
}
exports.toRay = toRay;
/** @return Decimal from a RAY Scaled BigInt */
function fromRay(wei) {
return formatDecimal(wei, 27);
}
exports.fromRay = fromRay;
/** @return ETH decimal from WEI Scaled BigInt */
function toEth(wei) {
return formatDecimal(wei, 18);
}
exports.toEth = toEth;
//# sourceMappingURL=DecimalUtils.js.map