/**
 * bb84 reference client (TypeScript) — the same wallet as bb84.py, for agents that run on Node 18+
 * (or Deno / Bun). Specification: https://bb84.com/agent/protocol.md (protocol version 1).
 *
 * Dependency: @noble/hashes (keccak-256) — `npm i @noble/hashes`. Everything else is the platform:
 * fetch, crypto.getRandomValues, and for the wallet file node:fs (only used by the CLI / save / load).
 *
 *   import { Wallet } from "./bb84";
 *   const w = Wallet.create(); await w.publishCommitment(); console.log(w.address);
 *   const w2 = await Wallet.load("wallet.json"); await w2.pay("alice", "2.50", "USDC", { memo: "Coffee" });
 *
 * SECRETS: the wallet state (spendSK, viewSK, r) IS the money. Store it where only the agent's process
 * can read it, never log it, never put it into a chat. An agent without private durable storage must
 * use the bb84 MCP server instead (https://bb84.com/developers).
 */
import { keccak_256 } from "@noble/hashes/sha3.js";

export const PROTOCOL_VERSION = 1;
export const CHAIN_ID = 42069000n;
export const CHAIN_LENGTH = 1000;
const BASE = (globalThis as any).process?.env?.BB84_BASE ?? "https://bb84.com";
const RELAY = `${BASE}/api/connect/web`;
const ENS = `${BASE}/api/ens`;
export const TOKENS: Record<string, string> = {
  USDC: "0x50590ee131edc98a7213c91ae82e3e8987b9b5ee",
  EURC: "0x47dbbf8233cd91c16360bdb69e325f771fd9a667",
};
export const DECIMALS = 6;
export const STEALTH_POOL = "0x4200000000000000000000000000000000000044";
export const COMMIT_KEY_REGISTRY = "0x420000000000000000000000000000000000004a";
const GAS_TRANSFER = 80000n, GAS_GOODS = 160000n, GAS_REGISTER = 200000n, GAS_SELF = 60000n;
const COMMIT_GAS = 100000n, COMMIT_EXPIRE_BLOCKS = 250n, MAX_FEE_CAP = 1_000_000_000n;
const MEMO_MAX_BYTES = 280;
const COMMIT_KEY_LENGTH = 2048, COMMIT_KEY_REANCHOR_AT = 64, COMMIT_KEY_EPOCH_SEARCH = 32;
const LABEL_RE = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;
const ADDR_RE = /^0x[0-9a-fA-F]{40}$/;
const AMOUNT_RE = /^\d{1,12}(\.\d{1,6})?$/;

// ─── bytes & hashing ─────────────────────────────────────────────────────────
export const keccak256 = (b: Uint8Array): Uint8Array => keccak_256(b);
export function kk(...parts: Uint8Array[]): Uint8Array {
  const n = parts.reduce((a, p) => a + p.length, 0);
  const out = new Uint8Array(n); let o = 0;
  for (const p of parts) { out.set(p, o); o += p.length; }
  return keccak256(out);
}
export const hex = (b: Uint8Array): string => Array.from(b, x => x.toString(16).padStart(2, "0")).join("");
export function fromHex(h: string): Uint8Array {
  const s = h.startsWith("0x") ? h.slice(2) : h;
  const out = new Uint8Array(s.length / 2);
  for (let i = 0; i < out.length; i++) out[i] = parseInt(s.slice(2 * i, 2 * i + 2), 16);
  return out;
}
const utf8 = (s: string) => new TextEncoder().encode(s);
const u32be = (n: number) => new Uint8Array([(n >>> 24) & 255, (n >>> 16) & 255, (n >>> 8) & 255, n & 255]);
function u64be(n: bigint): Uint8Array { const b = new Uint8Array(8); new DataView(b.buffer).setBigUint64(0, n, false); return b; }
function be32(n: bigint): Uint8Array { return fromHex(n.toString(16).padStart(64, "0")); }
function randomBytes(n: number): Uint8Array { const b = new Uint8Array(n); crypto.getRandomValues(b); return b; }

const D_OTA_SPEND = kk(utf8("OP_OTA_SPEND_v1"));
const D_HASH_ADDR = kk(utf8("OP_HASH_ADDR_v1"));
const D_NULLIFIER = kk(utf8("OP_NULLIFIER_v1"));
const D_COMMIT_BIND = kk(utf8("OP_COMMIT_BIND_v1"));
const D_COMMIT_KEY = kk(utf8("OP_OTA_COMMITKEY_v1"));
const SEL_TRANSFER = fromHex("a9059cbb");
const SEL_REGISTER_FOR = kk(utf8("registerCommitmentFor(address,bytes32)")).slice(0, 4);
export const ZERO32 = new Uint8Array(32);

// ─── hash chain, address ─────────────────────────────────────────────────────
/** chain[0] = keccak(D_OTA_SPEND ‖ spendSK ‖ r); chain[k] = keccak(chain[k-1]); commitment = chain[length]. */
export function deriveChain(spendSK: Uint8Array, r: Uint8Array, length = CHAIN_LENGTH): Uint8Array[] {
  const chain = [kk(D_OTA_SPEND, spendSK, r)];
  for (let i = 0; i < length; i++) chain.push(keccak256(chain[i]));
  return chain;
}
/** trunc20(keccak(D_HASH_ADDR ‖ commitment)) */
export const otaAddress = (commitment: Uint8Array): string => "0x" + hex(kk(D_HASH_ADDR, commitment).slice(12));

// ─── RLP ─────────────────────────────────────────────────────────────────────
function minBytes(n: bigint): Uint8Array { if (n === 0n) return new Uint8Array(0); let h = n.toString(16); if (h.length % 2) h = "0" + h; return fromHex(h); }
export function rlpStr(b: Uint8Array): Uint8Array {
  if (b.length === 1 && b[0] < 0x80) return b;
  if (b.length < 56) return new Uint8Array([0x80 + b.length, ...b]);
  const lb = minBytes(BigInt(b.length));
  return new Uint8Array([0xb7 + lb.length, ...lb, ...b]);
}
export function rlpList(items: Uint8Array[]): Uint8Array {
  const n = items.reduce((a, i) => a + i.length, 0);
  const p = new Uint8Array(n); let o = 0;
  for (const i of items) { p.set(i, o); o += i.length; }
  if (p.length < 56) return new Uint8Array([0xc0 + p.length, ...p]);
  const lb = minBytes(BigInt(p.length));
  return new Uint8Array([0xf7 + lb.length, ...lb, ...p]);
}
export const rlpInt = (n: bigint): Uint8Array => rlpStr(minBytes(n));

export interface Step { from: Uint8Array; nonce: bigint; to: Uint8Array; data: Uint8Array; gas: bigint; feeCap: bigint; tipCap: bigint; value?: bigint; newCommitment?: Uint8Array; newChainLength?: number; }

/** keccak(RLP([chainId, from, nonce, to, value, gas, gasFeeCap, gasTipCap, data, newCommitment, newChainLength])) with the REVEAL nonce. */
export function txDigest(s: Step, revealNonce: bigint): Uint8Array {
  return kk(rlpList([rlpInt(CHAIN_ID), rlpStr(s.from), rlpInt(revealNonce), rlpStr(s.to), rlpInt(s.value ?? 0n), rlpInt(s.gas),
    rlpInt(s.feeCap), rlpInt(s.tipCap), rlpStr(s.data), rlpStr(s.newCommitment ?? ZERO32), rlpInt(BigInt(s.newChainLength ?? 0))]));
}

/** HashCommitTx (0x7c, nonce N) + HashRevealTx (0x7f, nonce N+1) for one spend step. */
export function buildSpendTxs(s: Step, preImage: Uint8Array, commitPreImage: Uint8Array = ZERO32): { commit: Uint8Array; reveal: Uint8Array } {
  const rn = s.nonce + 1n;
  const digest = txDigest(s, rn);
  const n8 = u64be(rn);
  const nullifier = kk(D_NULLIFIER, preImage, n8, digest);
  const hashCommit = kk(D_COMMIT_BIND, nullifier, preImage, digest, n8);
  const fields = [rlpInt(CHAIN_ID), rlpStr(s.from), rlpInt(s.nonce), rlpStr(hashCommit), rlpInt(COMMIT_GAS), rlpInt(s.feeCap), rlpInt(s.tipCap), rlpInt(COMMIT_EXPIRE_BLOCKS)];
  if (commitPreImage.some(b => b !== 0)) fields.push(rlpStr(commitPreImage));
  const commit = new Uint8Array([0x7c, ...rlpList(fields)]);
  const reveal = new Uint8Array([0x7f, ...rlpList([rlpInt(CHAIN_ID), rlpStr(s.from), rlpInt(rn), rlpStr(s.to), rlpInt(s.value ?? 0n), rlpInt(s.gas),
    rlpInt(s.feeCap), rlpInt(s.tipCap), rlpStr(s.data), rlpStr(nullifier), rlpStr(preImage), rlpInt(0n), rlpStr(s.newCommitment ?? ZERO32), rlpInt(BigInt(s.newChainLength ?? 0))])]);
  return { commit, reveal };
}

// ─── calldata ────────────────────────────────────────────────────────────────
export function toUnits(amount: string, decimals = DECIMALS): bigint {
  const a = amount.trim().replace(",", ".");
  if (!AMOUNT_RE.test(a)) throw new Bb84Error("amount", `bad amount ${amount}`);
  const [whole, frac = ""] = a.split(".");
  return BigInt(whole) * 10n ** BigInt(decimals) + BigInt((frac + "0".repeat(decimals)).slice(0, decimals));
}
export function fromUnits(u: bigint, decimals = DECIMALS): string {
  const s = u.toString().padStart(decimals + 1, "0");
  return (s.slice(0, -decimals) + "." + s.slice(-decimals)).replace(/\.?0+$/, "");
}
/** transfer(address,uint256) ‖ type byte (0x00 friends / 0x01 goods & services) ‖ UTF-8 memo (≤ 280 bytes, cut on a character boundary). */
export function transferData(to: string, units: bigint, memo = "", goods = false): Uint8Array {
  const head = new Uint8Array(68);
  head.set(SEL_TRANSFER, 0); head.set(fromHex(to.slice(2)), 16); head.set(be32(units), 36);
  const full = utf8(memo.trim());
  let end = Math.min(full.length, MEMO_MAX_BYTES);
  while (end > 0 && end < full.length && (full[end] & 0xc0) === 0x80) end--;
  const m = full.slice(0, end);
  if (m.length) return new Uint8Array([...head, goods ? 1 : 0, ...m]);
  return goods ? new Uint8Array([...head, 1]) : head;
}
export function registerForData(ota: string, commitment: Uint8Array): Uint8Array {
  const out = new Uint8Array(68);
  out.set(SEL_REGISTER_FOR, 0); out.set(fromHex(ota.slice(2)), 16); out.set(commitment, 36);
  return out;
}

// ─── commit key ──────────────────────────────────────────────────────────────
export const commitKeySeed = (spendSK: Uint8Array, address: string, epoch: number): Uint8Array => kk(D_COMMIT_KEY, spendSK, fromHex(address.slice(2)), u32be(epoch));
export function commitKeyElement(seed: Uint8Array, index: number): Uint8Array { let h = seed; for (let i = 0; i < index; i++) h = keccak256(h); return h; }
export const commitKeyAnchorData = (spendSK: Uint8Array, address: string, epoch: number): Uint8Array =>
  new Uint8Array([...commitKeyElement(commitKeySeed(spendSK, address, epoch), COMMIT_KEY_LENGTH), ...u32be(COMMIT_KEY_LENGTH)]);

// ─── HTTP ────────────────────────────────────────────────────────────────────
export class Bb84Error extends Error { constructor(public code: string, message: string) { super(message); } }

async function http(method: "GET" | "POST", url: string, body?: unknown): Promise<[number, any]> {
  let res: Response;
  try {
    res = await fetch(url, { method, headers: { "Accept": "application/json", ...(body !== undefined ? { "Content-Type": "application/json" } : {}), "User-Agent": "bb84-agent-client/1 (+https://bb84.com/agent/protocol.md)" },
      body: body === undefined ? undefined : JSON.stringify(body) });
  } catch (e: any) { throw new Bb84Error("network", `${url}: ${e?.message ?? e}`); }
  return [res.status, await res.json().catch(() => ({}))];
}
async function ok(method: "GET" | "POST", url: string, body?: unknown): Promise<any> {
  const [code, d] = await http(method, url, body);
  if (code !== 200) throw new Bb84Error(d.code ?? `http_${code}`, d.error ?? `${url} → HTTP ${code}`);
  return d;
}
export interface ChainState { address: string; registered: boolean; depth: number; nonce: number; isContract: boolean; isMerchant: boolean; deleted: boolean; unrevealed?: boolean; publishedCommitment: string | null; balances?: Record<string, string>; name?: string | null; commitKey?: { last: string; depth: number }; }
export const chainState = (address: string): Promise<ChainState> => ok("GET", `${RELAY}/chain/${address}`);
export const fees = (): Promise<{ gasFeeCap: string; gasTipCap: string; blockNumber: number }> => ok("GET", `${RELAY}/fees`);
export async function sendRaw(raw: Uint8Array): Promise<string> { return (await ok("POST", `${RELAY}/send`, { raw: "0x" + hex(raw) })).txHash; }
export async function waitReceipt(h: string, timeoutMs: number): Promise<{ status: string } | null> {
  const end = Date.now() + timeoutMs;
  while (Date.now() < end) {
    const r = await ok("GET", `${RELAY}/tx/${h}`).catch(() => null);
    if (r?.receipt) return r.receipt;
    await new Promise(r => setTimeout(r, 1500));
  }
  return null;
}
export async function resolveName(name: string): Promise<{ address: string; name: string; commitment?: string }> {
  const label = name.trim().toLowerCase().replace(/\.bb84\.(eth|com)$/, "");
  if (!LABEL_RE.test(label)) throw new Bb84Error("name", `${name} is not a bb84 name`);
  const [code, d] = await http("GET", `${ENS}/address/${label}`);
  if (code === 200 && ADDR_RE.test(d.address ?? "")) return d;
  if (code === 409 && d.deleted) throw new Bb84Error("deleted", `${label}.bb84.eth belongs to a deleted address`);
  if (code === 409) throw new Bb84Error("reserved", `${label}.bb84.eth is reserved`);
  throw new Bb84Error("not_found", `${label}.bb84.eth is not registered`);
}

// ─── the wallet ──────────────────────────────────────────────────────────────
export interface WalletState { version: 1; chainId: number; spendSK: string; viewSK: string; r: string; chainLength: number; address: string; commitment: string; label: string | null; commitKeyEpoch: number; createdAt: number; pendingRenewal?: { r: string; commitment: string } | null; }

export class Wallet {
  chain: Uint8Array[]; commitment: Uint8Array; address: string; path: string | null = null;
  pendingRenewal: { r: string; commitment: string } | null = null;
  constructor(public spendSK: Uint8Array, public viewSK: Uint8Array, public r: Uint8Array, public chainLength = CHAIN_LENGTH,
              address?: string, public label: string | null = null, public commitKeyEpoch = 0, public createdAt = Math.floor(Date.now() / 1000)) {
    this.chain = deriveChain(spendSK, r, chainLength);
    this.commitment = this.chain[chainLength];
    this.address = (address ?? otaAddress(this.commitment)).toLowerCase();   // fixed by the first commitment, kept across renewals
  }
  static create(): Wallet { return new Wallet(randomBytes(32), randomBytes(32), randomBytes(32)); }
  static fromState(d: WalletState, path: string | null = null): Wallet {
    if (d.version !== 1 || BigInt(d.chainId) !== CHAIN_ID) throw new Bb84Error("state", "not a bb84 wallet state of version 1");
    const w = new Wallet(fromHex(d.spendSK), fromHex(d.viewSK), fromHex(d.r), d.chainLength ?? CHAIN_LENGTH, d.address, d.label ?? null, d.commitKeyEpoch ?? 0, d.createdAt);
    w.pendingRenewal = d.pendingRenewal ?? null; w.path = path;
    return w;
  }
  static async load(path: string): Promise<Wallet> {
    const fs = await import("node:fs/promises");
    return Wallet.fromState(JSON.parse(await fs.readFile(path, "utf8")), path);
  }
  toState(): WalletState {
    return { version: 1, chainId: Number(CHAIN_ID), spendSK: hex(this.spendSK), viewSK: hex(this.viewSK), r: hex(this.r), chainLength: this.chainLength,
      address: this.address, commitment: hex(this.commitment), label: this.label, commitKeyEpoch: this.commitKeyEpoch, createdAt: this.createdAt,
      ...(this.pendingRenewal ? { pendingRenewal: this.pendingRenewal } : {}) };
  }
  async save(path?: string): Promise<void> {
    const p = path ?? this.path; if (!p) throw new Bb84Error("state", "no wallet file path");
    const fs = await import("node:fs/promises");
    await fs.writeFile(p + ".tmp", JSON.stringify(this.toState(), null, 1), { mode: 0o600 });
    await fs.rename(p + ".tmp", p); this.path = p;
  }
  get name(): string | null { return this.label ? `${this.label}.bb84.eth` : null; }

  async publishCommitment(): Promise<void> { await ok("POST", `${ENS}/commitment`, { address: this.address, commitment: "0x" + hex(this.commitment) }); }
  /** Fresh wallets only (before the first payment / before publishCommitment): the unpublished commitment proves ownership. */
  async registerName(label: string): Promise<string> {
    label = label.trim().toLowerCase();
    if (!LABEL_RE.test(label)) throw new Bb84Error("name", "label: 1-32 characters, a-z 0-9, inner hyphens");
    await ok("POST", `${ENS}/register`, { address: this.address, label, commitment: "0x" + hex(this.commitment) });
    this.label = label; return this.name!;
  }
  async autoName(): Promise<string> { this.label = (await ok("GET", `${ENS}/name/${this.address}`)).label; return this.name!; }
  async status() {
    const st = await chainState(this.address);
    if (this.pendingRenewal) await this.settleRenewal(st);
    const balances = Object.fromEntries(Object.entries(st.balances ?? {}).map(([k, v]) => [k, fromUnits(BigInt(v))]));
    return { address: this.address, name: st.name ?? this.name, activated: st.registered, stepsLeft: st.depth, balances, deleted: st.deleted, commitKey: st.commitKey };
  }

  async pay(to: string, amount: string, asset: string, opts: { memo?: string; goods?: boolean; allowSuspect?: boolean; log?: (s: string) => void } = {}) {
    const log = opts.log ?? (() => {});
    asset = asset.toUpperCase();
    if (!TOKENS[asset]) throw new Bb84Error("asset", "asset must be USDC or EURC");
    const units = toUnits(amount);
    if (units <= 0n) throw new Bb84Error("amount", "amount must be > 0");
    const toAddr = ADDR_RE.test(to) ? to.toLowerCase() : (await resolveName(to)).address.toLowerCase();
    if (toAddr === this.address) throw new Bb84Error("recipient", "cannot pay the wallet's own address");
    const me = await chainState(this.address);
    if (me.deleted) throw new Bb84Error("deleted", "this wallet was deleted on-chain");
    if (!me.registered) throw new Bb84Error("unfunded", `${this.address} is not activated yet: it has to receive a payment first`);
    const rc = await chainState(toAddr);
    if (rc.deleted) throw new Bb84Error("recipient_deleted", "the recipient address was deleted by its owner");
    let register = false;
    if (rc.registered) {
      if (rc.depth === 0) throw new Bb84Error("recipient_locked", "the recipient can never spend again (chain depth 0)");
      if (rc.unrevealed && rc.depth !== CHAIN_LENGTH && !opts.allowSuspect) throw new Bb84Error("recipient_suspect", `recipient activated with depth ${rc.depth} and never spent; pass allowSuspect to pay anyway`);
    } else if (!rc.isContract && !rc.isMerchant) {
      if (!rc.publishedCommitment) throw new Bb84Error("recipient_unregistered", "the recipient is not activated and published no commitment");
      register = true;
    }
    const goods = !!opts.goods || rc.isMerchant;
    const bal = BigInt(me.balances?.[asset] ?? "0");
    if (bal < units) throw new Bb84Error("balance", `not enough ${asset}: ${fromUnits(bal)} available, ${fromUnits(units)} needed`);
    const anchorEpoch = this.commitKeyAnchorDue(me);
    const need = 1 + (register ? 1 : 0) + (anchorEpoch === null ? 0 : 1);
    if (me.depth < need) throw new Bb84Error("exhausted", `only ${me.depth} hash-chain steps left, ${need} needed`);
    if (anchorEpoch !== null) {
      log(`anchoring commit key (epoch ${anchorEpoch})`);
      await this.spendStep(COMMIT_KEY_REGISTRY, commitKeyAnchorData(this.spendSK, this.address, anchorEpoch), GAS_SELF, log);
      this.commitKeyEpoch = anchorEpoch; if (this.path) await this.save();
    }
    if (register) {
      log(`activating recipient ${toAddr}`);
      await this.spendStep(STEALTH_POOL, registerForData(toAddr, fromHex(rc.publishedCommitment!.slice(2).padStart(64, "0"))), GAS_REGISTER, log);
    }
    log(`paying ${fromUnits(units)} ${asset} to ${toAddr}`);
    const txHash = await this.spendStep(TOKENS[asset], transferData(toAddr, units, opts.memo ?? "", goods), goods ? GAS_GOODS : GAS_TRANSFER, log);
    return { txHash, to: toAddr, amount: fromUnits(units), asset, goods };
  }

  private commitKeyEpochFor(last: string, depth: number): number | null {
    const want = last.slice(2).padStart(64, "0").toLowerCase();
    const epochs = [this.commitKeyEpoch, ...Array.from({ length: COMMIT_KEY_EPOCH_SEARCH }, (_, i) => i).filter(e => e !== this.commitKeyEpoch)];
    for (const epoch of epochs) {
      const seed = commitKeySeed(this.spendSK, this.address, epoch);
      const top = depth > 0 ? keccak256(commitKeyElement(seed, depth - 1)) : seed;
      if (hex(top) === want) return epoch;
    }
    return null;
  }
  private commitKeyAnchorDue(me: ChainState): number | null {
    const last = me.commitKey?.last ?? "0x0", depth = me.commitKey?.depth ?? 0;
    if (BigInt(last) === 0n) return 0;
    if (depth > COMMIT_KEY_REANCHOR_AT) return null;
    const epoch = this.commitKeyEpochFor(last, depth);
    return epoch === null ? null : epoch + 1;
  }
  private commitPreImage(me: ChainState): Uint8Array {
    const last = me.commitKey?.last ?? "0x0", depth = me.commitKey?.depth ?? 0;
    if (BigInt(last) === 0n || depth === 0) return ZERO32;
    const epoch = this.commitKeyEpochFor(last, depth);
    if (epoch === null) throw new Bb84Error("commit_key", "this address has a commit key this wallet cannot derive");
    this.commitKeyEpoch = epoch;
    return commitKeyElement(commitKeySeed(this.spendSK, this.address, epoch), depth - 1);
  }
  /** One commit + reveal. Preimage = chain[depth-1] from the chain's depth, never a local counter. */
  private async spendStep(to: string, data: Uint8Array, gas: bigint, log: (s: string) => void): Promise<string> {
    const me = await chainState(this.address);
    if (this.pendingRenewal) await this.settleRenewal(me);
    if (me.depth < 1) throw new Bb84Error("exhausted", "hash chain used up");
    const preImage = this.chain[me.depth - 1];
    const commitPre = this.commitPreImage(me);
    let renewal: { r: string; commitment: string } | null = null;
    let newCommitment: Uint8Array = ZERO32, newChainLength = 0;
    if (me.depth === 1) {
      const newR = randomBytes(32);
      const newChain = deriveChain(this.spendSK, newR, CHAIN_LENGTH);
      newCommitment = newChain[CHAIN_LENGTH]; newChainLength = CHAIN_LENGTH;
      renewal = { r: hex(newR), commitment: hex(newCommitment) };
      this.pendingRenewal = renewal; if (this.path) await this.save();
    }
    const f = await fees();
    let feeCap = BigInt(f.gasFeeCap) > MAX_FEE_CAP ? MAX_FEE_CAP : BigInt(f.gasFeeCap);
    let tipCap = BigInt(f.gasTipCap) > feeCap ? feeCap : BigInt(f.gasTipCap);
    const step: Step = { from: fromHex(this.address.slice(2)), nonce: BigInt(me.nonce), to: fromHex(to.slice(2)), data, gas, feeCap, tipCap, newCommitment, newChainLength };
    let commitHash = "";
    for (let attempt = 0; ; attempt++) {
      const { commit } = buildSpendTxs({ ...step, feeCap, tipCap }, preImage, commitPre);
      try { commitHash = await sendRaw(commit); break; }
      catch (e: any) {
        if (String(e?.message).toLowerCase().includes("underpriced") && attempt < 2 && feeCap < MAX_FEE_CAP) {
          feeCap = feeCap * 2n > MAX_FEE_CAP ? MAX_FEE_CAP : feeCap * 2n; tipCap = tipCap * 2n > feeCap ? feeCap : tipCap * 2n; continue;
        }
        throw e;
      }
    }
    log(`  commit ${commitHash}`);
    if (!(await waitReceipt(commitHash, 90000))) throw new Bb84Error("timeout", `commit ${commitHash} not confirmed within 90 s; nothing sent, it expires after ${COMMIT_EXPIRE_BLOCKS} blocks`);
    const { reveal } = buildSpendTxs({ ...step, feeCap, tipCap }, preImage, commitPre);
    const revealHash = await sendRaw(reveal);
    log(`  reveal ${revealHash}`);
    const rc = await waitReceipt(revealHash, 90000);
    if (!rc) throw new Bb84Error("timeout", `reveal ${revealHash} not confirmed within 90 s; check status later`);
    if (renewal) await this.adoptRenewal(renewal);
    if (rc.status !== "0x1") throw new Bb84Error("reverted", `reveal ${revealHash} executed but reverted; the step is consumed`);
    return revealHash;
  }
  private async adoptRenewal(renewal: { r: string; commitment: string }): Promise<void> {
    this.r = fromHex(renewal.r); this.chain = deriveChain(this.spendSK, this.r, CHAIN_LENGTH);
    this.commitment = this.chain[CHAIN_LENGTH]; this.chainLength = CHAIN_LENGTH; this.pendingRenewal = null;
    if (this.path) await this.save();
  }
  private async settleRenewal(st: ChainState): Promise<void> {
    if (!this.pendingRenewal) return;
    if (st.depth === CHAIN_LENGTH && st.registered) await this.adoptRenewal(this.pendingRenewal);
    else if (st.depth === 0 && st.registered) throw new Bb84Error("exhausted", "the chain ended without a renewal; this address can never spend again");
    else if (st.depth > 1) { this.pendingRenewal = null; if (this.path) await this.save(); }
  }
}

// ─── offline self-test (vectors shared with bb84.py) ─────────────────────────
export function selftest(): boolean {
  const V = {
    spendSK: "4a30ffbf97c7df9f07ec26e718a8f6cfaaa13d074dd0deddef47e3dde8d663ba", viewSK: "722fed365ef7c360f5d431b36ef76148794d7f9611aa5e4128f0ffc59ff58f22",
    r: "659298cde88f0e5b10d8b00b35eb2a2f14ed97bcb20f619d38425df6a02650d2", address: "0xb4b030d0d7d47943e039a6eddc5b711f8827efe4",
    commitment: "419d3b69febc6b506ddf7e7cb6f7cf4c428344822b6151031e1833781269caba", chain999: "d08271239a2797952933f75c03a827f77597c64b5f373cac11336f6bb8ba3592",
    data: "a9059cbb00000000000000000000000042ed65db186dfdbc1ba5f0e979dceaeb4f63014d000000000000000000000000000000000000000000000000000000000016e360014b616666656520c2b72070725f303132333435363738396162636465663031323334353637",
    commit: "7cf84b840281ec0894b4b030d0d7d47943e039a6eddc5b711f8827efe480a0c9b79dcea5bc0094fa4568976f981d1c28714fe04db66190d86bc13e668b3267830186a0843b9aca008316e36081fa",
    reveal: "7ff9010f840281ec0894b4b030d0d7d47943e039a6eddc5b711f8827efe4019450590ee131edc98a7213c91ae82e3e8987b9b5ee8083027100843b9aca008316e360b86aa9059cbb00000000000000000000000042ed65db186dfdbc1ba5f0e979dceaeb4f63014d000000000000000000000000000000000000000000000000000000000016e360014b616666656520c2b72070725f303132333435363738396162636465663031323334353637a0478fb7cbb79211b19b3533af1c9319ca030dd83b04249f9a659348e8e23e8389a0d08271239a2797952933f75c03a827f77597c64b5f373cac11336f6bb8ba359280a0000000000000000000000000000000000000000000000000000000000000000080",
  };
  let okAll = true;
  const check = (name: string, cond: boolean) => { okAll &&= cond; console.log((cond ? "  ok   " : "  FAIL ") + name); };
  check("keccak256('')", hex(keccak256(new Uint8Array(0))) === "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470");
  const w = new Wallet(fromHex(V.spendSK), fromHex(V.viewSK), fromHex(V.r));
  check("chain[999]", hex(w.chain[999]) === V.chain999);
  check("commitment", hex(w.commitment) === V.commitment);
  check("address", w.address === V.address);
  const data = transferData("0x42ed65db186dfdbc1ba5f0e979dceaeb4f63014d", 1500000n, "Kaffee · pr_0123456789abcdef01234567", true);
  check("transfer calldata", hex(data) === V.data);
  const { commit, reveal } = buildSpendTxs({ from: fromHex(w.address.slice(2)), nonce: 0n, to: fromHex(TOKENS.USDC.slice(2)), data, gas: 160000n, feeCap: 1000000000n, tipCap: 1500000n }, w.chain[999]);
  check("HashCommitTx bytes", hex(commit) === V.commit);
  check("HashRevealTx bytes", hex(reveal) === V.reveal);
  check("registerCommitmentFor selector", hex(SEL_REGISTER_FOR) === "79176c17");
  check("toUnits('12.5')", toUnits("12.5") === 12500000n);
  console.log("selftest", okAll ? "passed" : "FAILED");
  return okAll;
}

// ─── CLI (node bb84.js new|status|pay|selftest) ──────────────────────────────
export async function main(argv: string[]): Promise<number> {
  const [cmd, ...rest] = argv;
  const file = (globalThis as any).process?.env?.BB84_WALLET_FILE ?? "bb84-wallet.json";
  try {
    if (cmd === "selftest") return selftest() ? 0 : 1;
    if (cmd === "new") {
      const fs = await import("node:fs/promises");
      if (await fs.stat(file).then(() => true, () => false)) { console.error(`${file} exists — refusing to overwrite a wallet`); return 2; }
      const w = Wallet.create(); await w.save(file);
      const i = rest.indexOf("--name");
      if (i >= 0 && rest[i + 1]) await w.registerName(rest[i + 1]); else await w.autoName();
      await w.publishCommitment(); await w.save();
      console.log(JSON.stringify({ address: w.address, name: w.name, payLink: `${BASE}/pay/${w.name}`, state: file }, null, 1)); return 0;
    }
    const w = await Wallet.load(file);
    if (cmd === "status") { console.log(JSON.stringify(await w.status(), null, 1)); await w.save(); return 0; }
    if (cmd === "pay") {
      const [to, amount, asset] = rest; const m = rest.indexOf("--memo");
      const res = await w.pay(to, amount, asset, { memo: m >= 0 ? rest[m + 1] : "", goods: rest.includes("--goods"), allowSuspect: rest.includes("--allow-suspect"), log: s => console.error(s) });
      await w.save(); console.log(JSON.stringify(res, null, 1)); return 0;
    }
    console.error("usage: bb84 new [--name label] | status | pay <to> <amount> <USDC|EURC> [--memo m] [--goods] | selftest"); return 2;
  } catch (e: any) {
    console.error(JSON.stringify({ error: e?.message ?? String(e), code: e?.code ?? "error" })); return 1;
  }
}
const _p = (globalThis as any).process;
if (_p?.argv?.[1] && /bb84\.(ts|js|cjs|mjs)$/.test(_p.argv[1])) main(_p.argv.slice(2)).then(code => { _p.exitCode = code; });
