import { Hex } from 'viem'; export function hexToBase64(hex: Hex): string { if (hex.length % 2 !== 0) { throw new Error('Hex string must have an even number of characters'); } const hexStr = hex.startsWith('0x') ? hex.slice(2) : hex; if (hexStr.length === 0) { return ''; } const bytes = new Uint8Array( hexStr.match(/.{1,2}/g)!.map((byte) => parseInt(byte, 16)) ); const base64 = btoa(String.fromCharCode(...bytes)); return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); } export function base64ToHex(base64: string): Hex { if (base64.length === 0) { return '0x'; } const urlSafeBase64 = base64.replace(/-/g, '+').replace(/_/g, '/'); const binaryStr = atob(urlSafeBase64); const hexArray = Array.from(binaryStr, (char) => char.charCodeAt(0).toString(16).padStart(2, '0') ); return `0x${hexArray.join('')}` as Hex; }