@lodestar/utils
Version:
Utilities required across multiple lodestar packages
65 lines • 2.33 kB
JavaScript
import { toRootHex } from "./bytes/index.js";
import { ETH_TO_WEI } from "./ethConversion.js";
/**
* Format bytes as `0x1234…1234`
* 4 bytes can represent 4294967296 values, so the chance of collision is low
*/
export function prettyBytes(root) {
const str = typeof root === "string" ? root : toRootHex(root);
return `${str.slice(0, 6)}…${str.slice(-4)}`;
}
/**
* Format bytes as `0x1234…`
* Paired with block numbers or slots, it can still act as a decent identify-able format
*/
export function prettyBytesShort(root) {
const str = typeof root === "string" ? root : toRootHex(root);
return `${str.slice(0, 6)}…`;
}
/**
* Truncate and format bytes as `0x123456789abc`
* 6 bytes is sufficient to avoid collisions and it allows to easily look up
* values on explorers like beaconcha.in while improving readability of logs
*/
export function truncBytes(root) {
const str = typeof root === "string" ? root : toRootHex(root);
return str.slice(0, 14);
}
/**
* Format a bigint value as a decimal string
*/
export function formatBigDecimal(numerator, denominator, maxDecimalFactor) {
const full = numerator / denominator;
const fraction = ((numerator - full * denominator) * maxDecimalFactor) / denominator;
// zeros to be added post decimal are number of zeros in maxDecimalFactor - number of digits in fraction
const zerosPostDecimal = String(maxDecimalFactor).length - 1 - String(fraction).length;
return `${full}.${"0".repeat(zerosPostDecimal)}${fraction}`;
}
// display upto 5 decimal places
const MAX_DECIMAL_FACTOR = BigInt("100000");
/**
* Format wei as ETH, with up to 5 decimals
*/
export function formatWeiToEth(wei) {
return formatBigDecimal(wei, ETH_TO_WEI, MAX_DECIMAL_FACTOR);
}
/**
* Format wei as ETH, with up to 5 decimals and append ' ETH'
*/
export function prettyWeiToEth(wei) {
return `${formatWeiToEth(wei)} ETH`;
}
/**
* Format milliseconds to time format HH:MM:SS.ms
*/
export function prettyMsToTime(timeMs) {
const date = new Date(0, 0, 0, 0, 0, 0, timeMs);
return `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}.${date.getMilliseconds()}`;
}
/**
* Remove 0x prefix from a string
*/
export function strip0xPrefix(hex) {
return hex.startsWith("0x") ? hex.slice(2) : hex;
}
//# sourceMappingURL=format.js.map