import * as console from "console"; import { Buffer } from "buffer"; import { bech32 } from "./lib/bech32"; export type DecodedBytes = { bytes: Buffer; prefix?: string; }; type BytesFromStringOptions = { bech32Limit?: number; invalidMessage?: string; }; function decodeHexStrict(value: string): Buffer | undefined { const bytes = Buffer.from(value, "hex"); if (bytes.length * 2 !== value.length) { return undefined; } return bytes; } export function bytesFromString(input: string, options: BytesFromStringOptions = {}): DecodedBytes { const invalidMessage = options.invalidMessage ?? "Invalid key string: expected bech32 or hex-encoded key"; const value = input.trim(); if (!value) { throw new Error(invalidMessage); } try { const decoded = bech32.decode(value, options.bech32Limit ?? 1000); return { bytes: Buffer.from(decoded.data), prefix: decoded.prefix, }; } catch (_) {} const hexBytes = decodeHexStrict(value); if (hexBytes) { return { bytes: hexBytes }; } throw new Error(invalidMessage); } export function logError(prefix: string, err: Error) { console.error(getErrorMessage(prefix, err)); } export function getErrorMessage(prefix: string, err?: Error): string { if (err) { if (err.constructor.name == "AggregateError") { //@ts-ignore let errors: Error[] = err.errors; let msgs = errors.map((e) => e.message); return prefix + " " + err.message + "[\n " + msgs.join("\n , ") + " ]"; } else { return prefix + " " + err.name + " " + err.message; } } return prefix + " : Unexpected Error"; }