UNPKG

@kyve/core-beta

Version:

🚀 The base KYVE node implementation.

140 lines (139 loc) • 4.76 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.callWithBackoffStrategy = exports.generateIndexPairs = exports.toHumanReadable = exports.sha256 = exports.bytesToBundle = exports.bundleToBytes = exports.standardizeJSON = exports.sleep = void 0; const bignumber_js_1 = require("bignumber.js"); const crypto_1 = __importDefault(require("crypto")); const INFINITY_LOOP = true; /** * Waits for a specific amount of time * * @method sleep * @param {number} timeoutMs * @return {Promise<void>} */ const sleep = (timeoutMs) => new Promise((resolve) => setTimeout(resolve, timeoutMs)); exports.sleep = sleep; /** * Standardizes any JSON object * * @method standardizeJSON * @param {any} object * @return {any} */ const standardizeJSON = (object) => JSON.parse(JSON.stringify(object)); exports.standardizeJSON = standardizeJSON; /** * Transforms a data bundle to raw bytes * * @method bundleToBytes * @param {DataItem[]} bundle * @return {Buffer} */ const bundleToBytes = (bundle) => Buffer.from(JSON.stringify(bundle)); exports.bundleToBytes = bundleToBytes; /** * Transforms raw bytes to a data bundle * * @method bytesToBundle * @param {DataItem[]} bundle * @return {Buffer} */ const bytesToBundle = (bytes) => JSON.parse(bytes.toString()); exports.bytesToBundle = bytesToBundle; /** * Creates a sha256 hash of raw byte data * * @method sha256 * @param {Buffer} data * @return {string} */ const sha256 = (data) => { if (data.byteLength) { return crypto_1.default.createHash("sha256").update(data).digest("hex"); } return ""; }; exports.sha256 = sha256; /** * Formats any bignumber into a human readable format * * @method toHumanReadable * @param {string} amount * @param {number} precision defines how many decimals after the comma should be returned * @return {string} */ const toHumanReadable = (amount, precision = 4) => { const fmt = new bignumber_js_1.BigNumber(amount || "0").div(10 ** 9).toFixed(precision, 1); if (precision > 1) { return `${fmt.split(".")[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",")}.${fmt.split(".")[1]}`; } return fmt.split(".")[0].replace(/\B(?=(\d{3})+(?!\d))/g, ","); }; exports.toHumanReadable = toHumanReadable; /** * Generates every index pair of an array length n. Note that this * method is O(n^2) * * @method generateIndexPairs * @param {number} n length of array * @return {[number, number][]} */ const generateIndexPairs = (n) => { const pairs = []; for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { if (i !== j && !pairs.some((pair) => pair[0] === j && pair[1] === i)) { pairs.push([i, j]); } } } return pairs; }; exports.generateIndexPairs = generateIndexPairs; /** * Calls any async function with a backoff strategy which behaviour * can be defined with options * * @method callWithBackoffStrategy * @param {() => Promise<T>} execution the method to execute with a backoff strategy * @param {OptionsRetryerType} options defines the backoff strategy. e.g the number of retries or the timeout limit * @param {onErrorRetryerType} onError a method which gets called if specified and if an error occurs calling the execution method * @return {Promise<T>} returns what the execution method returns */ async function callWithBackoffStrategy(execution, options, onError) { let time = options.increaseByMs; let requests = 1; return new Promise((resolve, reject) => { (async function () { while (INFINITY_LOOP) { try { return resolve(await execution()); } catch (e) { if (onError) { await onError(e, { nextTimeoutInMs: time, numberOfRetries: requests, options, }); } await (0, exports.sleep)(time); if (time < options.limitTimeoutMs) { time += options.increaseByMs; if (time > options.limitTimeoutMs) { time = options.limitTimeoutMs; } } if (options.maxRequests && requests >= options.maxRequests) { throw e; } requests++; } } })().catch((err) => reject(err)); }); } exports.callWithBackoffStrategy = callWithBackoffStrategy;