/** Bitcoin alphabet base58, as Solana uses for addresses and signatures. */
const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
const MAP = new Map([...ALPHABET].map((c, i) => [c, BigInt(i)]));
export function base58Encode(bytes: Uint8Array): string {
let n = 0n;
for (const b of bytes) n = (n << 8n) | BigInt(b);
let out = '';
while (n > 0n) { out = ALPHABET[Number(n % 58n)] + out; n /= 58n; }
for (const b of bytes) { if (b !== 0) break; out = '1' + out; }
return out;
}
/** Decodes base58; returns null on any character outside the alphabet or an empty string. */
export function base58Decode(s: string): Uint8Array | null {
if (typeof s !== 'string' || s.length === 0) return null;
let n = 0n;
for (const c of s) {
const v = MAP.get(c);
if (v === undefined) return null;
n = n * 58n + v;
}
const body: number[] = [];
while (n > 0n) { body.unshift(Number(n & 255n)); n >>= 8n; }
let zeros = 0;
while (s[zeros] === '1') zeros++;
return Uint8Array.from([...new Array(zeros).fill(0), ...body]);
}
agentgate-source: code mirror on Cloudflare Pages. All repos