@hyperlane-xyz/utils
Version:
General utilities and types for the Hyperlane network
71 lines • 2.64 kB
JavaScript
import { ensure0x, strip0x } from './addresses.js';
export function toTitleCase(str) {
return str.replace(/\w\S*/g, (txt) => {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
export function toUpperCamelCase(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
// Only allows letters and numbers
const alphanumericRgex = /[^a-zA-Z0-9]/gi;
export function sanitizeString(str) {
if (!str || typeof str !== 'string')
return '';
return str.replaceAll(alphanumericRgex, '').toLowerCase();
}
export function trimToLength(value, maxLength) {
if (!value)
return '';
const trimmed = value.trim();
return trimmed.length > maxLength
? trimmed.substring(0, maxLength) + '...'
: trimmed;
}
export function streamToString(stream) {
return new Promise((resolve, reject) => {
const chunks = [];
stream
.setEncoding('utf8')
.on('data', (chunk) => chunks.push(chunk))
.on('error', (err) => reject(err instanceof Error ? err : new Error(String(err))))
.on('end', () => resolve(String.prototype.concat(...chunks)));
});
}
export function errorToString(error, maxLength = 300) {
if (!error)
return 'Unknown Error';
if (typeof error === 'string')
return trimToLength(error, maxLength);
if (typeof error === 'number')
return `Error code: ${error}`;
const details = error.message || error.reason || error;
if (typeof details === 'string')
return trimToLength(details, maxLength);
return trimToLength(JSON.stringify(details), maxLength);
}
function isErrorWithContext(e) {
return e instanceof Error && 'context' in e;
}
/**
* Formats an error for display, including the cause chain and any Solana
* program logs attached to preflight failure errors.
*/
export function formatError(error, depth = 0) {
if (!(error instanceof Error))
return String(error);
const parts = [error.message];
// SolanaError preflight failures attach { logs, unitsConsumed, ... } to context
if (isErrorWithContext(error) &&
Array.isArray(error.context?.logs) &&
error.context.logs.length > 0) {
parts.push(`Logs:\n ${error.context.logs.join('\n ')}`);
}
if (error.cause != null && depth < 10) {
parts.push(`Caused by: ${formatError(error.cause, depth + 1)}`);
}
return parts.join('\n');
}
export const fromHexString = (hexstr) => Buffer.from(strip0x(hexstr), 'hex');
export const toHexString = (buf) => ensure0x(buf.toString('hex'));
//# sourceMappingURL=strings.js.map