@pyro-labs/utils
Version:
Utility functions for Pyro SDK
98 lines • 2.77 kB
JavaScript
;
/**
* @pyro/utils - Utility functions for Pyro SDK
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.toHex = toHex;
exports.hexToBigInt = hexToBigInt;
exports.bytesToHex = bytesToHex;
exports.hexToBytes = hexToBytes;
exports.sleep = sleep;
exports.retry = retry;
__exportStar(require("./logger"), exports);
function toHex(value) {
if (value instanceof Uint8Array) {
return bytesToHex(value);
}
if (typeof value === "bigint") {
return "0x" + value.toString(16);
}
if (typeof value === "number") {
return "0x" + value.toString(16);
}
if (typeof value === "string") {
if (value.startsWith("0x")) {
return value;
}
return "0x" + BigInt(value).toString(16);
}
throw new Error(`Invalid value type for hex conversion: ${typeof value}`);
}
/**
* Convert hex string to bigint
*/
function hexToBigInt(hex) {
if (hex.startsWith("0x")) {
return BigInt(hex);
}
return BigInt("0x" + hex);
}
/**
* Convert bytes to hex string
*/
function bytesToHex(bytes) {
return ("0x" +
Array.from(bytes)
.map((b) => b.toString(16).padStart(2, "0"))
.join(""));
}
/**
* Convert hex string to bytes
*/
function hexToBytes(hex) {
const cleanHex = hex.startsWith("0x") ? hex.slice(2) : hex;
const bytes = new Uint8Array(cleanHex.length / 2);
for (let i = 0; i < cleanHex.length; i += 2) {
bytes[i / 2] = parseInt(cleanHex.substr(i, 2), 16);
}
return bytes;
}
/**
* Sleep utility
*/
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Retry utility
*/
async function retry(fn, maxRetries = 3, delay = 1000) {
let lastError;
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
}
catch (error) {
lastError = error;
if (i < maxRetries - 1) {
await sleep(delay * (i + 1));
}
}
}
throw lastError;
}
//# sourceMappingURL=index.js.map