export type Account = { balanceCents: number; frozen: boolean };export type TransferFailure = | { kind: "invalid_amount" } | { kind: "same_account" } | { kind: "unknown_account"; id: string } | { kind: "frozen"; id: string } | { kind: "insufficient_funds"; id: string; balanceCents: number; amountCents: number };export class TransferError extends Error { declare readonly kind: TransferFailure["kind"]; declare readonly id?: string; declare readonly balanceCents?: number; declare readonly amountCents?: number; constructor(failure: TransferFailure) { super(failure.kind); Object.assign(this, failure); }}const lookup = (accounts: Record<string, Account>, id: string): Account => { if (!Object.hasOwn(accounts, id)) throw new TransferError({ kind: "unknown_account", id }); return accounts[id];};/** Throws TransferError when the transfer is not allowed. */export function transfer( accounts: Record<string, Account>, from: string, to: string, amountCents: number,): Record<string, Account> { if (!Number.isInteger(amountCents) || amountCents <= 0) throw new TransferError({ kind: "invalid_amount" }); if (from === to) throw new TransferError({ kind: "same_account" }); const src = lookup(accounts, from); const dst = lookup(accounts, to); if (src.frozen) throw new TransferError({ kind: "frozen", id: from }); if (dst.frozen) throw new TransferError({ kind: "frozen", id: to }); if (src.balanceCents < amountCents) { throw new TransferError({ kind: "insufficient_funds", id: from, balanceCents: src.balanceCents, amountCents }); } return { ...accounts, [from]: { ...src, balanceCents: src.balanceCents - amountCents }, [to]: { ...dst, balanceCents: dst.balanceCents + amountCents }, };}