import { fromBase64, toBase64, toHex } from "@cosmjs/encoding";

/** безопасный юнит для байтов */
export type Bytes = Uint8Array;

/** b64 -> bytes */
export function base64ToBytes(b64: string): Bytes {
    return fromBase64(b64);
}

/** bytes -> b64 */
export function bytesToBase64(b: Bytes): string {
    return toBase64(b);
}

/** bytes -> hex (lowercase) */
export function bytesToHex(b: Bytes): string {
    return toHex(b);
}

/** hex -> bytes (принимает без 0x и с 0x) */
export function hexToBytes(hex: string): Bytes {
    const s = hex.startsWith("0x") ? hex.slice(2) : hex;
    if (s.length % 2 !== 0) throw new Error("hex length must be even");
    const out = new Uint8Array(s.length / 2);
    for (let i = 0; i < out.length; i++) {
        out[i] = parseInt(s.substr(i * 2, 2), 16);
    }
    return out;
}

/** sha256(bytes) -> hex (UPPERCASE) */
export async function sha256Hex(bytes: Bytes): Promise<string> {
    const digest = await crypto.subtle.digest("SHA-256", bytes);
    const hex = bytesToHex(new Uint8Array(digest));
    return hex.toUpperCase();
}