@qntx/wallet-engine 0.4.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["NAME_MAX","isNonNegativeInt","KNOWN_GROUP_KEYS","KNOWN_WALLET_KEYS","PUBKEY_RE","isObject","isObject","runPay"],"sources":["../src/controller.ts","../src/events.ts","../src/errors.ts","../src/store/guard.ts","../src/store/memory.ts","../src/accounts/errors.ts","../src/accounts/controller.ts","../../../node_modules/.bun/@noble+hashes@2.4.0/node_modules/@noble/hashes/_u64.js","../../../node_modules/.bun/@noble+hashes@2.4.0/node_modules/@noble/hashes/utils.js","../../../node_modules/.bun/@noble+hashes@2.4.0/node_modules/@noble/hashes/_md.js","../../../node_modules/.bun/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha2.js","../src/backup/errors.ts","../src/backup/controller.ts","../src/meta/doc.ts","../src/meta/errors.ts","../src/meta/controller.ts","../src/payments/parse.ts","../src/spark/errors.ts","../src/payments/errors.ts","../src/payments/pay.ts","../src/payments/resolve.ts","../src/payments/zap.ts","../src/spark/notes.ts","../src/spark/exit-chain-codec.ts","../src/spark/store.ts","../src/spark/controller.ts","../src/engine.ts","../src/backup/memory.ts"],"sourcesContent":["import { createStore } from \"zustand/vanilla\";\nimport type { StoreApi } from \"zustand/vanilla\";\n\nexport type ControllerOptions<S> = {\n readonly name: string;\n readonly defaultState: () => S;\n};\n\n/**\n * Controller base: a zustand vanilla store plus lifecycle. `update` applies a recipe that must\n * return a NEW state object; returning the same reference is a no-op (no set, no notification).\n * Persistence and migrations layer on later — this package carries only what its first user needs.\n */\nexport abstract class Controller<S extends Record<string, unknown>> {\n readonly name: string;\n readonly store: StoreApi<S>;\n\n protected constructor(options: ControllerOptions<S>) {\n this.name = options.name;\n this.store = createStore<S>(options.defaultState);\n }\n\n getState(): S {\n return this.store.getState();\n }\n\n protected update(recipe: (state: S) => S): void {\n this.store.setState((state) => recipe(state));\n }\n\n abstract init(): Promise<void>;\n abstract destroy(): Promise<void>;\n}\n","/** Log port: listener failures are reported here and never reach the emitter or peers. */\nexport type EngineLogger = {\n readonly warn: (message: string, error?: unknown) => void;\n};\n\nexport type EventBus<E> = {\n /** Synchronous dispatch to every current listener in registration order. */\n emit: <K extends keyof E>(type: K, payload: E[K]) => void;\n on: <K extends keyof E>(type: K, listener: (payload: E[K]) => void) => () => void;\n};\n\nexport function createEventBus<E>(logger: EngineLogger): EventBus<E> {\n const listeners = new Map<keyof E, Set<(payload: unknown) => void>>();\n return {\n emit<K extends keyof E>(type: K, payload: E[K]): void {\n const set = listeners.get(type);\n if (set === undefined) {\n return;\n }\n for (const listener of set) {\n try {\n listener(payload);\n } catch (error) {\n logger.warn(\"event listener threw\", error);\n }\n }\n },\n on<K extends keyof E>(type: K, listener: (payload: E[K]) => void): () => void {\n let set = listeners.get(type);\n if (set === undefined) {\n set = new Set();\n listeners.set(type, set);\n }\n // The set is keyed by event type, so each listener only ever receives its own payload.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const stored = listener as (payload: unknown) => void;\n set.add(stored);\n return () => {\n set.delete(stored);\n };\n },\n };\n}\n","export type EngineErrorCode = \"closed\" | \"integrity\" | \"invalid-input\";\n\n/** Typed engine errors: store codes are `closed` and `integrity` (decrypt or bind failure). */\nexport class EngineStoreError extends Error {\n readonly code: EngineErrorCode;\n\n constructor(code: EngineErrorCode, message: string) {\n super(message);\n this.name = \"EngineStoreError\";\n this.code = code;\n }\n}\n","import { EngineStoreError } from \"../errors.ts\";\n\n/** NUL is the composite-key/AAD separator — a name or key containing it collides. */\nexport function checkName(kind: \"collection\" | \"key\", value: string): void {\n if (value.includes(\"\\u0000\")) {\n throw new EngineStoreError(\"invalid-input\", `${kind} must not contain NUL`);\n }\n}\n","import { EngineStoreError } from \"../errors.ts\";\nimport { checkName } from \"./guard.ts\";\nimport type { EngineCollection, EngineStore } from \"./port.ts\";\n\n/** In-memory EngineStore: the Node/test implementation — same contract, no durability. */\nexport function createMemoryEngineStore(backing?: {\n readonly collections?: Map<string, Map<string, Uint8Array>>;\n}): EngineStore {\n const collections = backing?.collections ?? new Map<string, Map<string, Uint8Array>>();\n let closed = false;\n const guard = (): void => {\n if (closed) {\n throw new EngineStoreError(\"closed\", \"engine store is closed\");\n }\n };\n return {\n collection(name: string): EngineCollection {\n checkName(\"collection\", name);\n let table = collections.get(name);\n if (table === undefined) {\n table = new Map();\n collections.set(name, table);\n }\n return {\n get: async (key) => {\n guard();\n checkName(\"key\", key);\n const value = table.get(key);\n return value === undefined ? undefined : new Uint8Array(value);\n },\n put: async (key, bytes) => {\n guard();\n checkName(\"key\", key);\n table.set(key, new Uint8Array(bytes));\n },\n delete: async (key) => {\n guard();\n checkName(\"key\", key);\n table.delete(key);\n },\n list: async () => {\n guard();\n return [...table.keys()];\n },\n };\n },\n close: async () => {\n closed = true;\n collections.clear();\n },\n };\n}\n","/** Account-tree error categories — messages never carry secrets. */\nexport type AccountTreeErrorCategory = \"invalid-input\" | \"rejected\" | \"not-found\" | \"locked\";\n\nexport class AccountTreeError extends Error {\n readonly category: AccountTreeErrorCategory;\n\n constructor(category: AccountTreeErrorCategory, message: string, cause?: unknown) {\n super(message, { cause });\n this.name = \"AccountTreeError\";\n this.category = category;\n }\n}\n","import type { SparkNetwork } from \"@qntx/spark\";\nimport type { Wallet } from \"@qntx/wallet\";\n\nimport { Controller } from \"../controller.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport type { MetaDoc, MetaDocGroup } from \"../meta/doc.ts\";\nimport type { SparkController } from \"../spark/controller.ts\";\nimport type { EngineCollection, EngineStore } from \"../store/port.ts\";\nimport { AccountTreeError } from \"./errors.ts\";\n\nexport type AccountGroup = {\n readonly walletId: string;\n readonly index: number;\n readonly name?: string;\n readonly hidden: boolean;\n /** A social identity (64 lowercase hex) bound to this group; one identity binds one group. */\n readonly boundPubkey?: string;\n /** Last local modification time (ms); reconcile-created entries start at 0. */\n readonly updatedAt: number;\n};\n\nexport type AccountTreeState = {\n readonly status: \"locked\" | \"ready\";\n readonly wallets: ReadonlyArray<{\n readonly walletId: string;\n readonly name?: string;\n readonly updatedAt: number;\n }>;\n readonly groups: Readonly<Record<string, ReadonlyArray<AccountGroup>>>;\n // oxlint-disable-next-line typescript/no-restricted-types -- spec shape: no wallets → null\n readonly selected: { readonly walletId: string; readonly groupIndex: number } | null;\n readonly totals: Readonly<Record<string, number>>;\n};\n\nexport type AccountTreeControllerOptions = {\n readonly wallet: Wallet;\n readonly spark: SparkController;\n readonly sparkNetwork: SparkNetwork;\n readonly logger: EngineLogger;\n readonly now: () => number;\n};\n\ntype PersistedTree = {\n readonly wallets: Readonly<\n Record<string, { readonly name?: string; readonly updatedAt: number }>\n >;\n readonly groups: Readonly<Record<string, ReadonlyArray<AccountGroup>>>;\n // oxlint-disable-next-line typescript/no-restricted-types -- wire contract: selected may be null\n readonly selected: { readonly walletId: string; readonly groupIndex: number } | null;\n readonly totals: Readonly<Record<string, number>>;\n};\n\nconst EMPTY_TREE: PersistedTree = { wallets: {}, groups: {}, selected: null, totals: {} };\n\nconst TOTAL_KEY = (walletId: string, index: number): string => `${walletId}:${index}`;\n\nconst withoutBinding = (g: AccountGroup): AccountGroup => {\n const { boundPubkey: _removed, ...rest } = g;\n void _removed;\n return rest;\n};\n\nconst NAME_MAX = 24;\nconst TOTALS_DEBOUNCE_MS = 1000;\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\nconst own = (o: Record<string, unknown>, k: string): boolean => Object.hasOwn(o, k);\n\nconst isNonNegativeInt = (v: unknown): v is number =>\n typeof v === \"number\" && Number.isSafeInteger(v) && v >= 0;\n\nfunction validateName(v: unknown): string | undefined {\n if (v === undefined) {\n return undefined;\n }\n if (typeof v !== \"string\") {\n return undefined;\n }\n const name = v.trim();\n return name.length > 0 && name.length <= NAME_MAX ? name : undefined;\n}\n\nconst KNOWN_GROUP_KEYS = new Set([\n \"walletId\",\n \"index\",\n \"name\",\n \"hidden\",\n \"boundPubkey\",\n \"updatedAt\",\n]);\nconst KNOWN_TOP_KEYS = new Set([\"wallets\", \"groups\", \"selected\", \"totals\"]);\nconst KNOWN_WALLET_KEYS = new Set([\"name\", \"updatedAt\"]);\nconst KNOWN_SELECTED_KEYS = new Set([\"walletId\", \"groupIndex\"]);\n\nconst PUBKEY_RE = /^[0-9a-f]{64}$/;\n\n/** Strict decode — any malformed shape or unknown key returns `undefined`. */\nfunction decodeTree(bytes: Uint8Array): PersistedTree | undefined {\n try {\n const text = new TextDecoder().decode(bytes);\n const raw: unknown = JSON.parse(text);\n if (!isPlainObject(raw)) {\n return undefined;\n }\n for (const k of Object.keys(raw)) {\n if (!KNOWN_TOP_KEYS.has(k)) {\n return undefined;\n }\n }\n const rawWallets = raw[\"wallets\"];\n const rawGroups = raw[\"groups\"];\n const rawSelected = raw[\"selected\"];\n const rawTotals = raw[\"totals\"];\n if (!isPlainObject(rawWallets) || !isPlainObject(rawGroups) || !isPlainObject(rawTotals)) {\n return undefined;\n }\n const wallets: Record<string, { name?: string; updatedAt: number }> = {};\n for (const [walletId, w] of Object.entries(rawWallets)) {\n if (!isPlainObject(w) || walletId.length === 0) {\n return undefined;\n }\n for (const k of Object.keys(w)) {\n if (!KNOWN_WALLET_KEYS.has(k)) {\n return undefined;\n }\n }\n const name = validateName(w[\"name\"]);\n if (w[\"name\"] !== undefined && name === undefined) {\n return undefined;\n }\n const { updatedAt } = w;\n if (!isNonNegativeInt(updatedAt)) {\n return undefined;\n }\n wallets[walletId] = { updatedAt, ...(name === undefined ? {} : { name }) };\n }\n const groups: Record<string, AccountGroup[]> = {};\n for (const [walletId, arr] of Object.entries(rawGroups)) {\n if (!Array.isArray(arr)) {\n return undefined;\n }\n const seen = new Set<number>();\n const list: AccountGroup[] = [];\n for (const item of arr) {\n if (!isPlainObject(item)) {\n return undefined;\n }\n for (const k of Object.keys(item)) {\n if (!KNOWN_GROUP_KEYS.has(k)) {\n return undefined;\n }\n }\n if (item[\"walletId\"] !== walletId || !isNonNegativeInt(item[\"index\"])) {\n return undefined;\n }\n const { index } = item;\n if (seen.has(index) || (item[\"hidden\"] !== true && item[\"hidden\"] !== false)) {\n return undefined;\n }\n seen.add(index);\n const name = validateName(item[\"name\"]);\n if (item[\"name\"] !== undefined && name === undefined) {\n return undefined;\n }\n const { updatedAt } = item;\n if (!isNonNegativeInt(updatedAt)) {\n return undefined;\n }\n const { boundPubkey } = item;\n if (\n boundPubkey !== undefined &&\n (typeof boundPubkey !== \"string\" || !PUBKEY_RE.test(boundPubkey))\n ) {\n return undefined;\n }\n list.push({\n walletId,\n index,\n hidden: item[\"hidden\"],\n updatedAt,\n ...(name === undefined ? {} : { name }),\n ...(boundPubkey === undefined ? {} : { boundPubkey }),\n });\n }\n list.sort((a, b) => a.index - b.index);\n groups[walletId] = list;\n }\n let selected: PersistedTree[\"selected\"] = null;\n if (rawSelected !== undefined && rawSelected !== null) {\n if (!isPlainObject(rawSelected)) {\n return undefined;\n }\n for (const k of Object.keys(rawSelected)) {\n if (!KNOWN_SELECTED_KEYS.has(k)) {\n return undefined;\n }\n }\n const { walletId } = rawSelected;\n const { groupIndex } = rawSelected;\n if (typeof walletId !== \"string\" || walletId.length === 0 || !isNonNegativeInt(groupIndex)) {\n return undefined;\n }\n selected = { walletId, groupIndex };\n }\n const totals: Record<string, number> = {};\n for (const [k, v] of Object.entries(rawTotals)) {\n if (!own(rawTotals, k) || !isNonNegativeInt(v)) {\n return undefined;\n }\n totals[k] = v;\n }\n return { wallets, groups, selected, totals };\n } catch {\n return undefined;\n }\n}\n\nfunction encodeTree(tree: PersistedTree): Uint8Array {\n return new TextEncoder().encode(JSON.stringify(tree));\n}\n\n/**\n * Declarative account tree: wallets come from the Wallet snapshot (reconciled on unlock and on\n * every snapshot change while unlocked), groups/names/hidden/selected/totals persist to the engine\n * store under `accounts/tree`. The controller drives `spark.setAccounts` with the selected group\n * only — an unselected group needs no live client (incoming transfers are claimed whenever it is\n * selected again). The active account's `balanceSats` feeds `totals`, debounced 1 s before\n * persist.\n */\nexport class AccountTreeController extends Controller<AccountTreeState> {\n private readonly options: AccountTreeControllerOptions;\n private col: EngineCollection | undefined;\n private sparkUnsubscribe: (() => void) | undefined;\n private totalsTimer: ReturnType<typeof setTimeout> | undefined;\n private persistChain: Promise<void> = Promise.resolve();\n\n constructor(options: AccountTreeControllerOptions) {\n super({\n name: \"accounts\",\n defaultState: () => ({\n status: \"locked\",\n wallets: [],\n groups: {},\n selected: null,\n totals: {},\n }),\n });\n this.options = options;\n }\n\n setStore(store: EngineStore | undefined): void {\n this.col = store === undefined ? undefined : store.collection(\"accounts\");\n }\n\n /** Load persisted state, reconcile with the snapshot, start driving Spark. */\n async init(): Promise<void> {\n const persisted = await this.load();\n this.update(() => ({ status: \"ready\", ...persistedToState(persisted) }));\n this.reconcile();\n // First drive: the reconciled selection always starts a client for it.\n this.driveSpark(this.getState().selected);\n this.sparkUnsubscribe = this.options.spark.store.subscribe((state) => {\n this.onSparkState(state.accounts);\n });\n }\n\n async destroy(): Promise<void> {\n this.sparkUnsubscribe?.();\n this.sparkUnsubscribe = undefined;\n await this.lock();\n }\n\n /** Locked: stop every Spark client, flush pending persists, then drop to the empty state. */\n async lock(): Promise<void> {\n this.sparkUnsubscribe?.();\n this.sparkUnsubscribe = undefined;\n this.options.spark.setAccounts([]);\n // Flush while the real state is still visible — updating first would persist empties over\n // names, groups, hidden flags and the selection.\n await this.flushTotals();\n this.col = undefined;\n this.update(() => ({\n status: \"locked\",\n wallets: [],\n groups: {},\n selected: null,\n totals: {},\n }));\n await Promise.resolve();\n }\n\n /** Reconcile groups/names/selected with `wallet.getSnapshot().wallets`; persists on change. */\n reconcile(): void {\n if (this.getState().status !== \"ready\") {\n return;\n }\n const snapshot = this.options.wallet.getSnapshot();\n const live = snapshot.wallets.map((w) => w.walletId);\n const liveSet = new Set(live);\n const state = this.getState();\n const entriesById = new Map(state.wallets.map((w) => [w.walletId, w]));\n const wallets = live.map((walletId) => {\n const existing = entriesById.get(walletId);\n return existing ?? { walletId, updatedAt: 0 };\n });\n const groups: Record<string, ReadonlyArray<AccountGroup>> = {};\n for (const walletId of live) {\n const existing = state.groups[walletId] ?? [];\n groups[walletId] =\n existing.length > 0 ? existing : [{ walletId, index: 0, hidden: false, updatedAt: 0 }];\n }\n const totals: Record<string, number> = {};\n for (const [k, v] of Object.entries(state.totals)) {\n const walletId = k.slice(0, Math.max(0, k.lastIndexOf(\":\")));\n if (liveSet.has(walletId)) {\n totals[k] = v;\n }\n }\n const selected = this.validSelection(groups, live, state.selected);\n const changed =\n JSON.stringify(wallets) !== JSON.stringify(state.wallets) ||\n JSON.stringify(groups) !== JSON.stringify(state.groups) ||\n JSON.stringify(totals) !== JSON.stringify(state.totals) ||\n JSON.stringify(selected) !== JSON.stringify(state.selected);\n if (changed) {\n this.update((s) => ({ ...s, wallets, groups, totals, selected }));\n this.persist();\n // Drive only on effective change — an unchanged reconcile must not stomp a caller-set\n // setAccounts (e.g. tests running two accounts at once).\n this.driveSpark(selected);\n }\n }\n\n addGroup(walletId: string): number {\n this.mustWallet(walletId);\n const groups = this.getState().groups[walletId] ?? [];\n let index = 0;\n for (const g of groups) {\n index = Math.max(index, g.index + 1);\n }\n const updatedAt = this.options.now();\n this.mutateGroups(walletId, (list) => [...list, { walletId, index, hidden: false, updatedAt }]);\n return index;\n }\n\n addGroups(walletId: string, indices: ReadonlyArray<number>): void {\n this.mustWallet(walletId);\n this.mutateGroups(walletId, (list) => {\n const have = new Set(list.map((g) => g.index));\n const added: AccountGroup[] = [];\n const updatedAt = this.options.now();\n for (const i of indices) {\n if (Number.isSafeInteger(i) && i >= 0 && !have.has(i)) {\n have.add(i);\n added.push({ walletId, index: i, hidden: false, updatedAt });\n }\n }\n return [...list, ...added].sort((a, b) => a.index - b.index);\n });\n }\n\n renameWallet(walletId: string, name: string): void {\n this.mustWallet(walletId);\n const trimmed = this.checkedName(name);\n const updatedAt = this.options.now();\n this.update((s) => ({\n ...s,\n wallets: s.wallets.map((w) =>\n w.walletId === walletId ? { walletId, name: trimmed, updatedAt } : w,\n ),\n }));\n this.persist();\n }\n\n renameGroup(walletId: string, index: number, name: string): void {\n this.mustGroup(walletId, index);\n const trimmed = this.checkedName(name);\n const updatedAt = this.options.now();\n this.mutateGroups(walletId, (list) =>\n list.map((g) => (g.index === index ? { ...g, name: trimmed, updatedAt } : g)),\n );\n }\n\n setHidden(walletId: string, index: number, hidden: boolean): void {\n const state = this.getState();\n this.mustGroup(walletId, index);\n const visible = this.visibleGroups(state).filter(\n (g) => !(g.walletId === walletId && g.index === index),\n );\n if (hidden && visible.length === 0) {\n throw new AccountTreeError(\"rejected\", \"cannot hide every account group\");\n }\n const updatedAt = this.options.now();\n this.mutateGroups(walletId, (list) =>\n list.map((g) => (g.index === index ? { ...g, hidden, updatedAt } : g)),\n );\n const sel = state.selected;\n if (sel !== null && sel.walletId === walletId && sel.groupIndex === index && hidden) {\n this.selectFallback();\n }\n }\n\n select(walletId: string, index: number): void {\n const state = this.getState();\n const group = (state.groups[walletId] ?? []).find((g) => g.index === index);\n if (group === undefined) {\n throw new AccountTreeError(\"not-found\", \"account group does not exist\");\n }\n if (group.hidden) {\n throw new AccountTreeError(\"rejected\", \"cannot select a hidden account group\");\n }\n if (state.selected?.walletId === walletId && state.selected.groupIndex === index) {\n return;\n }\n this.update((s) => ({ ...s, selected: { walletId, groupIndex: index } }));\n this.persist();\n this.driveSpark(this.getState().selected);\n }\n\n /**\n * Binds a social identity to one group. The identity is unique across the whole tree — every\n * group in every wallet carrying it loses the binding (each entry re-stamped).\n */\n bind(walletId: string, index: number, pubkey: string): void {\n this.mustGroup(walletId, index);\n if (!PUBKEY_RE.test(pubkey)) {\n throw new AccountTreeError(\"invalid-input\", \"boundPubkey must be 64 lowercase hex\");\n }\n const updatedAt = this.options.now();\n this.update((s) => ({\n ...s,\n groups: Object.fromEntries(\n Object.entries(s.groups).map(([wid, list]) => [\n wid,\n list.map((g) => {\n if (wid === walletId && g.index === index) {\n return { ...g, boundPubkey: pubkey, updatedAt };\n }\n if (g.boundPubkey === pubkey) {\n return { ...withoutBinding(g), updatedAt };\n }\n return g;\n }),\n ]),\n ),\n }));\n this.persist();\n }\n\n unbind(walletId: string, index: number): void {\n this.mustGroup(walletId, index);\n const updatedAt = this.options.now();\n this.mutateGroups(walletId, (list) =>\n list.map((g) => (g.index === index ? { ...withoutBinding(g), updatedAt } : g)),\n );\n }\n\n /**\n * Which group currently holds a pubkey — merges can leave the same identity on groups in two\n * wallets; the newest `updatedAt` wins, ties resolve by snapshot wallet order then lower index.\n */\n bindingOf(pubkey: string): { walletId: string; groupIndex: number } | undefined {\n const s = this.getState();\n let best:\n | { walletId: string; groupIndex: number; updatedAt: number; walletPos: number }\n | undefined;\n let walletPos = -1;\n for (const w of s.wallets) {\n walletPos += 1;\n for (const g of s.groups[w.walletId] ?? []) {\n if (g.boundPubkey !== pubkey) {\n continue;\n }\n if (\n best === undefined ||\n g.updatedAt > best.updatedAt ||\n (g.updatedAt === best.updatedAt &&\n (walletPos < best.walletPos ||\n (walletPos === best.walletPos && g.index < best.groupIndex)))\n ) {\n best = { walletId: w.walletId, groupIndex: g.index, updatedAt: g.updatedAt, walletPos };\n }\n }\n }\n return best === undefined\n ? undefined\n : { walletId: best.walletId, groupIndex: best.groupIndex };\n }\n\n /** The wallet's metadata document — every group, hidden included. */\n exportMeta(walletId: string): MetaDoc {\n this.mustWallet(walletId);\n const s = this.getState();\n const w = s.wallets.find((x) => x.walletId === walletId);\n const wallet: MetaDoc[\"wallet\"] = {\n updatedAt: w?.updatedAt ?? 0,\n ...(w?.name === undefined ? {} : { name: w.name }),\n };\n const groups: MetaDocGroup[] = [];\n for (const g of s.groups[walletId] ?? []) {\n groups.push({\n index: g.index,\n hidden: g.hidden,\n updatedAt: g.updatedAt,\n ...(g.name === undefined ? {} : { name: g.name }),\n ...(g.boundPubkey === undefined ? {} : { boundPubkey: g.boundPubkey }),\n });\n }\n return { v: 1, wallet, groups };\n }\n\n /**\n * Entry-level last-writer-wins merge: a newer remote `updatedAt` replaces the local entry, a tie\n * keeps local; remote-only groups are added. `selected`/hidden rules are re-validated — if the\n * merge hides the selected group it is re-selected, and a merge may never leave every group\n * hidden (the selected one stays visible and is re-stamped so the fix propagates).\n */\n mergeMeta(walletId: string, doc: MetaDoc): { changed: boolean; localNewer: boolean } {\n this.mustWallet(walletId);\n let changed = false;\n let localNewer = false;\n const s = this.getState();\n const localWallet = s.wallets.find((w) => w.walletId === walletId);\n const walletUpdatedAt = localWallet?.updatedAt ?? 0;\n let wallet = localWallet ?? { walletId, updatedAt: 0 };\n if (doc.wallet.updatedAt > walletUpdatedAt) {\n wallet = {\n walletId,\n updatedAt: doc.wallet.updatedAt,\n ...(doc.wallet.name === undefined ? {} : { name: doc.wallet.name }),\n };\n changed = true;\n } else if (walletUpdatedAt > doc.wallet.updatedAt) {\n localNewer = true;\n }\n const localByIndex = new Map((s.groups[walletId] ?? []).map((g) => [g.index, g]));\n const groups = [...(s.groups[walletId] ?? [])];\n for (const remote of doc.groups) {\n const local = localByIndex.get(remote.index);\n if (local === undefined) {\n groups.push({\n walletId,\n index: remote.index,\n hidden: remote.hidden,\n updatedAt: remote.updatedAt,\n ...(remote.name === undefined ? {} : { name: remote.name }),\n ...(remote.boundPubkey === undefined ? {} : { boundPubkey: remote.boundPubkey }),\n });\n changed = true;\n continue;\n }\n if (remote.updatedAt > local.updatedAt) {\n const replaced: AccountGroup = {\n walletId,\n index: remote.index,\n hidden: remote.hidden,\n updatedAt: remote.updatedAt,\n ...(remote.name === undefined ? {} : { name: remote.name }),\n ...(remote.boundPubkey === undefined ? {} : { boundPubkey: remote.boundPubkey }),\n };\n const at = groups.findIndex((g) => g.index === remote.index);\n groups[at] = replaced;\n changed = true;\n } else if (local.updatedAt > remote.updatedAt) {\n localNewer = true;\n }\n }\n for (const g of groups) {\n if (!doc.groups.some((r) => r.index === g.index) && g.updatedAt > 0) {\n localNewer = true;\n }\n }\n groups.sort((a, b) => a.index - b.index);\n // Re-validate selection: merge may have hidden the selected group or every group.\n const walletOrder = s.wallets.map((w) => w.walletId);\n let selected = this.validSelection(\n { ...s.groups, [walletId]: groups },\n walletOrder,\n s.selected,\n );\n const visible = groups.some((g) => !g.hidden);\n if (!visible && groups.length > 0) {\n // A merge must never hide every group — keep the selected (or first) one visible and\n // stamp it so the local correction wins the next merge too.\n const keep = selected ?? { walletId, groupIndex: groups[0]?.index ?? 0 };\n const now = this.options.now();\n for (const [i, g] of groups.entries()) {\n if (g.index === keep.groupIndex) {\n groups[i] = { ...g, hidden: false, updatedAt: now };\n }\n }\n selected = keep;\n changed = true;\n localNewer = true;\n }\n if (\n selected?.walletId !== s.selected?.walletId ||\n selected?.groupIndex !== s.selected?.groupIndex\n ) {\n changed = true;\n }\n if (changed) {\n this.update((st) => ({\n ...st,\n wallets: st.wallets.map((w) => (w.walletId === walletId ? wallet : w)),\n groups: { ...st.groups, [walletId]: groups },\n selected,\n }));\n this.persist();\n this.driveSpark(selected);\n }\n return { changed, localNewer };\n }\n\n /** Sequential inspect from 0 upward; index 0 always included; stop after 2 consecutive unused. */\n async discoverSpark(walletId: string): Promise<number[]> {\n this.mustWallet(walletId);\n const found: number[] = [0];\n let index = 0;\n let unused = 0;\n while (found.length < 65) {\n const ref = { walletId, groupIndex: index, network: this.options.sparkNetwork } as const;\n // oxlint-disable-next-line eslint/no-await-in-loop -- discovery is sequential per spec\n const { used } = await this.options.spark.inspect(ref);\n if (used) {\n if (index !== 0) {\n found.push(index);\n }\n unused = 0;\n } else {\n unused += 1;\n if (index !== 0 && unused >= 2) {\n break;\n }\n }\n index += 1;\n }\n return found;\n }\n\n /** Refresh `totals` for every other visible group; per-group failures are logged and skipped. */\n async refreshTotals(): Promise<void> {\n const state = this.getState();\n const sel = state.selected;\n const targets = this.visibleGroups(state).filter(\n (g) => !(sel !== null && g.walletId === sel.walletId && g.index === sel.groupIndex),\n );\n let cursor = 0;\n const worker = async (): Promise<void> => {\n while (cursor < targets.length) {\n const group = targets[cursor];\n cursor += 1;\n if (group === undefined) {\n return;\n }\n try {\n const ref = {\n walletId: group.walletId,\n groupIndex: group.index,\n network: this.options.sparkNetwork,\n } as const;\n // oxlint-disable-next-line eslint/no-await-in-loop -- workers drain a shared cursor\n const { balanceSats } = await this.options.spark.inspect(ref);\n this.setTotal(group.walletId, group.index, balanceSats);\n } catch (error) {\n this.options.logger.warn(\n `refreshTotals failed for ${group.walletId}:${group.index}`,\n error,\n );\n }\n }\n };\n await Promise.all([worker(), worker()]);\n }\n\n private onSparkState(\n accounts: Readonly<Record<string, { readonly balanceSats?: number }>>,\n ): void {\n const sel = this.getState().selected;\n if (sel === null) {\n return;\n }\n const accountKey = `${sel.walletId}:${sel.groupIndex}:${this.options.sparkNetwork}`;\n const balance = accounts[accountKey]?.balanceSats;\n if (balance !== undefined) {\n this.setTotal(sel.walletId, sel.groupIndex, balance);\n }\n }\n\n private setTotal(walletId: string, index: number, balanceSats: number): void {\n const k = TOTAL_KEY(walletId, index);\n if (this.getState().totals[k] === balanceSats) {\n return;\n }\n this.update((s) => ({ ...s, totals: { ...s.totals, [k]: balanceSats } }));\n this.scheduleTotalsPersist();\n }\n\n private driveSpark(selected: AccountTreeState[\"selected\"]): void {\n this.options.spark.setAccounts(\n selected === null ? [] : [{ ...selected, network: this.options.sparkNetwork }],\n );\n }\n\n private visibleGroups(state: AccountTreeState): AccountGroup[] {\n const out: AccountGroup[] = [];\n for (const w of state.wallets) {\n for (const g of state.groups[w.walletId] ?? []) {\n if (!g.hidden) {\n out.push(g);\n }\n }\n }\n return out;\n }\n\n private validSelection(\n groups: Record<string, ReadonlyArray<AccountGroup>>,\n walletOrder: ReadonlyArray<string>,\n current: AccountTreeState[\"selected\"],\n ): AccountTreeState[\"selected\"] {\n if (current !== null) {\n const g = (groups[current.walletId] ?? []).find((x) => x.index === current.groupIndex);\n if (g !== undefined && !g.hidden) {\n return current;\n }\n }\n for (const walletId of walletOrder) {\n for (const g of groups[walletId] ?? []) {\n if (!g.hidden) {\n return { walletId, groupIndex: g.index };\n }\n }\n }\n return null;\n }\n\n private selectFallback(): void {\n const state = this.getState();\n const next = this.validSelection(\n state.groups,\n state.wallets.map((w) => w.walletId),\n null,\n );\n this.update((s) => ({ ...s, selected: next }));\n this.persist();\n this.driveSpark(next);\n }\n\n private mutateGroups(\n walletId: string,\n fn: (list: ReadonlyArray<AccountGroup>) => ReadonlyArray<AccountGroup>,\n ): void {\n this.update((s) => ({\n ...s,\n groups: { ...s.groups, [walletId]: fn(s.groups[walletId] ?? []) },\n }));\n this.persist();\n }\n\n private mustWallet(walletId: string): void {\n if (this.getState().status !== \"ready\") {\n throw new AccountTreeError(\"locked\", \"account tree is locked\");\n }\n if (!this.getState().wallets.some((w) => w.walletId === walletId)) {\n throw new AccountTreeError(\"not-found\", \"wallet does not exist\");\n }\n }\n\n private mustGroup(walletId: string, index: number): void {\n this.mustWallet(walletId);\n if (!(this.getState().groups[walletId] ?? []).some((g) => g.index === index)) {\n throw new AccountTreeError(\"not-found\", \"account group does not exist\");\n }\n }\n\n private checkedName(name: string): string {\n const trimmed = name.trim();\n if (trimmed.length === 0 || trimmed.length > NAME_MAX) {\n throw new AccountTreeError(\"invalid-input\", \"name must be 1-24 characters\");\n }\n return trimmed;\n }\n\n private async load(): Promise<PersistedTree> {\n if (this.col === undefined) {\n return EMPTY_TREE;\n }\n const bytes = await this.col.get(\"tree\");\n if (bytes === undefined) {\n return EMPTY_TREE;\n }\n const tree = decodeTree(bytes);\n if (tree === undefined) {\n this.options.logger.warn(\"invalid persisted account tree — starting empty\");\n return EMPTY_TREE;\n }\n return tree;\n }\n\n /** Queues a store write behind the previous one — the last queued write always lands last. */\n private persist(): void {\n const { col } = this;\n if (col === undefined) {\n return;\n }\n const previous = this.persistChain;\n this.persistChain = (async () => {\n try {\n await previous;\n const s = this.getState();\n const tree: PersistedTree = {\n wallets: Object.fromEntries(\n s.wallets.map((w) => [\n w.walletId,\n { updatedAt: w.updatedAt, ...(w.name === undefined ? {} : { name: w.name }) },\n ]),\n ),\n groups: s.groups,\n selected: s.selected,\n totals: s.totals,\n };\n await col.put(\"tree\", encodeTree(tree));\n } catch (error) {\n this.options.logger.warn(\"account tree persist failed\", error);\n }\n })();\n }\n\n private scheduleTotalsPersist(): void {\n if (this.totalsTimer !== undefined) {\n return;\n }\n this.totalsTimer = setTimeout(() => {\n this.totalsTimer = undefined;\n this.persist();\n }, TOTALS_DEBOUNCE_MS);\n }\n\n private async flushTotals(): Promise<void> {\n if (this.totalsTimer !== undefined) {\n clearTimeout(this.totalsTimer);\n this.totalsTimer = undefined;\n this.persist();\n }\n await this.persistChain;\n }\n}\n\nfunction persistedToState(tree: PersistedTree): Omit<AccountTreeState, \"status\"> {\n const wallets: Array<{\n readonly walletId: string;\n readonly name?: string;\n readonly updatedAt: number;\n }> = [];\n for (const [walletId, w] of Object.entries(tree.wallets)) {\n if (w.name === undefined) {\n wallets.push({ walletId, updatedAt: w.updatedAt });\n } else {\n wallets.push({ walletId, name: w.name, updatedAt: w.updatedAt });\n }\n }\n return {\n wallets,\n groups: tree.groups,\n selected: tree.selected,\n totals: tree.totals,\n };\n}\n","const U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();\nconst _32n = /* @__PURE__ */ BigInt(32);\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// Split a JS number into u32 halves without a BigInt allocation. Exact only for integers\n// `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below\n// that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).\nconst fromNumH = (n) => (n / 2 ** 32) | 0;\nconst fromNumL = (n) => n >>> 0;\n// Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call\n// BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.\nfunction setU64FromNum(view, byteOffset, n, isLE) {\n const h = fromNumH(n);\n const l = fromNumL(n);\n view.setUint32(byteOffset, isLE ? l : h, isLE);\n view.setUint32(byteOffset + 4, isLE ? h : l, isLE);\n}\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h, _l, s) => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h, l) => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h, _l) => h;\n// 64-bit left rotates (rotl*) are not defined here: sha3.ts, their only consumer, keeps\n// local copies so V8 inlines them into keccakP.\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, fromNumH, fromNumL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, setU64FromNum, shrSH, shrSL, split, toBig };\n","/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1));\n}\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @returns The validated number.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number')\n throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);\n if (!Number.isSafeInteger(n) || n < 0)\n throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);\n return n;\n}\n/**\n * Asserts something is a boolean.\n * @param value - value to validate\n * @param title - label included in thrown errors\n * @returns The validated boolean.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a boolean option.\n * ```ts\n * abool(true, 'enableXOF');\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(value, length, title = '') {\n // Success path first: this runs at the start of every update() / digestInto(), and the\n // common `abytes(data)` form must not pay for length handling it does not use.\n if (isBytes(value) && (length === undefined || value.length === length))\n return value;\n // Error path: recompute freely to build the exact message.\n if (length !== undefined)\n anumber(length, 'length');\n const bytes = isBytes(value);\n const ofLen = length !== undefined ? ` of length ${length}` : '';\n const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n}\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('expected hash wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1 || h.blockLen < 1)\n throw new Error('hash blockLen / outputLen must be >= 1');\n}\nconst aobject = (value, label) => {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError((label === 'object' ? '' : `\"${label}\" `) + 'expected object, got type=' + typeof value);\n};\nconst aopts = (value, label) => {\n aobject(value, label);\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null)\n throw new TypeError(`\"${label}\" expected plain object`);\n // Object.assign() treats an own \"__proto__\" source key as a write to the target's legacy\n // prototype setter. Reject it before merging so inherited option values cannot be injected.\n if (Object.hasOwn(value, '__proto__'))\n throw new TypeError(`\"${label}.__proto__\" is not allowed`);\n};\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their\n // truthiness is checked - re-validating their type per call was pure hot-path overhead.\n if (instance.destroyed)\n throw new Error('hash was destroyed');\n if (checkFinished && instance.finished)\n throw new Error('digest() was already called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'output');\n // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast\n // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.\n const min = instance.outputLen;\n if (!(out.length >= min)) {\n throw new RangeError('\"output\" expected length >= ' + min);\n }\n}\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Whether the current platform is little-endian. */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.\n// prettier-ignore\nfunction asciiToBase16(ch) {\n return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48\n : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)\n : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)\n : undefined;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi)); // parse first char, multiply it by 16\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\n}\n/**\n * Yields to the host task scheduler so timers, I/O, and rendering can make progress.\n * Uses the Web Scheduling API when available or `setTimeout` as a cross-platform fallback.\n * Host-task yields are much slower than microtasks (roughly 1ms with the timer fallback), so\n * async loops should use `asyncTick >= 10` to amortize scheduling overhead to about 10% while\n * still allowing other event-loop work to proceed.\n * @param onReject - optional cleanup invoked only if the host yield fails\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport function nextTick(onReject) {\n const host = globalThis;\n if (typeof host.scheduler?.yield === 'function') {\n const promise = host.scheduler.yield();\n // Keep the original scheduler rejection; this handler exists only for cleanup.\n if (onReject)\n promise.catch(onReject);\n return promise;\n }\n return new Promise((resolve) => host.setTimeout(resolve, 0));\n}\n/**\n * Returns control to the host event loop every `tick` milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @param onReject - optional cleanup invoked only if a host yield fails\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(iters, tick, cb, onReject) {\n anumber(iters, 'iters');\n anumber(tick, 'tick');\n if (typeof cb !== 'function')\n throw new TypeError('callback must be a function');\n // Callback is synchronous by contract; asyncLoop only yields between sync work windows.\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick(onReject);\n // Track only synchronous work time; scheduler delay after yielding is outside our budget.\n ts = Date.now();\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new TypeError('string expected');\n const encoded = new TextEncoder().encode(str);\n try {\n // Copy into the current realm for Firefox extension contexts. Callers that own the returned\n // buffer can then wipe it independently of TextEncoder's temporary result.\n return new Uint8Array(encoded); // https://bugzil.la/1681809\n }\n finally {\n clean(encoded);\n }\n}\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n if (typeof data === 'string')\n return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/**\n * Validates declared required and optional field types on a plain object.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `abytes()`, `abool()`, or `anumber()` instead.\n * @param object - object to validate\n * @param fields - map of required field names to expected types\n * @param optFields - map of optional field names to expected types\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate required and optional option fields.\n * ```ts\n * validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' });\n * ```\n */\nexport const validateObject = (object, fields = {}, optFields = {}, title = 'object') => {\n aobject(object, title);\n aobject(fields, 'fields');\n aobject(optFields, 'optFields');\n function checkField(fieldName, expectedType, isOpt) {\n const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n // Config fields must be explicit own properties. Optional inherited values are rejected too\n // because callers keep reading the same options object after validation.\n const val = object[fieldName];\n // Runtime objects such as Field instances intentionally satisfy required method slots\n // via their shared prototype.\n if (!Object.hasOwn(object, fieldName) &&\n (isOpt ? val !== undefined : expectedType !== 'function')) {\n throw new TypeError(`${label} is invalid: expected own property`);\n }\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @param title - label included in thrown override errors\n * @returns Fresh merged option object with a null prototype.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(defaults, opts, title = 'opts') {\n aopts(defaults, 'defaults');\n if (opts !== undefined)\n aopts(opts, title);\n // Callers read optional fields directly, so omitted values must not fall through to ambient\n // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).\n const merged = Object.assign(Object.create(null), defaults, opts);\n return merged;\n}\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher(hashCons, info = {}) {\n if (typeof hashCons !== 'function')\n throw new TypeError('\"hashCons\" expected function, got type=' + typeof hashCons);\n info = checkOpts({}, info, 'info');\n const hashC = (msg, opts) => hashCons(opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 §10.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix) => ({\n // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n // Larger suffix values would need base-128 OID encoding and a different length byte.\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { setU64FromNum } from \"./_u64.js\";\nimport { abytes, aexists, aoutput, createView } from \"./utils.js\";\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport class HashMD {\n blockLen;\n outputLen;\n canXOF = false;\n padOffset;\n isLE;\n // For partial updates less than block size\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n let processed = false;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n processed = true;\n continue;\n }\n // When the whole input is buffered in one go (common for short messages), passing `data`\n // directly avoids allocating a subarray view.\n buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n processed = true;\n }\n }\n this.length += data.length;\n // Shared schedule buffers only pick up input-derived words inside process(); if everything\n // was buffered without processing, there is nothing to zero.\n if (processed)\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message, then zero-pad the rest of the block\n buffer[pos++] = 0b10000000;\n buffer.fill(0, pos);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n buffer.fill(0);\n }\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an\n // integer below 2**53, so the split inside the helper stays exact).\n setU64FromNum(view, blockLen - 8, this.length * 8, isLE);\n this.process(view, 0);\n // The final block above is processed outside update(), so the shared message-schedule\n // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().\n this.roundClean();\n // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.\n const oview = out === buffer ? view : createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n const outLen = len / 4;\n const state = this.get();\n // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.\n if (len % 4 || outLen > state.length)\n throw new Error('invalid outputLen');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneIntoMeta(to) {\n const { buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (pos)\n to.buffer.set(buffer); // Avoid a hot modulo guard.\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */\nclass SHA2_32B extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and makes sha256 3x slower (measured).\n A = 0;\n B = 0;\n C = 0;\n D = 0;\n E = 0;\n F = 0;\n G = 0;\n H = 0;\n constructor(outputLen, IV) {\n super(64, outputLen, 8, false);\n this.A = IV[0] | 0;\n this.B = IV[1] | 0;\n this.C = IV[2] | 0;\n this.D = IV[3] | 0;\n this.E = IV[4] | 0;\n this.F = IV[5] | 0;\n this.G = IV[6] | 0;\n this.H = IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */\nexport class _SHA256 extends SHA2_32B {\n constructor() {\n super(32, SHA256_IV);\n }\n}\n/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */\nexport class _SHA224 extends SHA2_32B {\n constructor() {\n super(28, SHA224_IV);\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// SHA-384 / SHA-512 round constants from RFC 6234 §5.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */\nclass SHA2_64B extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and slows hashing down (measured on sha256).\n Ah = 0;\n Al = 0;\n Bh = 0;\n Bl = 0;\n Ch = 0;\n Cl = 0;\n Dh = 0;\n Dl = 0;\n Eh = 0;\n El = 0;\n Fh = 0;\n Fl = 0;\n Gh = 0;\n Gl = 0;\n Hh = 0;\n Hl = 0;\n constructor(outputLen, IV) {\n super(128, outputLen, 16, false);\n this.Ah = IV[0] | 0;\n this.Al = IV[1] | 0;\n this.Bh = IV[2] | 0;\n this.Bl = IV[3] | 0;\n this.Ch = IV[4] | 0;\n this.Cl = IV[5] | 0;\n this.Dh = IV[6] | 0;\n this.Dl = IV[7] | 0;\n this.Eh = IV[8] | 0;\n this.El = IV[9] | 0;\n this.Fh = IV[10] | 0;\n this.Fl = IV[11] | 0;\n this.Gh = IV[12] | 0;\n this.Gl = IV[13] | 0;\n this.Hh = IV[14] | 0;\n this.Hl = IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA512 extends SHA2_64B {\n constructor() {\n super(64, SHA512_IV);\n }\n}\n/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA384 extends SHA2_64B {\n constructor() {\n super(48, SHA384_IV);\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B {\n constructor() {\n super(28, T224_IV);\n }\n}\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B {\n constructor() {\n super(32, T256_IV);\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n","/** BackupController error categories — never carry file contents, digests or secrets. */\nexport type BackupErrorCategory = \"cloud\" | \"conflict\" | \"unavailable\";\n\nexport class BackupControllerError extends Error {\n readonly category: BackupErrorCategory;\n\n constructor(category: BackupErrorCategory, message: string) {\n super(message);\n this.name = \"BackupControllerError\";\n this.category = category;\n }\n}\n","/**\n * The backup reconcile loop (design/backup.mdx \"同步\"): keeps the cloud file\n * `qntx-wallet-backup-<id>.json` in step with the vault. Single-flight — a trigger during a run\n * schedules exactly one rerun; `lock()` bumps a generation so a stale run never writes state, store\n * or cloud after that point.\n *\n * Security shape: the engine only ever moves ciphertext. The BEK stays in the enclave; the local\n * record is a digest/coverage baseline, not a key.\n */\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, utf8ToBytes } from \"@noble/hashes/utils.js\";\n\nimport type {\n Wallet,\n BackupHeader,\n BackupInfo,\n WalletInfo,\n WalletSnapshot,\n UnlockFactor,\n InitialFactor,\n} from \"@qntx/wallet\";\nimport { parseBackupHeader } from \"@qntx/wallet\";\n\nimport { Controller } from \"../controller.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport type { EngineStore } from \"../store/port.ts\";\nimport { BackupControllerError } from \"./errors.ts\";\nimport type { BackupErrorCategory } from \"./errors.ts\";\nimport type { CloudStore } from \"./port.ts\";\n\nexport type BackupControllerState = {\n readonly status: \"locked\" | \"unavailable\" | \"off\" | \"syncing\" | \"synced\" | \"conflict\" | \"error\";\n /** The retained backup key's public summary from the wallet snapshot. */\n // oxlint-disable-next-line typescript/no-restricted-types -- the snapshot contract is `null`\n readonly backup: BackupInfo | null;\n readonly uploadedAt: number | undefined;\n readonly unprotected: {\n readonly walletIds: ReadonlyArray<string>;\n readonly nostrKeyIds: ReadonlyArray<string>;\n };\n readonly error: BackupErrorCategory | undefined;\n};\n\n/** The EngineStore `backup/state` record — a baseline, never a key. */\ntype BackupRecord = {\n readonly id: string;\n readonly digest: string | undefined;\n readonly uploadedAt: number | undefined;\n readonly walletIds: ReadonlyArray<string>;\n readonly nostrKeyIds: ReadonlyArray<string>;\n};\n\nconst COLLECTION = \"backup\";\nconst RECORD_KEY = \"state\";\nconst FILE_PREFIX = \"qntx-wallet-backup-\";\nconst FILE_SUFFIX = \".json\";\n\nfunction fileName(id: string): string {\n return `${FILE_PREFIX}${id}${FILE_SUFFIX}`;\n}\n\nfunction digestOf(text: string): string {\n return bytesToHex(sha256(utf8ToBytes(text)));\n}\n\nfunction sorted(values: Iterable<string>): ReadonlyArray<string> {\n return [...values].sort();\n}\n\nfunction sameSet(a: ReadonlyArray<string>, b: ReadonlyArray<string>): boolean {\n return a.length === b.length && a.every((v, i) => v === b[i]);\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null;\n\nconst isStringArray = (v: unknown): v is string[] =>\n Array.isArray(v) && v.every((e) => typeof e === \"string\");\n\n/** Strict record validation — anything malformed reads as absent (and is logged). */\nfunction parseRecord(bytes: Uint8Array | undefined): BackupRecord | undefined {\n if (bytes === undefined) {\n return undefined;\n }\n try {\n const value: unknown = JSON.parse(new TextDecoder().decode(bytes));\n if (!isObject(value)) {\n return undefined;\n }\n const o = value;\n const { id } = o;\n const { digest } = o;\n const { uploadedAt } = o;\n const { walletIds } = o;\n const { nostrKeyIds } = o;\n if (typeof id !== \"string\" || !/^[0-9a-f]{32}$/.test(id)) {\n return undefined;\n }\n if (digest !== undefined && (typeof digest !== \"string\" || !/^[0-9a-f]{64}$/.test(digest))) {\n return undefined;\n }\n if (\n uploadedAt !== undefined &&\n (typeof uploadedAt !== \"number\" || !Number.isSafeInteger(uploadedAt))\n ) {\n return undefined;\n }\n if (!isStringArray(walletIds) || !isStringArray(nostrKeyIds)) {\n return undefined;\n }\n return { id, digest, uploadedAt, walletIds, nostrKeyIds };\n } catch {\n return undefined;\n }\n}\n\nexport type BackupControllerOptions = {\n readonly wallet: Wallet;\n readonly cloud: CloudStore | undefined;\n readonly now: () => number;\n readonly logger: EngineLogger;\n};\n\nexport class BackupController extends Controller<BackupControllerState> {\n private readonly wallet: Wallet;\n private readonly cloud: CloudStore | undefined;\n private readonly now: () => number;\n private readonly logger: EngineLogger;\n\n private engineStore: EngineStore | undefined;\n private generation = 0;\n private current: Promise<void> | undefined;\n private rerun = false;\n /** Set by restore() before the store opens — written as a record on the first reconcile. */\n private pendingAdoption: { readonly id: string; readonly digest: string } | undefined;\n\n constructor(options: BackupControllerOptions) {\n super({ name: \"backup\", defaultState: () => defaultState() });\n this.wallet = options.wallet;\n this.cloud = options.cloud;\n this.now = options.now;\n this.logger = options.logger;\n }\n\n async init(): Promise<void> {\n await Promise.resolve();\n }\n\n async destroy(): Promise<void> {\n this.generation += 1;\n await Promise.resolve();\n }\n\n /** The engine hands over the store on unlock and takes it back on lock. */\n setStore(store: EngineStore | undefined): void {\n this.engineStore = store;\n }\n\n /** Bumps the generation: an in-flight reconcile writes nothing after this point. */\n lock(): void {\n this.generation += 1;\n this.engineStore = undefined;\n this.update(() => defaultState());\n }\n\n trigger(): void {\n void this.triggerAsync();\n }\n\n private async triggerAsync(): Promise<void> {\n try {\n await this.reconcile();\n } catch (error) {\n this.logger.warn(\"backup reconcile trigger failed\", error);\n }\n }\n\n /** Explicit sync — awaits the run so callers see its outcome. */\n async sync(): Promise<void> {\n await this.reconcile();\n }\n\n async enable(options: {\n readonly verify: UnlockFactor;\n readonly factors: ReadonlyArray<UnlockFactor>;\n }): Promise<void> {\n // Check before the ceremony: the user must not verify and retain a BEK when there is\n // nowhere to upload it.\n if (this.cloud === undefined || !(await this.cloud.available())) {\n throw new BackupControllerError(\"unavailable\", \"the cloud store is unavailable\");\n }\n await this.wallet.backup.enable(options);\n await this.reconcileOrThrow();\n }\n\n async disable(): Promise<void> {\n await this.wallet.backup.disable();\n await this.reconcileOrThrow();\n }\n\n /** Files under our prefix with a parseable header. */\n async list(): Promise<ReadonlyArray<{ readonly name: string; readonly header: BackupHeader }>> {\n if (this.cloud === undefined) {\n return [];\n }\n const all = await this.cloud.list();\n const names = all.filter((n) => n.startsWith(FILE_PREFIX) && n.endsWith(FILE_SUFFIX));\n const { cloud } = this;\n const texts = await Promise.all(names.map(async (name) => cloud.read(name)));\n const out: Array<{ name: string; header: BackupHeader }> = [];\n for (const [index, name] of names.entries()) {\n const text = texts[index];\n if (text === undefined) {\n continue;\n }\n try {\n out.push({ name, header: parseBackupHeader(text) });\n } catch {\n this.logger.warn(\"backup file failed to parse\", new Error(name));\n }\n }\n return out;\n }\n\n async restore(options: {\n readonly name: string;\n readonly backupFactor: UnlockFactor;\n readonly factor?: InitialFactor;\n }): Promise<ReadonlyArray<WalletInfo>> {\n if (this.cloud === undefined) {\n throw new BackupControllerError(\"cloud\", \"no cloud store configured\");\n }\n const text = await this.cloud.read(options.name);\n if (text === undefined) {\n throw new BackupControllerError(\"cloud\", \"backup file not found\");\n }\n const id = idFromName(options.name);\n if (id === undefined) {\n throw new BackupControllerError(\"cloud\", \"unrecognized backup file name\");\n }\n const wasUninitialized = this.wallet.getSnapshot().vault === \"uninitialized\";\n if (wasUninitialized) {\n // Set before the kernel restore: the commit's status event can already trigger the\n // first reconcile once the engine store opens.\n this.pendingAdoption = { id, digest: digestOf(text) };\n }\n let wallets: ReadonlyArray<WalletInfo>;\n try {\n wallets = await this.wallet.backup.restore({\n envelope: text,\n backupFactor: options.backupFactor,\n ...(options.factor === undefined ? {} : { factor: options.factor }),\n });\n } catch (error) {\n this.pendingAdoption = undefined;\n throw error;\n }\n const { backup } = this.wallet.getSnapshot();\n if (!wasUninitialized && backup !== null && backup.id === id) {\n // Own-lineage merge: baseline to this file's digest, empty coverage forces the next\n // sync to upload the merged superset.\n const previous = await this.readRecord();\n await this.writeRecord({\n id,\n digest: digestOf(text),\n uploadedAt: previous?.uploadedAt,\n walletIds: [],\n nostrKeyIds: [],\n });\n }\n // Converge now — the commit's snapshot trigger may have run before the baseline landed.\n // Restore already succeeded, so a failed reconcile only leaves its status behind.\n try {\n await this.reconcile();\n } catch {\n /* state carries the outcome */\n }\n return wallets;\n }\n\n private async reconcileOrThrow(): Promise<void> {\n await this.reconcile();\n const { status, error } = this.getState();\n if (status === \"error\" || status === \"conflict\" || status === \"unavailable\") {\n throw new BackupControllerError(error ?? \"cloud\", `backup sync failed: ${status}`);\n }\n }\n\n private async readRecord(): Promise<BackupRecord | undefined> {\n const bytes = await this.engineStore?.collection(COLLECTION).get(RECORD_KEY);\n const record = parseRecord(bytes);\n if (bytes !== undefined && record === undefined) {\n this.logger.warn(\"backup record failed to parse — treating as absent\", new Error(COLLECTION));\n }\n return record;\n }\n\n private async writeRecord(record: BackupRecord): Promise<void> {\n await this.engineStore\n ?.collection(COLLECTION)\n .put(RECORD_KEY, new TextEncoder().encode(JSON.stringify(record)));\n }\n\n private async deleteRecord(): Promise<void> {\n await this.engineStore?.collection(COLLECTION).delete(RECORD_KEY);\n }\n\n private snapshot(): WalletSnapshot {\n return this.wallet.getSnapshot();\n }\n\n private unprotected(snapshot: WalletSnapshot, record: BackupRecord | undefined) {\n const covered =\n snapshot.backup !== null &&\n record !== undefined &&\n record.id === snapshot.backup.id &&\n record.digest !== undefined;\n const wallets = snapshot.wallets.filter((w) => w.backup !== \"mnemonic\");\n const keys = snapshot.nostr.keys.filter(\n (k) => k.ref.kind === \"standalone\" && k.backedUp === false,\n );\n const walletIds = wallets\n .map((w) => w.walletId)\n .filter((id) => !covered || !record.walletIds.includes(id));\n const nostrKeyIds = keys\n .map((k) => k.publicKey)\n .filter((id) => !covered || !record.nostrKeyIds.includes(id));\n return { walletIds: sorted(walletIds), nostrKeyIds: sorted(nostrKeyIds) };\n }\n\n private coverage(snapshot: WalletSnapshot): {\n readonly walletIds: ReadonlyArray<string>;\n readonly nostrKeyIds: ReadonlyArray<string>;\n } {\n return {\n walletIds: sorted(snapshot.wallets.map((w) => w.walletId)),\n nostrKeyIds: sorted(\n snapshot.nostr.keys.filter((k) => k.ref.kind === \"standalone\").map((k) => k.publicKey),\n ),\n };\n }\n\n private setStatus(\n generation: number,\n status: BackupControllerState[\"status\"],\n error?: BackupErrorCategory,\n record?: BackupRecord,\n ): void {\n if (generation !== this.generation) {\n return;\n }\n const snapshot = this.snapshot();\n this.update((state) => ({\n ...state,\n status,\n backup: snapshot.backup,\n uploadedAt: record?.uploadedAt,\n error,\n unprotected: this.unprotected(snapshot, record),\n }));\n }\n\n /**\n * Single-flight: a trigger during a run flags exactly one rerun inside the same promise, so\n * `sync()`/`enable()` await real convergence instead of a mid-run snapshot.\n */\n private async reconcile(): Promise<void> {\n if (this.current !== undefined) {\n this.rerun = true;\n return this.current;\n }\n this.current = (async () => {\n try {\n do {\n this.rerun = false;\n // The generation is read per pass: a lock invalidates the current pass, and a\n // trigger flagged under it still earns a fresh pass after unlock.\n // oxlint-disable-next-line eslint/no-await-in-loop -- passes must serialize: one rerun flag, one pass at a time\n await this.pass(this.generation);\n } while (this.rerun);\n } finally {\n this.current = undefined;\n }\n })();\n return this.current;\n }\n\n private async pass(generation: number): Promise<void> {\n const snapshot = this.snapshot();\n if (snapshot.vault !== \"unlocked\" || this.engineStore === undefined) {\n return;\n }\n let record = await this.readRecord();\n if (this.cloud === undefined || !(await this.cloud.available())) {\n this.setStatus(generation, \"unavailable\", undefined, record);\n return;\n }\n if (generation !== this.generation) {\n return;\n }\n\n // Pending adoption lands once — and only when the vault's backup key is the file's key.\n const adoption = this.pendingAdoption;\n if (adoption !== undefined) {\n this.pendingAdoption = undefined;\n if (snapshot.backup?.id === adoption.id) {\n record = {\n id: adoption.id,\n digest: adoption.digest,\n uploadedAt: undefined,\n walletIds: [],\n nostrKeyIds: [],\n };\n if (generation !== this.generation) {\n return;\n }\n await this.writeRecord(record);\n } else {\n this.logger.warn(\n \"backup adoption dropped — the vault's backup key is not the file's\",\n new Error(adoption.id),\n );\n }\n }\n\n const { backup } = snapshot;\n if (backup === null) {\n // Backup off in the vault: remove our file + record, then report off.\n if (record !== undefined) {\n try {\n if (generation !== this.generation) {\n return;\n }\n await this.cloud.delete(fileName(record.id));\n if (generation !== this.generation) {\n return;\n }\n await this.deleteRecord();\n } catch (error) {\n this.logger.warn(\"backup cloud delete failed — retrying next reconcile\", error);\n this.setStatus(generation, \"error\", \"cloud\", record);\n return;\n }\n }\n this.setStatus(generation, \"off\", undefined, undefined);\n return;\n }\n\n const baseline = record !== undefined && record.id === backup.id ? record.digest : undefined;\n const cov = this.coverage(snapshot);\n if (\n baseline !== undefined &&\n record !== undefined &&\n sameSet(cov.walletIds, record.walletIds) &&\n sameSet(cov.nostrKeyIds, record.nostrKeyIds)\n ) {\n this.setStatus(generation, \"synced\", undefined, record);\n return;\n }\n\n this.setStatus(generation, \"syncing\", undefined, record);\n try {\n const envelope = await this.wallet.backup.update();\n if (generation !== this.generation) {\n return;\n }\n const name = fileName(backup.id);\n const remote = await this.cloud.read(name);\n const digest = digestOf(envelope);\n if (remote !== undefined && digestOf(remote) !== baseline) {\n this.setStatus(generation, \"conflict\", \"conflict\", record);\n return;\n }\n if (generation !== this.generation) {\n return;\n }\n await this.cloud.write(name, envelope);\n const readBack = await this.cloud.read(name);\n if (readBack !== envelope) {\n this.setStatus(generation, \"error\", \"cloud\", record);\n return;\n }\n const next: BackupRecord = {\n id: backup.id,\n digest,\n uploadedAt: this.now(),\n walletIds: cov.walletIds,\n nostrKeyIds: cov.nostrKeyIds,\n };\n if (generation !== this.generation) {\n return;\n }\n await this.writeRecord(next);\n if (record !== undefined && record.id !== backup.id) {\n try {\n if (generation !== this.generation) {\n return;\n }\n await this.cloud.delete(fileName(record.id));\n } catch (error) {\n this.logger.warn(\"stale backup file delete failed\", error);\n }\n }\n this.setStatus(generation, \"synced\", undefined, next);\n } catch (error) {\n if (generation !== this.generation) {\n return;\n }\n this.logger.warn(\"backup reconcile failed\", error);\n this.setStatus(generation, \"error\", \"cloud\", record);\n }\n }\n}\n\nfunction defaultState(): BackupControllerState {\n return {\n status: \"locked\",\n backup: null,\n uploadedAt: undefined,\n unprotected: { walletIds: [], nostrKeyIds: [] },\n error: undefined,\n };\n}\n\nfunction idFromName(name: string): string | undefined {\n if (!name.startsWith(FILE_PREFIX) || !name.endsWith(FILE_SUFFIX)) {\n return undefined;\n }\n const id = name.slice(FILE_PREFIX.length, name.length - FILE_SUFFIX.length);\n return /^[0-9a-f]{32}$/.test(id) ? id : undefined;\n}\n","/**\n * Wallet metadata document — the plaintext exchanged over kind-30078 events between this wallet's\n * own devices. One document per wallet; entry-level last-writer-wins on `updatedAt`.\n */\n\nexport type MetaDocWallet = {\n readonly name?: string;\n readonly updatedAt: number;\n};\n\nexport type MetaDocGroup = {\n readonly index: number;\n readonly name?: string;\n readonly hidden: boolean;\n readonly boundPubkey?: string;\n readonly updatedAt: number;\n};\n\nexport type MetaDoc = {\n readonly v: 1;\n readonly wallet: MetaDocWallet;\n readonly groups: ReadonlyArray<MetaDocGroup>;\n};\n\nexport const META_DOC_MAX_BYTES = 65536;\n\nconst NAME_MAX = 24;\nconst PUBKEY_RE = /^[0-9a-f]{64}$/;\nconst KNOWN_DOC_KEYS = new Set([\"v\", \"wallet\", \"groups\"]);\nconst KNOWN_WALLET_KEYS = new Set([\"name\", \"updatedAt\"]);\nconst KNOWN_GROUP_KEYS = new Set([\"index\", \"name\", \"hidden\", \"boundPubkey\", \"updatedAt\"]);\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\nconst isNonNegativeInt = (v: unknown): v is number =>\n typeof v === \"number\" && Number.isSafeInteger(v) && v >= 0;\n\nconst validName = (v: unknown): boolean =>\n v === undefined || (typeof v === \"string\" && v.trim().length > 0 && v.trim().length <= NAME_MAX);\n\nconst trimmedName = (v: unknown): string | undefined =>\n typeof v === \"string\" ? v.trim() : undefined;\n\n/** Strict decode — any malformed shape, unknown key or duplicate index returns `undefined`. */\nexport function decodeMetaDoc(value: unknown): MetaDoc | undefined {\n if (!isObject(value)) {\n return undefined;\n }\n for (const k of Object.keys(value)) {\n if (!KNOWN_DOC_KEYS.has(k)) {\n return undefined;\n }\n }\n if (value[\"v\"] !== 1) {\n return undefined;\n }\n const { wallet } = value;\n if (!isObject(wallet)) {\n return undefined;\n }\n for (const k of Object.keys(wallet)) {\n if (!KNOWN_WALLET_KEYS.has(k)) {\n return undefined;\n }\n }\n if (!validName(wallet[\"name\"]) || !isNonNegativeInt(wallet[\"updatedAt\"])) {\n return undefined;\n }\n const { groups } = value;\n if (!Array.isArray(groups)) {\n return undefined;\n }\n const seen = new Set<number>();\n const out: MetaDocGroup[] = [];\n for (const item of groups) {\n if (!isObject(item)) {\n return undefined;\n }\n for (const k of Object.keys(item)) {\n if (!KNOWN_GROUP_KEYS.has(k)) {\n return undefined;\n }\n }\n const { index } = item;\n if (!isNonNegativeInt(index) || seen.has(index)) {\n return undefined;\n }\n seen.add(index);\n if (!validName(item[\"name\"]) || (item[\"hidden\"] !== true && item[\"hidden\"] !== false)) {\n return undefined;\n }\n const { boundPubkey } = item;\n if (\n boundPubkey !== undefined &&\n (typeof boundPubkey !== \"string\" || !PUBKEY_RE.test(boundPubkey))\n ) {\n return undefined;\n }\n if (!isNonNegativeInt(item[\"updatedAt\"])) {\n return undefined;\n }\n const gName = trimmedName(item[\"name\"]);\n out.push({\n index,\n hidden: item[\"hidden\"],\n updatedAt: item[\"updatedAt\"],\n ...(gName === undefined ? {} : { name: gName }),\n ...(boundPubkey === undefined ? {} : { boundPubkey }),\n });\n }\n out.sort((a, b) => a.index - b.index);\n const name = trimmedName(wallet[\"name\"]);\n return {\n v: 1,\n wallet: {\n updatedAt: wallet[\"updatedAt\"],\n ...(name === undefined ? {} : { name }),\n },\n groups: out,\n };\n}\n\n/** UTF-8 JSON — `undefined` when the document exceeds the 64 KB limit. */\nexport function encodeMetaDoc(doc: MetaDoc): Uint8Array | undefined {\n const bytes = new TextEncoder().encode(JSON.stringify(doc));\n return bytes.byteLength <= META_DOC_MAX_BYTES ? bytes : undefined;\n}\n\nexport function decodeMetaDocBytes(bytes: Uint8Array): MetaDoc | undefined {\n if (bytes.byteLength > META_DOC_MAX_BYTES) {\n return undefined;\n }\n try {\n return decodeMetaDoc(JSON.parse(new TextDecoder().decode(bytes)));\n } catch {\n return undefined;\n }\n}\n","/** Meta-sync error categories — messages never carry event or document content. */\nexport type MetaSyncErrorCategory = \"network\" | \"internal\" | \"unsupported\" | \"corrupt\";\n\nexport class MetaSyncError extends Error {\n readonly category: MetaSyncErrorCategory;\n\n constructor(category: MetaSyncErrorCategory, message: string, cause?: unknown) {\n super(message, { cause });\n this.name = \"MetaSyncError\";\n this.category = category;\n }\n}\n","import type { Event, Filter } from \"@qntx/nostr\";\nimport { verifyEvent } from \"@qntx/nostr\";\nimport type { Wallet } from \"@qntx/wallet\";\nimport type { NostrKeyRef, WalletSigner } from \"@qntx/wallet/nostr\";\n\nimport type { AccountTreeController } from \"../accounts/controller.ts\";\nimport { Controller } from \"../controller.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport { decodeMetaDocBytes, encodeMetaDoc } from \"./doc.ts\";\nimport type { MetaSyncErrorCategory } from \"./errors.ts\";\nimport { MetaSyncError } from \"./errors.ts\";\n\nexport const META_SYNC_KIND = 30078;\nconst PUBLISH_DEBOUNCE_MS = 2000;\n\nexport type MetaSyncRelayPort = {\n readonly fetch: (filter: Filter) => Promise<ReadonlyArray<Event>>;\n readonly publish: (event: Event) => Promise<void>;\n};\n\nexport type MetaSyncConfig = {\n /** The `d` tag that names this wallet's metadata document. */\n readonly tag: string;\n readonly relays: MetaSyncRelayPort;\n};\n\nexport type MetaSyncWalletStatus = {\n readonly status: \"unavailable\" | \"syncing\" | \"synced\" | \"error\";\n readonly error?: MetaSyncErrorCategory;\n};\n\nexport type MetaSyncState = {\n readonly wallets: Readonly<Record<string, MetaSyncWalletStatus>>;\n};\n\nexport type MetaSyncControllerOptions = {\n readonly wallet: Wallet;\n readonly accounts: AccountTreeController;\n /** `nostr(wallet)` — the signer is requested per wallet for its group-0 derived key. */\n readonly nostr: { readonly signer: (ref: NostrKeyRef) => WalletSigner };\n readonly metaSync: MetaSyncConfig | undefined;\n readonly logger: EngineLogger;\n readonly now: () => number;\n};\n\n/**\n * Wallet-metadata sync over kind-30078 addressable events: one NIP-44-encrypted document per\n * wallet, authored by its group-0 derived key. Pull always precedes publish in an unlock session —\n * replaceable events would otherwise let a stale local tree overwrite a newer remote document.\n * Debounced publishes are per wallet; a generation counter cancels in-flight write-backs on lock.\n */\nexport class MetaSyncController extends Controller<MetaSyncState> {\n private readonly options: MetaSyncControllerOptions;\n private generation = 0;\n private readonly pulled = new Set<string>();\n private readonly lastRemoteCreatedAt = new Map<string, number>();\n private readonly lastExported = new Map<string, string>();\n private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();\n private readonly inflight = new Set<string>();\n private accountsUnsubscribe: (() => void) | undefined;\n\n constructor(options: MetaSyncControllerOptions) {\n super({ name: \"metaSync\", defaultState: () => ({ wallets: {} }) });\n this.options = options;\n }\n\n /** Unlocked: pull every wallet whose group-0 identity exists, then watch the tree. */\n async init(): Promise<void> {\n const gen = ++this.generation;\n this.accountsUnsubscribe = this.options.accounts.store.subscribe(() => {\n this.onTreeChange();\n });\n // pullAll covers every snapshot wallet at init — reconcile() is for additions later.\n await this.pullAll(gen);\n }\n\n async destroy(): Promise<void> {\n await this.lock();\n }\n\n /** Locked: cancel debounces and in-flight write-backs, forget the pull/publish bookkeeping. */\n async lock(): Promise<void> {\n this.generation += 1;\n this.accountsUnsubscribe?.();\n this.accountsUnsubscribe = undefined;\n for (const timer of this.timers.values()) {\n clearTimeout(timer);\n }\n this.timers.clear();\n this.pulled.clear();\n this.lastRemoteCreatedAt.clear();\n this.lastExported.clear();\n this.inflight.clear();\n this.update(() => ({ wallets: {} }));\n await Promise.resolve();\n }\n\n /** Snapshot changed while unlocked: pull newly-seen wallets, drop removed ones. */\n reconcile(): void {\n if (this.options.metaSync === undefined) {\n return;\n }\n const snap = this.options.wallet.getSnapshot();\n const live = new Set(snap.wallets.map((w) => w.walletId));\n const gen = this.generation;\n for (const w of snap.wallets) {\n if (this.getState().wallets[w.walletId] === undefined) {\n void this.pullOne(w.walletId, gen);\n }\n }\n this.update((s) => {\n const wallets = Object.fromEntries(\n Object.entries(s.wallets).filter(([walletId]) => live.has(walletId)),\n );\n return { ...s, wallets };\n });\n }\n\n /** Manual re-pull of every wallet that can sync. */\n async sync(): Promise<void> {\n await this.pullAll(this.generation);\n }\n\n private async pullAll(gen: number): Promise<void> {\n const snap = this.options.wallet.getSnapshot();\n await Promise.all(snap.wallets.map(async (w) => this.pullOne(w.walletId, gen)));\n }\n\n private async pubkeyFor(signer: WalletSigner): Promise<string> {\n return signer.getPublicKey();\n }\n\n private signerFor(walletId: string): WalletSigner | undefined {\n const snap = this.options.wallet.getSnapshot();\n const ref = { kind: \"derived\" as const, walletId, groupIndex: 0 };\n const hasKey = snap.nostr.keys.some(\n (k) => k.ref.kind === \"derived\" && k.ref.walletId === walletId && k.ref.groupIndex === 0,\n );\n if (!hasKey) {\n return undefined;\n }\n return this.options.nostr.signer(ref);\n }\n\n private setStatus(walletId: string, status: MetaSyncWalletStatus): void {\n this.update((s) => ({ ...s, wallets: { ...s.wallets, [walletId]: status } }));\n }\n\n private async pullOne(walletId: string, gen: number): Promise<void> {\n const config = this.options.metaSync;\n if (config === undefined || this.inflight.has(walletId)) {\n return;\n }\n const signer = this.signerFor(walletId);\n if (signer === undefined) {\n if (gen === this.generation) {\n this.setStatus(walletId, { status: \"unavailable\" });\n }\n return;\n }\n this.inflight.add(walletId);\n this.setStatus(walletId, { status: \"syncing\" });\n try {\n const pubkey = await this.pubkeyFor(signer);\n const events = await config.relays.fetch(this.filterFor(pubkey, config.tag));\n let remote: Event | undefined;\n let remoteSkipped = 0;\n for (const e of events) {\n if (!this.acceptableEvent(e, pubkey, config.tag)) {\n remoteSkipped += 1;\n continue;\n }\n if (remote === undefined || e.created_at > remote.created_at) {\n remote = e;\n }\n }\n if (remote === undefined) {\n // No doc on the relay: publish only when the local tree holds a real edit\n // (updatedAt > 0) — a fresh device must not replace nothing with empty defaults.\n const local = this.options.accounts.exportMeta(walletId);\n const hasEdits = local.wallet.updatedAt > 0 || local.groups.some((g) => g.updatedAt > 0);\n if (gen !== this.generation) {\n return;\n }\n this.pulled.add(walletId);\n this.rememberExport(walletId);\n this.setStatus(walletId, { status: \"synced\" });\n if (hasEdits) {\n await this.publishNow(walletId, gen);\n }\n } else {\n // A verified event we cannot read must never be overwritten — a newer app version\n // (e.g. v: 2) is the most likely cause; decode failure is data corruption.\n const decrypt = signer.nip44Decrypt;\n const plaintext =\n decrypt === undefined\n ? undefined\n : await decrypt.call(signer, pubkey, remote.content).catch(() => undefined);\n const doc =\n plaintext === undefined\n ? undefined\n : decodeMetaDocBytes(new TextEncoder().encode(plaintext));\n if (doc === undefined) {\n if (gen !== this.generation) {\n return;\n }\n const error: MetaSyncErrorCategory =\n plaintext !== undefined && isUnsupportedDoc(plaintext) ? \"unsupported\" : \"corrupt\";\n this.setStatus(walletId, { status: \"error\", error });\n this.options.logger.warn(`meta sync: unreadable remote doc (${error})`);\n return; // not in `pulled` — debounced publishes stay blocked too\n }\n const merge = this.options.accounts.mergeMeta(walletId, doc);\n if (gen !== this.generation) {\n return;\n }\n this.lastRemoteCreatedAt.set(walletId, remote.created_at);\n this.pulled.add(walletId);\n this.rememberExport(walletId);\n this.setStatus(walletId, { status: \"synced\" });\n if (merge.localNewer) {\n await this.publishNow(walletId, gen);\n }\n }\n if (remoteSkipped > 0) {\n this.options.logger.warn(`meta sync: ignored ${remoteSkipped} invalid remote events`);\n }\n } catch (error) {\n if (gen === this.generation) {\n this.setStatus(walletId, { status: \"error\", error: categorizeSync(error) });\n this.options.logger.warn(\"meta sync pull failed\", error);\n }\n } finally {\n this.inflight.delete(walletId);\n }\n }\n\n private filterFor(pubkey: string, tag: string): Filter {\n return { kinds: [META_SYNC_KIND], authors: [pubkey], \"#d\": [tag] };\n }\n\n private acceptableEvent(e: Event, pubkey: string, tag: string): boolean {\n if (e.kind !== META_SYNC_KIND || e.pubkey !== pubkey || !verifyEvent(e)) {\n return false;\n }\n const dTags = e.tags.filter((t) => t[0] === \"d\");\n return dTags.length === 1 && dTags[0]?.[1] === tag;\n }\n\n /** Snapshot the wallet's exported doc — the debounce publishes only on a real change. */\n private rememberExport(walletId: string): void {\n try {\n const doc = this.options.accounts.exportMeta(walletId);\n this.lastExported.set(walletId, JSON.stringify(doc));\n } catch {\n // Wallet not in the tree — nothing to remember.\n }\n }\n\n private onTreeChange(): void {\n if (this.options.metaSync === undefined) {\n return;\n }\n for (const walletId of this.pulled) {\n let current: string | undefined;\n try {\n current = JSON.stringify(this.options.accounts.exportMeta(walletId));\n } catch {\n continue;\n }\n if (current === this.lastExported.get(walletId)) {\n continue;\n }\n this.lastExported.set(walletId, current);\n const existing = this.timers.get(walletId);\n if (existing !== undefined) {\n clearTimeout(existing);\n }\n const gen = this.generation;\n this.timers.set(\n walletId,\n setTimeout(() => {\n this.timers.delete(walletId);\n void this.publishNow(walletId, gen);\n }, PUBLISH_DEBOUNCE_MS),\n );\n }\n }\n\n private async publishNow(walletId: string, gen: number): Promise<void> {\n const config = this.options.metaSync;\n if (config === undefined || !this.pulled.has(walletId)) {\n return;\n }\n const signer = this.signerFor(walletId);\n if (signer === undefined) {\n this.setStatus(walletId, { status: \"unavailable\" });\n return;\n }\n try {\n const doc = this.options.accounts.exportMeta(walletId);\n const bytes = encodeMetaDoc(doc);\n if (bytes === undefined) {\n throw new MetaSyncError(\"internal\", \"meta doc exceeds 64 KB\");\n }\n const encrypt = signer.nip44Encrypt;\n if (encrypt === undefined) {\n throw new MetaSyncError(\"internal\", \"signer lacks nip44 encryption\");\n }\n const pubkey = await this.pubkeyFor(signer);\n const content = await encrypt.call(signer, pubkey, new TextDecoder().decode(bytes));\n const lastRemote = this.lastRemoteCreatedAt.get(walletId) ?? 0;\n const created_at = Math.max(Math.floor(this.options.now() / 1000), lastRemote + 1);\n const event = await signer.signEvent({\n pubkey,\n kind: META_SYNC_KIND,\n created_at,\n tags: [[\"d\", config.tag]],\n content,\n });\n if (gen !== this.generation) {\n return;\n }\n await config.relays.publish(event);\n } catch (error) {\n if (gen === this.generation) {\n this.setStatus(walletId, { status: \"error\", error: categorizeSync(error) });\n this.options.logger.warn(\"meta sync publish failed\", error);\n }\n }\n }\n}\n\nfunction categorizeSync(error: unknown): MetaSyncErrorCategory {\n return error instanceof MetaSyncError ? error.category : \"network\";\n}\n\n/** A decrypted doc that parses as JSON with a numeric `v` above 1 is a newer schema, not garbage. */\nfunction isUnsupportedDoc(plaintext: string): boolean {\n try {\n const doc: unknown = JSON.parse(plaintext);\n return (\n typeof doc === \"object\" &&\n doc !== null &&\n \"v\" in doc &&\n typeof doc.v === \"number\" &&\n doc.v > 1\n );\n } catch {\n return false;\n }\n}\n","import { bytesToHex } from \"@noble/hashes/utils.js\";\n\nimport {\n bitcoinAddressScript,\n decodeBolt11,\n decodeSparkAddress,\n parseSparkInvoice,\n} from \"@qntx/spark\";\nimport type { SparkNetwork } from \"@qntx/spark\";\nimport type { LnurlPayRequest, LnurlWithdrawRequest } from \"@qntx/spark/lnurl\";\nimport { decodeLnurl, lightningAddressUrl } from \"@qntx/spark/lnurl\";\n\nexport type PaymentOption =\n | { readonly kind: \"spark\"; readonly address: string }\n | {\n readonly kind: \"spark-invoice\";\n readonly invoice: string;\n readonly amountSats?: number;\n readonly memo?: string;\n readonly expiresAt?: number;\n }\n | {\n readonly kind: \"lightning\";\n readonly invoice: string;\n readonly amountSats?: number;\n readonly paymentHash: string;\n readonly description?: string;\n readonly expiresAt: number;\n }\n | { readonly kind: \"lnurl-pay\"; readonly request: LnurlPayRequest; readonly address?: string }\n | { readonly kind: \"lnurl-withdraw\"; readonly request: LnurlWithdrawRequest }\n | { readonly kind: \"bitcoin\"; readonly address: string };\n\nexport type PaymentRequest = {\n readonly options: ReadonlyArray<PaymentOption>;\n readonly amountSats?: number;\n readonly label?: string;\n readonly message?: string;\n};\n\nexport type PaymentParse =\n | { readonly kind: \"request\"; readonly request: PaymentRequest }\n | { readonly kind: \"lnurl\"; readonly url: string; readonly address?: string }\n | {\n readonly kind: \"unsupported\";\n readonly format:\n | \"bolt12\"\n | \"silent-payment\"\n | \"lnurl-auth\"\n | \"spark-token-invoice\"\n | \"nostr-wallet-connect\";\n }\n | {\n readonly kind: \"invalid\";\n readonly reason: \"network\" | \"expired\" | \"amount-mismatch\" | \"malformed\";\n }\n | { readonly kind: \"unrecognized\" };\n\nexport type ParseOptions = {\n readonly network: SparkNetwork;\n readonly now: number;\n};\n\n/** Invoices with less than this much life left are treated as already expired. */\nconst BOLT11_EXPIRY_GRACE_MS = 60_000;\n\ntype ParseFailure = {\n readonly kind: \"invalid\";\n readonly reason: \"network\" | \"expired\" | \"amount-mismatch\" | \"malformed\";\n};\n\nconst invalid = (reason: ParseFailure[\"reason\"]): PaymentParse => ({ kind: \"invalid\", reason });\n\n/** BTC decimal `amount` → sats. At most 8 decimal places; must fit a safe integer. */\nfunction btcAmountSats(text: string): number | undefined {\n const match = /^(\\d+)(?:\\.(\\d{1,8}))?$/.exec(text);\n if (match === null) {\n return undefined;\n }\n const [, whole] = match;\n if (whole === undefined) {\n return undefined;\n }\n const sats = BigInt(whole) * 100_000_000n + BigInt((match[2] ?? \"\").padEnd(8, \"0\") || \"0\");\n return sats <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(sats) : undefined;\n}\n\ntype Bolt11Fields = {\n readonly amountSats?: number;\n readonly paymentHash: string;\n readonly description?: string;\n readonly expiresAt: number;\n};\n\n/**\n * BOLT11 → fields, network- and expiry-checked. `undefined` = not a bolt11 string; `\"network\"` /\n * `\"expired\"` / `\"malformed\"` are the failure modes.\n */\nfunction bolt11Fields(\n text: string,\n options: ParseOptions,\n): Bolt11Fields | \"network\" | \"expired\" | \"malformed\" | undefined {\n let decoded;\n try {\n decoded = decodeBolt11(text);\n } catch {\n return undefined;\n }\n const network =\n decoded.network === \"mainnet\"\n ? \"mainnet\"\n : decoded.network === \"regtest\"\n ? \"regtest\"\n : undefined;\n if (network === undefined) {\n return \"network\";\n }\n if (network !== options.network) {\n return \"network\";\n }\n const expiresAt = (decoded.timestamp + decoded.expirySeconds) * 1000;\n if (expiresAt <= options.now + BOLT11_EXPIRY_GRACE_MS) {\n return \"expired\";\n }\n return {\n ...(decoded.amountMsat === undefined\n ? {}\n : { amountSats: Math.ceil(Number(decoded.amountMsat) / 1000) }),\n paymentHash: bytesToHex(decoded.paymentHash),\n ...(decoded.description === undefined ? {} : { description: decoded.description }),\n expiresAt,\n };\n}\n\n/** Spark address or sats/token invoice → options. `null` means not a spark input. */\nfunction sparkOptions(\n text: string,\n options: ParseOptions,\n): PaymentOption[] | \"network\" | \"expired\" | \"malformed\" | \"token\" | undefined {\n let decoded;\n try {\n decoded = decodeSparkAddress(text);\n } catch {\n return undefined;\n }\n if (decoded.network !== options.network) {\n return \"network\";\n }\n if (decoded.invoice === undefined) {\n return [{ kind: \"spark\", address: text }];\n }\n // Expiry lives in the unsigned fields — check it before validating the signature so an\n // expired invoice reports `expired` rather than `malformed`.\n if (decoded.invoice.expiresAt !== undefined && decoded.invoice.expiresAt <= options.now) {\n return \"expired\";\n }\n if (decoded.invoice.payment?.type === \"tokens\") {\n return \"token\";\n }\n let parsed;\n try {\n parsed = parseSparkInvoice(text, { network: options.network, now: options.now });\n } catch {\n return \"malformed\";\n }\n const { payment } = parsed.fields;\n return [\n {\n kind: \"spark-invoice\",\n invoice: text,\n ...(payment?.type === \"sats\" && payment.amount !== undefined\n ? { amountSats: payment.amount }\n : {}),\n ...(parsed.fields.memo === undefined ? {} : { memo: parsed.fields.memo }),\n ...(parsed.fields.expiresAt === undefined ? {} : { expiresAt: parsed.fields.expiresAt }),\n },\n ];\n}\n\n/** Does `address` decode under the other network? Used only to classify a rejection. */\nfunction decodesOnOtherNetwork(address: string, options: ParseOptions): boolean {\n try {\n bitcoinAddressScript(address, options.network === \"mainnet\" ? \"regtest\" : \"mainnet\");\n return true;\n } catch {\n return false;\n }\n}\n\n/** BIP-21 URI → request. Only the `spark=` and `lightning=` payment methods are supported. */\nfunction bip21Parse(text: string, options: ParseOptions): PaymentParse {\n const q = text.indexOf(\"?\");\n const address = text.slice(\"bitcoin:\".length, q === -1 ? undefined : q);\n const params = new Map<string, string>();\n if (q !== -1) {\n for (const pair of text.slice(q + 1).split(\"&\")) {\n const eq = pair.indexOf(\"=\");\n if (eq === -1) {\n return invalid(\"malformed\");\n }\n let key;\n let value;\n try {\n key = decodeURIComponent(pair.slice(0, eq)).toLowerCase();\n value = decodeURIComponent(pair.slice(eq + 1));\n } catch {\n return invalid(\"malformed\");\n }\n if (params.has(key)) {\n return invalid(\"malformed\");\n }\n if (key.startsWith(\"req-\") && !BIP21_KNOWN_REQ_PARAMS.has(key)) {\n return invalid(\"malformed\");\n }\n params.set(key, value);\n }\n }\n const options_: PaymentOption[] = [];\n let declaredSats: number | undefined;\n const spark = params.get(\"spark\");\n if (spark !== undefined) {\n const parsed = sparkOptions(spark, options);\n if (parsed === undefined || parsed === \"malformed\") {\n return invalid(\"malformed\");\n }\n if (parsed === \"token\") {\n return { kind: \"unsupported\", format: \"spark-token-invoice\" };\n }\n if (parsed === \"network\" || parsed === \"expired\") {\n return invalid(parsed);\n }\n options_.push(...parsed);\n const sats = parsed.find((o) => o.kind === \"spark-invoice\")?.amountSats;\n if (sats !== undefined) {\n if (declaredSats !== undefined && declaredSats !== sats) {\n return invalid(\"amount-mismatch\");\n }\n declaredSats = sats;\n }\n }\n const lightning = params.get(\"lightning\");\n if (lightning !== undefined) {\n const parsed = bolt11Fields(lightning, options);\n if (parsed === undefined || parsed === \"malformed\") {\n return invalid(\"malformed\");\n }\n if (parsed === \"network\" || parsed === \"expired\") {\n return invalid(parsed);\n }\n options_.push({\n kind: \"lightning\",\n invoice: lightning,\n ...(parsed.amountSats === undefined ? {} : { amountSats: parsed.amountSats }),\n paymentHash: parsed.paymentHash,\n ...(parsed.description === undefined ? {} : { description: parsed.description }),\n expiresAt: parsed.expiresAt,\n });\n if (parsed.amountSats !== undefined) {\n if (declaredSats !== undefined && declaredSats !== parsed.amountSats) {\n return invalid(\"amount-mismatch\");\n }\n declaredSats = parsed.amountSats;\n }\n }\n if (address.length > 0) {\n try {\n bitcoinAddressScript(address, options.network);\n } catch {\n return invalid(decodesOnOtherNetwork(address, options) ? \"network\" : \"malformed\");\n }\n options_.push({ kind: \"bitcoin\", address });\n }\n const declaredAmount = params.get(\"amount\");\n if (declaredAmount !== undefined) {\n const sats = btcAmountSats(declaredAmount);\n if (sats === undefined) {\n return invalid(\"malformed\");\n }\n if (declaredSats !== undefined && declaredSats !== sats) {\n return invalid(\"amount-mismatch\");\n }\n declaredSats = sats;\n }\n if (options_.length === 0) {\n if (params.has(\"lno\")) {\n return { kind: \"unsupported\", format: \"bolt12\" };\n }\n if (params.has(\"sp\")) {\n return { kind: \"unsupported\", format: \"silent-payment\" };\n }\n return invalid(\"malformed\");\n }\n return {\n kind: \"request\",\n request: {\n options: options_,\n ...(declaredSats === undefined ? {} : { amountSats: declaredSats }),\n ...(params.get(\"label\") === undefined ? {} : { label: params.get(\"label\") ?? \"\" }),\n ...(params.get(\"message\") === undefined ? {} : { message: params.get(\"message\") ?? \"\" }),\n },\n };\n}\n\nconst BIP21_KNOWN_REQ_PARAMS = new Set([\"req-amount\", \"req-label\", \"req-message\"]);\n\n/** `input` → PaymentParse. Never throws: every failure is a structured result. */\nexport function parsePayment(input: string, options: ParseOptions): PaymentParse {\n try {\n const text = input.trim();\n if (/^nostr\\+walletconnect:/i.test(text)) {\n return { kind: \"unsupported\", format: \"nostr-wallet-connect\" };\n }\n const stripped = text.toLowerCase().startsWith(\"lightning:\")\n ? text.slice(\"lightning:\".length)\n : text;\n if (/^bitcoin:/i.test(stripped)) {\n return bip21Parse(`bitcoin:${stripped.slice(stripped.indexOf(\":\") + 1)}`, options);\n }\n const bolt11 = bolt11Fields(stripped, options);\n if (bolt11 === \"network\" || bolt11 === \"expired\" || bolt11 === \"malformed\") {\n return invalid(bolt11);\n }\n if (bolt11 !== undefined) {\n const option: PaymentOption = {\n kind: \"lightning\",\n invoice: stripped,\n ...(bolt11.amountSats === undefined ? {} : { amountSats: bolt11.amountSats }),\n paymentHash: bolt11.paymentHash,\n ...(bolt11.description === undefined ? {} : { description: bolt11.description }),\n expiresAt: bolt11.expiresAt,\n };\n return {\n kind: \"request\",\n request: {\n options: [option],\n ...(bolt11.amountSats === undefined ? {} : { amountSats: bolt11.amountSats }),\n },\n };\n }\n const spark = sparkOptions(stripped, options);\n if (spark === \"token\") {\n return { kind: \"unsupported\", format: \"spark-token-invoice\" };\n }\n if (spark === \"network\" || spark === \"expired\" || spark === \"malformed\") {\n return invalid(spark);\n }\n if (spark !== undefined) {\n return { kind: \"request\", request: { options: spark } };\n }\n if (/^(lnurlp|lnurlw):/i.test(stripped)) {\n const rest = stripped.slice(stripped.indexOf(\"://\") + 3);\n const host = rest.split(/[/?#]/, 1)[0] ?? \"\";\n const url = `${host.toLowerCase().endsWith(\".onion\") ? \"http\" : \"https\"}://${rest}`;\n if (new URL(url).searchParams.get(\"tag\") === \"login\") {\n return { kind: \"unsupported\", format: \"lnurl-auth\" };\n }\n return { kind: \"lnurl\", url };\n }\n if (/^keyauth:/i.test(stripped)) {\n return { kind: \"unsupported\", format: \"lnurl-auth\" };\n }\n if (!stripped.includes(\":\") && stripped.includes(\"@\")) {\n return { kind: \"lnurl\", url: lightningAddressUrl(stripped), address: stripped };\n }\n // BOLT12 offer: bech32 charset, anchored — a lightning address like lnolan@x must not match.\n if (/^lno1[02-9ac-hj-np-z]+$/i.test(stripped)) {\n return { kind: \"unsupported\", format: \"bolt12\" };\n }\n try {\n const url = decodeLnurl(stripped);\n if (new URL(url).searchParams.get(\"tag\") === \"login\") {\n return { kind: \"unsupported\", format: \"lnurl-auth\" };\n }\n return { kind: \"lnurl\", url };\n } catch {\n // not a bech32 LNURL\n }\n try {\n bitcoinAddressScript(stripped, options.network);\n return { kind: \"request\", request: { options: [{ kind: \"bitcoin\", address: stripped }] } };\n } catch {\n if (decodesOnOtherNetwork(stripped, options)) {\n return invalid(\"network\");\n }\n }\n return { kind: \"unrecognized\" };\n } catch {\n return invalid(\"malformed\");\n }\n}\n","/** SparkController error categories — never carry request bytes or secrets. */\nexport type SparkErrorCategory =\n | \"network\"\n | \"approval-required\"\n | \"insufficient-funds\"\n | \"rejected\"\n | \"internal\";\n\nexport class SparkControllerError extends Error {\n readonly category: SparkErrorCategory;\n\n constructor(category: SparkErrorCategory, message: string, cause?: unknown) {\n super(message, { cause });\n this.name = \"SparkControllerError\";\n this.category = category;\n }\n}\n\n/** Maps a thrown client/kernel error into a category without leaking payloads. */\nexport function categorize(error: unknown): SparkErrorCategory {\n const name = error instanceof Error ? error.name : \"\";\n const message = error instanceof Error ? error.message : \"\";\n if (/approval|denied|rejected/i.test(message)) {\n return /required/i.test(message) ? \"approval-required\" : \"rejected\";\n }\n if (/insufficient|not enough|balance/i.test(message)) {\n return \"insufficient-funds\";\n }\n if (name === \"SparkRequestError\" || /fetch|network|timeout|unavailable|closed/i.test(message)) {\n return \"network\";\n }\n return \"internal\";\n}\n","/** Payment layer error categories — messages never carry remote or secret content. */\nexport type PaymentErrorCategory = \"invalid-input\" | \"network\" | \"rejected\";\n\nexport class PaymentError extends Error {\n readonly category: PaymentErrorCategory;\n\n constructor(category: PaymentErrorCategory, message: string, cause?: unknown) {\n super(message, { cause });\n this.name = \"PaymentError\";\n this.category = category;\n }\n}\n","import type {\n CooperativeExitResult,\n LightningInvoice,\n LightningPayment,\n SparkTransfer,\n} from \"@qntx/spark\";\nimport { requestInvoice, submitWithdraw } from \"@qntx/spark/lnurl\";\nimport type { UnlockFactor } from \"@qntx/wallet\";\nimport type { SparkAccountRef } from \"@qntx/wallet/protocol\";\n\nimport type { SparkController } from \"../spark/controller.ts\";\nimport { SparkControllerError } from \"../spark/errors.ts\";\nimport { PaymentError } from \"./errors.ts\";\nimport type { PaymentOption } from \"./parse.ts\";\n\nexport type PayParams = {\n readonly account: SparkAccountRef;\n readonly option: PaymentOption;\n /** Caller-supplied amount — required by open invoices, the `spark` option, and LNURL flows. */\n readonly amountSats?: number;\n readonly comment?: string;\n readonly maxFeeSats?: number;\n readonly speed?: \"FAST\" | \"MEDIUM\" | \"SLOW\";\n readonly verify: UnlockFactor;\n};\n\nexport type PayContext = {\n readonly spark: SparkController;\n readonly fetch: typeof globalThis.fetch;\n readonly now: () => number;\n};\n\nexport type PayResult =\n | { readonly kind: \"spark\"; readonly transfer: SparkTransfer }\n | { readonly kind: \"lightning\"; readonly payment: LightningPayment }\n | { readonly kind: \"withdraw\"; readonly exit: CooperativeExitResult }\n | { readonly kind: \"lnurl-withdraw\"; readonly invoice: LightningInvoice };\n\n/**\n * Executes one parsed payment option. Every input validation happens before the approval round — a\n * `PaymentError` here never consumed a verification. `SparkControllerError` and `WalletError` pass\n * through untouched.\n */\nexport async function pay(context: PayContext, params: PayParams): Promise<PayResult> {\n const { spark } = context;\n const ref = params.account;\n let result: PayResult;\n switch (params.option.kind) {\n case \"spark\": {\n if (params.amountSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"spark payment: amountSats is required\");\n }\n const transfer = await spark.send(ref, {\n receiver: params.option.address,\n amountSats: params.amountSats,\n verify: params.verify,\n });\n result = { kind: \"spark\", transfer };\n break;\n }\n case \"spark-invoice\": {\n if (params.option.expiresAt !== undefined && params.option.expiresAt <= context.now()) {\n throw new PaymentError(\"rejected\", \"spark invoice expired\");\n }\n if (\n params.option.amountSats !== undefined &&\n params.amountSats !== undefined &&\n params.amountSats !== params.option.amountSats\n ) {\n throw new PaymentError(\n \"invalid-input\",\n \"spark invoice: amountSats conflicts with the invoice amount\",\n );\n }\n // A fixed-amount invoice derives the amount itself — only an open one takes the caller's.\n const invoiceAmount = params.option.amountSats === undefined ? params.amountSats : undefined;\n const transfer = await spark.paySparkInvoice(ref, {\n invoice: params.option.invoice,\n ...(invoiceAmount === undefined ? {} : { amountSats: invoiceAmount }),\n verify: params.verify,\n });\n result = { kind: \"spark\", transfer };\n break;\n }\n case \"lightning\": {\n if (params.option.amountSats === undefined && params.amountSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"amountless invoice: amountSats is required\");\n }\n if (params.maxFeeSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"lightning payment: maxFeeSats is required\");\n }\n // amountSats is only for amountless invoices — a fixed-amount invoice must not carry it.\n if (params.option.expiresAt <= context.now() + 60_000) {\n throw new PaymentError(\"rejected\", \"lightning invoice expired\");\n }\n if (\n params.option.amountSats !== undefined &&\n params.amountSats !== undefined &&\n params.amountSats !== params.option.amountSats\n ) {\n throw new PaymentError(\"invalid-input\", \"amountSats conflicts with the invoice amount\");\n }\n const payment = await spark.payInvoice(ref, {\n invoice: params.option.invoice,\n maxFeeSats: params.maxFeeSats,\n ...(params.option.amountSats === undefined && params.amountSats !== undefined\n ? { amountSats: params.amountSats }\n : {}),\n verify: params.verify,\n });\n result = { kind: \"lightning\", payment };\n break;\n }\n case \"lnurl-pay\": {\n const { request } = params.option;\n if (params.amountSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"lnurl-pay: amountSats is required\");\n }\n if (params.maxFeeSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"lnurl-pay: maxFeeSats is required\");\n }\n const amountMsat = params.amountSats * 1000;\n if (amountMsat < request.minSendableMsat || amountMsat > request.maxSendableMsat) {\n throw new PaymentError(\"rejected\", \"lnurl-pay: amount outside the service's range\");\n }\n if (request.commentAllowed === 0 && params.comment !== undefined) {\n throw new PaymentError(\"rejected\", \"lnurl-pay: comments not accepted by this service\");\n }\n if (params.comment !== undefined && params.comment.length > request.commentAllowed) {\n throw new PaymentError(\"rejected\", \"lnurl-pay: comment exceeds the service's limit\");\n }\n let requested;\n try {\n requested = await requestInvoice(request, {\n fetch: context.fetch,\n network: ref.network,\n amountMsat,\n ...(params.comment === undefined ? {} : { comment: params.comment }),\n });\n } catch (error) {\n if (error instanceof PaymentError || error instanceof SparkControllerError) {\n throw error;\n }\n throw new PaymentError(\"network\", \"lnurl-pay: invoice request failed\", error);\n }\n const payment = await spark.payInvoice(ref, {\n invoice: requested.invoice,\n maxFeeSats: params.maxFeeSats,\n verify: params.verify,\n });\n result = { kind: \"lightning\", payment };\n break;\n }\n case \"lnurl-withdraw\": {\n const { request } = params.option;\n if (params.amountSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"lnurl-withdraw: amountSats is required\");\n }\n const amountMsat = params.amountSats * 1000;\n if (amountMsat < request.minWithdrawableMsat || amountMsat > request.maxWithdrawableMsat) {\n throw new PaymentError(\"rejected\", \"lnurl-withdraw: amount outside the service's range\");\n }\n const invoice = await spark.createInvoice(ref, {\n amountSats: params.amountSats,\n memo: request.defaultDescription,\n });\n try {\n await submitWithdraw(request, { fetch: context.fetch, invoice: invoice.invoice });\n } catch (error) {\n if (error instanceof PaymentError || error instanceof SparkControllerError) {\n throw error;\n }\n throw new PaymentError(\"network\", \"lnurl-withdraw: submission failed\", error);\n }\n result = { kind: \"lnurl-withdraw\", invoice };\n break;\n }\n case \"bitcoin\": {\n if (params.amountSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"bitcoin payment: amountSats is required\");\n }\n const exit = await spark.withdraw(ref, {\n address: params.option.address,\n speed: params.speed ?? \"MEDIUM\",\n verify: params.verify,\n amountSats: params.amountSats,\n ...(params.maxFeeSats === undefined ? {} : { maxFeeSats: params.maxFeeSats }),\n });\n result = { kind: \"withdraw\", exit };\n break;\n }\n }\n return result;\n}\n","import { resolveLnurl } from \"@qntx/spark/lnurl\";\n\nimport { PaymentError } from \"./errors.ts\";\nimport { parsePayment } from \"./parse.ts\";\nimport type { PaymentParse, ParseOptions } from \"./parse.ts\";\n\nexport type ResolveOptions = ParseOptions & {\n readonly fetch: typeof globalThis.fetch;\n};\n\n/**\n * `parsePayment` plus LNURL dereferencing: an `lnurl` result is fetched and turned into a concrete\n * `lnurl-pay` / `lnurl-withdraw` request (`tag=login` endpoints report as unsupported). Network\n * failures throw `PaymentError(\"network\")` — remote error bodies never enter the message.\n */\nexport async function resolvePayment(\n input: string,\n options: ResolveOptions,\n): Promise<PaymentParse> {\n const parsed = parsePayment(input, options);\n if (parsed.kind !== \"lnurl\") {\n return parsed;\n }\n let resolved;\n try {\n resolved = await resolveLnurl(parsed.url, { fetch: options.fetch });\n } catch {\n throw new PaymentError(\"network\", \"lnurl: resolution failed\");\n }\n if (resolved.tag === \"payRequest\") {\n return {\n kind: \"request\",\n request: {\n options: [\n {\n kind: \"lnurl-pay\",\n request: resolved,\n ...(parsed.address === undefined ? {} : { address: parsed.address }),\n },\n ],\n },\n };\n }\n if (resolved.tag === \"withdrawRequest\") {\n return {\n kind: \"request\",\n request: { options: [{ kind: \"lnurl-withdraw\", request: resolved }] },\n };\n }\n return { kind: \"unsupported\", format: \"lnurl-auth\" };\n}\n","import { bytesToHex } from \"@noble/hashes/utils.js\";\n\nimport { signedMatchesUnsigned, verifyEvent } from \"@qntx/nostr\";\nimport type { Event, NostrSigner } from \"@qntx/nostr\";\nimport { makeZapRequest } from \"@qntx/nostr/nips/nip57\";\nimport { SparkInputError, decodeBolt11 } from \"@qntx/spark\";\nimport type { LightningPayment, SparkNetwork } from \"@qntx/spark\";\nimport { encodeLnurl, lightningAddressUrl, requestInvoice, resolveLnurl } from \"@qntx/spark/lnurl\";\nimport type { UnlockFactor } from \"@qntx/wallet\";\nimport type { SparkAccountRef } from \"@qntx/wallet/protocol\";\n\nimport type { SparkController } from \"../spark/controller.ts\";\nimport { categorize } from \"../spark/errors.ts\";\nimport { PaymentError } from \"./errors.ts\";\n\n/** A profile zap names the recipient pubkey; an event zap carries the event it zaps. */\nexport type ZapRecipient =\n | { readonly pubkey: string; readonly lightning: string }\n | { readonly event: Event; readonly lightning: string };\n\nexport type PrepareZapParams = {\n /** Any `NostrSigner` — wallet key, external key, NIP-07/46 — signs the 9734. */\n readonly signer: NostrSigner;\n readonly recipient: ZapRecipient;\n readonly amountSats: number;\n readonly comment?: string | undefined;\n readonly relays: ReadonlyArray<string>;\n readonly network: SparkNetwork;\n};\n\nexport type PrepareZapContext = {\n readonly fetch: typeof globalThis.fetch;\n readonly now: () => number;\n};\n\n/** Everything a payer needs: the signed 9734, the invoice, and the note fields. */\nexport type PreparedZap = {\n readonly zapRequest: Event;\n readonly invoice: string;\n /** Hex payment hash decoded from the invoice. */\n readonly paymentHash: string;\n /** Millisecond expiry decoded from the invoice. */\n readonly expiresAt: number;\n readonly amountSats: number;\n /** The LNURL service's 9735 signing pubkey. */\n readonly receiptPubkey: string;\n readonly recipientPubkey: string;\n readonly eventId?: string;\n readonly comment?: string;\n /** The lud16 or LNURL as given. */\n readonly lightning: string;\n};\n\nexport type PayZapOptions = {\n readonly maxFeeSats: number;\n readonly verify: UnlockFactor;\n readonly now: () => number;\n};\n\n/** Everything up to payment: resolve LNURL, sign the 9734, request the invoice. */\nexport async function prepareZap(\n params: PrepareZapParams,\n context: PrepareZapContext,\n): Promise<PreparedZap> {\n const amountMsat = params.amountSats * 1000;\n if (\n !Number.isSafeInteger(params.amountSats) ||\n params.amountSats <= 0 ||\n !Number.isSafeInteger(amountMsat)\n ) {\n throw new PaymentError(\"invalid-input\", \"zap amount is not a positive safe integer\");\n }\n try {\n const resolved = await resolveLnurl(params.recipient.lightning, { fetch: context.fetch });\n if (resolved.tag !== \"payRequest\") {\n throw new PaymentError(\"rejected\", \"recipient is not an LNURL-pay endpoint\");\n }\n if (!resolved.allowsNostr || resolved.nostrPubkey === undefined) {\n throw new PaymentError(\"rejected\", \"LNURL service does not accept nostr zaps\");\n }\n if (amountMsat < resolved.minSendableMsat || amountMsat > resolved.maxSendableMsat) {\n throw new PaymentError(\"rejected\", \"zap amount outside the service's bounds\");\n }\n if (params.comment !== undefined) {\n if (resolved.commentAllowed === 0) {\n throw new PaymentError(\"rejected\", \"the service does not accept comments\");\n }\n if (params.comment.length > resolved.commentAllowed) {\n throw new PaymentError(\"rejected\", \"comment exceeds the service's limit\");\n }\n }\n // LNURL detection is case-insensitive; the 9734 carries lowercase bech32.\n const lnurl = params.recipient.lightning.toLowerCase().startsWith(\"lnurl1\")\n ? params.recipient.lightning.toLowerCase()\n : encodeLnurl(lightningAddressUrl(params.recipient.lightning));\n const base = {\n amount: amountMsat,\n relays: [...params.relays],\n comment: params.comment,\n lnurl,\n };\n const template =\n \"event\" in params.recipient\n ? makeZapRequest({ event: params.recipient.event, ...base })\n : makeZapRequest({ pubkey: params.recipient.pubkey, ...base });\n const unsigned = { ...template, pubkey: await params.signer.getPublicKey() };\n const zapRequest = await params.signer.signEvent(unsigned);\n // External signers (NIP-07/46) are untrusted: the 9734 must be validly signed over exactly\n // the template, or the receipt would commit to content the user never approved.\n if (!verifyEvent(zapRequest) || !signedMatchesUnsigned(zapRequest, unsigned)) {\n throw new PaymentError(\"rejected\", \"signer returned a zap request that does not match\");\n }\n const { invoice } = await requestInvoice(resolved, {\n fetch: context.fetch,\n network: params.network,\n amountMsat,\n ...(params.comment === undefined ? {} : { comment: params.comment }),\n zapRequest: JSON.stringify(zapRequest),\n });\n const decoded = decodeBolt11(invoice);\n const expiresAt = (decoded.timestamp + decoded.expirySeconds) * 1000;\n if (expiresAt <= context.now() + 60_000) {\n throw new PaymentError(\"rejected\", \"zap invoice expires too soon\");\n }\n const eventId = \"event\" in params.recipient ? params.recipient.event.id : undefined;\n return {\n zapRequest,\n invoice,\n paymentHash: bytesToHex(decoded.paymentHash),\n expiresAt,\n amountSats: params.amountSats,\n receiptPubkey: bytesToHex(resolved.nostrPubkey),\n recipientPubkey:\n \"event\" in params.recipient ? params.recipient.event.pubkey : params.recipient.pubkey,\n ...(eventId === undefined ? {} : { eventId }),\n ...(params.comment === undefined ? {} : { comment: params.comment }),\n lightning: params.recipient.lightning,\n };\n } catch (error) {\n if (error instanceof PaymentError) {\n throw error;\n }\n if (\n error instanceof SparkInputError ||\n (error instanceof Error && error.cause instanceof SparkInputError)\n ) {\n throw new PaymentError(\"rejected\", \"zap failed invoice validation\");\n }\n throw new PaymentError(categorizePayment(error), \"zap failed\");\n }\n}\n\n/**\n * Pays a prepared zap through the controller's approve-first path. A nearly-expired invoice is\n * rejected before approval — the user may have sat on the confirm screen since `prepareZap`.\n */\nexport async function payZap(\n spark: SparkController,\n account: SparkAccountRef,\n prepared: PreparedZap,\n options: PayZapOptions,\n): Promise<LightningPayment> {\n if (prepared.expiresAt <= options.now() + 60_000) {\n throw new PaymentError(\"rejected\", \"zap invoice expired\");\n }\n return spark.payInvoice(account, {\n invoice: prepared.invoice,\n maxFeeSats: options.maxFeeSats,\n verify: options.verify,\n note: {\n kind: \"zap\",\n recipientPubkey: prepared.recipientPubkey,\n ...(prepared.eventId === undefined ? {} : { eventId: prepared.eventId }),\n ...(prepared.comment === undefined ? {} : { comment: prepared.comment }),\n lightning: prepared.lightning,\n },\n });\n}\n\nfunction categorizePayment(error: unknown): \"network\" | \"rejected\" {\n const category = categorize(error);\n return category === \"network\" ? \"network\" : \"rejected\";\n}\n","import type { SparkPayment } from \"@qntx/spark\";\n\n/**\n * Local, engine-side metadata pinned to a history entry by transfer id. Written after the payment\n * it annotates has already succeeded — a missing or malformed note must never affect the payment\n * itself.\n */\nexport type PaymentNote = {\n readonly kind: \"zap\";\n /** 64 lowercase hex. */\n readonly recipientPubkey: string;\n /** 64 lowercase hex — event zaps carry the zapped event's id. */\n readonly eventId?: string;\n /** At most 2000 characters. */\n readonly comment?: string;\n /** The lud16 or LNURL the zap resolved. */\n readonly lightning: string;\n};\n\nexport type SparkActivity = SparkPayment & { readonly note?: PaymentNote };\n\nconst HEX64 = /^[0-9a-f]{64}$/;\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\nconst NOTE_FIELDS: ReadonlySet<string> = new Set([\n \"kind\",\n \"recipientPubkey\",\n \"eventId\",\n \"comment\",\n \"lightning\",\n]);\n\n/** Strict read-side validation: anything off-shape is `undefined`, never a throw. */\nexport function parsePaymentNote(value: unknown): PaymentNote | undefined {\n if (!isObject(value)) {\n return undefined;\n }\n for (const field of Object.keys(value)) {\n if (!NOTE_FIELDS.has(field)) {\n return undefined;\n }\n }\n const { kind, recipientPubkey, eventId, comment, lightning } = value;\n if (kind !== \"zap\") {\n return undefined;\n }\n if (typeof recipientPubkey !== \"string\" || !HEX64.test(recipientPubkey)) {\n return undefined;\n }\n if (eventId !== undefined && (typeof eventId !== \"string\" || !HEX64.test(eventId))) {\n return undefined;\n }\n if (comment !== undefined && (typeof comment !== \"string\" || comment.length > 2000)) {\n return undefined;\n }\n if (typeof lightning !== \"string\" || lightning.length === 0) {\n return undefined;\n }\n return {\n kind: \"zap\",\n recipientPubkey,\n ...(eventId === undefined ? {} : { eventId }),\n ...(comment === undefined ? {} : { comment }),\n lightning,\n };\n}\n\nexport function encodePaymentNote(note: PaymentNote): Uint8Array {\n return new TextEncoder().encode(JSON.stringify(note));\n}\n","/**\n * SparkExitChain persistence codec: JSON with Uint8Arrays tagged `{ $b64: \"…\" }` — small and\n * explicit rather than schema-bound, so upstream field additions survive a round-trip.\n */\nimport { base64 } from \"@scure/base\";\n\nimport type { SparkExitChain } from \"@qntx/spark\";\n\nfunction encodeValue(value: unknown): unknown {\n if (value instanceof Uint8Array) {\n return { $b64: base64.encode(value) };\n }\n if (Array.isArray(value)) {\n return value.map(encodeValue);\n }\n if (typeof value === \"object\" && value !== null) {\n return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, encodeValue(v)]));\n }\n return value;\n}\n\nfunction decodeValue(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(decodeValue);\n }\n if (typeof value === \"object\" && value !== null) {\n const entries = Object.entries(value);\n const b64: unknown =\n entries.length === 1 && entries[0]?.[0] === \"$b64\" ? entries[0][1] : undefined;\n if (typeof b64 === \"string\") {\n return base64.decode(b64);\n }\n return Object.fromEntries(entries.map(([k, v]) => [k, decodeValue(v)]));\n }\n return value;\n}\n\nexport function encodeExitChain(chain: SparkExitChain): Uint8Array {\n return new TextEncoder().encode(JSON.stringify(encodeValue(chain)));\n}\n\nexport function decodeExitChain(bytes: Uint8Array): SparkExitChain {\n const decoded: unknown = decodeValue(JSON.parse(new TextDecoder().decode(bytes)));\n // The codec round-trips what encodeExitChain wrote — the shape is structural.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return decoded as SparkExitChain;\n}\n","import type { SparkExitChain, SparkStore } from \"@qntx/spark\";\n\nimport type { EngineCollection } from \"../store/port.ts\";\nimport { decodeExitChain, encodeExitChain } from \"./exit-chain-codec.ts\";\n\nconst ALL = \"__all__\";\n\n/**\n * SparkStore over one EngineCollection: chains keyed by leafId, plus an index record listing them\n * (`exitChains` is a full listing — the port has no secondary index).\n */\nexport function sparkStore(col: EngineCollection): SparkStore {\n const readIndex = async (): Promise<string[]> => {\n const index = await col.get(ALL);\n if (index === undefined) {\n return [];\n }\n const parsed: unknown = JSON.parse(new TextDecoder().decode(index));\n if (!Array.isArray(parsed)) {\n return [];\n }\n return parsed.filter((v): v is string => typeof v === \"string\");\n };\n const writeIndex = async (ids: ReadonlyArray<string>): Promise<void> => {\n await col.put(ALL, new TextEncoder().encode(JSON.stringify(ids)));\n };\n return {\n exitChains: async () => {\n const ids = await readIndex();\n const chains: SparkExitChain[] = [];\n for (const leafId of ids) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- reads must stay ordered and sequential\n const record = await col.get(leafId);\n if (record !== undefined) {\n chains.push(decodeExitChain(record));\n }\n }\n return chains;\n },\n putExitChains: async (chains) => {\n const ids = await readIndex();\n const set = new Set(ids);\n for (const chain of chains) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- writes commit one record at a time\n await col.put(chain.leafId, encodeExitChain(chain));\n set.add(chain.leafId);\n }\n await writeIndex([...set]);\n },\n deleteExitChains: async (leafIds) => {\n const ids = await readIndex();\n const drop = new Set(leafIds);\n for (const leafId of leafIds) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- deletes commit one record at a time\n await col.delete(leafId);\n }\n await writeIndex(ids.filter((leafId) => !drop.has(leafId)));\n },\n };\n}\n","import {\n bitcoinAddressScript,\n decodeSparkAddress,\n encodeSparkAddress,\n parseSparkInvoice,\n SparkInputError,\n uuidv7,\n} from \"@qntx/spark\";\nimport type {\n CooperativeExitResult,\n LightningInvoice,\n LightningPayment,\n SparkClient,\n SparkPayment,\n SparkTransfer,\n} from \"@qntx/spark\";\nimport { registerLightningAddress, unregisterLightningAddress } from \"@qntx/spark/lnurl\";\nimport type { UnlockFactor } from \"@qntx/wallet\";\nimport type { SparkAccountRef, SparkApproveIntent } from \"@qntx/wallet/protocol\";\nimport type { SparkSigner } from \"@qntx/wallet/spark\";\n\nimport { Controller } from \"../controller.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport type { EngineStore, EngineCollection } from \"../store/port.ts\";\nimport { categorize, SparkControllerError } from \"./errors.ts\";\nimport { encodePaymentNote, parsePaymentNote } from \"./notes.ts\";\nimport type { PaymentNote, SparkActivity } from \"./notes.ts\";\nimport { sparkStore } from \"./store.ts\";\n\nexport type SparkAccountState = {\n readonly status: \"locked\" | \"connecting\" | \"ready\" | \"error\";\n readonly balanceSats?: number;\n readonly identityPublicKey?: string;\n readonly sparkAddress?: string;\n readonly errorCategory?: string;\n /** First history page (20 entries, newest first), refreshed alongside the balance. */\n readonly recent?: ReadonlyArray<SparkActivity>;\n};\n\nexport type SparkControllerState = {\n readonly accounts: Readonly<Record<string, SparkAccountState>>;\n};\n\ntype SparkApis = {\n readonly signer: (ref: SparkAccountRef) => SparkSigner;\n readonly approve: (params: {\n account: SparkAccountRef;\n intent: SparkApproveIntent;\n verify: UnlockFactor;\n }) => Promise<unknown>;\n};\n\nexport type SparkClientFactory = (options: {\n readonly ref: SparkAccountRef;\n readonly store: ReturnType<typeof sparkStore>;\n readonly signer: SparkSigner;\n readonly fetch: typeof globalThis.fetch;\n}) => SparkClient;\n\nexport type SparkControllerOptions = {\n readonly spark: SparkApis;\n readonly fetch: typeof globalThis.fetch;\n readonly random: (length: number) => Uint8Array;\n readonly now: () => number;\n readonly logger: EngineLogger;\n readonly createClient: SparkClientFactory;\n};\n\nconst key = (ref: SparkAccountRef): string => `${ref.walletId}:${ref.groupIndex}:${ref.network}`;\n\n/** TransferId: the client and SO expect a UUIDv7 — mint it from the injected clock+random. */\nconst transferId = (random: (n: number) => Uint8Array, now: () => number): string =>\n uuidv7(random, now);\n\n/** Catch-up sync for one pass: claim every pending transfer, then read balance and identity. */\nasync function resync(\n client: SparkClient,\n log: (transferId: string, error: unknown) => void,\n): Promise<{ balance: number; identity: Uint8Array }> {\n const { failures } = await client.transfers.claimPending();\n for (const failure of failures) {\n log(failure.transferId, failure.error);\n }\n const [balance, identity] = await Promise.all([client.balance(), client.identityPublicKey()]);\n return { balance, identity };\n}\n\n/** Abortable backoff — resolves early when the signal aborts; removes its listener. */\nasync function eventsBackoff(failures: number, signal: AbortSignal): Promise<void> {\n await new Promise<void>((resolve) => {\n const timer = setTimeout(\n () => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n },\n Math.min(2 ** failures, 30) * 1000,\n );\n const onAbort = (): void => {\n clearTimeout(timer);\n resolve();\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\nexport class SparkController extends Controller<SparkControllerState> {\n private readonly options: SparkControllerOptions;\n private engineStore: EngineStore | undefined;\n private readonly accounts = new Map<string, SparkAccountRef>();\n private readonly clients = new Map<string, SparkClient>();\n private readonly recentSeq = new Map<string, number>();\n private readonly aborts = new Map<string, AbortController>();\n\n constructor(options: SparkControllerOptions) {\n super({ name: \"spark\", defaultState: () => ({ accounts: {} }) });\n this.options = options;\n }\n\n /** Engine calls this with the open store on unlock; `undefined` on lock. */\n setStore(store: EngineStore | undefined): void {\n this.engineStore = store;\n }\n\n /**\n * Declarative account set: refs not yet tracked are patched `locked` and started when the store\n * is open; tracked refs no longer listed are stopped and dropped; running refs stay untouched.\n */\n setAccounts(refs: ReadonlyArray<SparkAccountRef>): void {\n const wanted = new Map(refs.map((ref) => [key(ref), ref]));\n for (const k of this.accounts.keys()) {\n if (!wanted.has(k)) {\n this.accounts.delete(k);\n this.stopAccount(k);\n }\n }\n for (const [k, ref] of wanted) {\n if (!this.accounts.has(k)) {\n this.accounts.set(k, ref);\n this.patch(k, { status: \"locked\" });\n }\n if (this.engineStore !== undefined && !this.clients.has(k)) {\n this.startAccount(ref);\n }\n }\n }\n\n async init(): Promise<void> {\n for (const ref of this.accounts.values()) {\n this.startAccount(ref);\n }\n await Promise.resolve();\n }\n\n async destroy(): Promise<void> {\n await this.lockAll();\n }\n\n private stopAccount(k: string): void {\n this.aborts.get(k)?.abort();\n this.aborts.delete(k);\n this.clients.get(k)?.close();\n this.clients.delete(k);\n this.update((s) => {\n if (!(k in s.accounts)) {\n return s;\n }\n const { [k]: _dropped, ...rest } = s.accounts;\n void _dropped;\n return { ...s, accounts: rest };\n });\n }\n\n /** Lock: abort every event loop, close every client, reset state. */\n async lockAll(): Promise<void> {\n for (const [k, client] of this.clients) {\n this.aborts.get(k)?.abort();\n client.close();\n }\n this.aborts.clear();\n this.clients.clear();\n this.engineStore = undefined;\n await Promise.resolve();\n this.update((s) =>\n Object.keys(s.accounts).length === 0\n ? s\n : {\n ...s,\n accounts: Object.fromEntries(\n Object.keys(s.accounts).map((k) => [k, { status: \"locked\" as const }]),\n ),\n },\n );\n }\n\n private startAccount(ref: SparkAccountRef): void {\n const k = key(ref);\n if (this.engineStore === undefined || this.clients.has(k)) {\n return;\n }\n this.patch(k, { status: \"connecting\" });\n try {\n const col = this.engineStore.collection(`spark-exit-chains:${k}`);\n const client = this.options.createClient({\n ref,\n store: sparkStore(col),\n signer: this.options.spark.signer(ref),\n fetch: this.options.fetch,\n });\n this.clients.set(k, client);\n const abort = new AbortController();\n this.aborts.set(k, abort);\n // The initial sync lives in the event loop's catch-up pass: a transient failure at\n // account start retries through the loop's backoff instead of leaving the account dead\n // in \"error\".\n this.runEvents(k, client, abort.signal, ref.network);\n } catch (error) {\n this.patch(k, { status: \"error\", errorCategory: categorize(error) });\n this.options.logger.warn(\"spark account failed to start\", error);\n }\n }\n\n private runEvents(\n k: string,\n client: SparkClient,\n signal: AbortSignal,\n network: SparkAccountRef[\"network\"],\n ): void {\n // Every pass resyncs before streaming: the catch-up claim retries anything a previous\n // pass failed on and covers events missed while disconnected — a failed claim is never\n // lost, only deferred one pass. Any throw or a clean stream end backs off (exponential,\n // abortable) and starts a new pass.\n const loop = async (): Promise<void> => {\n let failures = 0;\n while (!signal.aborted) {\n try {\n // Catch-up: claim pending transfers and refresh the balance snapshot. Per-transfer\n // failures are logged, not fatal — one poisoned transfer must not fail the pass.\n // oxlint-disable-next-line no-await-in-loop -- catch-up sync must precede streaming\n const { balance, identity } = await resync(client, (transferId, error) => {\n this.options.logger.warn(\n `spark catch-up claim failed for ${transferId} (${categorize(error)})`,\n );\n });\n if (signal.aborted) {\n return;\n }\n this.patch(k, {\n balanceSats: balance,\n status: \"ready\",\n identityPublicKey: [...identity].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\"),\n sparkAddress: encodeSparkAddress({\n network,\n identityPublicKey: identity,\n }),\n });\n void this.refreshRecent(k, client);\n const iterator = client.events(signal)[Symbol.asyncIterator]();\n let open = true;\n while (open) {\n // oxlint-disable-next-line no-await-in-loop -- events arrive in stream order\n const item = await iterator.next();\n if (item.done === true) {\n open = false;\n } else {\n const event = item.value;\n if (event.type === \"transfer\") {\n try {\n // oxlint-disable-next-line no-await-in-loop -- claims are ordered per event\n await this.handleTransfer(client, event, signal, k);\n failures = 0;\n } catch (error) {\n // A terminal status (expired, returned…) is not a stream failure — log the\n // transfer and keep consuming the stream.\n if (!(error instanceof SparkInputError)) {\n throw error;\n }\n this.options.logger.warn(\n `spark claim of ${event.transferId} rejected (${categorize(error)})`,\n );\n failures = 0;\n }\n }\n }\n }\n // A clean end is abnormal for a permanent stream — back off like a failure.\n failures += 1;\n this.options.logger.warn(\"spark event stream ended — resubscribing\");\n } catch (error) {\n if (signal.aborted) {\n return;\n }\n failures += 1;\n if (failures === 1) {\n this.patch(k, { status: \"error\", errorCategory: categorize(error) });\n }\n this.options.logger.warn(\"spark event stream failed — resubscribing\", error);\n }\n // oxlint-disable-next-line no-await-in-loop -- the backoff bounds resubscribe pace\n await eventsBackoff(failures, signal);\n }\n };\n void loop();\n }\n\n private async handleTransfer(\n client: SparkClient,\n event: { readonly direction: \"incoming\" | \"outgoing\"; readonly transferId: string },\n signal: AbortSignal,\n k: string,\n ): Promise<void> {\n if (event.direction === \"incoming\") {\n // claim(id) re-queries until the transfer turns claimable — it owns the protocol-level\n // wait for the SSP's claimable window, so no extra delay or pending-list scan here.\n await client.transfers.claim(event.transferId, { signal });\n }\n this.patch(k, { balanceSats: await client.balance() });\n void this.refreshRecent(k, client);\n }\n\n private notesCollection(k: string): EngineCollection | undefined {\n return this.engineStore?.collection(`spark-notes:${k}`);\n }\n\n /** Attach locally written notes to a history page; malformed records warn and drop. */\n private async withNotes(\n k: string,\n payments: ReadonlyArray<SparkPayment>,\n ): Promise<ReadonlyArray<SparkActivity>> {\n const col = this.notesCollection(k);\n if (col === undefined) {\n return payments;\n }\n return Promise.all(\n payments.map(async (payment): Promise<SparkActivity> => {\n const bytes = await col.get(payment.id);\n if (bytes === undefined) {\n return payment;\n }\n let note: PaymentNote | undefined;\n try {\n note = parsePaymentNote(JSON.parse(new TextDecoder().decode(bytes)));\n } catch {\n note = undefined;\n }\n if (note === undefined) {\n this.options.logger.warn(\n `spark note record for ${payment.id} ignored: malformed`,\n new Error(\"malformed payment note\"),\n );\n return payment;\n }\n return { ...payment, note };\n }),\n );\n }\n\n /**\n * Refill `recent` from the first history page. A failure keeps the previous page — it never\n * touches `status`/`errorCategory`. A per-account sequence keeps a slower older refresh from\n * overwriting a newer one.\n */\n private async refreshRecent(k: string, client: SparkClient): Promise<void> {\n const seq = (this.recentSeq.get(k) ?? 0) + 1;\n this.recentSeq.set(k, seq);\n try {\n const { payments } = await client.transfers.history({ limit: 20 });\n const items = await this.withNotes(k, payments);\n // A stale seq or a closed client (lockAll cleared the map) must not write.\n if (this.recentSeq.get(k) === seq && this.clients.get(k) === client) {\n this.patch(k, { recent: items });\n }\n } catch (error) {\n this.options.logger.warn(`spark recent refresh failed for ${k}`, error);\n }\n }\n\n private patch(k: string, delta: Partial<SparkAccountState>): void {\n this.update((s) => ({\n ...s,\n accounts: { ...s.accounts, [k]: { status: \"locked\" as const, ...s.accounts[k], ...delta } },\n }));\n }\n\n private clientFor(ref: SparkAccountRef): SparkClient {\n const client = this.clients.get(key(ref));\n if (client === undefined) {\n throw new SparkControllerError(\"internal\", \"account is not connected\");\n }\n return client;\n }\n\n private async guarded<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n if (error instanceof SparkControllerError) {\n throw error;\n }\n throw new SparkControllerError(categorize(error), \"spark action failed\", error);\n }\n }\n\n /**\n * One-off balance + activity probe for an account that may not be running: builds a temporary\n * client through the same factory on the account's own exit-chain collection (nothing diverges —\n * `balance()`/`transfers.history` never write it), reads, and closes it in `finally`.\n */\n async inspect(ref: SparkAccountRef): Promise<{ balanceSats: number; used: boolean }> {\n return this.guarded(async () => {\n if (this.engineStore === undefined) {\n throw new SparkControllerError(\"internal\", \"engine store is not open\");\n }\n const k = key(ref);\n const running = this.clients.get(k);\n if (running !== undefined) {\n const [balance, page] = await Promise.all([\n running.balance(),\n running.transfers.history({ limit: 1 }),\n ]);\n return { balanceSats: balance, used: balance > 0 || page.payments.length > 0 };\n }\n const client = this.options.createClient({\n ref,\n store: sparkStore(this.engineStore.collection(`spark-exit-chains:${k}`)),\n signer: this.options.spark.signer(ref),\n fetch: this.options.fetch,\n });\n try {\n const [balance, page] = await Promise.all([\n client.balance(),\n client.transfers.history({ limit: 1 }),\n ]);\n return { balanceSats: balance, used: balance > 0 || page.payments.length > 0 };\n } finally {\n client.close();\n }\n });\n }\n\n /** History for one account: a client page merged with locally written notes by id. */\n async history(\n ref: SparkAccountRef,\n options?: {\n readonly limit?: number;\n readonly offset?: number;\n },\n ): Promise<{\n readonly items: ReadonlyArray<SparkActivity>;\n readonly nextOffset: number | undefined;\n }> {\n return this.guarded(async () => {\n const client = this.clientFor(ref);\n const { payments, nextOffset } = await client.transfers.history({\n ...(options?.limit === undefined ? {} : { limit: options.limit }),\n ...(options?.offset === undefined ? {} : { offset: options.offset }),\n });\n return { items: await this.withNotes(key(ref), payments), nextOffset };\n });\n }\n\n async send(\n ref: SparkAccountRef,\n params: {\n receiver: string;\n amountSats: number;\n verify: UnlockFactor;\n },\n ): Promise<SparkTransfer> {\n return this.guarded(async () => {\n const client = this.clientFor(ref);\n const receiver = decodeSparkAddress(params.receiver);\n if (receiver.network !== ref.network) {\n throw new SparkControllerError(\"rejected\", \"receiver address is on a different network\");\n }\n const identity = receiver.identityPublicKey;\n await this.options.spark.approve({\n account: ref,\n intent: {\n kind: \"transfer\",\n receivers: [{ identityPublicKey: identity, amountSats: params.amountSats }],\n },\n verify: params.verify,\n });\n const transfer = await client.transfers.send({\n receiver: params.receiver,\n amountSats: params.amountSats,\n transferId: transferId(this.options.random, this.options.now),\n });\n void this.refreshRecent(key(ref), client);\n return transfer;\n });\n }\n\n async registerLightningAddress(\n ref: SparkAccountRef,\n params: { serverUrl: string; domain: string; username: string; description: string },\n ): Promise<{ lnurl: string; lightningAddress: string }> {\n const signer = this.options.spark.signer(ref);\n try {\n return await registerLightningAddress({ ...params, fetch: this.options.fetch, signer });\n } catch (error) {\n throw error instanceof SparkControllerError\n ? error\n : new SparkControllerError(\"internal\", \"registration failed\");\n }\n }\n\n async unregisterLightningAddress(\n ref: SparkAccountRef,\n params: { serverUrl: string; domain: string; username: string },\n ): Promise<void> {\n const signer = this.options.spark.signer(ref);\n try {\n await unregisterLightningAddress({ ...params, fetch: this.options.fetch, signer });\n } catch (error) {\n throw error instanceof SparkControllerError\n ? error\n : new SparkControllerError(\"internal\", \"unregistration failed\");\n }\n }\n\n async payInvoice(\n ref: SparkAccountRef,\n params: {\n invoice: string;\n amountSats?: number;\n maxFeeSats: number;\n verify: UnlockFactor;\n /** Local annotation written under the payment's transfer id after it succeeds. */\n note?: PaymentNote;\n },\n ): Promise<LightningPayment> {\n return this.guarded(async () => {\n const client = this.clientFor(ref);\n await this.options.spark.approve({\n account: ref,\n intent: {\n kind: \"lightning\",\n invoice: params.invoice,\n ...(params.amountSats === undefined ? {} : { amountSats: params.amountSats }),\n maxFeeSats: params.maxFeeSats,\n },\n verify: params.verify,\n });\n const payment = await client.lightning.pay({\n invoice: params.invoice,\n maxFeeSats: params.maxFeeSats,\n ...(params.amountSats === undefined ? {} : { amountSats: params.amountSats }),\n transferId: transferId(this.options.random, this.options.now),\n });\n if (params.note !== undefined) {\n try {\n await this.notesCollection(key(ref))?.put(\n payment.transferId,\n encodePaymentNote(params.note),\n );\n } catch (error) {\n // The payment already succeeded — a lost annotation is a warning, not a failure.\n this.options.logger.warn(\"spark note write failed\", error);\n }\n }\n void this.refreshRecent(key(ref), client);\n return payment;\n });\n }\n\n /**\n * Pays a Spark invoice address. The approval intent mirrors `send`: receiver identity and amount\n * come from the parsed invoice (the supplied `amountSats` fills an open invoice). Then\n * `client.invoices.pay` executes it.\n */\n async paySparkInvoice(\n ref: SparkAccountRef,\n params: { invoice: string; amountSats?: number; verify: UnlockFactor },\n ): Promise<SparkTransfer> {\n return this.guarded(async () => {\n const client = this.clientFor(ref);\n const parsed = parseSparkInvoice(params.invoice, {\n network: ref.network,\n now: this.options.now(),\n });\n const invoicePayment = parsed.fields.payment;\n if (invoicePayment !== undefined && invoicePayment.type !== \"sats\") {\n throw new SparkControllerError(\n \"rejected\",\n \"spark invoice: only sats invoices are supported\",\n );\n }\n if (\n invoicePayment?.type === \"sats\" &&\n invoicePayment.amount !== undefined &&\n params.amountSats !== undefined &&\n params.amountSats !== invoicePayment.amount\n ) {\n throw new SparkControllerError(\n \"rejected\",\n \"spark invoice: amountSats conflicts with the invoice amount\",\n );\n }\n const amountSats =\n invoicePayment?.type === \"sats\" && invoicePayment.amount !== undefined\n ? invoicePayment.amount\n : params.amountSats;\n if (amountSats === undefined) {\n throw new SparkControllerError(\n \"rejected\",\n \"spark invoice: amountless invoice requires amountSats\",\n );\n }\n await this.options.spark.approve({\n account: ref,\n intent: {\n kind: \"transfer\",\n receivers: [{ identityPublicKey: parsed.receiverIdentityPublicKey, amountSats }],\n },\n verify: params.verify,\n });\n const result = await client.invoices.pay(params.invoice, {\n amount: amountSats,\n transferId: transferId(this.options.random, this.options.now),\n });\n void this.refreshRecent(key(ref), client);\n // invoices.pay returns a string for token invoices — unreachable after the pre-approval\n // sats check above, kept as the internal guard.\n if (typeof result === \"string\") {\n throw new SparkControllerError(\"internal\", \"unexpected token invoice result\");\n }\n return result;\n });\n }\n\n async createInvoice(\n ref: SparkAccountRef,\n params: { amountSats: number; memo?: string },\n ): Promise<LightningInvoice> {\n return this.guarded(async () =>\n this.clientFor(ref).lightning.createInvoice({\n amountSats: params.amountSats,\n ...(params.memo === undefined ? {} : { memo: params.memo }),\n }),\n );\n }\n\n async receiveAddress(ref: SparkAccountRef): Promise<string | undefined> {\n const state = this.getState().accounts[key(ref)];\n await Promise.resolve();\n return state?.sparkAddress;\n }\n\n /**\n * Cooperative exit to an L1 address. The client exits `amountSats` of leaves and the payout is\n * `amountSats - fee`, so the approval intent carries the PAYOUT: `amountSats: exit - fee` and\n * `maxFeeSats: fee` — the kernel matches the exit output against the intent, not the leaf total.\n */\n async withdraw(\n ref: SparkAccountRef,\n params: {\n address: string;\n amountSats?: number;\n speed: \"FAST\" | \"MEDIUM\" | \"SLOW\";\n maxFeeSats?: number;\n verify: UnlockFactor;\n },\n ): Promise<CooperativeExitResult> {\n return this.guarded(async () => {\n const client = this.clientFor(ref);\n try {\n bitcoinAddressScript(params.address, ref.network);\n } catch {\n throw new SparkControllerError(\"rejected\", \"withdrawal address is not on this network\");\n }\n const exitAmount = params.amountSats ?? (await client.balance());\n const quote = await client.withdrawals.quoteCooperativeExit({\n address: params.address,\n amountSats: exitAmount,\n });\n const fee =\n quote.fees[\n params.speed === \"FAST\" ? \"fast\" : params.speed === \"MEDIUM\" ? \"medium\" : \"slow\"\n ];\n if (params.maxFeeSats !== undefined && params.maxFeeSats < fee) {\n throw new SparkControllerError(\"rejected\", \"maxFeeSats below the quoted fee\");\n }\n if (fee >= exitAmount) {\n throw new SparkControllerError(\n \"insufficient-funds\",\n \"exit fee meets or exceeds the amount\",\n );\n }\n await this.options.spark.approve({\n account: ref,\n intent: {\n kind: \"exit\",\n address: params.address,\n amountSats: exitAmount - fee,\n maxFeeSats: fee,\n },\n verify: params.verify,\n });\n const exit = await client.withdrawals.cooperativeExit({\n address: params.address,\n speed: params.speed,\n maxFeeSats: fee,\n amountSats: exitAmount,\n transferId: transferId(this.options.random, this.options.now),\n });\n void this.refreshRecent(key(ref), client);\n return exit;\n });\n }\n}\n","/**\n * Composition root: wires the Wallet's lock state to the SparkController's lifecycle. Unlocked →\n * open the EngineStore and start every declared account; locked → abort event loops, close every\n * client, close the store and reset account state. Transitions are serialized on one promise chain,\n * so an unlock→lock flip can never overlap a still-opening store.\n */\nimport { createSparkClient } from \"@qntx/spark\";\nimport type { LightningPayment, SparkNetwork } from \"@qntx/spark\";\nimport type { Wallet } from \"@qntx/wallet\";\nimport { nostr } from \"@qntx/wallet/nostr\";\nimport type { SparkAccountRef } from \"@qntx/wallet/protocol\";\nimport { spark } from \"@qntx/wallet/spark\";\n\nimport { AccountTreeController } from \"./accounts/controller.ts\";\nimport { BackupController } from \"./backup/controller.ts\";\nimport type { CloudStore } from \"./backup/port.ts\";\nimport type { EngineLogger } from \"./events.ts\";\nimport { MetaSyncController } from \"./meta/controller.ts\";\nimport type { MetaSyncConfig } from \"./meta/controller.ts\";\nimport { parsePayment } from \"./payments/parse.ts\";\nimport type { PaymentParse } from \"./payments/parse.ts\";\nimport { pay as runPay } from \"./payments/pay.ts\";\nimport type { PayParams } from \"./payments/pay.ts\";\nimport { resolvePayment } from \"./payments/resolve.ts\";\nimport { payZap, prepareZap } from \"./payments/zap.ts\";\nimport type { PrepareZapParams, PreparedZap, PayZapOptions } from \"./payments/zap.ts\";\nimport { SparkController } from \"./spark/controller.ts\";\nimport type { SparkControllerOptions } from \"./spark/controller.ts\";\nimport type { EngineStore } from \"./store/port.ts\";\n\nexport type EngineOptions = {\n readonly wallet: Wallet;\n /** Every Spark account the engine touches lives on this network. */\n readonly sparkNetwork: SparkNetwork;\n readonly fetch: typeof globalThis.fetch;\n readonly random: (length: number) => Uint8Array;\n readonly now: () => number;\n readonly logger: EngineLogger;\n readonly openStore: () => Promise<EngineStore>;\n /** Cloud file transport for the backup controller; absent → `unavailable`. */\n readonly cloud?: CloudStore;\n /** Kind-30078 wallet-metadata sync; absent → every wallet reports `unavailable`. */\n readonly metaSync?: MetaSyncConfig;\n /** Test seam — defaults to the wallet's real spark proxy. */\n readonly sparkApis?: SparkControllerOptions[\"spark\"];\n};\n\nexport type WalletEngine = {\n readonly spark: SparkController;\n readonly accounts: AccountTreeController;\n readonly metaSync: MetaSyncController;\n readonly backup: BackupController;\n readonly zaps: {\n readonly prepare: (params: PrepareZapParams) => Promise<PreparedZap>;\n readonly pay: (\n account: SparkAccountRef,\n prepared: PreparedZap,\n options: Omit<PayZapOptions, \"now\">,\n ) => Promise<LightningPayment>;\n };\n readonly payments: {\n readonly parse: (input: string, network: SparkNetwork) => PaymentParse;\n readonly resolve: (input: string, network: SparkNetwork) => Promise<PaymentParse>;\n readonly pay: (params: PayParams) => Promise<unknown>;\n };\n readonly unsubscribe: () => void;\n};\n\nexport function createWalletEngine(options: EngineOptions): WalletEngine {\n const backup = new BackupController({\n wallet: options.wallet,\n cloud: options.cloud,\n now: options.now,\n logger: options.logger,\n });\n\n const controller = new SparkController({\n spark: options.sparkApis ?? spark(options.wallet),\n fetch: options.fetch,\n random: options.random,\n now: options.now,\n logger: options.logger,\n createClient: ({ ref, store, signer, fetch }) =>\n createSparkClient({\n network: ref.network,\n signer,\n store,\n fetch,\n }),\n });\n\n const accounts = new AccountTreeController({\n wallet: options.wallet,\n spark: controller,\n sparkNetwork: options.sparkNetwork,\n logger: options.logger,\n now: options.now,\n });\n\n const metaSync = new MetaSyncController({\n wallet: options.wallet,\n accounts,\n nostr: { signer: (ref) => nostr(options.wallet).signer(ref) },\n metaSync: options.metaSync,\n logger: options.logger,\n now: options.now,\n });\n\n // The transition chain: every status change queues behind the previous one, so a late lock\n // always observes the snapshot left by a settled unlock (and vice versa).\n let chain: Promise<void> = Promise.resolve();\n let store: EngineStore | undefined;\n let started = false;\n\n const transition = async (): Promise<void> => {\n const unlocked = options.wallet.getSnapshot().vault === \"unlocked\";\n if (unlocked && !started) {\n started = true;\n try {\n store = await options.openStore();\n } catch (error) {\n // No store, no clients — reset so the next status event retries cleanly.\n started = false;\n store = undefined;\n options.logger.warn(\"engine store failed to open\", error);\n return;\n }\n controller.setStore(store);\n backup.setStore(store);\n accounts.setStore(store);\n backup.trigger(); // reconcile — never awaited on the transition chain\n // Load + reconcile + drive the selected account through spark.setAccounts.\n await accounts.init();\n await controller.init();\n // Pull → merge → maybe publish for every wallet with a group-0 identity.\n await metaSync.init();\n } else if (!unlocked && started) {\n started = false;\n // Lock: cancel sync write-backs, tree → locked, spark.setAccounts([]), totals flush.\n await metaSync.lock();\n await accounts.lock();\n await controller.lockAll();\n controller.setStore(undefined);\n const s = store;\n store = undefined;\n await s?.close();\n }\n };\n\n const snapshotListener = (): void => {\n // Every snapshot change while unlocked nudges the reconcile; the lock transition is\n // handled inside transition() and bumps the backup generation.\n if (options.wallet.getSnapshot().vault === \"unlocked\") {\n backup.trigger();\n accounts.reconcile();\n metaSync.reconcile();\n } else {\n backup.lock();\n }\n };\n\n const schedule = (): void => {\n const previous = chain;\n chain = (async () => {\n try {\n await previous;\n await transition();\n } catch (error) {\n options.logger.warn(\"engine lock transition failed\", error);\n }\n })();\n };\n const unsubscribe = options.wallet.subscribe(() => {\n schedule();\n snapshotListener();\n });\n schedule();\n return {\n spark: controller,\n accounts,\n metaSync,\n backup,\n zaps: {\n prepare: async (params) => prepareZap(params, { fetch: options.fetch, now: options.now }),\n pay: async (account, prepared, payOptions) =>\n payZap(controller, account, prepared, { ...payOptions, now: options.now }),\n },\n payments: {\n parse: (input, network) => parsePayment(input, { network, now: options.now() }),\n resolve: async (input, network) =>\n resolvePayment(input, { network, now: options.now(), fetch: options.fetch }),\n pay: async (params) =>\n runPay({ spark: controller, fetch: options.fetch, now: options.now }, params),\n },\n unsubscribe,\n };\n}\n","import type { CloudStore } from \"./port.ts\";\n\nconst tick = Promise.resolve();\n\n/** In-memory CloudStore for tests and the playground; swap the Map for cross-engine sharing. */\nexport function createMemoryCloudStore(backing?: Map<string, string>): CloudStore {\n const files = backing ?? new Map<string, string>();\n let reachable = true;\n const store: CloudStore & { readonly setReachable: (v: boolean) => void } = {\n available: async () => {\n await tick;\n return reachable;\n },\n list: async () => {\n await tick;\n return [...files.keys()].sort();\n },\n read: async (name) => {\n await tick;\n return files.get(name);\n },\n write: async (name, text) => {\n await tick;\n files.set(name, text);\n },\n delete: async (name) => {\n await tick;\n files.delete(name);\n },\n setReachable: (v) => {\n reachable = v;\n },\n };\n return store;\n}\n"],"ignoreList":[7,8,9,10],"mappings":";;;;;;;;;;;;;;;AAaA,IAAsB,aAAtB,MAAoE;CAClE;CACA;CAEA,YAAsB,SAA+B;EACnD,KAAK,OAAO,QAAQ;EACpB,KAAK,QAAQ,YAAe,QAAQ,YAAY;CAClD;CAEA,WAAc;EACZ,OAAO,KAAK,MAAM,SAAS;CAC7B;CAEA,OAAiB,QAA+B;EAC9C,KAAK,MAAM,UAAU,UAAU,OAAO,KAAK,CAAC;CAC9C;AAIF;;;ACrBA,SAAgB,eAAkB,QAAmC;CACnE,MAAM,4BAAY,IAAI,IAA8C;CACpE,OAAO;EACL,KAAwB,MAAS,SAAqB;GACpD,MAAM,MAAM,UAAU,IAAI,IAAI;GAC9B,IAAI,QAAQ,KAAA,GACV;GAEF,KAAK,MAAM,YAAY,KACrB,IAAI;IACF,SAAS,OAAO;GAClB,SAAS,OAAO;IACd,OAAO,KAAK,wBAAwB,KAAK;GAC3C;EAEJ;EACA,GAAsB,MAAS,UAA+C;GAC5E,IAAI,MAAM,UAAU,IAAI,IAAI;GAC5B,IAAI,QAAQ,KAAA,GAAW;IACrB,sBAAM,IAAI,IAAI;IACd,UAAU,IAAI,MAAM,GAAG;GACzB;GAGA,MAAM,SAAS;GACf,IAAI,IAAI,MAAM;GACd,aAAa;IACX,IAAI,OAAO,MAAM;GACnB;EACF;CACF;AACF;;;;ACvCA,IAAa,mBAAb,cAAsC,MAAM;CAC1C;CAE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C;EAC7E;EACA,UAAU;GACR,QAAQ,OAAO,YAAY,aAAa,OAAO;IAAE;IAAS,KAAK,QAAQ,IAAI;GAAE,CAAC;GAC9E,SAAS,OAAO,OAAO,YACrB,eAAe,OAAO;IAAE;IAAS,KAAK,QAAQ,IAAI;IAAG,OAAO,QAAQ;GAAM,CAAC;GAC7E,KAAK,OAAO,WACVC,IAAO;IAAE,OAAO;IAAY,OAAO,QAAQ;IAAO,KAAK,QAAQ;GAAI,GAAG,MAAM;EAChF;EACA;CACF;AACF;;;AClMA,MAAM,OAAO,QAAQ,QAAQ;;AAG7B,SAAgB,uBAAuB,SAA2C;CAChF,MAAM,QAAQ,2BAAW,IAAI,IAAoB;CACjD,IAAI,YAAY;CA0BhB,OAAO;EAxBL,WAAW,YAAY;GACrB,MAAM;GACN,OAAO;EACT;EACA,MAAM,YAAY;GAChB,MAAM;GACN,OAAO,CAAC,GAAG,MAAM,KAAK,CAAC,CAAC,CAAC,KAAK;EAChC;EACA,MAAM,OAAO,SAAS;GACpB,MAAM;GACN,OAAO,MAAM,IAAI,IAAI;EACvB;EACA,OAAO,OAAO,MAAM,SAAS;GAC3B,MAAM;GACN,MAAM,IAAI,MAAM,IAAI;EACtB;EACA,QAAQ,OAAO,SAAS;GACtB,MAAM;GACN,MAAM,OAAO,IAAI;EACnB;EACA,eAAe,MAAM;GACnB,YAAY;EACd;CAES;AACb"}
1
+ {"version":3,"file":"index.mjs","names":["isObject","str","NAME_MAX","isNonNegativeInt","KNOWN_GROUP_KEYS","KNOWN_WALLET_KEYS","PUBKEY_RE","hex","obj","isObject","arr","COLLECTION","key","isObject","isObject","isObject","isObject","isObject","isObject","isObject","obj","isObject","runPay"],"sources":["../src/controller.ts","../src/events.ts","../src/errors.ts","../src/store/guard.ts","../src/store/memory.ts","../src/chains/bitcoin-scan.ts","../src/transactions/route.ts","../src/accounts/errors.ts","../src/accounts/controller.ts","../src/chains/evm.ts","../src/assets/controller.ts","../src/backup/errors.ts","../src/backup/controller.ts","../src/meta/doc.ts","../src/meta/errors.ts","../src/meta/controller.ts","../src/chains/bitcoin.ts","../src/networks/registry.ts","../src/networks/controller.ts","../src/payments/parse.ts","../src/spark/errors.ts","../src/payments/errors.ts","../src/payments/pay.ts","../src/payments/resolve.ts","../src/payments/zap.ts","../src/spark/notes.ts","../src/spark/exit-chain-codec.ts","../src/spark/store.ts","../src/spark/controller.ts","../src/transactions/bitcoin.ts","../src/transactions/evm.ts","../src/chains/solana.ts","../src/transactions/solana.ts","../src/transactions/controller.ts","../src/engine.ts","../src/backup/memory.ts"],"sourcesContent":["import { createStore } from \"zustand/vanilla\";\nimport type { StoreApi } from \"zustand/vanilla\";\n\nexport type ControllerOptions<S> = {\n readonly name: string;\n readonly defaultState: () => S;\n};\n\n/**\n * Controller base: a zustand vanilla store plus lifecycle. `update` applies a recipe that must\n * return a NEW state object; returning the same reference is a no-op (no set, no notification).\n * Persistence and migrations layer on later — this package carries only what its first user needs.\n */\nexport abstract class Controller<S extends Record<string, unknown>> {\n readonly name: string;\n readonly store: StoreApi<S>;\n\n protected constructor(options: ControllerOptions<S>) {\n this.name = options.name;\n this.store = createStore<S>(options.defaultState);\n }\n\n getState(): S {\n return this.store.getState();\n }\n\n protected update(recipe: (state: S) => S): void {\n this.store.setState((state) => recipe(state));\n }\n\n abstract init(): Promise<void>;\n abstract destroy(): Promise<void>;\n}\n","/** Log port: listener failures are reported here and never reach the emitter or peers. */\nexport type EngineLogger = {\n readonly warn: (message: string, error?: unknown) => void;\n};\n\nexport type EventBus<E> = {\n /** Synchronous dispatch to every current listener in registration order. */\n emit: <K extends keyof E>(type: K, payload: E[K]) => void;\n on: <K extends keyof E>(type: K, listener: (payload: E[K]) => void) => () => void;\n};\n\nexport function createEventBus<E>(logger: EngineLogger): EventBus<E> {\n const listeners = new Map<keyof E, Set<(payload: unknown) => void>>();\n return {\n emit<K extends keyof E>(type: K, payload: E[K]): void {\n const set = listeners.get(type);\n if (set === undefined) {\n return;\n }\n for (const listener of set) {\n try {\n listener(payload);\n } catch (error) {\n logger.warn(\"event listener threw\", error);\n }\n }\n },\n on<K extends keyof E>(type: K, listener: (payload: E[K]) => void): () => void {\n let set = listeners.get(type);\n if (set === undefined) {\n set = new Set();\n listeners.set(type, set);\n }\n // The set is keyed by event type, so each listener only ever receives its own payload.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const stored = listener as (payload: unknown) => void;\n set.add(stored);\n return () => {\n set.delete(stored);\n };\n },\n };\n}\n","export type EngineErrorCode = \"closed\" | \"integrity\" | \"invalid-input\";\n\n/** Typed engine errors: store codes are `closed` and `integrity` (decrypt or bind failure). */\nexport class EngineStoreError extends Error {\n readonly code: EngineErrorCode;\n\n constructor(code: EngineErrorCode, message: string) {\n super(message);\n this.name = \"EngineStoreError\";\n this.code = code;\n }\n}\n","import { EngineStoreError } from \"../errors.ts\";\n\n/** NUL is the composite-key/AAD separator — a name or key containing it collides. */\nexport function checkName(kind: \"collection\" | \"key\", value: string): void {\n if (value.includes(\"\\u0000\")) {\n throw new EngineStoreError(\"invalid-input\", `${kind} must not contain NUL`);\n }\n}\n","import { EngineStoreError } from \"../errors.ts\";\nimport { checkName } from \"./guard.ts\";\nimport type { EngineCollection, EngineStore } from \"./port.ts\";\n\n/** In-memory EngineStore: the Node/test implementation — same contract, no durability. */\nexport function createMemoryEngineStore(backing?: {\n readonly collections?: Map<string, Map<string, Uint8Array>>;\n}): EngineStore {\n const collections = backing?.collections ?? new Map<string, Map<string, Uint8Array>>();\n let closed = false;\n const guard = (): void => {\n if (closed) {\n throw new EngineStoreError(\"closed\", \"engine store is closed\");\n }\n };\n return {\n collection(name: string): EngineCollection {\n checkName(\"collection\", name);\n let table = collections.get(name);\n if (table === undefined) {\n table = new Map();\n collections.set(name, table);\n }\n return {\n get: async (key) => {\n guard();\n checkName(\"key\", key);\n const value = table.get(key);\n return value === undefined ? undefined : new Uint8Array(value);\n },\n put: async (key, bytes) => {\n guard();\n checkName(\"key\", key);\n table.set(key, new Uint8Array(bytes));\n },\n delete: async (key) => {\n guard();\n checkName(\"key\", key);\n table.delete(key);\n },\n list: async () => {\n guard();\n return [...table.keys()];\n },\n };\n },\n close: async () => {\n closed = true;\n collections.clear();\n },\n };\n}\n","/**\n * Gap-20 BIP-44/86 account scanning over Esplora — derives /0/* and /1/* from the account xpub,\n * walks each chain in windows until 20 consecutive unused addresses, persists the discovered\n * addresses/txs/UTXOs in EngineStore (rebuildable from a rescan), and exposes the next unused\n * receive/change address.\n */\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { Address, OutScript } from \"@scure/btc-signer\";\nimport type { NETWORK as BTC_NETWORK } from \"@scure/btc-signer\";\n\nimport type { BitcoinAccountTemplate } from \"@qntx/wallet-chains/bitcoin\";\nimport { bitcoinAddressFromXpub } from \"@qntx/wallet-chains/bitcoin\";\n\nimport type { EngineStore } from \"../store/port.ts\";\nimport type { Esplora } from \"./bitcoin.ts\";\n\nconst GAP = 20;\nconst COLL = \"btc-scan\";\n\nexport type BtcChain = 0 | 1;\n\nexport type ScanAddress = {\n readonly chain: BtcChain;\n readonly index: number;\n readonly address: string;\n readonly used: boolean;\n};\n\nexport type ScanUtxo = {\n readonly txid: string;\n readonly vout: number;\n readonly value: number;\n readonly address: string;\n readonly height: number;\n};\n\nexport type ScanState = {\n readonly addresses: ReadonlyArray<ScanAddress>;\n readonly utxos: ReadonlyArray<ScanUtxo>;\n readonly scannedAt: number;\n};\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null;\nconst isUnknownArray = (v: unknown): v is ReadonlyArray<unknown> => Array.isArray(v);\nconst asArray = (v: unknown): ReadonlyArray<unknown> => (isUnknownArray(v) ? v : []);\n\n/** The scriptPubKey bytes of a bech32/base58 address on `network`. */\nexport const scriptPubKey = (address: string, network: typeof BTC_NETWORK): Uint8Array =>\n OutScript.encode(Address(network).decode(address));\n\n/** Esplora scripthash: sha256 of the scriptPubKey, digest hex as-is (verified vs electrs REST). */\nexport const scripthash = (address: string, network: typeof BTC_NETWORK): string =>\n [...sha256(OutScript.encode(Address(network).decode(address)))]\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n\nconst windowUsed = async (\n es: Esplora,\n params: typeof BTC_NETWORK,\n addrs: ReadonlyArray<ScanAddress>,\n): Promise<ReadonlyArray<boolean>> =>\n Promise.all(\n addrs.map(async (a) => {\n const txs: unknown = await es.get(`/scripthash/${scripthash(a.address, params)}/txs`);\n return isUnknownArray(txs) && txs.length > 0;\n }),\n );\n\nexport const scanChain = async (\n es: Esplora,\n xpub: string,\n template: BitcoinAccountTemplate,\n network: string,\n params: typeof BTC_NETWORK,\n chain: BtcChain,\n start = 0,\n): Promise<ReadonlyArray<ScanAddress>> => {\n const batch: ScanAddress[] = Array.from({ length: GAP }, (_, i) => {\n const index = start + i;\n return {\n chain,\n index,\n address: bitcoinAddressFromXpub(xpub, template, network, chain, index),\n used: false,\n };\n });\n const used = await windowUsed(es, params, batch);\n const marked = batch.map((a, i) => ({\n chain: a.chain,\n index: a.index,\n address: a.address,\n used: used[i] === true,\n }));\n if (!marked.some((a) => a.used)) {\n return marked;\n }\n const rest = await scanChain(es, xpub, template, network, params, chain, start + GAP);\n return [...marked, ...rest];\n};\n\nconst scanAddressUtxos = async (\n es: Esplora,\n a: ScanAddress,\n params: typeof BTC_NETWORK,\n): Promise<ReadonlyArray<ScanUtxo>> => {\n const utxos: unknown = await es.get(`/scripthash/${scripthash(a.address, params)}/utxo`);\n return asArray(utxos).flatMap((u): ScanUtxo[] => {\n const o = isObject(u) ? u : {};\n const status = isObject(o[\"status\"]) ? o[\"status\"] : {};\n const txid = typeof o[\"txid\"] === \"string\" ? o[\"txid\"] : \"\";\n if (txid === \"\") {\n return [];\n }\n return [\n {\n txid,\n vout: typeof o[\"vout\"] === \"number\" ? o[\"vout\"] : 0,\n value: typeof o[\"value\"] === \"number\" ? o[\"value\"] : 0,\n address: a.address,\n height: typeof status[\"block_height\"] === \"number\" ? status[\"block_height\"] : 0,\n },\n ];\n });\n};\n\nexport const scanUtxos = async (\n es: Esplora,\n addresses: ReadonlyArray<ScanAddress>,\n params: typeof BTC_NETWORK,\n): Promise<ReadonlyArray<ScanUtxo>> => {\n const candidates = addresses.filter((a) => a.used || a.chain === 1 || a.index < GAP);\n return Promise.all(candidates.map(async (a) => scanAddressUtxos(es, a, params))).then((r) =>\n r.flat(),\n );\n};\n\nexport class BitcoinScanStore {\n private engineStore: EngineStore | undefined;\n\n async unlock(store: EngineStore): Promise<ScanState | undefined> {\n this.engineStore = store;\n const raw = await store.collection(COLL).get(\"state\");\n const parsed: unknown =\n raw === undefined ? undefined : JSON.parse(new TextDecoder().decode(raw));\n if (\n !isObject(parsed) ||\n !Array.isArray(parsed[\"addresses\"]) ||\n !Array.isArray(parsed[\"utxos\"])\n ) {\n return undefined;\n }\n const state: ScanState = {\n addresses: asArray(parsed[\"addresses\"]).flatMap((a) => toScanAddress(a)),\n utxos: asArray(parsed[\"utxos\"]).flatMap((u) => toScanUtxo(u)),\n scannedAt: typeof parsed[\"scannedAt\"] === \"number\" ? parsed[\"scannedAt\"] : 0,\n };\n return state;\n }\n\n async persist(state: ScanState): Promise<void> {\n const store = this.engineStore;\n if (store !== undefined) {\n await store.collection(COLL).put(\"state\", new TextEncoder().encode(JSON.stringify(state)));\n }\n }\n\n nextUnused(state: ScanState, chain: BtcChain): ScanAddress | undefined {\n return state.addresses.find((a) => a.chain === chain && !a.used);\n }\n\n lock(): void {\n this.engineStore = undefined;\n }\n}\n\nconst str = (v: unknown): string | undefined => (typeof v === \"string\" ? v : undefined);\nconst num = (v: unknown): number | undefined => (typeof v === \"number\" ? v : undefined);\n\nconst toScanAddress = (v: unknown): ScanAddress[] => {\n if (!isObject(v)) {\n return [];\n }\n const chain = num(v[\"chain\"]);\n const index = num(v[\"index\"]);\n const address = str(v[\"address\"]);\n const used = v[\"used\"] === true;\n return chain !== undefined &&\n index !== undefined &&\n address !== undefined &&\n (chain === 0 || chain === 1)\n ? [{ chain: chain === 0 ? (0 as const) : (1 as const), index, address, used }]\n : [];\n};\n\nconst toScanUtxo = (v: unknown): ScanUtxo[] => {\n if (!isObject(v)) {\n return [];\n }\n const txid = str(v[\"txid\"]);\n const vout = num(v[\"vout\"]);\n const value = num(v[\"value\"]);\n const address = str(v[\"address\"]);\n const height = num(v[\"height\"]);\n return txid !== undefined && vout !== undefined && value !== undefined && address !== undefined\n ? [{ txid, vout, value, address, height: height ?? 0 }]\n : [];\n};\n\nconst toLockedUtxo = (v: unknown): LockedUtxo | undefined => {\n const [base] = toScanUtxo(v);\n if (base === undefined || !isObject(v)) {\n return undefined;\n }\n const status = str(v[\"status\"]);\n const txId = str(v[\"txId\"]);\n if (status !== \"confirmed\" && status !== \"locked\" && status !== \"frozen\") {\n return undefined;\n }\n const locked: LockedUtxo =\n txId === undefined\n ? {\n txid: base.txid,\n vout: base.vout,\n value: base.value,\n address: base.address,\n height: base.height,\n status,\n }\n : {\n txid: base.txid,\n vout: base.vout,\n value: base.value,\n address: base.address,\n height: base.height,\n status,\n txId,\n };\n return locked;\n};\n\n/** Persistent UTXO lock/spent lifecycle — locked by an in-flight tx, released or spent at its end. */\nexport type LockedUtxo = ScanUtxo & {\n readonly status: \"confirmed\" | \"locked\" | \"frozen\";\n readonly txId?: string;\n};\n\nexport class BtcUtxoStore {\n private engineStore: EngineStore | undefined;\n private utxos = new Map<string, LockedUtxo>();\n\n async unlock(store: EngineStore): Promise<void> {\n this.engineStore = store;\n const raw = await store.collection(\"btc-utxos\").get(\"state\");\n this.utxos =\n raw === undefined\n ? new Map<string, LockedUtxo>()\n : new Map<string, LockedUtxo>(\n Object.entries(\n ((): Record<string, LockedUtxo> => {\n const rawParsed: unknown = JSON.parse(new TextDecoder().decode(raw));\n const parsed = isObject(rawParsed) ? rawParsed : {};\n const pairs: ReadonlyArray<readonly [string, LockedUtxo]> = Object.entries(\n parsed,\n ).flatMap(([k, v]) => {\n const u = toLockedUtxo(v);\n return u === undefined ? [] : [[k, u] as const];\n });\n return Object.fromEntries(pairs);\n })(),\n ),\n );\n }\n\n private async persist(): Promise<void> {\n const store = this.engineStore;\n if (store !== undefined) {\n await store\n .collection(\"btc-utxos\")\n .put(\"state\", new TextEncoder().encode(JSON.stringify(Object.fromEntries(this.utxos))));\n }\n }\n\n private static key(u: { txid: string; vout: number }): string {\n return `${u.txid}:${u.vout}`;\n }\n\n replace(utxos: ReadonlyArray<ScanUtxo>): void {\n const locked = [...this.utxos.entries()].filter(\n ([, u]) => u.status === \"locked\" || u.status === \"frozen\",\n );\n this.utxos = new Map(\n utxos.map((u) => [\n BtcUtxoStore.key(u),\n {\n txid: u.txid,\n vout: u.vout,\n value: u.value,\n address: u.address,\n height: u.height,\n status: \"confirmed\" as const,\n },\n ]),\n );\n for (const [k, u] of locked) {\n this.utxos.set(k, u);\n }\n }\n\n lock(utxos: ReadonlyArray<ScanUtxo>, txId: string): void {\n for (const u of utxos) {\n this.utxos.set(BtcUtxoStore.key(u), {\n txid: u.txid,\n vout: u.vout,\n value: u.value,\n address: u.address,\n height: u.height,\n status: \"locked\",\n txId,\n });\n }\n void this.persist();\n }\n\n /** Released on failed/rejected/dropped; spent-removed on confirmed. */\n endTx(txId: string, final: \"confirmed\" | \"failed\" | \"rejected\" | \"dropped\"): void {\n if (final === \"confirmed\") {\n for (const [k, u] of this.utxos) {\n if (u.txId === txId) {\n this.utxos.delete(k);\n }\n }\n } else {\n for (const [k, u] of this.utxos) {\n if (u.txId === txId && u.status === \"locked\") {\n this.utxos.set(k, {\n txid: u.txid,\n vout: u.vout,\n value: u.value,\n address: u.address,\n height: u.height,\n status: \"confirmed\",\n });\n }\n }\n }\n void this.persist();\n }\n\n spendable(): ReadonlyArray<LockedUtxo> {\n return [...this.utxos.values()].filter(\n (u) => u.status === \"confirmed\" && !(u.value === 546 || u.value === 330),\n );\n }\n\n frozen(): ReadonlyArray<LockedUtxo> {\n return [...this.utxos.values()].filter(\n (u) => u.status === \"frozen\" || u.value === 546 || u.value === 330,\n );\n }\n\n all(): ReadonlyArray<LockedUtxo> {\n return [...this.utxos.values()];\n }\n\n lockStore(): void {\n this.engineStore = undefined;\n }\n}\n","/**\n * Per-chain route interface: each family module owns build → sign → broadcast and its status poll;\n * the controller owns lifecycle, persistence and the polling timer.\n */\nimport type { Wallet } from \"@qntx/wallet\";\nimport type { decodeEvm } from \"@qntx/wallet-chains/evm\";\nimport type { chains } from \"@qntx/wallet/chains\";\n\nimport type { EvmFeeTier } from \"../chains/evm.ts\";\nimport type { SolanaFeeTier } from \"../chains/solana.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport type { NetworkController } from \"../networks/controller.ts\";\nimport type { EngineStore } from \"../store/port.ts\";\n\nexport type SignParams = Parameters<ReturnType<typeof chains>[\"sign\"]>[0];\nexport type AccountRef = SignParams[\"request\"][\"account\"];\nexport type DisplayIntent = ReturnType<typeof decodeEvm>;\n\nexport type TxState =\n | \"draft\"\n | \"signed\"\n | \"submitted\"\n | \"pending\"\n | \"confirmed\"\n | \"failed\"\n | \"rejected\"\n | \"dropped\"\n | \"replaced\";\n\nexport type TrackedTransaction = {\n readonly id: string;\n readonly family: \"evm\" | \"solana\" | \"bitcoin\";\n readonly network: string;\n readonly account: string;\n readonly hash: string | undefined;\n readonly state: TxState;\n readonly intent: DisplayIntent | undefined;\n readonly nonce: number;\n /** Solana only — the blockhash expiry that turns an unconfirmed tx `dropped`. */\n readonly lastValidBlockHeight?: number;\n /** EVM replacement — the earlier transaction this one bumps or cancels. */\n readonly replaces?: string;\n /** CPFP — the unconfirmed parent this child pushes. */\n readonly parentId?: string;\n /** Bitcoin build record persisted at send for RBF/CPFP rebuilds. */\n readonly btc?: {\n readonly inputs: ReadonlyArray<{\n readonly txid: string;\n readonly vout: number;\n readonly value: number;\n readonly address: string;\n }>;\n readonly outputs: ReadonlyArray<{\n readonly address: string;\n readonly value: number;\n readonly own: boolean;\n }>;\n readonly vsize: number;\n readonly fee: number;\n readonly feeRate: number;\n };\n readonly submittedAt: number;\n readonly error: string | undefined;\n};\n\nexport type SendParams = {\n readonly account: AccountRef;\n readonly network: string;\n readonly to: string;\n readonly amount: bigint;\n /** ERC-20 contract — when set, `to`/`amount` are the transfer recipient/units and value is 0. */\n readonly token?: string;\n readonly fee: EvmFeeTier | SolanaFeeTier;\n /** SPL mint decimals — required when `token` is a Solana mint. */\n readonly decimals?: number;\n readonly verify: SignParams[\"verify\"];\n};\n\nexport type Options = {\n readonly wallet: Wallet;\n readonly networks: NetworkController;\n readonly openStore: () => Promise<EngineStore>;\n readonly random: (n: number) => Uint8Array;\n readonly setTimer: (ms: number, fn: () => unknown) => () => void;\n readonly now: () => number;\n readonly logger: EngineLogger;\n readonly pollMs?: number;\n /** Test seam — defaults to the wallet's real chains proxy. */\n readonly chains?: ReturnType<typeof chains>;\n};\n\nexport type RouteContext = {\n readonly options: Options;\n readonly transition: (\n tx: TrackedTransaction,\n next: Partial<TrackedTransaction>,\n ) => Promise<TrackedTransaction>;\n readonly track: (id: string, hash: string) => void;\n readonly newId: () => string;\n};\n\nexport const newId = (random: (n: number) => Uint8Array): string =>\n `tx-${[...random(8)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\")}`;\n\nexport const errorMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n","/** Account-tree error categories — messages never carry secrets. */\nexport type AccountTreeErrorCategory = \"invalid-input\" | \"rejected\" | \"not-found\" | \"locked\";\n\nexport class AccountTreeError extends Error {\n readonly category: AccountTreeErrorCategory;\n\n constructor(category: AccountTreeErrorCategory, message: string, cause?: unknown) {\n super(message, { cause });\n this.name = \"AccountTreeError\";\n this.category = category;\n }\n}\n","import { isAddress } from \"viem\";\n\nimport type { SparkNetwork } from \"@qntx/spark\";\nimport type { Wallet } from \"@qntx/wallet\";\nimport { bitcoinNetwork } from \"@qntx/wallet-chains/bitcoin\";\nimport { chains } from \"@qntx/wallet/chains\";\n\nimport { scanChain } from \"../chains/bitcoin-scan.ts\";\nimport type { Esplora } from \"../chains/bitcoin.ts\";\nimport { Controller } from \"../controller.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport type { MetaDoc, MetaDocGroup } from \"../meta/doc.ts\";\nimport type { SparkController } from \"../spark/controller.ts\";\nimport type { EngineCollection, EngineStore } from \"../store/port.ts\";\nimport { errorMessage } from \"../transactions/route.ts\";\nimport { AccountTreeError } from \"./errors.ts\";\n\nexport type AccountGroup = {\n readonly walletId: string;\n readonly index: number;\n /** `discoverGroups` result — family key → used; a family error lives under `errors`. */\n readonly used?: Readonly<Record<string, boolean>>;\n readonly errors?: Readonly<Record<string, string>>;\n readonly name?: string;\n readonly hidden: boolean;\n /** A social identity (64 lowercase hex) bound to this group; one identity binds one group. */\n readonly boundPubkey?: string;\n /** Last local modification time (ms); reconcile-created entries start at 0. */\n readonly updatedAt: number;\n};\n\nexport type AccountTreeState = {\n readonly status: \"locked\" | \"ready\";\n readonly wallets: ReadonlyArray<{\n readonly walletId: string;\n readonly name?: string;\n readonly updatedAt: number;\n }>;\n readonly groups: Readonly<Record<string, ReadonlyArray<AccountGroup>>>;\n // oxlint-disable-next-line typescript/no-restricted-types -- spec shape: no wallets → null\n readonly selected: { readonly walletId: string; readonly groupIndex: number } | null;\n readonly totals: Readonly<Record<string, number>>;\n};\n\ntype DiscoveryNetworks = {\n readonly client: (network: string) => {\n readonly getTransactionCount: (p: {\n readonly address: `0x${string}`;\n readonly blockTag: \"latest\";\n }) => Promise<number>;\n readonly getBalance: (p: { readonly address: `0x${string}` }) => Promise<bigint>;\n };\n readonly solanaRpc: (network: string) => {\n readonly call: (method: string, params: unknown[]) => Promise<unknown>;\n };\n readonly esplora: (network: string) => Esplora;\n readonly enabled: (family: \"evm\" | \"solana\" | \"bitcoin\") => ReadonlyArray<string>;\n};\n\nexport type AccountTreeControllerOptions = {\n readonly wallet: Wallet;\n readonly spark: SparkController;\n readonly sparkNetwork: SparkNetwork;\n readonly networks?: DiscoveryNetworks;\n readonly chains?: {\n readonly account: (params: {\n readonly walletId: string;\n readonly groupIndex: number;\n readonly template: string;\n readonly network: string;\n }) => Promise<{ readonly address?: string; readonly xpub?: string }>;\n };\n readonly logger: EngineLogger;\n readonly now: () => number;\n};\n\ntype PersistedTree = {\n readonly wallets: Readonly<\n Record<string, { readonly name?: string; readonly updatedAt: number }>\n >;\n readonly groups: Readonly<Record<string, ReadonlyArray<AccountGroup>>>;\n // oxlint-disable-next-line typescript/no-restricted-types -- wire contract: selected may be null\n readonly selected: { readonly walletId: string; readonly groupIndex: number } | null;\n readonly totals: Readonly<Record<string, number>>;\n};\n\nconst EMPTY_TREE: PersistedTree = { wallets: {}, groups: {}, selected: null, totals: {} };\n\nconst TOTAL_KEY = (walletId: string, index: number): string => `${walletId}:${index}`;\n\nconst withoutBinding = (g: AccountGroup): AccountGroup => {\n const { boundPubkey: _removed, ...rest } = g;\n void _removed;\n return rest;\n};\n\nconst NAME_MAX = 24;\nconst TOTALS_DEBOUNCE_MS = 1000;\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\nconst own = (o: Record<string, unknown>, k: string): boolean => Object.hasOwn(o, k);\n\nconst isNonNegativeInt = (v: unknown): v is number =>\n typeof v === \"number\" && Number.isSafeInteger(v) && v >= 0;\n\nfunction validateName(v: unknown): string | undefined {\n if (v === undefined) {\n return undefined;\n }\n if (typeof v !== \"string\") {\n return undefined;\n }\n const name = v.trim();\n return name.length > 0 && name.length <= NAME_MAX ? name : undefined;\n}\n\nconst KNOWN_GROUP_KEYS = new Set([\n \"walletId\",\n \"index\",\n \"name\",\n \"hidden\",\n \"boundPubkey\",\n \"updatedAt\",\n]);\nconst KNOWN_TOP_KEYS = new Set([\"wallets\", \"groups\", \"selected\", \"totals\"]);\nconst KNOWN_WALLET_KEYS = new Set([\"name\", \"updatedAt\"]);\nconst KNOWN_SELECTED_KEYS = new Set([\"walletId\", \"groupIndex\"]);\n\nconst PUBKEY_RE = /^[0-9a-f]{64}$/;\n\n/** Strict decode — any malformed shape or unknown key returns `undefined`. */\nfunction decodeTree(bytes: Uint8Array): PersistedTree | undefined {\n try {\n const text = new TextDecoder().decode(bytes);\n const raw: unknown = JSON.parse(text);\n if (!isPlainObject(raw)) {\n return undefined;\n }\n for (const k of Object.keys(raw)) {\n if (!KNOWN_TOP_KEYS.has(k)) {\n return undefined;\n }\n }\n const rawWallets = raw[\"wallets\"];\n const rawGroups = raw[\"groups\"];\n const rawSelected = raw[\"selected\"];\n const rawTotals = raw[\"totals\"];\n if (!isPlainObject(rawWallets) || !isPlainObject(rawGroups) || !isPlainObject(rawTotals)) {\n return undefined;\n }\n const wallets: Record<string, { name?: string; updatedAt: number }> = {};\n for (const [walletId, w] of Object.entries(rawWallets)) {\n if (!isPlainObject(w) || walletId.length === 0) {\n return undefined;\n }\n for (const k of Object.keys(w)) {\n if (!KNOWN_WALLET_KEYS.has(k)) {\n return undefined;\n }\n }\n const name = validateName(w[\"name\"]);\n if (w[\"name\"] !== undefined && name === undefined) {\n return undefined;\n }\n const { updatedAt } = w;\n if (!isNonNegativeInt(updatedAt)) {\n return undefined;\n }\n wallets[walletId] = { updatedAt, ...(name === undefined ? {} : { name }) };\n }\n const groups: Record<string, AccountGroup[]> = {};\n for (const [walletId, arr] of Object.entries(rawGroups)) {\n if (!Array.isArray(arr)) {\n return undefined;\n }\n const seen = new Set<number>();\n const list: AccountGroup[] = [];\n for (const item of arr) {\n if (!isPlainObject(item)) {\n return undefined;\n }\n for (const k of Object.keys(item)) {\n if (!KNOWN_GROUP_KEYS.has(k)) {\n return undefined;\n }\n }\n if (item[\"walletId\"] !== walletId || !isNonNegativeInt(item[\"index\"])) {\n return undefined;\n }\n const { index } = item;\n if (seen.has(index) || (item[\"hidden\"] !== true && item[\"hidden\"] !== false)) {\n return undefined;\n }\n seen.add(index);\n const name = validateName(item[\"name\"]);\n if (item[\"name\"] !== undefined && name === undefined) {\n return undefined;\n }\n const { updatedAt } = item;\n if (!isNonNegativeInt(updatedAt)) {\n return undefined;\n }\n const { boundPubkey } = item;\n if (\n boundPubkey !== undefined &&\n (typeof boundPubkey !== \"string\" || !PUBKEY_RE.test(boundPubkey))\n ) {\n return undefined;\n }\n list.push({\n walletId,\n index,\n hidden: item[\"hidden\"],\n updatedAt,\n ...(name === undefined ? {} : { name }),\n ...(boundPubkey === undefined ? {} : { boundPubkey }),\n });\n }\n list.sort((a, b) => a.index - b.index);\n groups[walletId] = list;\n }\n let selected: PersistedTree[\"selected\"] = null;\n if (rawSelected !== undefined && rawSelected !== null) {\n if (!isPlainObject(rawSelected)) {\n return undefined;\n }\n for (const k of Object.keys(rawSelected)) {\n if (!KNOWN_SELECTED_KEYS.has(k)) {\n return undefined;\n }\n }\n const { walletId } = rawSelected;\n const { groupIndex } = rawSelected;\n if (typeof walletId !== \"string\" || walletId.length === 0 || !isNonNegativeInt(groupIndex)) {\n return undefined;\n }\n selected = { walletId, groupIndex };\n }\n const totals: Record<string, number> = {};\n for (const [k, v] of Object.entries(rawTotals)) {\n if (!own(rawTotals, k) || !isNonNegativeInt(v)) {\n return undefined;\n }\n totals[k] = v;\n }\n return { wallets, groups, selected, totals };\n } catch {\n return undefined;\n }\n}\n\nfunction encodeTree(tree: PersistedTree): Uint8Array {\n return new TextEncoder().encode(JSON.stringify(tree));\n}\n\n/**\n * Declarative account tree: wallets come from the Wallet snapshot (reconciled on unlock and on\n * every snapshot change while unlocked), groups/names/hidden/selected/totals persist to the engine\n * store under `accounts/tree`. The controller drives `spark.setAccounts` with the selected group\n * only — an unselected group needs no live client (incoming transfers are claimed whenever it is\n * selected again). The active account's `balanceSats` feeds `totals`, debounced 1 s before\n * persist.\n */\nconst check = async (\n family: string,\n run: () => Promise<boolean>,\n): Promise<readonly [string, { readonly used: boolean; readonly error?: string }]> => {\n try {\n return [family, { used: await run() }] as const;\n } catch (error) {\n return [family, { used: false, error: errorMessage(error) }] as const;\n }\n};\n\nconst evmAddress = (v: unknown): `0x${string}` | undefined =>\n typeof v === \"string\" && isAddress(v) ? v : undefined;\n\nconst addressOf = (v: unknown): string | undefined => (typeof v === \"string\" ? v : undefined);\n\nexport class AccountTreeController extends Controller<AccountTreeState> {\n private readonly options: AccountTreeControllerOptions;\n private col: EngineCollection | undefined;\n private sparkUnsubscribe: (() => void) | undefined;\n private totalsTimer: ReturnType<typeof setTimeout> | undefined;\n private persistChain: Promise<void> = Promise.resolve();\n\n constructor(options: AccountTreeControllerOptions) {\n super({\n name: \"accounts\",\n defaultState: () => ({\n status: \"locked\",\n wallets: [],\n groups: {},\n selected: null,\n totals: {},\n }),\n });\n this.options = options;\n }\n\n setStore(store: EngineStore | undefined): void {\n this.col = store === undefined ? undefined : store.collection(\"accounts\");\n }\n\n /** Load persisted state, reconcile with the snapshot, start driving Spark. */\n async init(): Promise<void> {\n const persisted = await this.load();\n this.update(() => ({ status: \"ready\", ...persistedToState(persisted) }));\n this.reconcile();\n // First drive: the reconciled selection always starts a client for it.\n this.driveSpark(this.getState().selected);\n this.sparkUnsubscribe = this.options.spark.store.subscribe((state) => {\n this.onSparkState(state.accounts);\n });\n }\n\n async destroy(): Promise<void> {\n this.sparkUnsubscribe?.();\n this.sparkUnsubscribe = undefined;\n await this.lock();\n }\n\n /** Locked: stop every Spark client, flush pending persists, then drop to the empty state. */\n async lock(): Promise<void> {\n this.sparkUnsubscribe?.();\n this.sparkUnsubscribe = undefined;\n this.options.spark.setAccounts([]);\n // Flush while the real state is still visible — updating first would persist empties over\n // names, groups, hidden flags and the selection.\n await this.flushTotals();\n this.col = undefined;\n this.update(() => ({\n status: \"locked\",\n wallets: [],\n groups: {},\n selected: null,\n totals: {},\n }));\n await Promise.resolve();\n }\n\n /** Reconcile groups/names/selected with `wallet.getSnapshot().wallets`; persists on change. */\n reconcile(): void {\n if (this.getState().status !== \"ready\") {\n return;\n }\n const snapshot = this.options.wallet.getSnapshot();\n const live = snapshot.wallets.map((w) => w.walletId);\n const liveSet = new Set(live);\n const state = this.getState();\n const entriesById = new Map(state.wallets.map((w) => [w.walletId, w]));\n const wallets = live.map((walletId) => {\n const existing = entriesById.get(walletId);\n return existing ?? { walletId, updatedAt: 0 };\n });\n const groups: Record<string, ReadonlyArray<AccountGroup>> = {};\n for (const walletId of live) {\n const existing = state.groups[walletId] ?? [];\n groups[walletId] =\n existing.length > 0 ? existing : [{ walletId, index: 0, hidden: false, updatedAt: 0 }];\n }\n const totals: Record<string, number> = {};\n for (const [k, v] of Object.entries(state.totals)) {\n const walletId = k.slice(0, Math.max(0, k.lastIndexOf(\":\")));\n if (liveSet.has(walletId)) {\n totals[k] = v;\n }\n }\n const selected = this.validSelection(groups, live, state.selected);\n const changed =\n JSON.stringify(wallets) !== JSON.stringify(state.wallets) ||\n JSON.stringify(groups) !== JSON.stringify(state.groups) ||\n JSON.stringify(totals) !== JSON.stringify(state.totals) ||\n JSON.stringify(selected) !== JSON.stringify(state.selected);\n if (changed) {\n this.update((s) => ({ ...s, wallets, groups, totals, selected }));\n this.persist();\n // Drive only on effective change — an unchanged reconcile must not stomp a caller-set\n // setAccounts (e.g. tests running two accounts at once).\n this.driveSpark(selected);\n }\n }\n\n addGroup(walletId: string): number {\n this.mustWallet(walletId);\n const groups = this.getState().groups[walletId] ?? [];\n let index = 0;\n for (const g of groups) {\n index = Math.max(index, g.index + 1);\n }\n const updatedAt = this.options.now();\n this.mutateGroups(walletId, (list) => [...list, { walletId, index, hidden: false, updatedAt }]);\n return index;\n }\n\n addGroups(walletId: string, indices: ReadonlyArray<number>): void {\n this.mustWallet(walletId);\n this.mutateGroups(walletId, (list) => {\n const have = new Set(list.map((g) => g.index));\n const added: AccountGroup[] = [];\n const updatedAt = this.options.now();\n for (const i of indices) {\n if (Number.isSafeInteger(i) && i >= 0 && !have.has(i)) {\n have.add(i);\n added.push({ walletId, index: i, hidden: false, updatedAt });\n }\n }\n return [...list, ...added].sort((a, b) => a.index - b.index);\n });\n }\n\n renameWallet(walletId: string, name: string): void {\n this.mustWallet(walletId);\n const trimmed = this.checkedName(name);\n const updatedAt = this.options.now();\n this.update((s) => ({\n ...s,\n wallets: s.wallets.map((w) =>\n w.walletId === walletId ? { walletId, name: trimmed, updatedAt } : w,\n ),\n }));\n this.persist();\n }\n\n renameGroup(walletId: string, index: number, name: string): void {\n this.mustGroup(walletId, index);\n const trimmed = this.checkedName(name);\n const updatedAt = this.options.now();\n this.mutateGroups(walletId, (list) =>\n list.map((g) => (g.index === index ? { ...g, name: trimmed, updatedAt } : g)),\n );\n }\n\n setHidden(walletId: string, index: number, hidden: boolean): void {\n const state = this.getState();\n this.mustGroup(walletId, index);\n const visible = this.visibleGroups(state).filter(\n (g) => !(g.walletId === walletId && g.index === index),\n );\n if (hidden && visible.length === 0) {\n throw new AccountTreeError(\"rejected\", \"cannot hide every account group\");\n }\n const updatedAt = this.options.now();\n this.mutateGroups(walletId, (list) =>\n list.map((g) => (g.index === index ? { ...g, hidden, updatedAt } : g)),\n );\n const sel = state.selected;\n if (sel !== null && sel.walletId === walletId && sel.groupIndex === index && hidden) {\n this.selectFallback();\n }\n }\n\n select(walletId: string, index: number): void {\n const state = this.getState();\n const group = (state.groups[walletId] ?? []).find((g) => g.index === index);\n if (group === undefined) {\n throw new AccountTreeError(\"not-found\", \"account group does not exist\");\n }\n if (group.hidden) {\n throw new AccountTreeError(\"rejected\", \"cannot select a hidden account group\");\n }\n if (state.selected?.walletId === walletId && state.selected.groupIndex === index) {\n return;\n }\n this.update((s) => ({ ...s, selected: { walletId, groupIndex: index } }));\n this.persist();\n this.driveSpark(this.getState().selected);\n }\n\n /**\n * Binds a social identity to one group. The identity is unique across the whole tree — every\n * group in every wallet carrying it loses the binding (each entry re-stamped).\n */\n bind(walletId: string, index: number, pubkey: string): void {\n this.mustGroup(walletId, index);\n if (!PUBKEY_RE.test(pubkey)) {\n throw new AccountTreeError(\"invalid-input\", \"boundPubkey must be 64 lowercase hex\");\n }\n const updatedAt = this.options.now();\n this.update((s) => ({\n ...s,\n groups: Object.fromEntries(\n Object.entries(s.groups).map(([wid, list]) => [\n wid,\n list.map((g) => {\n if (wid === walletId && g.index === index) {\n return { ...g, boundPubkey: pubkey, updatedAt };\n }\n if (g.boundPubkey === pubkey) {\n return { ...withoutBinding(g), updatedAt };\n }\n return g;\n }),\n ]),\n ),\n }));\n this.persist();\n }\n\n unbind(walletId: string, index: number): void {\n this.mustGroup(walletId, index);\n const updatedAt = this.options.now();\n this.mutateGroups(walletId, (list) =>\n list.map((g) => (g.index === index ? { ...withoutBinding(g), updatedAt } : g)),\n );\n }\n\n /**\n * Which group currently holds a pubkey — merges can leave the same identity on groups in two\n * wallets; the newest `updatedAt` wins, ties resolve by snapshot wallet order then lower index.\n */\n bindingOf(pubkey: string): { walletId: string; groupIndex: number } | undefined {\n const s = this.getState();\n let best:\n | { walletId: string; groupIndex: number; updatedAt: number; walletPos: number }\n | undefined;\n let walletPos = -1;\n for (const w of s.wallets) {\n walletPos += 1;\n for (const g of s.groups[w.walletId] ?? []) {\n if (g.boundPubkey !== pubkey) {\n continue;\n }\n if (\n best === undefined ||\n g.updatedAt > best.updatedAt ||\n (g.updatedAt === best.updatedAt &&\n (walletPos < best.walletPos ||\n (walletPos === best.walletPos && g.index < best.groupIndex)))\n ) {\n best = { walletId: w.walletId, groupIndex: g.index, updatedAt: g.updatedAt, walletPos };\n }\n }\n }\n return best === undefined\n ? undefined\n : { walletId: best.walletId, groupIndex: best.groupIndex };\n }\n\n /** The wallet's metadata document — every group, hidden included. */\n exportMeta(walletId: string): MetaDoc {\n this.mustWallet(walletId);\n const s = this.getState();\n const w = s.wallets.find((x) => x.walletId === walletId);\n const wallet: MetaDoc[\"wallet\"] = {\n updatedAt: w?.updatedAt ?? 0,\n ...(w?.name === undefined ? {} : { name: w.name }),\n };\n const groups: MetaDocGroup[] = [];\n for (const g of s.groups[walletId] ?? []) {\n groups.push({\n index: g.index,\n hidden: g.hidden,\n updatedAt: g.updatedAt,\n ...(g.name === undefined ? {} : { name: g.name }),\n ...(g.boundPubkey === undefined ? {} : { boundPubkey: g.boundPubkey }),\n });\n }\n return { v: 1, wallet, groups };\n }\n\n /**\n * Entry-level last-writer-wins merge: a newer remote `updatedAt` replaces the local entry, a tie\n * keeps local; remote-only groups are added. `selected`/hidden rules are re-validated — if the\n * merge hides the selected group it is re-selected, and a merge may never leave every group\n * hidden (the selected one stays visible and is re-stamped so the fix propagates).\n */\n mergeMeta(walletId: string, doc: MetaDoc): { changed: boolean; localNewer: boolean } {\n this.mustWallet(walletId);\n let changed = false;\n let localNewer = false;\n const s = this.getState();\n const localWallet = s.wallets.find((w) => w.walletId === walletId);\n const walletUpdatedAt = localWallet?.updatedAt ?? 0;\n let wallet = localWallet ?? { walletId, updatedAt: 0 };\n if (doc.wallet.updatedAt > walletUpdatedAt) {\n wallet = {\n walletId,\n updatedAt: doc.wallet.updatedAt,\n ...(doc.wallet.name === undefined ? {} : { name: doc.wallet.name }),\n };\n changed = true;\n } else if (walletUpdatedAt > doc.wallet.updatedAt) {\n localNewer = true;\n }\n const localByIndex = new Map((s.groups[walletId] ?? []).map((g) => [g.index, g]));\n const groups = [...(s.groups[walletId] ?? [])];\n for (const remote of doc.groups) {\n const local = localByIndex.get(remote.index);\n if (local === undefined) {\n groups.push({\n walletId,\n index: remote.index,\n hidden: remote.hidden,\n updatedAt: remote.updatedAt,\n ...(remote.name === undefined ? {} : { name: remote.name }),\n ...(remote.boundPubkey === undefined ? {} : { boundPubkey: remote.boundPubkey }),\n });\n changed = true;\n continue;\n }\n if (remote.updatedAt > local.updatedAt) {\n const replaced: AccountGroup = {\n walletId,\n index: remote.index,\n hidden: remote.hidden,\n updatedAt: remote.updatedAt,\n ...(remote.name === undefined ? {} : { name: remote.name }),\n ...(remote.boundPubkey === undefined ? {} : { boundPubkey: remote.boundPubkey }),\n };\n const at = groups.findIndex((g) => g.index === remote.index);\n groups[at] = replaced;\n changed = true;\n } else if (local.updatedAt > remote.updatedAt) {\n localNewer = true;\n }\n }\n for (const g of groups) {\n if (!doc.groups.some((r) => r.index === g.index) && g.updatedAt > 0) {\n localNewer = true;\n }\n }\n groups.sort((a, b) => a.index - b.index);\n // Re-validate selection: merge may have hidden the selected group or every group.\n const walletOrder = s.wallets.map((w) => w.walletId);\n let selected = this.validSelection(\n { ...s.groups, [walletId]: groups },\n walletOrder,\n s.selected,\n );\n const visible = groups.some((g) => !g.hidden);\n if (!visible && groups.length > 0) {\n // A merge must never hide every group — keep the selected (or first) one visible and\n // stamp it so the local correction wins the next merge too.\n const keep = selected ?? { walletId, groupIndex: groups[0]?.index ?? 0 };\n const now = this.options.now();\n for (const [i, g] of groups.entries()) {\n if (g.index === keep.groupIndex) {\n groups[i] = { ...g, hidden: false, updatedAt: now };\n }\n }\n selected = keep;\n changed = true;\n localNewer = true;\n }\n if (\n selected?.walletId !== s.selected?.walletId ||\n selected?.groupIndex !== s.selected?.groupIndex\n ) {\n changed = true;\n }\n if (changed) {\n this.update((st) => ({\n ...st,\n wallets: st.wallets.map((w) => (w.walletId === walletId ? wallet : w)),\n groups: { ...st.groups, [walletId]: groups },\n selected,\n }));\n this.persist();\n this.driveSpark(selected);\n }\n return { changed, localNewer };\n }\n\n /** Sequential inspect from 0 upward; index 0 always included; stop after 2 consecutive unused. */\n async discoverSpark(walletId: string): Promise<number[]> {\n this.mustWallet(walletId);\n const found: number[] = [0];\n let index = 0;\n let unused = 0;\n while (found.length < 65) {\n const ref = { walletId, groupIndex: index, network: this.options.sparkNetwork } as const;\n // oxlint-disable-next-line eslint/no-await-in-loop -- discovery is sequential per spec\n const { used } = await this.options.spark.inspect(ref);\n if (used) {\n if (index !== 0) {\n found.push(index);\n }\n unused = 0;\n } else {\n unused += 1;\n if (index !== 0 && unused >= 2) {\n break;\n }\n }\n index += 1;\n }\n return found;\n }\n\n /**\n * Per-group chain-family discovery — same stop rule as `discoverSpark`: group 0 always, stop\n * after two consecutive fully-unused groups. A family error is reported on the group and does NOT\n * count as unused (the group stays in `found` — it can't be proven empty).\n */\n async discoverGroups(walletId: string): Promise<number[]> {\n this.mustWallet(walletId);\n const apis = this.options.chains ?? chains(this.options.wallet);\n const nets = this.options.networks;\n const found: number[] = [0];\n let index = 0;\n let unused = 0;\n while (index < 65) {\n const groupIndex = index;\n const evm = async (): Promise<boolean> => {\n if (nets === undefined) {\n return false;\n }\n const seen = await Promise.all(\n nets.enabled(\"evm\").map(async (network) => {\n const acct = await apis.account({\n walletId,\n groupIndex,\n template: \"evm.bip44\",\n network,\n });\n const address = \"address\" in acct ? evmAddress(acct.address) : undefined;\n if (address === undefined) {\n return false;\n }\n const client = nets.client(network);\n const [nonce, balance] = await Promise.all([\n client.getTransactionCount({ address, blockTag: \"latest\" }),\n client.getBalance({ address }),\n ]);\n return nonce > 0 || balance > 0n;\n }),\n );\n return seen.some(Boolean);\n };\n const solana = async (): Promise<boolean> => {\n if (nets === undefined) {\n return false;\n }\n const seen = await Promise.all(\n nets.enabled(\"solana\").map(async (network) => {\n const acct = await apis.account({\n walletId,\n groupIndex,\n template: \"solana.bip44-change\",\n network,\n });\n const address = \"address\" in acct ? addressOf(acct.address) : undefined;\n if (address === undefined) {\n return false;\n }\n const rpc = nets.solanaRpc(network);\n const sigs: unknown = await rpc.call(\"getSignaturesForAddress\", [\n address,\n { limit: 1 },\n ]);\n return Array.isArray(sigs) && sigs.length > 0;\n }),\n );\n return seen.some(Boolean);\n };\n const bitcoin = async (): Promise<boolean> => {\n if (nets === undefined) {\n return false;\n }\n const combos = nets\n .enabled(\"bitcoin\")\n .flatMap((network) =>\n ([\"btc.bip44\", \"btc.bip49\", \"btc.bip84\", \"btc.bip86\"] as const).map(\n (template) => [network, template] as const,\n ),\n );\n const seen = await Promise.all(\n combos.map(async ([network, template]) => {\n const net = bitcoinNetwork(network);\n const es = nets.esplora(network);\n const acct = await apis.account({ walletId, groupIndex, template, network });\n const xpub = \"xpub\" in acct ? acct.xpub : undefined;\n if (xpub === undefined) {\n return false;\n }\n const [receive, change] = await Promise.all([\n scanChain(es, xpub, template, network, net.params, 0),\n scanChain(es, xpub, template, network, net.params, 1),\n ]);\n return receive.some((a) => a.used) || change.some((a) => a.used);\n }),\n );\n return seen.some(Boolean);\n };\n const spark = async (): Promise<boolean> => {\n const ref = {\n walletId,\n groupIndex,\n network: this.options.sparkNetwork,\n } as const;\n const { used } = await this.options.spark.inspect(ref);\n return used;\n };\n // oxlint-disable-next-line eslint/no-await-in-loop -- discovery is sequential per spec\n const results = await Promise.all([\n check(\"spark\", spark),\n check(\"evm\", evm),\n check(\"solana\", solana),\n check(\"bitcoin\", bitcoin),\n ]);\n const usedMap = Object.fromEntries(results.map(([k, v]) => [k, v.used]));\n const errorMap = Object.fromEntries(\n results.flatMap(([k, v]) => (v.error === undefined ? [] : [[k, v.error] as const])),\n );\n const anyUsed = results.some(([, v]) => v.used);\n const anyError = results.some(([, v]) => v.error !== undefined);\n this.mutateGroups(walletId, (list) => {\n const have = list.some((g) => g.index === groupIndex);\n const updatedAt = this.options.now();\n if (!have) {\n return [\n ...list,\n {\n walletId,\n index: groupIndex,\n hidden: false,\n used: usedMap,\n errors: errorMap,\n updatedAt,\n },\n ].sort((a, b) => a.index - b.index);\n }\n return list.map((g) =>\n g.index === groupIndex ? { ...g, used: usedMap, errors: errorMap, updatedAt } : g,\n );\n });\n if (anyUsed || anyError) {\n if (index !== 0 && anyUsed) {\n found.push(index);\n }\n unused = 0;\n } else {\n unused += 1;\n if (index !== 0 && unused >= 2) {\n break;\n }\n }\n index += 1;\n }\n return found;\n }\n\n /** Refresh `totals` for every other visible group; per-group failures are logged and skipped. */\n async refreshTotals(): Promise<void> {\n const state = this.getState();\n const sel = state.selected;\n const targets = this.visibleGroups(state).filter(\n (g) => !(sel !== null && g.walletId === sel.walletId && g.index === sel.groupIndex),\n );\n let cursor = 0;\n const worker = async (): Promise<void> => {\n while (cursor < targets.length) {\n const group = targets[cursor];\n cursor += 1;\n if (group === undefined) {\n return;\n }\n try {\n const ref = {\n walletId: group.walletId,\n groupIndex: group.index,\n network: this.options.sparkNetwork,\n } as const;\n // oxlint-disable-next-line eslint/no-await-in-loop -- workers drain a shared cursor\n const { balanceSats } = await this.options.spark.inspect(ref);\n this.setTotal(group.walletId, group.index, balanceSats);\n } catch (error) {\n this.options.logger.warn(\n `refreshTotals failed for ${group.walletId}:${group.index}`,\n error,\n );\n }\n }\n };\n await Promise.all([worker(), worker()]);\n }\n\n private onSparkState(\n accounts: Readonly<Record<string, { readonly balanceSats?: number }>>,\n ): void {\n const sel = this.getState().selected;\n if (sel === null) {\n return;\n }\n const accountKey = `${sel.walletId}:${sel.groupIndex}:${this.options.sparkNetwork}`;\n const balance = accounts[accountKey]?.balanceSats;\n if (balance !== undefined) {\n this.setTotal(sel.walletId, sel.groupIndex, balance);\n }\n }\n\n private setTotal(walletId: string, index: number, balanceSats: number): void {\n const k = TOTAL_KEY(walletId, index);\n if (this.getState().totals[k] === balanceSats) {\n return;\n }\n this.update((s) => ({ ...s, totals: { ...s.totals, [k]: balanceSats } }));\n this.scheduleTotalsPersist();\n }\n\n private driveSpark(selected: AccountTreeState[\"selected\"]): void {\n this.options.spark.setAccounts(\n selected === null ? [] : [{ ...selected, network: this.options.sparkNetwork }],\n );\n }\n\n private visibleGroups(state: AccountTreeState): AccountGroup[] {\n const out: AccountGroup[] = [];\n for (const w of state.wallets) {\n for (const g of state.groups[w.walletId] ?? []) {\n if (!g.hidden) {\n out.push(g);\n }\n }\n }\n return out;\n }\n\n private validSelection(\n groups: Record<string, ReadonlyArray<AccountGroup>>,\n walletOrder: ReadonlyArray<string>,\n current: AccountTreeState[\"selected\"],\n ): AccountTreeState[\"selected\"] {\n if (current !== null) {\n const g = (groups[current.walletId] ?? []).find((x) => x.index === current.groupIndex);\n if (g !== undefined && !g.hidden) {\n return current;\n }\n }\n for (const walletId of walletOrder) {\n for (const g of groups[walletId] ?? []) {\n if (!g.hidden) {\n return { walletId, groupIndex: g.index };\n }\n }\n }\n return null;\n }\n\n private selectFallback(): void {\n const state = this.getState();\n const next = this.validSelection(\n state.groups,\n state.wallets.map((w) => w.walletId),\n null,\n );\n this.update((s) => ({ ...s, selected: next }));\n this.persist();\n this.driveSpark(next);\n }\n\n private mutateGroups(\n walletId: string,\n fn: (list: ReadonlyArray<AccountGroup>) => ReadonlyArray<AccountGroup>,\n ): void {\n this.update((s) => ({\n ...s,\n groups: { ...s.groups, [walletId]: fn(s.groups[walletId] ?? []) },\n }));\n this.persist();\n }\n\n private mustWallet(walletId: string): void {\n if (this.getState().status !== \"ready\") {\n throw new AccountTreeError(\"locked\", \"account tree is locked\");\n }\n if (!this.getState().wallets.some((w) => w.walletId === walletId)) {\n throw new AccountTreeError(\"not-found\", \"wallet does not exist\");\n }\n }\n\n private mustGroup(walletId: string, index: number): void {\n this.mustWallet(walletId);\n if (!(this.getState().groups[walletId] ?? []).some((g) => g.index === index)) {\n throw new AccountTreeError(\"not-found\", \"account group does not exist\");\n }\n }\n\n private checkedName(name: string): string {\n const trimmed = name.trim();\n if (trimmed.length === 0 || trimmed.length > NAME_MAX) {\n throw new AccountTreeError(\"invalid-input\", \"name must be 1-24 characters\");\n }\n return trimmed;\n }\n\n private async load(): Promise<PersistedTree> {\n if (this.col === undefined) {\n return EMPTY_TREE;\n }\n const bytes = await this.col.get(\"tree\");\n if (bytes === undefined) {\n return EMPTY_TREE;\n }\n const tree = decodeTree(bytes);\n if (tree === undefined) {\n this.options.logger.warn(\"invalid persisted account tree — starting empty\");\n return EMPTY_TREE;\n }\n return tree;\n }\n\n /** Queues a store write behind the previous one — the last queued write always lands last. */\n private persist(): void {\n const { col } = this;\n if (col === undefined) {\n return;\n }\n const previous = this.persistChain;\n this.persistChain = (async () => {\n try {\n await previous;\n const s = this.getState();\n const tree: PersistedTree = {\n wallets: Object.fromEntries(\n s.wallets.map((w) => [\n w.walletId,\n { updatedAt: w.updatedAt, ...(w.name === undefined ? {} : { name: w.name }) },\n ]),\n ),\n groups: s.groups,\n selected: s.selected,\n totals: s.totals,\n };\n await col.put(\"tree\", encodeTree(tree));\n } catch (error) {\n this.options.logger.warn(\"account tree persist failed\", error);\n }\n })();\n }\n\n private scheduleTotalsPersist(): void {\n if (this.totalsTimer !== undefined) {\n return;\n }\n this.totalsTimer = setTimeout(() => {\n this.totalsTimer = undefined;\n this.persist();\n }, TOTALS_DEBOUNCE_MS);\n }\n\n private async flushTotals(): Promise<void> {\n if (this.totalsTimer !== undefined) {\n clearTimeout(this.totalsTimer);\n this.totalsTimer = undefined;\n this.persist();\n }\n await this.persistChain;\n }\n}\n\nfunction persistedToState(tree: PersistedTree): Omit<AccountTreeState, \"status\"> {\n const wallets: Array<{\n readonly walletId: string;\n readonly name?: string;\n readonly updatedAt: number;\n }> = [];\n for (const [walletId, w] of Object.entries(tree.wallets)) {\n if (w.name === undefined) {\n wallets.push({ walletId, updatedAt: w.updatedAt });\n } else {\n wallets.push({ walletId, name: w.name, updatedAt: w.updatedAt });\n }\n }\n return {\n wallets,\n groups: tree.groups,\n selected: tree.selected,\n totals: tree.totals,\n };\n}\n","/**\n * EVM chain adapter: native transfers through a viem PublicClient injected by NetworkController.\n * Fee tiers come from eth_feeHistory (20 blocks, p10/p50/p90 → slow/normal/fast, maxFee = 2×baseFee +\n * priority); networks that cannot answer feeHistory fall back to eth_gasPrice. gas = estimateGas ×\n * 1.2 (ceil). Nonces are allocated on a per-(network, from) serial queue as max(pending count, last\n * submitted + 1). Finalization uses the `finalized` block tag; receipts with status 0 fail.\n */\nimport { encodeFunctionData, isAddress, numberToHex } from \"viem\";\nimport type { PublicClient } from \"viem\";\n\nimport type { EvmTransaction, SignRequest } from \"@qntx/wallet-chains\";\nimport { checksumEvmAddress } from \"@qntx/wallet-chains/evm\";\n\nexport type EvmSignRequest = Extract<SignRequest, { kind: \"evm.transaction\" }>;\nexport type EvmSignResult = {\n readonly kind: \"evm.transaction\";\n readonly signedTransaction: Uint8Array;\n};\n\nexport type EvmFeeTier = \"slow\" | \"normal\" | \"fast\";\n\nexport type EvmUnsignedTransaction = {\n readonly family: \"evm\";\n readonly network: string;\n readonly from: string;\n readonly to: string;\n readonly value: bigint;\n readonly data: string;\n readonly nonce: number;\n readonly gas: bigint;\n readonly gasPrice?: bigint;\n readonly maxFeePerGas?: bigint;\n readonly maxPriorityFeePerGas?: bigint;\n};\n\nexport type EvmFeeQuote = {\n readonly tier: EvmFeeTier;\n readonly wei: bigint;\n readonly maxFeePerGas: bigint;\n readonly maxPriorityFeePerGas: bigint | undefined;\n};\nexport type ChainTxStatus = \"pending\" | \"confirmed\" | \"failed\" | \"finalized\";\n\nexport const ERC20_ABI = [\n {\n type: \"function\",\n name: \"transfer\",\n inputs: [\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n ],\n outputs: [{ name: \"\", type: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"balanceOf\",\n inputs: [{ name: \"account\", type: \"address\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"symbol\",\n inputs: [],\n outputs: [{ name: \"\", type: \"string\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"decimals\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint8\" }],\n stateMutability: \"view\",\n },\n] as const;\n\nconst checkedAddress = (v: string): `0x${string}` => {\n if (!isAddress(v)) {\n throw new TypeError(`malformed evm address: ${v}`);\n }\n return v;\n};\n\nconst hex = (v: bigint | number): string => numberToHex(v);\n\nexport class EvmChainAdapter {\n readonly family = \"evm\";\n private readonly nonces = new Map<string, Promise<unknown>>();\n private readonly lastNonce = new Map<string, number>();\n\n private async serial<T>(key: string, run: () => Promise<T>): Promise<T> {\n const prior = this.nonces.get(key) ?? Promise.resolve();\n const next = (async () => {\n try {\n await prior;\n } catch {\n // a failed earlier run must not poison the nonce queue\n }\n return run();\n })();\n this.nonces.set(key, next);\n return next;\n }\n\n private async rpc(client: PublicClient, method: string, params: unknown[]): Promise<unknown> {\n return client.transport.request({ method, params });\n }\n\n private async rpcHex(client: PublicClient, method: string, params: unknown[]): Promise<string> {\n const result: unknown = await this.rpc(client, method, params);\n if (typeof result !== \"string\") {\n throw new TypeError(`${method} returned a malformed result`);\n }\n return result;\n }\n\n /** Allocate the next nonce for (network, from) — serial per key. */\n private async nonce(client: PublicClient, network: string, from: string): Promise<number> {\n const key = `${network}:${from}`;\n return this.serial(key, async () => {\n const pending = Number(\n await this.rpcHex(client, \"eth_getTransactionCount\", [from, \"pending\"]),\n );\n const local = this.lastNonce.get(key);\n const nonce = Math.max(pending, local === undefined ? 0 : local + 1);\n this.lastNonce.set(key, nonce);\n return nonce;\n });\n }\n\n /** ERC-20 gas is buffered ×1.1 instead of the native ×1.2 (chains.mdx \"EVM\"). */\n async build(\n client: PublicClient,\n network: string,\n from: string,\n intent:\n | { readonly kind: \"native\"; readonly to: string; readonly value: bigint }\n | {\n readonly kind: \"erc20\";\n readonly token: string;\n readonly to: string;\n readonly value: bigint;\n },\n ): Promise<EvmUnsignedTransaction> {\n const nonce = await this.nonce(client, network, from);\n const erc20 = intent.kind === \"erc20\";\n const to = checksumEvmAddress(erc20 ? intent.token : intent.to);\n const value = erc20 ? 0n : intent.value;\n const data = erc20\n ? encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"transfer\",\n args: [checkedAddress(intent.to), intent.value],\n })\n : \"0x\";\n const estimate = BigInt(\n await this.rpcHex(client, \"eth_estimateGas\", [{ from, to, value: hex(value), data }]),\n );\n const scale = erc20 ? 11n : 12n;\n const gas = (estimate * scale) / 10n + ((estimate * scale) % 10n === 0n ? 0n : 1n);\n return { family: \"evm\", network, from, to, value, data, nonce, gas };\n }\n\n async estimateFee(client: PublicClient): Promise<ReadonlyArray<EvmFeeQuote>> {\n try {\n const history: unknown = await this.rpc(client, \"eth_feeHistory\", [\n \"0x14\",\n \"latest\",\n [10, 50, 90],\n ]);\n if (\n typeof history !== \"object\" ||\n history === null ||\n !(\"baseFeePerGas\" in history) ||\n !Array.isArray(history.baseFeePerGas) ||\n !(\"reward\" in history) ||\n !Array.isArray(history.reward)\n ) {\n throw new TypeError(\"eth_feeHistory returned a malformed result\");\n }\n const { baseFeePerGas, reward } = history;\n if (\n !Array.isArray(baseFeePerGas) ||\n !baseFeePerGas.every((v) => typeof v === \"string\") ||\n !Array.isArray(reward) ||\n !reward.every((r) => Array.isArray(r) && r.every((v) => typeof v === \"string\"))\n ) {\n throw new TypeError(\"eth_feeHistory returned a malformed result\");\n }\n const baseFee = BigInt(baseFeePerGas.at(-1) ?? \"0x0\");\n const tier = (i: number, name: EvmFeeTier): EvmFeeQuote => {\n const last = reward.at(-1);\n const priority = last === undefined ? 0n : BigInt(last[i] ?? \"0x0\");\n const maxFeePerGas = baseFee * 2n + priority;\n return { tier: name, wei: maxFeePerGas, maxFeePerGas, maxPriorityFeePerGas: priority };\n };\n return [tier(0, \"slow\"), tier(1, \"normal\"), tier(2, \"fast\")];\n } catch {\n const price = BigInt(await this.rpcHex(client, \"eth_gasPrice\", []));\n return ([\"slow\", \"normal\", \"fast\"] as const).map((name) => ({\n tier: name,\n wei: price,\n maxFeePerGas: price,\n maxPriorityFeePerGas: undefined,\n }));\n }\n }\n\n applyFee(tx: EvmUnsignedTransaction, fee: EvmFeeQuote): EvmUnsignedTransaction {\n if (fee.maxPriorityFeePerGas === undefined) {\n return { ...tx, gasPrice: fee.maxFeePerGas };\n }\n return {\n ...tx,\n maxFeePerGas: fee.maxFeePerGas,\n maxPriorityFeePerGas: fee.maxPriorityFeePerGas,\n };\n }\n\n toSignRequest<A extends SignRequest[\"account\"]>(\n tx: EvmUnsignedTransaction,\n account: A,\n chainId: number,\n ): EvmSignRequest & { readonly account: A } {\n const base = {\n chainId,\n nonce: tx.nonce,\n gas: hex(tx.gas),\n to: tx.to,\n value: hex(tx.value),\n data: tx.data,\n };\n const transaction: EvmTransaction =\n tx.gasPrice === undefined\n ? {\n ...base,\n type: \"eip1559\",\n accessList: [],\n maxFeePerGas: hex(tx.maxFeePerGas ?? 0n),\n maxPriorityFeePerGas: hex(tx.maxPriorityFeePerGas ?? 0n),\n }\n : { ...base, type: \"legacy\", gasPrice: hex(tx.gasPrice) };\n return { kind: \"evm.transaction\", network: tx.network, account, tx: transaction };\n }\n\n finalize(\n _tx: EvmUnsignedTransaction,\n signed: { kind: string; signedTransaction?: Uint8Array },\n ): string {\n const bytes = signed.signedTransaction;\n if (signed.kind !== \"evm.transaction\" || bytes === undefined) {\n throw new Error(`unexpected sign result ${signed.kind}`);\n }\n return `0x${[...bytes].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\")}`;\n }\n\n async broadcast(client: PublicClient, raw: string): Promise<string> {\n return this.rpcHex(client, \"eth_sendRawTransaction\", [raw]);\n }\n\n async status(client: PublicClient, hash: string): Promise<ChainTxStatus> {\n const receipt: unknown = await this.rpc(client, \"eth_getTransactionReceipt\", [hash]);\n if (receipt === null || typeof receipt !== \"object\") {\n return \"pending\";\n }\n if (\n \"status\" in receipt &&\n typeof receipt.status === \"string\" &&\n BigInt(receipt.status) === 0n\n ) {\n return \"failed\";\n }\n try {\n const finalized: unknown = await this.rpc(client, \"eth_getBlockByNumber\", [\n \"finalized\",\n false,\n ]);\n if (\n finalized !== null &&\n typeof finalized === \"object\" &&\n \"number\" in finalized &&\n typeof finalized.number === \"string\" &&\n \"blockNumber\" in receipt &&\n typeof receipt.blockNumber === \"string\" &&\n BigInt(receipt.blockNumber) <= BigInt(finalized.number)\n ) {\n return \"finalized\";\n }\n } catch {\n // endpoint does not know the `finalized` tag — receipt confirmation is enough\n }\n return \"confirmed\";\n }\n}\n","/**\n * EVM balances per (account address, network). Native via eth_getBalance; token balanceOf calls go\n * through the network's Multicall3 (one aggregate eth_call) when the registry declares it,\n * otherwise one eth_call per token. Custom tokens persist in the EngineStore as unverified until a\n * built-in-table merge marks them otherwise. State values are display-only: transaction build\n * always re-reads the chain.\n */\nimport { encodeFunctionData, decodeFunctionResult, isAddress, isHex } from \"viem\";\nimport type { PublicClient } from \"viem\";\n\nimport { bitcoinNetwork } from \"@qntx/wallet-chains/bitcoin\";\n\nimport { BtcUtxoStore, scanChain, scanUtxos } from \"../chains/bitcoin-scan.ts\";\nimport { ERC20_ABI } from \"../chains/evm.ts\";\nimport { Controller } from \"../controller.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport type { NetworkController } from \"../networks/controller.ts\";\nimport type { EngineStore } from \"../store/port.ts\";\n\nconst obj = (v: unknown): Record<string, unknown> | undefined => (isObject(v) ? v : undefined);\n\nconst arr = (v: unknown): v is ReadonlyArray<unknown> => Array.isArray(v);\n\nconst COLLECTION = \"assets-custom-tokens\";\nconst POLL_MS = 60_000;\n\nexport type TokenBalance = {\n readonly address: string;\n readonly symbol: string;\n readonly decimals: number;\n readonly balance: string;\n /** False for user-added tokens until they appear in the built-in table. */\n readonly verified: boolean;\n};\n\nexport type AccountBalances = {\n readonly native: string;\n readonly tokens: ReadonlyArray<TokenBalance>;\n /** Bitcoin only — confirmed + own unconfirmed change; frozen 546/330-sat UTXOs shown apart. */\n readonly unconfirmed?: string;\n readonly frozen?: string;\n};\n\nexport type AssetsControllerState = {\n readonly balances: Record<string, AccountBalances>;\n};\n\ntype Options = {\n readonly networks: NetworkController;\n readonly openStore: () => Promise<EngineStore>;\n readonly setTimer: (ms: number, fn: () => unknown) => () => void;\n readonly logger: EngineLogger;\n};\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null;\n\nconst checked = (v: string): `0x${string}` => {\n if (!isAddress(v)) {\n throw new TypeError(`malformed evm address: ${v}`);\n }\n return v;\n};\n\nconst key = (network: string, address: string): string => `${network}:${address}`;\n\nexport const MULTICALL3_ABI = [\n {\n type: \"function\",\n name: \"aggregate3\",\n inputs: [\n {\n name: \"calls\",\n type: \"tuple[]\",\n components: [\n { name: \"target\", type: \"address\" },\n { name: \"allowFailure\", type: \"bool\" },\n { name: \"callData\", type: \"bytes\" },\n ],\n },\n ],\n outputs: [\n {\n name: \"returnData\",\n type: \"tuple[]\",\n components: [\n { name: \"success\", type: \"bool\" },\n { name: \"returnData\", type: \"bytes\" },\n ],\n },\n ],\n stateMutability: \"payable\",\n },\n] as const;\n\nexport class AssetsController extends Controller<AssetsControllerState> {\n private readonly options: Options;\n private engineStore: EngineStore | undefined;\n private readonly bitcoinUtxos = new BtcUtxoStore();\n private visible = false;\n private cancelPoll: (() => void) | undefined;\n private readonly customTokens = new Map<\n string,\n ReadonlyArray<{ address: string; verified: boolean }>\n >();\n\n constructor(options: Options) {\n super({ name: \"assets\", defaultState: () => ({ balances: {} }) });\n this.options = options;\n }\n\n async init(): Promise<void> {\n this.engineStore = await this.options.openStore();\n const listed = await this.engineStore.collection(COLLECTION).get(\"customTokens\");\n if (listed !== undefined) {\n const parsed: unknown = JSON.parse(new TextDecoder().decode(listed));\n if (isObject(parsed)) {\n for (const [network, arr] of Object.entries(parsed)) {\n if (Array.isArray(arr)) {\n const tokens = arr.flatMap((t: unknown) =>\n isObject(t) && typeof t[\"address\"] === \"string\" && typeof t[\"verified\"] === \"boolean\"\n ? [{ address: t[\"address\"], verified: t[\"verified\"] }]\n : [],\n );\n this.customTokens.set(network, tokens);\n }\n }\n }\n }\n if (this.visible) {\n this.armPoll();\n }\n }\n\n lock(): void {\n this.cancelPoll?.();\n this.cancelPoll = undefined;\n this.customTokens.clear();\n this.engineStore = undefined;\n this.update(() => ({ balances: {} }));\n }\n\n async destroy(): Promise<void> {\n this.lock();\n await Promise.resolve();\n }\n\n setVisible(visible: boolean): void {\n this.visible = visible;\n if (!visible) {\n this.cancelPoll?.();\n this.cancelPoll = undefined;\n return;\n }\n this.armPoll();\n }\n\n private armPoll(): void {\n if (this.cancelPoll !== undefined) {\n return;\n }\n this.cancelPoll = this.options.setTimer(POLL_MS, () => {\n void (async () => {\n try {\n await this.refreshAll();\n } catch (error) {\n this.options.logger.warn(\"assets refresh failed\", error);\n }\n })();\n });\n }\n\n private async refreshAll(): Promise<void> {\n await Promise.all(\n Object.keys(this.getState().balances).flatMap((entry) => {\n const [network, address] = entry.split(\":\");\n return network === undefined || address === undefined\n ? []\n : [this.refresh(address, network)];\n }),\n );\n }\n\n async refresh(address: string, network: string): Promise<void> {\n const info = this.options.networks.info(network);\n if (info.family === \"solana\") {\n await this.refreshSolana(address, network);\n return;\n }\n if (info.family === \"bitcoin\") {\n await this.refreshBitcoin(address, network);\n return;\n }\n const client = this.options.networks.client(network);\n const native = BigInt(\n await this.rpcHex(client, \"eth_getBalance\", [address, \"latest\"]),\n ).toString();\n const custom = this.customTokens.get(network) ?? [];\n const tokens = await this.readTokens(\n client,\n info.multicall3,\n address,\n custom.map((t) => ({ address: t.address, verified: t.verified })),\n );\n this.update((s) => ({\n balances: { ...s.balances, [key(network, address)]: { native, tokens } },\n }));\n }\n\n /** SOL via getBalance; SPL via getTokenAccountsByOwner (jsonParsed) for known mints. */\n private async refreshSolana(owner: string, network: string): Promise<void> {\n const rpc = this.options.networks.solanaRpc(network);\n const bal = obj(await rpc.call(\"getBalance\", [owner, { commitment: \"confirmed\" }]));\n const balValue = bal?.[\"value\"];\n const native =\n typeof balValue === \"string\"\n ? balValue\n : typeof balValue === \"number\"\n ? String(balValue)\n : \"0\";\n const custom = this.customTokens.get(network) ?? [];\n const tokens = await Promise.all(\n custom.map(async (t) => {\n const accounts = obj(\n await rpc.call(\"getTokenAccountsByOwner\", [\n owner,\n { mint: t.address },\n { encoding: \"jsonParsed\" },\n ]),\n );\n const first = arr(accounts?.[\"value\"]) ? accounts?.[\"value\"][0] : undefined;\n const parsed = obj(obj(obj(obj(obj(first)?.[\"account\"])?.[\"data\"])?.[\"parsed\"])?.[\"info\"]);\n const amount = obj(parsed?.[\"tokenAmount\"]);\n const mintInfo = obj(\n await rpc.call(\"getAccountInfo\", [t.address, { encoding: \"jsonParsed\" }]),\n );\n const mintParsed = obj(obj(obj(obj(mintInfo?.[\"value\"])?.[\"data\"])?.[\"parsed\"])?.[\"info\"]);\n return {\n address: t.address,\n symbol: \"?\",\n decimals: typeof mintParsed?.[\"decimals\"] === \"number\" ? mintParsed[\"decimals\"] : 9,\n balance: typeof amount?.[\"amount\"] === \"string\" ? amount[\"amount\"] : \"0\",\n verified: t.verified,\n };\n }),\n );\n this.update((s) => ({\n balances: { ...s.balances, [key(network, owner)]: { native, tokens } },\n }));\n }\n\n private async readTokens(\n client: PublicClient,\n multicall3: string | undefined,\n owner: string,\n tokens: ReadonlyArray<{ address: string; verified: boolean }>,\n ): Promise<ReadonlyArray<TokenBalance>> {\n if (tokens.length === 0) {\n return [];\n }\n const balances =\n multicall3 === undefined\n ? await Promise.all(tokens.map(async (t) => this.balanceOf(client, t.address, owner)))\n : await this.balanceOfBatch(\n client,\n multicall3,\n owner,\n tokens.map((t) => t.address),\n );\n return Promise.all(\n tokens.map(async (t, i) => ({\n address: t.address,\n symbol: (await this.callString(client, t.address, \"symbol\")) ?? \"?\",\n decimals: (await this.callNumber(client, t.address, \"decimals\")) ?? 18,\n balance: balances[i]?.toString() ?? \"0\",\n verified: t.verified,\n })),\n );\n }\n\n private async balanceOfBatch(\n client: PublicClient,\n multicall3: string,\n owner: string,\n tokens: ReadonlyArray<string>,\n ): Promise<ReadonlyArray<bigint | undefined>> {\n const data = encodeFunctionData({\n abi: MULTICALL3_ABI,\n functionName: \"aggregate3\",\n args: [\n tokens.map((token) => ({\n target: checked(token),\n allowFailure: true,\n callData: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n args: [checked(owner)],\n }),\n })),\n ],\n });\n const result = await this.rpcHex(client, \"eth_call\", [{ to: multicall3, data }, \"latest\"]);\n if (!isHex(result)) {\n throw new TypeError(\"eth_call returned malformed data\");\n }\n const decoded = decodeFunctionResult({\n abi: MULTICALL3_ABI,\n functionName: \"aggregate3\",\n data: result,\n });\n return decoded.map((r) =>\n r.success\n ? decodeFunctionResult({\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n data: r.returnData,\n })\n : undefined,\n );\n }\n\n private async balanceOf(\n client: PublicClient,\n token: string,\n owner: string,\n ): Promise<bigint | undefined> {\n const data = encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n args: [checked(owner)],\n });\n const result = await this.rpcHex(client, \"eth_call\", [{ to: token, data }, \"latest\"]);\n if (!isHex(result)) {\n throw new TypeError(\"eth_call returned malformed data\");\n }\n return decodeFunctionResult({\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n data: result,\n });\n }\n\n private async callString(\n client: PublicClient,\n token: string,\n fn: \"symbol\",\n ): Promise<string | undefined> {\n const data = encodeFunctionData({ abi: ERC20_ABI, functionName: fn });\n const result = await this.rpcHex(client, \"eth_call\", [{ to: token, data }, \"latest\"]);\n if (!isHex(result)) {\n return undefined;\n }\n try {\n return decodeFunctionResult({ abi: ERC20_ABI, functionName: fn, data: result });\n } catch {\n return undefined;\n }\n }\n\n private async callNumber(\n client: PublicClient,\n token: string,\n fn: \"decimals\",\n ): Promise<number | undefined> {\n const data = encodeFunctionData({ abi: ERC20_ABI, functionName: fn });\n const result = await this.rpcHex(client, \"eth_call\", [{ to: token, data }, \"latest\"]);\n if (!isHex(result)) {\n return undefined;\n }\n try {\n return decodeFunctionResult({ abi: ERC20_ABI, functionName: fn, data: result });\n } catch {\n return undefined;\n }\n }\n\n /** Reads symbol/decimals on-chain, marks unverified, persists; throws when the calls fail. */\n async addToken(network: string, address: string): Promise<void> {\n const info = this.options.networks.info(network);\n if (info.family === \"solana\") {\n const rpc = this.options.networks.solanaRpc(network);\n const mint = obj(await rpc.call(\"getAccountInfo\", [address, { encoding: \"jsonParsed\" }]));\n const decimals = obj(obj(obj(mint?.[\"value\"])?.[\"data\"])?.[\"parsed\"])?.[\"info\"];\n if (typeof obj(decimals)?.[\"decimals\"] !== \"number\") {\n throw new TypeError(`${address} is not a readable SPL mint on ${network}`);\n }\n await this.persistToken(network, address);\n return;\n }\n const client = this.options.networks.client(network);\n await this.callString(client, address, \"symbol\");\n await this.callNumber(client, address, \"decimals\");\n await this.persistToken(network, address);\n }\n\n private async persistToken(network: string, address: string): Promise<void> {\n const existing = this.customTokens.get(network) ?? [];\n if (existing.some((t) => t.address === address)) {\n return;\n }\n const next = [...existing, { address, verified: false }];\n this.customTokens.set(network, next);\n if (this.engineStore !== undefined) {\n const merged: Record<string, ReadonlyArray<{ address: string; verified: boolean }>> = {\n [network]: next,\n };\n for (const [n, list] of this.customTokens) {\n if (n !== network) {\n merged[n] = list;\n }\n }\n await this.engineStore\n .collection(COLLECTION)\n .put(\"customTokens\", new TextEncoder().encode(JSON.stringify(merged)));\n }\n }\n\n private async rpc(client: PublicClient, method: string, params: unknown[]): Promise<unknown> {\n return client.transport.request({ method, params });\n }\n\n private async rpcHex(client: PublicClient, method: string, params: unknown[]): Promise<string> {\n const result: unknown = await this.rpc(client, method, params);\n if (typeof result !== \"string\") {\n throw new TypeError(`${method} returned a malformed result`);\n }\n return result;\n }\n\n /** BTC balance = confirmed spendable + own unconfirmed change; frozen 546/330 shown separately. */\n async refreshBitcoin(xpub: string, network: string): Promise<void> {\n const es = this.options.networks.esplora(network);\n const net = bitcoinNetwork(network);\n const template = \"btc.bip84\" as const;\n const receive = await scanChain(es, xpub, template, network, net.params, 0);\n const change = await scanChain(es, xpub, template, network, net.params, 1);\n const addresses = [...receive, ...change];\n const scanned = await scanUtxos(es, addresses, net.params);\n this.bitcoinUtxos.replace(scanned);\n const changeSet = new Set(change.map((a) => a.address));\n let confirmed = 0n;\n let ownUnconfirmed = 0n;\n let frozen = 0n;\n for (const u of this.bitcoinUtxos.all()) {\n const v = BigInt(u.value);\n if (u.status === \"frozen\" || u.value === 546 || u.value === 330) {\n frozen += v;\n } else if (u.height > 0) {\n confirmed += v;\n } else if (changeSet.has(u.address)) {\n ownUnconfirmed += v;\n }\n }\n this.update((s) => ({\n ...s,\n balances: {\n ...s.balances,\n [`${xpub}:${network}:BTC`]: {\n native: confirmed.toString(),\n tokens: [],\n unconfirmed: ownUnconfirmed.toString(),\n frozen: frozen.toString(),\n },\n },\n }));\n }\n}\n","/** BackupController error categories — never carry file contents, digests or secrets. */\nexport type BackupErrorCategory = \"cloud\" | \"conflict\" | \"unavailable\";\n\nexport class BackupControllerError extends Error {\n readonly category: BackupErrorCategory;\n\n constructor(category: BackupErrorCategory, message: string) {\n super(message);\n this.name = \"BackupControllerError\";\n this.category = category;\n }\n}\n","/**\n * The backup reconcile loop (design/backup.mdx \"同步\"): keeps the cloud file\n * `qntx-wallet-backup-<id>.json` in step with the vault. Single-flight — a trigger during a run\n * schedules exactly one rerun; `lock()` bumps a generation so a stale run never writes state, store\n * or cloud after that point.\n *\n * Security shape: the engine only ever moves ciphertext. The BEK stays in the enclave; the local\n * record is a digest/coverage baseline, not a key.\n */\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, utf8ToBytes } from \"@noble/hashes/utils.js\";\n\nimport type {\n Wallet,\n BackupHeader,\n BackupInfo,\n WalletInfo,\n WalletSnapshot,\n UnlockFactor,\n InitialFactor,\n} from \"@qntx/wallet\";\nimport { parseBackupHeader } from \"@qntx/wallet\";\n\nimport { Controller } from \"../controller.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport type { EngineStore } from \"../store/port.ts\";\nimport { BackupControllerError } from \"./errors.ts\";\nimport type { BackupErrorCategory } from \"./errors.ts\";\nimport type { CloudStore } from \"./port.ts\";\n\nexport type BackupControllerState = {\n readonly status: \"locked\" | \"unavailable\" | \"off\" | \"syncing\" | \"synced\" | \"conflict\" | \"error\";\n /** The retained backup key's public summary from the wallet snapshot. */\n // oxlint-disable-next-line typescript/no-restricted-types -- the snapshot contract is `null`\n readonly backup: BackupInfo | null;\n readonly uploadedAt: number | undefined;\n readonly unprotected: {\n readonly walletIds: ReadonlyArray<string>;\n readonly nostrKeyIds: ReadonlyArray<string>;\n };\n readonly error: BackupErrorCategory | undefined;\n};\n\n/** The EngineStore `backup/state` record — a baseline, never a key. */\ntype BackupRecord = {\n readonly id: string;\n readonly digest: string | undefined;\n readonly uploadedAt: number | undefined;\n readonly walletIds: ReadonlyArray<string>;\n readonly nostrKeyIds: ReadonlyArray<string>;\n};\n\nconst COLLECTION = \"backup\";\nconst RECORD_KEY = \"state\";\nconst FILE_PREFIX = \"qntx-wallet-backup-\";\nconst FILE_SUFFIX = \".json\";\n\nfunction fileName(id: string): string {\n return `${FILE_PREFIX}${id}${FILE_SUFFIX}`;\n}\n\nfunction digestOf(text: string): string {\n return bytesToHex(sha256(utf8ToBytes(text)));\n}\n\nfunction sorted(values: Iterable<string>): ReadonlyArray<string> {\n return [...values].sort();\n}\n\nfunction sameSet(a: ReadonlyArray<string>, b: ReadonlyArray<string>): boolean {\n return a.length === b.length && a.every((v, i) => v === b[i]);\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null;\n\nconst isStringArray = (v: unknown): v is string[] =>\n Array.isArray(v) && v.every((e) => typeof e === \"string\");\n\n/** Strict record validation — anything malformed reads as absent (and is logged). */\nfunction parseRecord(bytes: Uint8Array | undefined): BackupRecord | undefined {\n if (bytes === undefined) {\n return undefined;\n }\n try {\n const value: unknown = JSON.parse(new TextDecoder().decode(bytes));\n if (!isObject(value)) {\n return undefined;\n }\n const o = value;\n const { id } = o;\n const { digest } = o;\n const { uploadedAt } = o;\n const { walletIds } = o;\n const { nostrKeyIds } = o;\n if (typeof id !== \"string\" || !/^[0-9a-f]{32}$/.test(id)) {\n return undefined;\n }\n if (digest !== undefined && (typeof digest !== \"string\" || !/^[0-9a-f]{64}$/.test(digest))) {\n return undefined;\n }\n if (\n uploadedAt !== undefined &&\n (typeof uploadedAt !== \"number\" || !Number.isSafeInteger(uploadedAt))\n ) {\n return undefined;\n }\n if (!isStringArray(walletIds) || !isStringArray(nostrKeyIds)) {\n return undefined;\n }\n return { id, digest, uploadedAt, walletIds, nostrKeyIds };\n } catch {\n return undefined;\n }\n}\n\nexport type BackupControllerOptions = {\n readonly wallet: Wallet;\n readonly cloud: CloudStore | undefined;\n readonly now: () => number;\n readonly logger: EngineLogger;\n};\n\nexport class BackupController extends Controller<BackupControllerState> {\n private readonly wallet: Wallet;\n private readonly cloud: CloudStore | undefined;\n private readonly now: () => number;\n private readonly logger: EngineLogger;\n\n private engineStore: EngineStore | undefined;\n private generation = 0;\n private current: Promise<void> | undefined;\n private rerun = false;\n /** Set by restore() before the store opens — written as a record on the first reconcile. */\n private pendingAdoption: { readonly id: string; readonly digest: string } | undefined;\n\n constructor(options: BackupControllerOptions) {\n super({ name: \"backup\", defaultState: () => defaultState() });\n this.wallet = options.wallet;\n this.cloud = options.cloud;\n this.now = options.now;\n this.logger = options.logger;\n }\n\n async init(): Promise<void> {\n await Promise.resolve();\n }\n\n async destroy(): Promise<void> {\n this.generation += 1;\n await Promise.resolve();\n }\n\n /** The engine hands over the store on unlock and takes it back on lock. */\n setStore(store: EngineStore | undefined): void {\n this.engineStore = store;\n }\n\n /** Bumps the generation: an in-flight reconcile writes nothing after this point. */\n lock(): void {\n this.generation += 1;\n this.engineStore = undefined;\n this.update(() => defaultState());\n }\n\n trigger(): void {\n void this.triggerAsync();\n }\n\n private async triggerAsync(): Promise<void> {\n try {\n await this.reconcile();\n } catch (error) {\n this.logger.warn(\"backup reconcile trigger failed\", error);\n }\n }\n\n /** Explicit sync — awaits the run so callers see its outcome. */\n async sync(): Promise<void> {\n await this.reconcile();\n }\n\n async enable(options: {\n readonly verify: UnlockFactor;\n readonly factors: ReadonlyArray<UnlockFactor>;\n }): Promise<void> {\n // Check before the ceremony: the user must not verify and retain a BEK when there is\n // nowhere to upload it.\n if (this.cloud === undefined || !(await this.cloud.available())) {\n throw new BackupControllerError(\"unavailable\", \"the cloud store is unavailable\");\n }\n await this.wallet.backup.enable(options);\n await this.reconcileOrThrow();\n }\n\n async disable(): Promise<void> {\n await this.wallet.backup.disable();\n await this.reconcileOrThrow();\n }\n\n /** Files under our prefix with a parseable header. */\n async list(): Promise<ReadonlyArray<{ readonly name: string; readonly header: BackupHeader }>> {\n if (this.cloud === undefined) {\n return [];\n }\n const all = await this.cloud.list();\n const names = all.filter((n) => n.startsWith(FILE_PREFIX) && n.endsWith(FILE_SUFFIX));\n const { cloud } = this;\n const texts = await Promise.all(names.map(async (name) => cloud.read(name)));\n const out: Array<{ name: string; header: BackupHeader }> = [];\n for (const [index, name] of names.entries()) {\n const text = texts[index];\n if (text === undefined) {\n continue;\n }\n try {\n out.push({ name, header: parseBackupHeader(text) });\n } catch {\n this.logger.warn(\"backup file failed to parse\", new Error(name));\n }\n }\n return out;\n }\n\n async restore(options: {\n readonly name: string;\n readonly backupFactor: UnlockFactor;\n readonly factor?: InitialFactor;\n }): Promise<ReadonlyArray<WalletInfo>> {\n if (this.cloud === undefined) {\n throw new BackupControllerError(\"cloud\", \"no cloud store configured\");\n }\n const text = await this.cloud.read(options.name);\n if (text === undefined) {\n throw new BackupControllerError(\"cloud\", \"backup file not found\");\n }\n const id = idFromName(options.name);\n if (id === undefined) {\n throw new BackupControllerError(\"cloud\", \"unrecognized backup file name\");\n }\n const wasUninitialized = this.wallet.getSnapshot().vault === \"uninitialized\";\n if (wasUninitialized) {\n // Set before the kernel restore: the commit's status event can already trigger the\n // first reconcile once the engine store opens.\n this.pendingAdoption = { id, digest: digestOf(text) };\n }\n let wallets: ReadonlyArray<WalletInfo>;\n try {\n wallets = await this.wallet.backup.restore({\n envelope: text,\n backupFactor: options.backupFactor,\n ...(options.factor === undefined ? {} : { factor: options.factor }),\n });\n } catch (error) {\n this.pendingAdoption = undefined;\n throw error;\n }\n const { backup } = this.wallet.getSnapshot();\n if (!wasUninitialized && backup !== null && backup.id === id) {\n // Own-lineage merge: baseline to this file's digest, empty coverage forces the next\n // sync to upload the merged superset.\n const previous = await this.readRecord();\n await this.writeRecord({\n id,\n digest: digestOf(text),\n uploadedAt: previous?.uploadedAt,\n walletIds: [],\n nostrKeyIds: [],\n });\n }\n // Converge now — the commit's snapshot trigger may have run before the baseline landed.\n // Restore already succeeded, so a failed reconcile only leaves its status behind.\n try {\n await this.reconcile();\n } catch {\n /* state carries the outcome */\n }\n return wallets;\n }\n\n private async reconcileOrThrow(): Promise<void> {\n await this.reconcile();\n const { status, error } = this.getState();\n if (status === \"error\" || status === \"conflict\" || status === \"unavailable\") {\n throw new BackupControllerError(error ?? \"cloud\", `backup sync failed: ${status}`);\n }\n }\n\n private async readRecord(): Promise<BackupRecord | undefined> {\n const bytes = await this.engineStore?.collection(COLLECTION).get(RECORD_KEY);\n const record = parseRecord(bytes);\n if (bytes !== undefined && record === undefined) {\n this.logger.warn(\"backup record failed to parse — treating as absent\", new Error(COLLECTION));\n }\n return record;\n }\n\n private async writeRecord(record: BackupRecord): Promise<void> {\n await this.engineStore\n ?.collection(COLLECTION)\n .put(RECORD_KEY, new TextEncoder().encode(JSON.stringify(record)));\n }\n\n private async deleteRecord(): Promise<void> {\n await this.engineStore?.collection(COLLECTION).delete(RECORD_KEY);\n }\n\n private snapshot(): WalletSnapshot {\n return this.wallet.getSnapshot();\n }\n\n private unprotected(snapshot: WalletSnapshot, record: BackupRecord | undefined) {\n const covered =\n snapshot.backup !== null &&\n record !== undefined &&\n record.id === snapshot.backup.id &&\n record.digest !== undefined;\n const wallets = snapshot.wallets.filter((w) => w.backup !== \"mnemonic\");\n const keys = snapshot.nostr.keys.filter(\n (k) => k.ref.kind === \"standalone\" && k.backedUp === false,\n );\n const walletIds = wallets\n .map((w) => w.walletId)\n .filter((id) => !covered || !record.walletIds.includes(id));\n const nostrKeyIds = keys\n .map((k) => k.publicKey)\n .filter((id) => !covered || !record.nostrKeyIds.includes(id));\n return { walletIds: sorted(walletIds), nostrKeyIds: sorted(nostrKeyIds) };\n }\n\n private coverage(snapshot: WalletSnapshot): {\n readonly walletIds: ReadonlyArray<string>;\n readonly nostrKeyIds: ReadonlyArray<string>;\n } {\n return {\n walletIds: sorted(snapshot.wallets.map((w) => w.walletId)),\n nostrKeyIds: sorted(\n snapshot.nostr.keys.filter((k) => k.ref.kind === \"standalone\").map((k) => k.publicKey),\n ),\n };\n }\n\n private setStatus(\n generation: number,\n status: BackupControllerState[\"status\"],\n error?: BackupErrorCategory,\n record?: BackupRecord,\n ): void {\n if (generation !== this.generation) {\n return;\n }\n const snapshot = this.snapshot();\n this.update((state) => ({\n ...state,\n status,\n backup: snapshot.backup,\n uploadedAt: record?.uploadedAt,\n error,\n unprotected: this.unprotected(snapshot, record),\n }));\n }\n\n /**\n * Single-flight: a trigger during a run flags exactly one rerun inside the same promise, so\n * `sync()`/`enable()` await real convergence instead of a mid-run snapshot.\n */\n private async reconcile(): Promise<void> {\n if (this.current !== undefined) {\n this.rerun = true;\n return this.current;\n }\n this.current = (async () => {\n try {\n do {\n this.rerun = false;\n // The generation is read per pass: a lock invalidates the current pass, and a\n // trigger flagged under it still earns a fresh pass after unlock.\n // oxlint-disable-next-line eslint/no-await-in-loop -- passes must serialize: one rerun flag, one pass at a time\n await this.pass(this.generation);\n } while (this.rerun);\n } finally {\n this.current = undefined;\n }\n })();\n return this.current;\n }\n\n private async pass(generation: number): Promise<void> {\n const snapshot = this.snapshot();\n if (snapshot.vault !== \"unlocked\" || this.engineStore === undefined) {\n return;\n }\n let record = await this.readRecord();\n if (this.cloud === undefined || !(await this.cloud.available())) {\n this.setStatus(generation, \"unavailable\", undefined, record);\n return;\n }\n if (generation !== this.generation) {\n return;\n }\n\n // Pending adoption lands once — and only when the vault's backup key is the file's key.\n const adoption = this.pendingAdoption;\n if (adoption !== undefined) {\n this.pendingAdoption = undefined;\n if (snapshot.backup?.id === adoption.id) {\n record = {\n id: adoption.id,\n digest: adoption.digest,\n uploadedAt: undefined,\n walletIds: [],\n nostrKeyIds: [],\n };\n if (generation !== this.generation) {\n return;\n }\n await this.writeRecord(record);\n } else {\n this.logger.warn(\n \"backup adoption dropped — the vault's backup key is not the file's\",\n new Error(adoption.id),\n );\n }\n }\n\n const { backup } = snapshot;\n if (backup === null) {\n // Backup off in the vault: remove our file + record, then report off.\n if (record !== undefined) {\n try {\n if (generation !== this.generation) {\n return;\n }\n await this.cloud.delete(fileName(record.id));\n if (generation !== this.generation) {\n return;\n }\n await this.deleteRecord();\n } catch (error) {\n this.logger.warn(\"backup cloud delete failed — retrying next reconcile\", error);\n this.setStatus(generation, \"error\", \"cloud\", record);\n return;\n }\n }\n this.setStatus(generation, \"off\", undefined, undefined);\n return;\n }\n\n const baseline = record !== undefined && record.id === backup.id ? record.digest : undefined;\n const cov = this.coverage(snapshot);\n if (\n baseline !== undefined &&\n record !== undefined &&\n sameSet(cov.walletIds, record.walletIds) &&\n sameSet(cov.nostrKeyIds, record.nostrKeyIds)\n ) {\n this.setStatus(generation, \"synced\", undefined, record);\n return;\n }\n\n this.setStatus(generation, \"syncing\", undefined, record);\n try {\n const envelope = await this.wallet.backup.update();\n if (generation !== this.generation) {\n return;\n }\n const name = fileName(backup.id);\n const remote = await this.cloud.read(name);\n const digest = digestOf(envelope);\n if (remote !== undefined && digestOf(remote) !== baseline) {\n this.setStatus(generation, \"conflict\", \"conflict\", record);\n return;\n }\n if (generation !== this.generation) {\n return;\n }\n await this.cloud.write(name, envelope);\n const readBack = await this.cloud.read(name);\n if (readBack !== envelope) {\n this.setStatus(generation, \"error\", \"cloud\", record);\n return;\n }\n const next: BackupRecord = {\n id: backup.id,\n digest,\n uploadedAt: this.now(),\n walletIds: cov.walletIds,\n nostrKeyIds: cov.nostrKeyIds,\n };\n if (generation !== this.generation) {\n return;\n }\n await this.writeRecord(next);\n if (record !== undefined && record.id !== backup.id) {\n try {\n if (generation !== this.generation) {\n return;\n }\n await this.cloud.delete(fileName(record.id));\n } catch (error) {\n this.logger.warn(\"stale backup file delete failed\", error);\n }\n }\n this.setStatus(generation, \"synced\", undefined, next);\n } catch (error) {\n if (generation !== this.generation) {\n return;\n }\n this.logger.warn(\"backup reconcile failed\", error);\n this.setStatus(generation, \"error\", \"cloud\", record);\n }\n }\n}\n\nfunction defaultState(): BackupControllerState {\n return {\n status: \"locked\",\n backup: null,\n uploadedAt: undefined,\n unprotected: { walletIds: [], nostrKeyIds: [] },\n error: undefined,\n };\n}\n\nfunction idFromName(name: string): string | undefined {\n if (!name.startsWith(FILE_PREFIX) || !name.endsWith(FILE_SUFFIX)) {\n return undefined;\n }\n const id = name.slice(FILE_PREFIX.length, name.length - FILE_SUFFIX.length);\n return /^[0-9a-f]{32}$/.test(id) ? id : undefined;\n}\n","/**\n * Wallet metadata document — the plaintext exchanged over kind-30078 events between this wallet's\n * own devices. One document per wallet; entry-level last-writer-wins on `updatedAt`.\n */\n\nexport type MetaDocWallet = {\n readonly name?: string;\n readonly updatedAt: number;\n};\n\nexport type MetaDocGroup = {\n readonly index: number;\n readonly name?: string;\n readonly hidden: boolean;\n readonly boundPubkey?: string;\n readonly updatedAt: number;\n};\n\nexport type MetaDoc = {\n readonly v: 1;\n readonly wallet: MetaDocWallet;\n readonly groups: ReadonlyArray<MetaDocGroup>;\n};\n\nexport const META_DOC_MAX_BYTES = 65536;\n\nconst NAME_MAX = 24;\nconst PUBKEY_RE = /^[0-9a-f]{64}$/;\nconst KNOWN_DOC_KEYS = new Set([\"v\", \"wallet\", \"groups\"]);\nconst KNOWN_WALLET_KEYS = new Set([\"name\", \"updatedAt\"]);\nconst KNOWN_GROUP_KEYS = new Set([\"index\", \"name\", \"hidden\", \"boundPubkey\", \"updatedAt\"]);\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\nconst isNonNegativeInt = (v: unknown): v is number =>\n typeof v === \"number\" && Number.isSafeInteger(v) && v >= 0;\n\nconst validName = (v: unknown): boolean =>\n v === undefined || (typeof v === \"string\" && v.trim().length > 0 && v.trim().length <= NAME_MAX);\n\nconst trimmedName = (v: unknown): string | undefined =>\n typeof v === \"string\" ? v.trim() : undefined;\n\n/** Strict decode — any malformed shape, unknown key or duplicate index returns `undefined`. */\nexport function decodeMetaDoc(value: unknown): MetaDoc | undefined {\n if (!isObject(value)) {\n return undefined;\n }\n for (const k of Object.keys(value)) {\n if (!KNOWN_DOC_KEYS.has(k)) {\n return undefined;\n }\n }\n if (value[\"v\"] !== 1) {\n return undefined;\n }\n const { wallet } = value;\n if (!isObject(wallet)) {\n return undefined;\n }\n for (const k of Object.keys(wallet)) {\n if (!KNOWN_WALLET_KEYS.has(k)) {\n return undefined;\n }\n }\n if (!validName(wallet[\"name\"]) || !isNonNegativeInt(wallet[\"updatedAt\"])) {\n return undefined;\n }\n const { groups } = value;\n if (!Array.isArray(groups)) {\n return undefined;\n }\n const seen = new Set<number>();\n const out: MetaDocGroup[] = [];\n for (const item of groups) {\n if (!isObject(item)) {\n return undefined;\n }\n for (const k of Object.keys(item)) {\n if (!KNOWN_GROUP_KEYS.has(k)) {\n return undefined;\n }\n }\n const { index } = item;\n if (!isNonNegativeInt(index) || seen.has(index)) {\n return undefined;\n }\n seen.add(index);\n if (!validName(item[\"name\"]) || (item[\"hidden\"] !== true && item[\"hidden\"] !== false)) {\n return undefined;\n }\n const { boundPubkey } = item;\n if (\n boundPubkey !== undefined &&\n (typeof boundPubkey !== \"string\" || !PUBKEY_RE.test(boundPubkey))\n ) {\n return undefined;\n }\n if (!isNonNegativeInt(item[\"updatedAt\"])) {\n return undefined;\n }\n const gName = trimmedName(item[\"name\"]);\n out.push({\n index,\n hidden: item[\"hidden\"],\n updatedAt: item[\"updatedAt\"],\n ...(gName === undefined ? {} : { name: gName }),\n ...(boundPubkey === undefined ? {} : { boundPubkey }),\n });\n }\n out.sort((a, b) => a.index - b.index);\n const name = trimmedName(wallet[\"name\"]);\n return {\n v: 1,\n wallet: {\n updatedAt: wallet[\"updatedAt\"],\n ...(name === undefined ? {} : { name }),\n },\n groups: out,\n };\n}\n\n/** UTF-8 JSON — `undefined` when the document exceeds the 64 KB limit. */\nexport function encodeMetaDoc(doc: MetaDoc): Uint8Array | undefined {\n const bytes = new TextEncoder().encode(JSON.stringify(doc));\n return bytes.byteLength <= META_DOC_MAX_BYTES ? bytes : undefined;\n}\n\nexport function decodeMetaDocBytes(bytes: Uint8Array): MetaDoc | undefined {\n if (bytes.byteLength > META_DOC_MAX_BYTES) {\n return undefined;\n }\n try {\n return decodeMetaDoc(JSON.parse(new TextDecoder().decode(bytes)));\n } catch {\n return undefined;\n }\n}\n","/** Meta-sync error categories — messages never carry event or document content. */\nexport type MetaSyncErrorCategory = \"network\" | \"internal\" | \"unsupported\" | \"corrupt\";\n\nexport class MetaSyncError extends Error {\n readonly category: MetaSyncErrorCategory;\n\n constructor(category: MetaSyncErrorCategory, message: string, cause?: unknown) {\n super(message, { cause });\n this.name = \"MetaSyncError\";\n this.category = category;\n }\n}\n","import type { Event, Filter } from \"@qntx/nostr\";\nimport { verifyEvent } from \"@qntx/nostr\";\nimport type { Wallet } from \"@qntx/wallet\";\nimport type { NostrKeyRef, WalletSigner } from \"@qntx/wallet/nostr\";\n\nimport type { AccountTreeController } from \"../accounts/controller.ts\";\nimport { Controller } from \"../controller.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport { decodeMetaDocBytes, encodeMetaDoc } from \"./doc.ts\";\nimport type { MetaSyncErrorCategory } from \"./errors.ts\";\nimport { MetaSyncError } from \"./errors.ts\";\n\nexport const META_SYNC_KIND = 30078;\nconst PUBLISH_DEBOUNCE_MS = 2000;\n\nexport type MetaSyncRelayPort = {\n readonly fetch: (filter: Filter) => Promise<ReadonlyArray<Event>>;\n readonly publish: (event: Event) => Promise<void>;\n};\n\nexport type MetaSyncConfig = {\n /** The `d` tag that names this wallet's metadata document. */\n readonly tag: string;\n readonly relays: MetaSyncRelayPort;\n};\n\nexport type MetaSyncWalletStatus = {\n readonly status: \"unavailable\" | \"syncing\" | \"synced\" | \"error\";\n readonly error?: MetaSyncErrorCategory;\n};\n\nexport type MetaSyncState = {\n readonly wallets: Readonly<Record<string, MetaSyncWalletStatus>>;\n};\n\nexport type MetaSyncControllerOptions = {\n readonly wallet: Wallet;\n readonly accounts: AccountTreeController;\n /** `nostr(wallet)` — the signer is requested per wallet for its group-0 derived key. */\n readonly nostr: { readonly signer: (ref: NostrKeyRef) => WalletSigner };\n readonly metaSync: MetaSyncConfig | undefined;\n readonly logger: EngineLogger;\n readonly now: () => number;\n};\n\n/**\n * Wallet-metadata sync over kind-30078 addressable events: one NIP-44-encrypted document per\n * wallet, authored by its group-0 derived key. Pull always precedes publish in an unlock session —\n * replaceable events would otherwise let a stale local tree overwrite a newer remote document.\n * Debounced publishes are per wallet; a generation counter cancels in-flight write-backs on lock.\n */\nexport class MetaSyncController extends Controller<MetaSyncState> {\n private readonly options: MetaSyncControllerOptions;\n private generation = 0;\n private readonly pulled = new Set<string>();\n private readonly lastRemoteCreatedAt = new Map<string, number>();\n private readonly lastExported = new Map<string, string>();\n private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();\n private readonly inflight = new Set<string>();\n private accountsUnsubscribe: (() => void) | undefined;\n\n constructor(options: MetaSyncControllerOptions) {\n super({ name: \"metaSync\", defaultState: () => ({ wallets: {} }) });\n this.options = options;\n }\n\n /** Unlocked: pull every wallet whose group-0 identity exists, then watch the tree. */\n async init(): Promise<void> {\n const gen = ++this.generation;\n this.accountsUnsubscribe = this.options.accounts.store.subscribe(() => {\n this.onTreeChange();\n });\n // pullAll covers every snapshot wallet at init — reconcile() is for additions later.\n await this.pullAll(gen);\n }\n\n async destroy(): Promise<void> {\n await this.lock();\n }\n\n /** Locked: cancel debounces and in-flight write-backs, forget the pull/publish bookkeeping. */\n async lock(): Promise<void> {\n this.generation += 1;\n this.accountsUnsubscribe?.();\n this.accountsUnsubscribe = undefined;\n for (const timer of this.timers.values()) {\n clearTimeout(timer);\n }\n this.timers.clear();\n this.pulled.clear();\n this.lastRemoteCreatedAt.clear();\n this.lastExported.clear();\n this.inflight.clear();\n this.update(() => ({ wallets: {} }));\n await Promise.resolve();\n }\n\n /** Snapshot changed while unlocked: pull newly-seen wallets, drop removed ones. */\n reconcile(): void {\n if (this.options.metaSync === undefined) {\n return;\n }\n const snap = this.options.wallet.getSnapshot();\n const live = new Set(snap.wallets.map((w) => w.walletId));\n const gen = this.generation;\n for (const w of snap.wallets) {\n if (this.getState().wallets[w.walletId] === undefined) {\n void this.pullOne(w.walletId, gen);\n }\n }\n this.update((s) => {\n const wallets = Object.fromEntries(\n Object.entries(s.wallets).filter(([walletId]) => live.has(walletId)),\n );\n return { ...s, wallets };\n });\n }\n\n /** Manual re-pull of every wallet that can sync. */\n async sync(): Promise<void> {\n await this.pullAll(this.generation);\n }\n\n private async pullAll(gen: number): Promise<void> {\n const snap = this.options.wallet.getSnapshot();\n await Promise.all(snap.wallets.map(async (w) => this.pullOne(w.walletId, gen)));\n }\n\n private async pubkeyFor(signer: WalletSigner): Promise<string> {\n return signer.getPublicKey();\n }\n\n private signerFor(walletId: string): WalletSigner | undefined {\n const snap = this.options.wallet.getSnapshot();\n const ref = { kind: \"derived\" as const, walletId, groupIndex: 0 };\n const hasKey = snap.nostr.keys.some(\n (k) => k.ref.kind === \"derived\" && k.ref.walletId === walletId && k.ref.groupIndex === 0,\n );\n if (!hasKey) {\n return undefined;\n }\n return this.options.nostr.signer(ref);\n }\n\n private setStatus(walletId: string, status: MetaSyncWalletStatus): void {\n this.update((s) => ({ ...s, wallets: { ...s.wallets, [walletId]: status } }));\n }\n\n private async pullOne(walletId: string, gen: number): Promise<void> {\n const config = this.options.metaSync;\n if (config === undefined || this.inflight.has(walletId)) {\n return;\n }\n const signer = this.signerFor(walletId);\n if (signer === undefined) {\n if (gen === this.generation) {\n this.setStatus(walletId, { status: \"unavailable\" });\n }\n return;\n }\n this.inflight.add(walletId);\n this.setStatus(walletId, { status: \"syncing\" });\n try {\n const pubkey = await this.pubkeyFor(signer);\n const events = await config.relays.fetch(this.filterFor(pubkey, config.tag));\n let remote: Event | undefined;\n let remoteSkipped = 0;\n for (const e of events) {\n if (!this.acceptableEvent(e, pubkey, config.tag)) {\n remoteSkipped += 1;\n continue;\n }\n if (remote === undefined || e.created_at > remote.created_at) {\n remote = e;\n }\n }\n if (remote === undefined) {\n // No doc on the relay: publish only when the local tree holds a real edit\n // (updatedAt > 0) — a fresh device must not replace nothing with empty defaults.\n const local = this.options.accounts.exportMeta(walletId);\n const hasEdits = local.wallet.updatedAt > 0 || local.groups.some((g) => g.updatedAt > 0);\n if (gen !== this.generation) {\n return;\n }\n this.pulled.add(walletId);\n this.rememberExport(walletId);\n this.setStatus(walletId, { status: \"synced\" });\n if (hasEdits) {\n await this.publishNow(walletId, gen);\n }\n } else {\n // A verified event we cannot read must never be overwritten — a newer app version\n // (e.g. v: 2) is the most likely cause; decode failure is data corruption.\n const decrypt = signer.nip44Decrypt;\n const plaintext =\n decrypt === undefined\n ? undefined\n : await decrypt.call(signer, pubkey, remote.content).catch(() => undefined);\n const doc =\n plaintext === undefined\n ? undefined\n : decodeMetaDocBytes(new TextEncoder().encode(plaintext));\n if (doc === undefined) {\n if (gen !== this.generation) {\n return;\n }\n const error: MetaSyncErrorCategory =\n plaintext !== undefined && isUnsupportedDoc(plaintext) ? \"unsupported\" : \"corrupt\";\n this.setStatus(walletId, { status: \"error\", error });\n this.options.logger.warn(`meta sync: unreadable remote doc (${error})`);\n return; // not in `pulled` — debounced publishes stay blocked too\n }\n const merge = this.options.accounts.mergeMeta(walletId, doc);\n if (gen !== this.generation) {\n return;\n }\n this.lastRemoteCreatedAt.set(walletId, remote.created_at);\n this.pulled.add(walletId);\n this.rememberExport(walletId);\n this.setStatus(walletId, { status: \"synced\" });\n if (merge.localNewer) {\n await this.publishNow(walletId, gen);\n }\n }\n if (remoteSkipped > 0) {\n this.options.logger.warn(`meta sync: ignored ${remoteSkipped} invalid remote events`);\n }\n } catch (error) {\n if (gen === this.generation) {\n this.setStatus(walletId, { status: \"error\", error: categorizeSync(error) });\n this.options.logger.warn(\"meta sync pull failed\", error);\n }\n } finally {\n this.inflight.delete(walletId);\n }\n }\n\n private filterFor(pubkey: string, tag: string): Filter {\n return { kinds: [META_SYNC_KIND], authors: [pubkey], \"#d\": [tag] };\n }\n\n private acceptableEvent(e: Event, pubkey: string, tag: string): boolean {\n if (e.kind !== META_SYNC_KIND || e.pubkey !== pubkey || !verifyEvent(e)) {\n return false;\n }\n const dTags = e.tags.filter((t) => t[0] === \"d\");\n return dTags.length === 1 && dTags[0]?.[1] === tag;\n }\n\n /** Snapshot the wallet's exported doc — the debounce publishes only on a real change. */\n private rememberExport(walletId: string): void {\n try {\n const doc = this.options.accounts.exportMeta(walletId);\n this.lastExported.set(walletId, JSON.stringify(doc));\n } catch {\n // Wallet not in the tree — nothing to remember.\n }\n }\n\n private onTreeChange(): void {\n if (this.options.metaSync === undefined) {\n return;\n }\n for (const walletId of this.pulled) {\n let current: string | undefined;\n try {\n current = JSON.stringify(this.options.accounts.exportMeta(walletId));\n } catch {\n continue;\n }\n if (current === this.lastExported.get(walletId)) {\n continue;\n }\n this.lastExported.set(walletId, current);\n const existing = this.timers.get(walletId);\n if (existing !== undefined) {\n clearTimeout(existing);\n }\n const gen = this.generation;\n this.timers.set(\n walletId,\n setTimeout(() => {\n this.timers.delete(walletId);\n void this.publishNow(walletId, gen);\n }, PUBLISH_DEBOUNCE_MS),\n );\n }\n }\n\n private async publishNow(walletId: string, gen: number): Promise<void> {\n const config = this.options.metaSync;\n if (config === undefined || !this.pulled.has(walletId)) {\n return;\n }\n const signer = this.signerFor(walletId);\n if (signer === undefined) {\n this.setStatus(walletId, { status: \"unavailable\" });\n return;\n }\n try {\n const doc = this.options.accounts.exportMeta(walletId);\n const bytes = encodeMetaDoc(doc);\n if (bytes === undefined) {\n throw new MetaSyncError(\"internal\", \"meta doc exceeds 64 KB\");\n }\n const encrypt = signer.nip44Encrypt;\n if (encrypt === undefined) {\n throw new MetaSyncError(\"internal\", \"signer lacks nip44 encryption\");\n }\n const pubkey = await this.pubkeyFor(signer);\n const content = await encrypt.call(signer, pubkey, new TextDecoder().decode(bytes));\n const lastRemote = this.lastRemoteCreatedAt.get(walletId) ?? 0;\n const created_at = Math.max(Math.floor(this.options.now() / 1000), lastRemote + 1);\n const event = await signer.signEvent({\n pubkey,\n kind: META_SYNC_KIND,\n created_at,\n tags: [[\"d\", config.tag]],\n content,\n });\n if (gen !== this.generation) {\n return;\n }\n await config.relays.publish(event);\n } catch (error) {\n if (gen === this.generation) {\n this.setStatus(walletId, { status: \"error\", error: categorizeSync(error) });\n this.options.logger.warn(\"meta sync publish failed\", error);\n }\n }\n }\n}\n\nfunction categorizeSync(error: unknown): MetaSyncErrorCategory {\n return error instanceof MetaSyncError ? error.category : \"network\";\n}\n\n/** A decrypted doc that parses as JSON with a numeric `v` above 1 is a newer schema, not garbage. */\nfunction isUnsupportedDoc(plaintext: string): boolean {\n try {\n const doc: unknown = JSON.parse(plaintext);\n return (\n typeof doc === \"object\" &&\n doc !== null &&\n \"v\" in doc &&\n typeof doc.v === \"number\" &&\n doc.v > 1\n );\n } catch {\n return false;\n }\n}\n","import { hex } from \"@scure/base\";\nimport { Transaction } from \"@scure/btc-signer\";\nimport type { NETWORK as BTC_MAINNET } from \"@scure/btc-signer\";\nimport { p2wpkh } from \"@scure/btc-signer/payment.js\";\n/**\n * Bitcoin chain adapter — Esplora client, gap-20 address scanning, PSBT construction with\n *\n * @scure/btc-signer selectUTXO (bip69), fee tiers from /fee-estimates (targets 1/3/6/144),\n * dust floors per output type, frozen 546/330-sat UTXOs, and POST /tx broadcasting. Custom\n * endpoints are validated by the genesis block hash via /block-height/0. RBF/CPFP are out\n * of scope for this layer.\n */\nimport type { TransactionInputUpdate } from \"@scure/btc-signer/psbt.js\";\nimport { selectUTXO } from \"@scure/btc-signer/utxo.js\";\n\nconst GAP_LIMIT = 20;\nexport { GAP_LIMIT };\nconst DUST: Record<string, number> = { p2wpkh: 294, p2tr: 330, p2pkh: 546 };\nconst FROZEN_AMOUNTS = new Set([546, 330]);\n\nexport type BtcNetworkId = `bip122:${string}`;\n\nexport type BtcUtxo = {\n readonly txid: string;\n readonly vout: number;\n readonly value: number;\n readonly address: string;\n readonly status: \"unconfirmed\" | \"confirmed\" | \"locked\" | \"frozen\";\n readonly height: number;\n};\n\nexport type BtcAddress = {\n readonly chain: 0 | 1;\n readonly index: number;\n readonly address: string;\n readonly used: boolean;\n};\n\nexport type Esplora = {\n readonly get: (path: string) => Promise<unknown>;\n readonly post: (path: string, body: string) => Promise<unknown>;\n};\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null;\n\nexport type EsploraResponse = {\n readonly ok: boolean;\n readonly status: number;\n readonly headers: { get: (name: string) => string | undefined };\n readonly json: () => Promise<unknown>;\n readonly text: () => Promise<string>;\n};\nexport type EsploraFetch = (\n url: string,\n init?: {\n method: string;\n headers?: Record<string, string>;\n body?: string;\n signal?: AbortSignal;\n },\n) => Promise<EsploraResponse>;\n\nexport class EsploraError extends Error {\n /** True for request timeout/abort, network failure, 429-after-retries and 5xx — safe to retry. */\n readonly transient: boolean;\n constructor(message: string, transient: boolean) {\n super(message);\n this.name = \"EsploraError\";\n this.transient = transient;\n }\n}\n\nconst MAX_IN_FLIGHT = 4;\nconst MAX_RETRIES = 3;\nconst MAX_BACKOFF_MS = 2000;\nconst REQUEST_TIMEOUT_MS = 10_000;\n\n/** Bounded-concurrency + 429-aware ordered failover over the endpoint list. */\nexport const esplora = (\n endpoints: ReadonlyArray<string>,\n fetchFn: EsploraFetch,\n sleep: (ms: number) => Promise<void>,\n timeoutMs: number = REQUEST_TIMEOUT_MS,\n): Esplora => {\n let inFlight = 0;\n const waiters: Array<() => void> = [];\n const acquire = async (): Promise<void> => {\n if (inFlight >= MAX_IN_FLIGHT) {\n await new Promise<void>((resolve) => {\n waiters.push(resolve);\n });\n }\n inFlight += 1;\n };\n const release = (): void => {\n inFlight -= 1;\n const next = waiters.shift();\n next?.();\n };\n const backoff = async (headers: EsploraResponse[\"headers\"], retry: number): Promise<void> => {\n const ra = headers.get(\"retry-after\");\n const retryAfterMs =\n ra !== null && ra !== \"\" && !Number.isNaN(Number(ra)) ? Number(ra) * 1000 : undefined;\n const jitter = Math.floor(Math.random() * 100);\n await sleep(retryAfterMs ?? Math.min(100 * 2 ** retry + jitter, MAX_BACKOFF_MS));\n };\n // One request inside a concurrency slot. A 429 releases the slot before anyone backs off:\n // retrying while holding it deadlocks once every slot is throttled at the same time.\n const request = async (\n base: string,\n path: string,\n body: string | undefined,\n ): Promise<{ readonly value: unknown } | { readonly throttled: EsploraResponse[\"headers\"] }> => {\n await acquire();\n try {\n let res: EsploraResponse;\n try {\n // An unbounded request can hang the whole scan — bound it so a stalled\n // electrs surfaces as a failure the caller can retry rather than a hang.\n res = await fetchFn(`${base.replace(/\\/$/, \"\")}${path}`, {\n ...(body === undefined\n ? { method: \"GET\" }\n : { method: \"POST\", headers: { \"content-type\": \"text/plain\" }, body }),\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n throw new EsploraError(\n `esplora ${base}${path}: request failed (${error instanceof Error ? error.name : \"unknown\"})`,\n true,\n );\n }\n if (res.status === 429) {\n return { throttled: res.headers };\n }\n if (!res.ok) {\n throw new EsploraError(`esplora ${base}${path}: ${res.status}`, res.status >= 500);\n }\n const text = await res.text();\n try {\n return { value: JSON.parse(text) as unknown };\n } catch {\n return { value: text };\n }\n } finally {\n release();\n }\n };\n const call = async (\n base: string,\n path: string,\n body: string | undefined,\n retry: number,\n ): Promise<unknown> => {\n const outcome = await request(base, path, body);\n if (\"value\" in outcome) {\n return outcome.value;\n }\n if (retry >= MAX_RETRIES) {\n throw new EsploraError(`esplora ${base}${path}: 429 after ${MAX_RETRIES} retries`, true);\n }\n await backoff(outcome.throttled, retry);\n return call(base, path, body, retry + 1);\n };\n const attempt = async (\n rest: ReadonlyArray<string>,\n path: string,\n body: string | undefined,\n last: unknown,\n ): Promise<unknown> => {\n const [base, ...next] = rest;\n if (base === undefined) {\n throw last instanceof Error ? last : new Error(\"all esplora endpoints failed\");\n }\n try {\n return await call(base, path, body, 0);\n } catch (error) {\n return attempt(next, path, body, error);\n }\n };\n return {\n get: async (path) => attempt(endpoints, path, undefined, undefined),\n post: async (path, body) => attempt(endpoints, path, body, undefined),\n };\n};\n\nexport const validateEndpoint = async (es: Esplora, genesisHash: string): Promise<void> => {\n const got = await es.get(\"/block-height/0\");\n if (got !== genesisHash) {\n throw new Error(`endpoint genesis ${String(got)} ≠ ${genesisHash}`);\n }\n};\n\nexport const feeTiers = async (\n es: Esplora,\n): Promise<ReadonlyArray<{ tier: \"fast\" | \"normal\" | \"slow\" | \"economy\"; satPerByte: number }>> => {\n const res = await es.get(\"/fee-estimates\");\n const estimates = isObject(res) ? res : {};\n const pick = (target: string): number => Math.max(1, Math.ceil(Number(estimates[target] ?? 1)));\n return [\n { tier: \"fast\", satPerByte: pick(\"1\") },\n { tier: \"normal\", satPerByte: pick(\"3\") },\n { tier: \"slow\", satPerByte: pick(\"6\") },\n { tier: \"economy\", satPerByte: pick(\"144\") },\n ];\n};\n\nexport const dustFor = (scriptType: string): number => DUST[scriptType] ?? 546;\n\nexport const isFrozen = (value: number): boolean => FROZEN_AMOUNTS.has(value);\n\nexport type BtcInput = TransactionInputUpdate;\n\nexport class BitcoinChainAdapter {\n /** Inputs for selectUTXO — the same TransactionInputUpdate objects added to the PSBT. */\n toInputs(\n utxos: ReadonlyArray<BtcUtxo>,\n fingerprint: number,\n pathOf: (utxo: BtcUtxo) => number[],\n pubkeyOf: (utxo: BtcUtxo) => Uint8Array,\n scriptOf: (utxo: BtcUtxo) => Uint8Array,\n template: string,\n rawTxOf?: (utxo: BtcUtxo) => Uint8Array | undefined,\n ): BtcInput[] {\n return utxos\n .filter((u) => u.status === \"confirmed\" && !isFrozen(u.value))\n .map((u) => {\n const pub = pubkeyOf(u);\n // bip49 is a segwit-wrapped P2SH spend (witnessUtxo + redeemScript);\n // bip44 P2PKH proves the prevout through the whole prior transaction.\n const entry: TransactionInputUpdate = {\n txid: u.txid,\n index: u.vout,\n sequence: 0xfffffffd,\n };\n if (template !== \"btc.bip44\") {\n entry.witnessUtxo = { amount: BigInt(u.value), script: scriptOf(u) };\n }\n if (template === \"btc.bip44\") {\n const raw = rawTxOf === undefined ? undefined : rawTxOf(u);\n if (raw === undefined) {\n throw new Error(`no raw transaction for bip44 input ${u.txid}`);\n }\n entry.nonWitnessUtxo = raw;\n }\n if (template === \"btc.bip86\") {\n entry.tapInternalKey = pub.subarray(1);\n entry.tapBip32Derivation = [\n [pub.subarray(1), { hashes: [], der: { fingerprint, path: pathOf(u) } }],\n ];\n } else {\n entry.bip32Derivation = [[pub, { fingerprint, path: pathOf(u) }]];\n if (template === \"btc.bip49\") {\n entry.redeemScript = p2wpkh(pub).script;\n }\n }\n return entry;\n });\n }\n\n buildPsbt(\n inputs: ReadonlyArray<BtcInput>,\n to: string,\n amount: bigint,\n feePerByte: bigint,\n changeAddress: string,\n network: typeof BTC_MAINNET,\n ): { readonly psbt: Uint8Array; readonly inputs: ReadonlyArray<BtcInput> } {\n const selection = selectUTXO([...inputs], [{ address: to, amount }], \"default\", {\n feePerByte,\n changeAddress,\n bip69: true,\n dust: BigInt(dustFor(\"p2wpkh\")),\n network,\n createTx: true,\n });\n if (selection === undefined || selection.tx === undefined) {\n throw new Error(\"insufficient confirmed utxo for the amount + fee\");\n }\n const wanted = new Set(\n (selection.inputs ?? []).flatMap((sel) => {\n const raw = sel.txid;\n if (!(raw instanceof Uint8Array)) {\n return [];\n }\n const forward = hex.encode(raw);\n const reverse = hex.encode(Uint8Array.from(raw).reverse());\n return [`${forward}:${String(sel.index ?? -1)}`, `${reverse}:${String(sel.index ?? -1)}`];\n }),\n );\n const chosen = inputs.filter((i) => wanted.has(`${String(i.txid)}:${String(i.index)}`));\n return { psbt: selection.tx.toPSBT(), inputs: chosen };\n }\n\n /** Fixed-input/output PSBT — the RBF/CPFP path, which chooses nothing itself. */\n buildExactPsbt(\n inputs: ReadonlyArray<BtcInput>,\n outputs: ReadonlyArray<{ readonly address: string; readonly amount: bigint }>,\n network: typeof BTC_MAINNET,\n ): { readonly psbt: Uint8Array; readonly vsize: number } {\n const tx = new Transaction();\n for (const input of inputs) {\n tx.addInput(input);\n }\n for (const out of outputs) {\n tx.addOutputAddress(out.address, out.amount, network);\n }\n // Unsigned tx has no witness — vsize is the BIP-141 weight estimate\n // (10.5 overhead + ~68/input + ~31/output for P2WPKH; taproot ~57.5/43).\n const tap = inputs.every((i) => i.tapInternalKey !== undefined);\n const vsize = Math.ceil(\n 10.5 + inputs.length * (tap ? 57.5 : 68) + outputs.length * (tap ? 43 : 31),\n );\n return { psbt: tx.toPSBT(), vsize };\n }\n}\n","/**\n * Built-in EVM network registry: the 8 mainnets from chains.mdx plus their main testnets. Each\n * chain id was checked against the chain's official documentation (source URL per entry).\n * Signing-time chainId always comes from this table, never from an RPC endpoint.\n */\n\nexport type NetworkInfo = {\n readonly id: string; // CAIP-2 eip155:<chainId>\n readonly chainId: number;\n readonly name: string;\n readonly symbol: string;\n readonly multicall3?: string;\n /** CAIP-2 family — `solana:<ref>` networks are validated against genesis-hash, not chainId. */\n readonly family: \"evm\" | \"solana\" | \"bitcoin\";\n readonly genesisHash?: string;\n readonly decimals: number;\n readonly testnet: boolean;\n};\n\nconst entry = (\n chainId: number,\n name: string,\n symbol: string,\n testnet: boolean,\n _source: string,\n): NetworkInfo => ({\n id: `eip155:${chainId}`,\n chainId,\n name,\n symbol,\n decimals: 18,\n testnet,\n family: \"evm\",\n // Canonical Multicall3 — https://github.com/mds1/multicall3 deployments (all entries below).\n multicall3: \"0xcA11bde05977b3631167028862bE2a173976CA11\",\n});\n\nexport const NETWORKS: ReadonlyArray<NetworkInfo> = [\n // https://chainlist.org + https://ethereum.org (Ethereum mainnet chainId 1)\n entry(1, \"Ethereum\", \"ETH\", false, \"https://ethereum.org/en/developers/docs/networks/\"),\n // https://docs.base.org — Base Sepolia 84532\n entry(8453, \"Base\", \"ETH\", false, \"https://docs.base.org/docs/network-information\"),\n // https://docs.arbitrum.io — Arbitrum Sepolia 421614\n entry(\n 42161,\n \"Arbitrum One\",\n \"ETH\",\n false,\n \"https://docs.arbitrum.io/for-devs/dev-tools-and-resources/chain-info\",\n ),\n // https://docs.optimism.io — OP Sepolia 11155420\n entry(10, \"OP Mainnet\", \"ETH\", false, \"https://docs.optimism.io/chain/networks\"),\n // https://docs.polygon.technology — Amoy 80002\n entry(\n 137,\n \"Polygon\",\n \"POL\",\n false,\n \"https://docs.polygon.technology/pos/reference/rpc-endpoints/\",\n ),\n // https://docs.bnbchain.org — BSC testnet 97\n entry(\n 56,\n \"BNB Smart Chain\",\n \"BNB\",\n false,\n \"https://docs.bnbchain.org/bnb-smart-chain/developers/json_rpc/\",\n ),\n // https://hyperliquid.gitbook.io — HyperEVM testnet 998\n entry(\n 999,\n \"HyperEVM\",\n \"HYPE\",\n false,\n \"https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/hyperevm\",\n ),\n // https://build.avax.network — Fuji 43113\n entry(\n 43114,\n \"Avalanche C-Chain\",\n \"AVAX\",\n false,\n \"https://build.avax.network/docs/tooling/rpc-providers\",\n ),\n entry(11155111, \"Sepolia\", \"ETH\", true, \"https://ethereum.org/en/developers/docs/networks/\"),\n entry(84532, \"Base Sepolia\", \"ETH\", true, \"https://docs.base.org/docs/network-information\"),\n entry(\n 421614,\n \"Arbitrum Sepolia\",\n \"ETH\",\n true,\n \"https://docs.arbitrum.io/for-devs/dev-tools-and-resources/chain-info\",\n ),\n entry(11155420, \"OP Sepolia\", \"ETH\", true, \"https://docs.optimism.io/chain/networks\"),\n entry(\n 80002,\n \"Polygon Amoy\",\n \"POL\",\n true,\n \"https://docs.polygon.technology/pos/reference/rpc-endpoints/\",\n ),\n entry(\n 97,\n \"BNB Smart Chain Testnet\",\n \"tBNB\",\n true,\n \"https://docs.bnbchain.org/bnb-smart-chain/developers/json_rpc/\",\n ),\n entry(\n 998,\n \"HyperEVM Testnet\",\n \"HYPE\",\n true,\n \"https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/hyperevm\",\n ),\n entry(\n 43113,\n \"Avalanche Fuji\",\n \"AVAX\",\n true,\n \"https://build.avax.network/docs/tooling/rpc-providers\",\n ),\n];\n\nexport const networkById = (id: string): NetworkInfo | undefined =>\n [...NETWORKS, ...SOLANA_NETWORKS, ...BITCOIN_NETWORKS].find((n) => n.id === id);\nexport const BITCOIN_NETWORKS: ReadonlyArray<NetworkInfo> = [\n {\n id: \"bip122:000000000019d6689c085ae165831e93\",\n chainId: 0,\n name: \"Bitcoin\",\n symbol: \"BTC\",\n decimals: 8,\n testnet: false,\n family: \"bitcoin\",\n genesisHash: \"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f\",\n },\n {\n id: \"bip122:00000000da84f2bafbbc53dee25a72ae\",\n chainId: 0,\n name: \"Bitcoin Testnet4\",\n symbol: \"tBTC\",\n decimals: 8,\n testnet: true,\n family: \"bitcoin\",\n genesisHash: \"00000000da84f2bafbbc53dee25a72ae507ff4914b867c565be350b0da8bf043\",\n },\n {\n id: \"bip122:00000008819873e925422c1ff0f99f7c\",\n chainId: 0,\n name: \"Bitcoin Signet\",\n symbol: \"sBTC\",\n decimals: 8,\n testnet: true,\n family: \"bitcoin\",\n genesisHash: \"00000008819873e925422c1ff0f99f7cc9bbb232af63a077a480a3633bee1ef6\",\n },\n {\n id: \"bip122:0f9188f13cb7b2c71f2a335e3a4fc328\",\n chainId: 0,\n name: \"Bitcoin Regtest\",\n symbol: \"rBTC\",\n decimals: 8,\n testnet: true,\n family: \"bitcoin\",\n genesisHash: \"0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206\",\n },\n];\n\nexport const SOLANA_NETWORKS: ReadonlyArray<NetworkInfo> = [\n {\n id: \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\",\n chainId: 0,\n name: \"Solana\",\n symbol: \"SOL\",\n decimals: 9,\n testnet: false,\n family: \"solana\",\n // https://solana.com/docs/references/clusters (mainnet genesis hash)\n genesisHash:\n \"5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpWvDVGok8cUQPCbq9AzdTQvpNbNvyq4qDvMNTrDDezsFapSihepu2eQEdje\",\n },\n {\n id: \"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1\",\n chainId: 0,\n name: \"Solana Devnet\",\n symbol: \"SOL\",\n decimals: 9,\n testnet: true,\n family: \"solana\",\n genesisHash: \"EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBGGSWgX4GwCJRmgdcvRaRmFbXfw3nDZBTqsr\",\n },\n];\n","import { createPublicClient, fallback, http } from \"viem\";\nimport type { PublicClient } from \"viem\";\n\n/**\n * EVM network controller: the built-in registry plus host-provided and user-added RPC endpoints.\n * Each network gets a lazily-created viem PublicClient on a `fallback` transport — endpoints are\n * tried in order (custom → host), each with the injected fetch, so a dead endpoint fails over\n * without code here. Custom RPC URLs are validated against the registry chain id with `eth_chainId`\n * and persisted in the EngineStore.\n */\nimport { esplora } from \"../chains/bitcoin.ts\";\nimport type { Esplora } from \"../chains/bitcoin.ts\";\nimport { Controller } from \"../controller.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport type { EngineStore } from \"../store/port.ts\";\nimport { networkById } from \"./registry.ts\";\nimport type { NetworkInfo } from \"./registry.ts\";\n\nconst esploraSleep = async (ms: number) =>\n new Promise<void>((resolve) => {\n setTimeout(resolve, ms);\n });\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null;\n\nexport type SolanaRpc = {\n readonly call: (method: string, params: unknown[]) => Promise<unknown>;\n};\n\ntype StoreOrUndefined = EngineStore | undefined;\n\nexport type NetworkControllerState = {\n readonly customRpc: Record<string, ReadonlyArray<string>>;\n};\n\ntype Options = {\n readonly fetch: typeof globalThis.fetch;\n readonly rpc: Readonly<Record<string, ReadonlyArray<string>>>;\n readonly openStore: () => Promise<EngineStore>;\n readonly logger: EngineLogger;\n};\n\nexport class NetworkController extends Controller<NetworkControllerState> {\n private readonly options: Options;\n private engineStore?: StoreOrUndefined;\n private readonly clients = new Map<string, PublicClient>();\n\n constructor(options: Options) {\n super({ name: \"networks\", defaultState: () => ({ customRpc: {} }) });\n this.options = options;\n }\n\n async init(): Promise<void> {\n this.engineStore = await this.options.openStore();\n const raw = await this.engineStore.collection(\"networks\").get(\"customRpc\");\n if (raw === undefined) {\n return;\n }\n const parsed: unknown = JSON.parse(new TextDecoder().decode(raw));\n if (typeof parsed === \"object\" && parsed !== null) {\n const map: Record<string, ReadonlyArray<string>> = {};\n for (const [k, v] of Object.entries(parsed)) {\n if (Array.isArray(v) && v.every((u) => typeof u === \"string\")) {\n map[k] = v;\n }\n }\n this.update((s) => ({ ...s, customRpc: map }));\n }\n }\n\n async destroy(): Promise<void> {\n this.lock();\n await Promise.resolve();\n }\n\n lock(): void {\n this.clients.clear();\n this.engineStore = undefined;\n }\n\n endpoints(network: string): ReadonlyArray<string> {\n return [...(this.getState().customRpc[network] ?? []), ...(this.options.rpc[network] ?? [])];\n }\n\n info(network: string): NetworkInfo {\n const info = networkById(network);\n if (info === undefined) {\n throw new Error(`unknown network ${network}`);\n }\n return info;\n }\n\n client(network: string): PublicClient {\n const info = this.info(network);\n const cached = this.clients.get(network);\n if (cached !== undefined) {\n return cached;\n }\n const urls = this.endpoints(network);\n if (urls.length === 0) {\n throw new Error(`no rpc endpoint for ${network}`);\n }\n const client = createPublicClient({\n chain: {\n id: info.chainId,\n name: info.name,\n nativeCurrency: { name: info.symbol, symbol: info.symbol, decimals: info.decimals },\n rpcUrls: { default: { http: urls } },\n },\n transport: fallback(urls.map((url) => http(url, { fetchFn: this.options.fetch }))),\n batch: { multicall: true },\n });\n this.clients.set(network, client);\n return client;\n }\n\n /** Validate a custom endpoint's reported chain id, then persist it first in the list. */\n /** Solana JSON-RPC over the ordered endpoint list — kit's transport is single-endpoint. */\n /** Networks with at least one configured endpoint, filtered by family. */\n enabled(family: \"evm\" | \"solana\" | \"bitcoin\"): ReadonlyArray<string> {\n const ids = new Set([\n ...Object.keys(this.options.rpc),\n ...Object.keys(this.getState().customRpc),\n ]);\n return [...ids].filter((id) => {\n const info = networkById(id);\n return info !== undefined && info.family === family;\n });\n }\n\n solanaRpc(network: string): SolanaRpc {\n const urls = this.endpoints(network);\n if (urls.length === 0) {\n throw new Error(`no rpc endpoint for ${network}`);\n }\n return {\n call: async (method, params) => {\n const attempt = async (rest: ReadonlyArray<string>, last: unknown): Promise<unknown> => {\n const [url, ...next] = rest;\n if (url === undefined) {\n throw last instanceof Error\n ? last\n : new Error(typeof last === \"string\" ? last : method);\n }\n try {\n const res = await this.options.fetch(url, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ jsonrpc: \"2.0\", id: 1, method, params }),\n });\n const body: unknown = await res.json();\n if (!isObject(body)) {\n return await attempt(next, new Error(`malformed response from ${url}`));\n }\n if (body[\"error\"] !== undefined) {\n const msg = isObject(body[\"error\"]) ? body[\"error\"][\"message\"] : undefined;\n return await attempt(next, new Error(typeof msg === \"string\" ? msg : method));\n }\n return body[\"result\"];\n } catch (error) {\n return attempt(next, error);\n }\n };\n return attempt(urls, undefined);\n },\n };\n }\n\n /** Bounded-concurrency + 429-aware ordered-failover Esplora client. */\n esplora(network: string): Esplora {\n const urls = this.endpoints(network);\n if (urls.length === 0) {\n throw new Error(`no esplora endpoint for ${network}`);\n }\n return esplora(\n urls,\n async (url, init) => {\n const r = await this.options.fetch(url, init);\n return {\n ok: r.ok,\n status: r.status,\n headers: { get: (h: string) => r.headers.get(h) ?? undefined },\n json: async () => r.json(),\n text: async () => r.text(),\n };\n },\n esploraSleep,\n );\n }\n\n async addRpc(network: string, url: string): Promise<void> {\n const info = this.info(network);\n if (info.family === \"bitcoin\") {\n const res = await this.options.fetch(`${url.replace(/\\/$/, \"\")}/block-height/0`);\n const genesisText = await res.text();\n const genesis = genesisText.trim();\n if (genesis !== info.genesisHash) {\n throw new Error(`${url} reports genesis ${genesis}, expected ${info.genesisHash ?? \"\"}`);\n }\n } else if (info.family === \"solana\") {\n const res = await this.options.fetch(url, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ jsonrpc: \"2.0\", id: 1, method: \"getGenesisHash\", params: [] }),\n });\n const body: unknown = await res.json();\n const genesis = isObject(body) ? body[\"result\"] : undefined;\n if (genesis !== info.genesisHash) {\n throw new Error(\n `${url} reports genesis hash ${String(genesis)}, expected ${info.genesisHash ?? \"\"}`,\n );\n }\n const current = this.getState().customRpc[network] ?? [];\n const customRpc = { ...this.getState().customRpc, [network]: [url, ...current] };\n this.update((s) => ({ ...s, customRpc }));\n const store = this.engineStore;\n if (store !== undefined) {\n await store\n .collection(\"networks\")\n .put(\"customRpc\", new TextEncoder().encode(JSON.stringify(customRpc)));\n }\n return;\n }\n const res = await this.options.fetch(url, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ jsonrpc: \"2.0\", id: 1, method: \"eth_chainId\", params: [] }),\n });\n const body: unknown = await res.json();\n const result =\n typeof body === \"object\" && body !== null && \"result\" in body ? body.result : undefined;\n if (typeof result !== \"string\") {\n throw new TypeError(`eth_chainId returned a malformed response from ${url}`);\n }\n const chainId = Number.parseInt(result, 16);\n if (chainId !== info.chainId) {\n throw new Error(`${url} reports chain id ${chainId}, expected ${info.chainId}`);\n }\n const current = this.getState().customRpc[network] ?? [];\n const customRpc = { ...this.getState().customRpc, [network]: [url, ...current] };\n this.update((s) => ({ ...s, customRpc }));\n this.clients.delete(network);\n const store = this.engineStore;\n if (store !== undefined) {\n await store\n .collection(\"networks\")\n .put(\"customRpc\", new TextEncoder().encode(JSON.stringify(customRpc)));\n }\n }\n}\n","import { bytesToHex } from \"@noble/hashes/utils.js\";\n\nimport {\n bitcoinAddressScript,\n decodeBolt11,\n decodeSparkAddress,\n parseSparkInvoice,\n} from \"@qntx/spark\";\nimport type { SparkNetwork } from \"@qntx/spark\";\nimport type { LnurlPayRequest, LnurlWithdrawRequest } from \"@qntx/spark/lnurl\";\nimport { decodeLnurl, lightningAddressUrl } from \"@qntx/spark/lnurl\";\n\nexport type PaymentOption =\n | { readonly kind: \"spark\"; readonly address: string }\n | {\n readonly kind: \"spark-invoice\";\n readonly invoice: string;\n readonly amountSats?: number;\n readonly memo?: string;\n readonly expiresAt?: number;\n }\n | {\n readonly kind: \"lightning\";\n readonly invoice: string;\n readonly amountSats?: number;\n readonly paymentHash: string;\n readonly description?: string;\n readonly expiresAt: number;\n }\n | { readonly kind: \"lnurl-pay\"; readonly request: LnurlPayRequest; readonly address?: string }\n | { readonly kind: \"lnurl-withdraw\"; readonly request: LnurlWithdrawRequest }\n | { readonly kind: \"bitcoin\"; readonly address: string };\n\nexport type PaymentRequest = {\n readonly options: ReadonlyArray<PaymentOption>;\n readonly amountSats?: number;\n readonly label?: string;\n readonly message?: string;\n};\n\nexport type PaymentParse =\n | { readonly kind: \"request\"; readonly request: PaymentRequest }\n | { readonly kind: \"lnurl\"; readonly url: string; readonly address?: string }\n | {\n readonly kind: \"unsupported\";\n readonly format:\n | \"bolt12\"\n | \"silent-payment\"\n | \"lnurl-auth\"\n | \"spark-token-invoice\"\n | \"nostr-wallet-connect\";\n }\n | {\n readonly kind: \"invalid\";\n readonly reason: \"network\" | \"expired\" | \"amount-mismatch\" | \"malformed\";\n }\n | { readonly kind: \"unrecognized\" };\n\nexport type ParseOptions = {\n readonly network: SparkNetwork;\n readonly now: number;\n};\n\n/** Invoices with less than this much life left are treated as already expired. */\nconst BOLT11_EXPIRY_GRACE_MS = 60_000;\n\ntype ParseFailure = {\n readonly kind: \"invalid\";\n readonly reason: \"network\" | \"expired\" | \"amount-mismatch\" | \"malformed\";\n};\n\nconst invalid = (reason: ParseFailure[\"reason\"]): PaymentParse => ({ kind: \"invalid\", reason });\n\n/** BTC decimal `amount` → sats. At most 8 decimal places; must fit a safe integer. */\nfunction btcAmountSats(text: string): number | undefined {\n const match = /^(\\d+)(?:\\.(\\d{1,8}))?$/.exec(text);\n if (match === null) {\n return undefined;\n }\n const [, whole] = match;\n if (whole === undefined) {\n return undefined;\n }\n const sats = BigInt(whole) * 100_000_000n + BigInt((match[2] ?? \"\").padEnd(8, \"0\") || \"0\");\n return sats <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(sats) : undefined;\n}\n\ntype Bolt11Fields = {\n readonly amountSats?: number;\n readonly paymentHash: string;\n readonly description?: string;\n readonly expiresAt: number;\n};\n\n/**\n * BOLT11 → fields, network- and expiry-checked. `undefined` = not a bolt11 string; `\"network\"` /\n * `\"expired\"` / `\"malformed\"` are the failure modes.\n */\nfunction bolt11Fields(\n text: string,\n options: ParseOptions,\n): Bolt11Fields | \"network\" | \"expired\" | \"malformed\" | undefined {\n let decoded;\n try {\n decoded = decodeBolt11(text);\n } catch {\n return undefined;\n }\n const network =\n decoded.network === \"mainnet\"\n ? \"mainnet\"\n : decoded.network === \"regtest\"\n ? \"regtest\"\n : undefined;\n if (network === undefined) {\n return \"network\";\n }\n if (network !== options.network) {\n return \"network\";\n }\n const expiresAt = (decoded.timestamp + decoded.expirySeconds) * 1000;\n if (expiresAt <= options.now + BOLT11_EXPIRY_GRACE_MS) {\n return \"expired\";\n }\n return {\n ...(decoded.amountMsat === undefined\n ? {}\n : { amountSats: Math.ceil(Number(decoded.amountMsat) / 1000) }),\n paymentHash: bytesToHex(decoded.paymentHash),\n ...(decoded.description === undefined ? {} : { description: decoded.description }),\n expiresAt,\n };\n}\n\n/** Spark address or sats/token invoice → options. `null` means not a spark input. */\nfunction sparkOptions(\n text: string,\n options: ParseOptions,\n): PaymentOption[] | \"network\" | \"expired\" | \"malformed\" | \"token\" | undefined {\n let decoded;\n try {\n decoded = decodeSparkAddress(text);\n } catch {\n return undefined;\n }\n if (decoded.network !== options.network) {\n return \"network\";\n }\n if (decoded.invoice === undefined) {\n return [{ kind: \"spark\", address: text }];\n }\n // Expiry lives in the unsigned fields — check it before validating the signature so an\n // expired invoice reports `expired` rather than `malformed`.\n if (decoded.invoice.expiresAt !== undefined && decoded.invoice.expiresAt <= options.now) {\n return \"expired\";\n }\n if (decoded.invoice.payment?.type === \"tokens\") {\n return \"token\";\n }\n let parsed;\n try {\n parsed = parseSparkInvoice(text, { network: options.network, now: options.now });\n } catch {\n return \"malformed\";\n }\n const { payment } = parsed.fields;\n return [\n {\n kind: \"spark-invoice\",\n invoice: text,\n ...(payment?.type === \"sats\" && payment.amount !== undefined\n ? { amountSats: payment.amount }\n : {}),\n ...(parsed.fields.memo === undefined ? {} : { memo: parsed.fields.memo }),\n ...(parsed.fields.expiresAt === undefined ? {} : { expiresAt: parsed.fields.expiresAt }),\n },\n ];\n}\n\n/** Does `address` decode under the other network? Used only to classify a rejection. */\nfunction decodesOnOtherNetwork(address: string, options: ParseOptions): boolean {\n try {\n bitcoinAddressScript(address, options.network === \"mainnet\" ? \"regtest\" : \"mainnet\");\n return true;\n } catch {\n return false;\n }\n}\n\n/** BIP-21 URI → request. Only the `spark=` and `lightning=` payment methods are supported. */\nfunction bip21Parse(text: string, options: ParseOptions): PaymentParse {\n const q = text.indexOf(\"?\");\n const address = text.slice(\"bitcoin:\".length, q === -1 ? undefined : q);\n const params = new Map<string, string>();\n if (q !== -1) {\n for (const pair of text.slice(q + 1).split(\"&\")) {\n const eq = pair.indexOf(\"=\");\n if (eq === -1) {\n return invalid(\"malformed\");\n }\n let key;\n let value;\n try {\n key = decodeURIComponent(pair.slice(0, eq)).toLowerCase();\n value = decodeURIComponent(pair.slice(eq + 1));\n } catch {\n return invalid(\"malformed\");\n }\n if (params.has(key)) {\n return invalid(\"malformed\");\n }\n if (key.startsWith(\"req-\") && !BIP21_KNOWN_REQ_PARAMS.has(key)) {\n return invalid(\"malformed\");\n }\n params.set(key, value);\n }\n }\n const options_: PaymentOption[] = [];\n let declaredSats: number | undefined;\n const spark = params.get(\"spark\");\n if (spark !== undefined) {\n const parsed = sparkOptions(spark, options);\n if (parsed === undefined || parsed === \"malformed\") {\n return invalid(\"malformed\");\n }\n if (parsed === \"token\") {\n return { kind: \"unsupported\", format: \"spark-token-invoice\" };\n }\n if (parsed === \"network\" || parsed === \"expired\") {\n return invalid(parsed);\n }\n options_.push(...parsed);\n const sats = parsed.find((o) => o.kind === \"spark-invoice\")?.amountSats;\n if (sats !== undefined) {\n if (declaredSats !== undefined && declaredSats !== sats) {\n return invalid(\"amount-mismatch\");\n }\n declaredSats = sats;\n }\n }\n const lightning = params.get(\"lightning\");\n if (lightning !== undefined) {\n const parsed = bolt11Fields(lightning, options);\n if (parsed === undefined || parsed === \"malformed\") {\n return invalid(\"malformed\");\n }\n if (parsed === \"network\" || parsed === \"expired\") {\n return invalid(parsed);\n }\n options_.push({\n kind: \"lightning\",\n invoice: lightning,\n ...(parsed.amountSats === undefined ? {} : { amountSats: parsed.amountSats }),\n paymentHash: parsed.paymentHash,\n ...(parsed.description === undefined ? {} : { description: parsed.description }),\n expiresAt: parsed.expiresAt,\n });\n if (parsed.amountSats !== undefined) {\n if (declaredSats !== undefined && declaredSats !== parsed.amountSats) {\n return invalid(\"amount-mismatch\");\n }\n declaredSats = parsed.amountSats;\n }\n }\n if (address.length > 0) {\n try {\n bitcoinAddressScript(address, options.network);\n } catch {\n return invalid(decodesOnOtherNetwork(address, options) ? \"network\" : \"malformed\");\n }\n options_.push({ kind: \"bitcoin\", address });\n }\n const declaredAmount = params.get(\"amount\");\n if (declaredAmount !== undefined) {\n const sats = btcAmountSats(declaredAmount);\n if (sats === undefined) {\n return invalid(\"malformed\");\n }\n if (declaredSats !== undefined && declaredSats !== sats) {\n return invalid(\"amount-mismatch\");\n }\n declaredSats = sats;\n }\n if (options_.length === 0) {\n if (params.has(\"lno\")) {\n return { kind: \"unsupported\", format: \"bolt12\" };\n }\n if (params.has(\"sp\")) {\n return { kind: \"unsupported\", format: \"silent-payment\" };\n }\n return invalid(\"malformed\");\n }\n return {\n kind: \"request\",\n request: {\n options: options_,\n ...(declaredSats === undefined ? {} : { amountSats: declaredSats }),\n ...(params.get(\"label\") === undefined ? {} : { label: params.get(\"label\") ?? \"\" }),\n ...(params.get(\"message\") === undefined ? {} : { message: params.get(\"message\") ?? \"\" }),\n },\n };\n}\n\nconst BIP21_KNOWN_REQ_PARAMS = new Set([\"req-amount\", \"req-label\", \"req-message\"]);\n\n/** `input` → PaymentParse. Never throws: every failure is a structured result. */\nexport function parsePayment(input: string, options: ParseOptions): PaymentParse {\n try {\n const text = input.trim();\n if (/^nostr\\+walletconnect:/i.test(text)) {\n return { kind: \"unsupported\", format: \"nostr-wallet-connect\" };\n }\n const stripped = text.toLowerCase().startsWith(\"lightning:\")\n ? text.slice(\"lightning:\".length)\n : text;\n if (/^bitcoin:/i.test(stripped)) {\n return bip21Parse(`bitcoin:${stripped.slice(stripped.indexOf(\":\") + 1)}`, options);\n }\n const bolt11 = bolt11Fields(stripped, options);\n if (bolt11 === \"network\" || bolt11 === \"expired\" || bolt11 === \"malformed\") {\n return invalid(bolt11);\n }\n if (bolt11 !== undefined) {\n const option: PaymentOption = {\n kind: \"lightning\",\n invoice: stripped,\n ...(bolt11.amountSats === undefined ? {} : { amountSats: bolt11.amountSats }),\n paymentHash: bolt11.paymentHash,\n ...(bolt11.description === undefined ? {} : { description: bolt11.description }),\n expiresAt: bolt11.expiresAt,\n };\n return {\n kind: \"request\",\n request: {\n options: [option],\n ...(bolt11.amountSats === undefined ? {} : { amountSats: bolt11.amountSats }),\n },\n };\n }\n const spark = sparkOptions(stripped, options);\n if (spark === \"token\") {\n return { kind: \"unsupported\", format: \"spark-token-invoice\" };\n }\n if (spark === \"network\" || spark === \"expired\" || spark === \"malformed\") {\n return invalid(spark);\n }\n if (spark !== undefined) {\n return { kind: \"request\", request: { options: spark } };\n }\n if (/^(lnurlp|lnurlw):/i.test(stripped)) {\n const rest = stripped.slice(stripped.indexOf(\"://\") + 3);\n const host = rest.split(/[/?#]/, 1)[0] ?? \"\";\n const url = `${host.toLowerCase().endsWith(\".onion\") ? \"http\" : \"https\"}://${rest}`;\n if (new URL(url).searchParams.get(\"tag\") === \"login\") {\n return { kind: \"unsupported\", format: \"lnurl-auth\" };\n }\n return { kind: \"lnurl\", url };\n }\n if (/^keyauth:/i.test(stripped)) {\n return { kind: \"unsupported\", format: \"lnurl-auth\" };\n }\n if (!stripped.includes(\":\") && stripped.includes(\"@\")) {\n return { kind: \"lnurl\", url: lightningAddressUrl(stripped), address: stripped };\n }\n // BOLT12 offer: bech32 charset, anchored — a lightning address like lnolan@x must not match.\n if (/^lno1[02-9ac-hj-np-z]+$/i.test(stripped)) {\n return { kind: \"unsupported\", format: \"bolt12\" };\n }\n try {\n const url = decodeLnurl(stripped);\n if (new URL(url).searchParams.get(\"tag\") === \"login\") {\n return { kind: \"unsupported\", format: \"lnurl-auth\" };\n }\n return { kind: \"lnurl\", url };\n } catch {\n // not a bech32 LNURL\n }\n try {\n bitcoinAddressScript(stripped, options.network);\n return { kind: \"request\", request: { options: [{ kind: \"bitcoin\", address: stripped }] } };\n } catch {\n if (decodesOnOtherNetwork(stripped, options)) {\n return invalid(\"network\");\n }\n }\n return { kind: \"unrecognized\" };\n } catch {\n return invalid(\"malformed\");\n }\n}\n","/** SparkController error categories — never carry request bytes or secrets. */\nexport type SparkErrorCategory =\n | \"network\"\n | \"approval-required\"\n | \"insufficient-funds\"\n | \"rejected\"\n | \"internal\";\n\nexport class SparkControllerError extends Error {\n readonly category: SparkErrorCategory;\n\n constructor(category: SparkErrorCategory, message: string, cause?: unknown) {\n super(message, { cause });\n this.name = \"SparkControllerError\";\n this.category = category;\n }\n}\n\n/** Maps a thrown client/kernel error into a category without leaking payloads. */\nexport function categorize(error: unknown): SparkErrorCategory {\n const name = error instanceof Error ? error.name : \"\";\n const message = error instanceof Error ? error.message : \"\";\n if (/approval|denied|rejected/i.test(message)) {\n return /required/i.test(message) ? \"approval-required\" : \"rejected\";\n }\n if (/insufficient|not enough|balance/i.test(message)) {\n return \"insufficient-funds\";\n }\n if (name === \"SparkRequestError\" || /fetch|network|timeout|unavailable|closed/i.test(message)) {\n return \"network\";\n }\n return \"internal\";\n}\n","/** Payment layer error categories — messages never carry remote or secret content. */\nexport type PaymentErrorCategory = \"invalid-input\" | \"network\" | \"rejected\";\n\nexport class PaymentError extends Error {\n readonly category: PaymentErrorCategory;\n\n constructor(category: PaymentErrorCategory, message: string, cause?: unknown) {\n super(message, { cause });\n this.name = \"PaymentError\";\n this.category = category;\n }\n}\n","import type {\n CooperativeExitResult,\n LightningInvoice,\n LightningPayment,\n SparkTransfer,\n} from \"@qntx/spark\";\nimport { requestInvoice, submitWithdraw } from \"@qntx/spark/lnurl\";\nimport type { UnlockFactor } from \"@qntx/wallet\";\nimport type { SparkAccountRef } from \"@qntx/wallet/protocol\";\n\nimport type { SparkController } from \"../spark/controller.ts\";\nimport { SparkControllerError } from \"../spark/errors.ts\";\nimport { PaymentError } from \"./errors.ts\";\nimport type { PaymentOption } from \"./parse.ts\";\n\nexport type PayParams = {\n readonly account: SparkAccountRef;\n readonly option: PaymentOption;\n /** Caller-supplied amount — required by open invoices, the `spark` option, and LNURL flows. */\n readonly amountSats?: number;\n readonly comment?: string;\n readonly maxFeeSats?: number;\n readonly speed?: \"FAST\" | \"MEDIUM\" | \"SLOW\";\n readonly verify: UnlockFactor;\n};\n\nexport type PayContext = {\n readonly spark: SparkController;\n readonly fetch: typeof globalThis.fetch;\n readonly now: () => number;\n};\n\nexport type PayResult =\n | { readonly kind: \"spark\"; readonly transfer: SparkTransfer }\n | { readonly kind: \"lightning\"; readonly payment: LightningPayment }\n | { readonly kind: \"withdraw\"; readonly exit: CooperativeExitResult }\n | { readonly kind: \"lnurl-withdraw\"; readonly invoice: LightningInvoice };\n\n/**\n * Executes one parsed payment option. Every input validation happens before the approval round — a\n * `PaymentError` here never consumed a verification. `SparkControllerError` and `WalletError` pass\n * through untouched.\n */\nexport async function pay(context: PayContext, params: PayParams): Promise<PayResult> {\n const { spark } = context;\n const ref = params.account;\n let result: PayResult;\n switch (params.option.kind) {\n case \"spark\": {\n if (params.amountSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"spark payment: amountSats is required\");\n }\n const transfer = await spark.send(ref, {\n receiver: params.option.address,\n amountSats: params.amountSats,\n verify: params.verify,\n });\n result = { kind: \"spark\", transfer };\n break;\n }\n case \"spark-invoice\": {\n if (params.option.expiresAt !== undefined && params.option.expiresAt <= context.now()) {\n throw new PaymentError(\"rejected\", \"spark invoice expired\");\n }\n if (\n params.option.amountSats !== undefined &&\n params.amountSats !== undefined &&\n params.amountSats !== params.option.amountSats\n ) {\n throw new PaymentError(\n \"invalid-input\",\n \"spark invoice: amountSats conflicts with the invoice amount\",\n );\n }\n // A fixed-amount invoice derives the amount itself — only an open one takes the caller's.\n const invoiceAmount = params.option.amountSats === undefined ? params.amountSats : undefined;\n const transfer = await spark.paySparkInvoice(ref, {\n invoice: params.option.invoice,\n ...(invoiceAmount === undefined ? {} : { amountSats: invoiceAmount }),\n verify: params.verify,\n });\n result = { kind: \"spark\", transfer };\n break;\n }\n case \"lightning\": {\n if (params.option.amountSats === undefined && params.amountSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"amountless invoice: amountSats is required\");\n }\n if (params.maxFeeSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"lightning payment: maxFeeSats is required\");\n }\n // amountSats is only for amountless invoices — a fixed-amount invoice must not carry it.\n if (params.option.expiresAt <= context.now() + 60_000) {\n throw new PaymentError(\"rejected\", \"lightning invoice expired\");\n }\n if (\n params.option.amountSats !== undefined &&\n params.amountSats !== undefined &&\n params.amountSats !== params.option.amountSats\n ) {\n throw new PaymentError(\"invalid-input\", \"amountSats conflicts with the invoice amount\");\n }\n const payment = await spark.payInvoice(ref, {\n invoice: params.option.invoice,\n maxFeeSats: params.maxFeeSats,\n ...(params.option.amountSats === undefined && params.amountSats !== undefined\n ? { amountSats: params.amountSats }\n : {}),\n verify: params.verify,\n });\n result = { kind: \"lightning\", payment };\n break;\n }\n case \"lnurl-pay\": {\n const { request } = params.option;\n if (params.amountSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"lnurl-pay: amountSats is required\");\n }\n if (params.maxFeeSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"lnurl-pay: maxFeeSats is required\");\n }\n const amountMsat = params.amountSats * 1000;\n if (amountMsat < request.minSendableMsat || amountMsat > request.maxSendableMsat) {\n throw new PaymentError(\"rejected\", \"lnurl-pay: amount outside the service's range\");\n }\n if (request.commentAllowed === 0 && params.comment !== undefined) {\n throw new PaymentError(\"rejected\", \"lnurl-pay: comments not accepted by this service\");\n }\n if (params.comment !== undefined && params.comment.length > request.commentAllowed) {\n throw new PaymentError(\"rejected\", \"lnurl-pay: comment exceeds the service's limit\");\n }\n let requested;\n try {\n requested = await requestInvoice(request, {\n fetch: context.fetch,\n network: ref.network,\n amountMsat,\n ...(params.comment === undefined ? {} : { comment: params.comment }),\n });\n } catch (error) {\n if (error instanceof PaymentError || error instanceof SparkControllerError) {\n throw error;\n }\n throw new PaymentError(\"network\", \"lnurl-pay: invoice request failed\", error);\n }\n const payment = await spark.payInvoice(ref, {\n invoice: requested.invoice,\n maxFeeSats: params.maxFeeSats,\n verify: params.verify,\n });\n result = { kind: \"lightning\", payment };\n break;\n }\n case \"lnurl-withdraw\": {\n const { request } = params.option;\n if (params.amountSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"lnurl-withdraw: amountSats is required\");\n }\n const amountMsat = params.amountSats * 1000;\n if (amountMsat < request.minWithdrawableMsat || amountMsat > request.maxWithdrawableMsat) {\n throw new PaymentError(\"rejected\", \"lnurl-withdraw: amount outside the service's range\");\n }\n const invoice = await spark.createInvoice(ref, {\n amountSats: params.amountSats,\n memo: request.defaultDescription,\n });\n try {\n await submitWithdraw(request, { fetch: context.fetch, invoice: invoice.invoice });\n } catch (error) {\n if (error instanceof PaymentError || error instanceof SparkControllerError) {\n throw error;\n }\n throw new PaymentError(\"network\", \"lnurl-withdraw: submission failed\", error);\n }\n result = { kind: \"lnurl-withdraw\", invoice };\n break;\n }\n case \"bitcoin\": {\n if (params.amountSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"bitcoin payment: amountSats is required\");\n }\n const exit = await spark.withdraw(ref, {\n address: params.option.address,\n speed: params.speed ?? \"MEDIUM\",\n verify: params.verify,\n amountSats: params.amountSats,\n ...(params.maxFeeSats === undefined ? {} : { maxFeeSats: params.maxFeeSats }),\n });\n result = { kind: \"withdraw\", exit };\n break;\n }\n }\n return result;\n}\n","import { resolveLnurl } from \"@qntx/spark/lnurl\";\n\nimport { PaymentError } from \"./errors.ts\";\nimport { parsePayment } from \"./parse.ts\";\nimport type { PaymentParse, ParseOptions } from \"./parse.ts\";\n\nexport type ResolveOptions = ParseOptions & {\n readonly fetch: typeof globalThis.fetch;\n};\n\n/**\n * `parsePayment` plus LNURL dereferencing: an `lnurl` result is fetched and turned into a concrete\n * `lnurl-pay` / `lnurl-withdraw` request (`tag=login` endpoints report as unsupported). Network\n * failures throw `PaymentError(\"network\")` — remote error bodies never enter the message.\n */\nexport async function resolvePayment(\n input: string,\n options: ResolveOptions,\n): Promise<PaymentParse> {\n const parsed = parsePayment(input, options);\n if (parsed.kind !== \"lnurl\") {\n return parsed;\n }\n let resolved;\n try {\n resolved = await resolveLnurl(parsed.url, { fetch: options.fetch });\n } catch {\n throw new PaymentError(\"network\", \"lnurl: resolution failed\");\n }\n if (resolved.tag === \"payRequest\") {\n return {\n kind: \"request\",\n request: {\n options: [\n {\n kind: \"lnurl-pay\",\n request: resolved,\n ...(parsed.address === undefined ? {} : { address: parsed.address }),\n },\n ],\n },\n };\n }\n if (resolved.tag === \"withdrawRequest\") {\n return {\n kind: \"request\",\n request: { options: [{ kind: \"lnurl-withdraw\", request: resolved }] },\n };\n }\n return { kind: \"unsupported\", format: \"lnurl-auth\" };\n}\n","import { bytesToHex } from \"@noble/hashes/utils.js\";\n\nimport { signedMatchesUnsigned, verifyEvent } from \"@qntx/nostr\";\nimport type { Event, NostrSigner } from \"@qntx/nostr\";\nimport { makeZapRequest } from \"@qntx/nostr/nips/nip57\";\nimport { SparkInputError, decodeBolt11 } from \"@qntx/spark\";\nimport type { LightningPayment, SparkNetwork } from \"@qntx/spark\";\nimport { encodeLnurl, lightningAddressUrl, requestInvoice, resolveLnurl } from \"@qntx/spark/lnurl\";\nimport type { UnlockFactor } from \"@qntx/wallet\";\nimport type { SparkAccountRef } from \"@qntx/wallet/protocol\";\n\nimport type { SparkController } from \"../spark/controller.ts\";\nimport { categorize } from \"../spark/errors.ts\";\nimport { PaymentError } from \"./errors.ts\";\n\n/** A profile zap names the recipient pubkey; an event zap carries the event it zaps. */\nexport type ZapRecipient =\n | { readonly pubkey: string; readonly lightning: string }\n | { readonly event: Event; readonly lightning: string };\n\nexport type PrepareZapParams = {\n /** Any `NostrSigner` — wallet key, external key, NIP-07/46 — signs the 9734. */\n readonly signer: NostrSigner;\n readonly recipient: ZapRecipient;\n readonly amountSats: number;\n readonly comment?: string | undefined;\n readonly relays: ReadonlyArray<string>;\n readonly network: SparkNetwork;\n};\n\nexport type PrepareZapContext = {\n readonly fetch: typeof globalThis.fetch;\n readonly now: () => number;\n};\n\n/** Everything a payer needs: the signed 9734, the invoice, and the note fields. */\nexport type PreparedZap = {\n readonly zapRequest: Event;\n readonly invoice: string;\n /** Hex payment hash decoded from the invoice. */\n readonly paymentHash: string;\n /** Millisecond expiry decoded from the invoice. */\n readonly expiresAt: number;\n readonly amountSats: number;\n /** The LNURL service's 9735 signing pubkey. */\n readonly receiptPubkey: string;\n readonly recipientPubkey: string;\n readonly eventId?: string;\n readonly comment?: string;\n /** The lud16 or LNURL as given. */\n readonly lightning: string;\n};\n\nexport type PayZapOptions = {\n readonly maxFeeSats: number;\n readonly verify: UnlockFactor;\n readonly now: () => number;\n};\n\n/** Everything up to payment: resolve LNURL, sign the 9734, request the invoice. */\nexport async function prepareZap(\n params: PrepareZapParams,\n context: PrepareZapContext,\n): Promise<PreparedZap> {\n const amountMsat = params.amountSats * 1000;\n if (\n !Number.isSafeInteger(params.amountSats) ||\n params.amountSats <= 0 ||\n !Number.isSafeInteger(amountMsat)\n ) {\n throw new PaymentError(\"invalid-input\", \"zap amount is not a positive safe integer\");\n }\n try {\n const resolved = await resolveLnurl(params.recipient.lightning, { fetch: context.fetch });\n if (resolved.tag !== \"payRequest\") {\n throw new PaymentError(\"rejected\", \"recipient is not an LNURL-pay endpoint\");\n }\n if (!resolved.allowsNostr || resolved.nostrPubkey === undefined) {\n throw new PaymentError(\"rejected\", \"LNURL service does not accept nostr zaps\");\n }\n if (amountMsat < resolved.minSendableMsat || amountMsat > resolved.maxSendableMsat) {\n throw new PaymentError(\"rejected\", \"zap amount outside the service's bounds\");\n }\n if (params.comment !== undefined) {\n if (resolved.commentAllowed === 0) {\n throw new PaymentError(\"rejected\", \"the service does not accept comments\");\n }\n if (params.comment.length > resolved.commentAllowed) {\n throw new PaymentError(\"rejected\", \"comment exceeds the service's limit\");\n }\n }\n // LNURL detection is case-insensitive; the 9734 carries lowercase bech32.\n const lnurl = params.recipient.lightning.toLowerCase().startsWith(\"lnurl1\")\n ? params.recipient.lightning.toLowerCase()\n : encodeLnurl(lightningAddressUrl(params.recipient.lightning));\n const base = {\n amount: amountMsat,\n relays: [...params.relays],\n comment: params.comment,\n lnurl,\n };\n const template =\n \"event\" in params.recipient\n ? makeZapRequest({ event: params.recipient.event, ...base })\n : makeZapRequest({ pubkey: params.recipient.pubkey, ...base });\n const unsigned = { ...template, pubkey: await params.signer.getPublicKey() };\n const zapRequest = await params.signer.signEvent(unsigned);\n // External signers (NIP-07/46) are untrusted: the 9734 must be validly signed over exactly\n // the template, or the receipt would commit to content the user never approved.\n if (!verifyEvent(zapRequest) || !signedMatchesUnsigned(zapRequest, unsigned)) {\n throw new PaymentError(\"rejected\", \"signer returned a zap request that does not match\");\n }\n const { invoice } = await requestInvoice(resolved, {\n fetch: context.fetch,\n network: params.network,\n amountMsat,\n ...(params.comment === undefined ? {} : { comment: params.comment }),\n zapRequest: JSON.stringify(zapRequest),\n });\n const decoded = decodeBolt11(invoice);\n const expiresAt = (decoded.timestamp + decoded.expirySeconds) * 1000;\n if (expiresAt <= context.now() + 60_000) {\n throw new PaymentError(\"rejected\", \"zap invoice expires too soon\");\n }\n const eventId = \"event\" in params.recipient ? params.recipient.event.id : undefined;\n return {\n zapRequest,\n invoice,\n paymentHash: bytesToHex(decoded.paymentHash),\n expiresAt,\n amountSats: params.amountSats,\n receiptPubkey: bytesToHex(resolved.nostrPubkey),\n recipientPubkey:\n \"event\" in params.recipient ? params.recipient.event.pubkey : params.recipient.pubkey,\n ...(eventId === undefined ? {} : { eventId }),\n ...(params.comment === undefined ? {} : { comment: params.comment }),\n lightning: params.recipient.lightning,\n };\n } catch (error) {\n if (error instanceof PaymentError) {\n throw error;\n }\n if (\n error instanceof SparkInputError ||\n (error instanceof Error && error.cause instanceof SparkInputError)\n ) {\n throw new PaymentError(\"rejected\", \"zap failed invoice validation\");\n }\n throw new PaymentError(categorizePayment(error), \"zap failed\");\n }\n}\n\n/**\n * Pays a prepared zap through the controller's approve-first path. A nearly-expired invoice is\n * rejected before approval — the user may have sat on the confirm screen since `prepareZap`.\n */\nexport async function payZap(\n spark: SparkController,\n account: SparkAccountRef,\n prepared: PreparedZap,\n options: PayZapOptions,\n): Promise<LightningPayment> {\n if (prepared.expiresAt <= options.now() + 60_000) {\n throw new PaymentError(\"rejected\", \"zap invoice expired\");\n }\n return spark.payInvoice(account, {\n invoice: prepared.invoice,\n maxFeeSats: options.maxFeeSats,\n verify: options.verify,\n note: {\n kind: \"zap\",\n recipientPubkey: prepared.recipientPubkey,\n ...(prepared.eventId === undefined ? {} : { eventId: prepared.eventId }),\n ...(prepared.comment === undefined ? {} : { comment: prepared.comment }),\n lightning: prepared.lightning,\n },\n });\n}\n\nfunction categorizePayment(error: unknown): \"network\" | \"rejected\" {\n const category = categorize(error);\n return category === \"network\" ? \"network\" : \"rejected\";\n}\n","import type { SparkPayment } from \"@qntx/spark\";\n\n/**\n * Local, engine-side metadata pinned to a history entry by transfer id. Written after the payment\n * it annotates has already succeeded — a missing or malformed note must never affect the payment\n * itself.\n */\nexport type PaymentNote = {\n readonly kind: \"zap\";\n /** 64 lowercase hex. */\n readonly recipientPubkey: string;\n /** 64 lowercase hex — event zaps carry the zapped event's id. */\n readonly eventId?: string;\n /** At most 2000 characters. */\n readonly comment?: string;\n /** The lud16 or LNURL the zap resolved. */\n readonly lightning: string;\n};\n\nexport type SparkActivity = SparkPayment & { readonly note?: PaymentNote };\n\nconst HEX64 = /^[0-9a-f]{64}$/;\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\nconst NOTE_FIELDS: ReadonlySet<string> = new Set([\n \"kind\",\n \"recipientPubkey\",\n \"eventId\",\n \"comment\",\n \"lightning\",\n]);\n\n/** Strict read-side validation: anything off-shape is `undefined`, never a throw. */\nexport function parsePaymentNote(value: unknown): PaymentNote | undefined {\n if (!isObject(value)) {\n return undefined;\n }\n for (const field of Object.keys(value)) {\n if (!NOTE_FIELDS.has(field)) {\n return undefined;\n }\n }\n const { kind, recipientPubkey, eventId, comment, lightning } = value;\n if (kind !== \"zap\") {\n return undefined;\n }\n if (typeof recipientPubkey !== \"string\" || !HEX64.test(recipientPubkey)) {\n return undefined;\n }\n if (eventId !== undefined && (typeof eventId !== \"string\" || !HEX64.test(eventId))) {\n return undefined;\n }\n if (comment !== undefined && (typeof comment !== \"string\" || comment.length > 2000)) {\n return undefined;\n }\n if (typeof lightning !== \"string\" || lightning.length === 0) {\n return undefined;\n }\n return {\n kind: \"zap\",\n recipientPubkey,\n ...(eventId === undefined ? {} : { eventId }),\n ...(comment === undefined ? {} : { comment }),\n lightning,\n };\n}\n\nexport function encodePaymentNote(note: PaymentNote): Uint8Array {\n return new TextEncoder().encode(JSON.stringify(note));\n}\n","/**\n * SparkExitChain persistence codec: JSON with Uint8Arrays tagged `{ $b64: \"…\" }` — small and\n * explicit rather than schema-bound, so upstream field additions survive a round-trip.\n */\nimport { base64 } from \"@scure/base\";\n\nimport type { SparkExitChain } from \"@qntx/spark\";\n\nfunction encodeValue(value: unknown): unknown {\n if (value instanceof Uint8Array) {\n return { $b64: base64.encode(value) };\n }\n if (Array.isArray(value)) {\n return value.map(encodeValue);\n }\n if (typeof value === \"object\" && value !== null) {\n return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, encodeValue(v)]));\n }\n return value;\n}\n\nfunction decodeValue(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(decodeValue);\n }\n if (typeof value === \"object\" && value !== null) {\n const entries = Object.entries(value);\n const b64: unknown =\n entries.length === 1 && entries[0]?.[0] === \"$b64\" ? entries[0][1] : undefined;\n if (typeof b64 === \"string\") {\n return base64.decode(b64);\n }\n return Object.fromEntries(entries.map(([k, v]) => [k, decodeValue(v)]));\n }\n return value;\n}\n\nexport function encodeExitChain(chain: SparkExitChain): Uint8Array {\n return new TextEncoder().encode(JSON.stringify(encodeValue(chain)));\n}\n\nexport function decodeExitChain(bytes: Uint8Array): SparkExitChain {\n const decoded: unknown = decodeValue(JSON.parse(new TextDecoder().decode(bytes)));\n // The codec round-trips what encodeExitChain wrote — the shape is structural.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return decoded as SparkExitChain;\n}\n","import type { SparkExitChain, SparkStore } from \"@qntx/spark\";\n\nimport type { EngineCollection } from \"../store/port.ts\";\nimport { decodeExitChain, encodeExitChain } from \"./exit-chain-codec.ts\";\n\nconst ALL = \"__all__\";\n\n/**\n * SparkStore over one EngineCollection: chains keyed by leafId, plus an index record listing them\n * (`exitChains` is a full listing — the port has no secondary index).\n */\nexport function sparkStore(col: EngineCollection): SparkStore {\n const readIndex = async (): Promise<string[]> => {\n const index = await col.get(ALL);\n if (index === undefined) {\n return [];\n }\n const parsed: unknown = JSON.parse(new TextDecoder().decode(index));\n if (!Array.isArray(parsed)) {\n return [];\n }\n return parsed.filter((v): v is string => typeof v === \"string\");\n };\n const writeIndex = async (ids: ReadonlyArray<string>): Promise<void> => {\n await col.put(ALL, new TextEncoder().encode(JSON.stringify(ids)));\n };\n return {\n exitChains: async () => {\n const ids = await readIndex();\n const chains: SparkExitChain[] = [];\n for (const leafId of ids) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- reads must stay ordered and sequential\n const record = await col.get(leafId);\n if (record !== undefined) {\n chains.push(decodeExitChain(record));\n }\n }\n return chains;\n },\n putExitChains: async (chains) => {\n const ids = await readIndex();\n const set = new Set(ids);\n for (const chain of chains) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- writes commit one record at a time\n await col.put(chain.leafId, encodeExitChain(chain));\n set.add(chain.leafId);\n }\n await writeIndex([...set]);\n },\n deleteExitChains: async (leafIds) => {\n const ids = await readIndex();\n const drop = new Set(leafIds);\n for (const leafId of leafIds) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- deletes commit one record at a time\n await col.delete(leafId);\n }\n await writeIndex(ids.filter((leafId) => !drop.has(leafId)));\n },\n };\n}\n","import {\n bitcoinAddressScript,\n decodeSparkAddress,\n encodeSparkAddress,\n parseSparkInvoice,\n SparkInputError,\n uuidv7,\n} from \"@qntx/spark\";\nimport type {\n CooperativeExitResult,\n LightningInvoice,\n LightningPayment,\n SparkClient,\n SparkPayment,\n SparkTransfer,\n} from \"@qntx/spark\";\nimport { registerLightningAddress, unregisterLightningAddress } from \"@qntx/spark/lnurl\";\nimport type { UnlockFactor } from \"@qntx/wallet\";\nimport type { SparkAccountRef, SparkApproveIntent } from \"@qntx/wallet/protocol\";\nimport type { SparkSigner } from \"@qntx/wallet/spark\";\n\nimport { Controller } from \"../controller.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport type { EngineStore, EngineCollection } from \"../store/port.ts\";\nimport { categorize, SparkControllerError } from \"./errors.ts\";\nimport { encodePaymentNote, parsePaymentNote } from \"./notes.ts\";\nimport type { PaymentNote, SparkActivity } from \"./notes.ts\";\nimport { sparkStore } from \"./store.ts\";\n\nexport type SparkAccountState = {\n readonly status: \"locked\" | \"connecting\" | \"ready\" | \"error\";\n readonly balanceSats?: number;\n readonly identityPublicKey?: string;\n readonly sparkAddress?: string;\n readonly errorCategory?: string;\n /** First history page (20 entries, newest first), refreshed alongside the balance. */\n readonly recent?: ReadonlyArray<SparkActivity>;\n};\n\nexport type SparkControllerState = {\n readonly accounts: Readonly<Record<string, SparkAccountState>>;\n};\n\ntype SparkApis = {\n readonly signer: (ref: SparkAccountRef) => SparkSigner;\n readonly approve: (params: {\n account: SparkAccountRef;\n intent: SparkApproveIntent;\n verify: UnlockFactor;\n }) => Promise<unknown>;\n};\n\nexport type SparkClientFactory = (options: {\n readonly ref: SparkAccountRef;\n readonly store: ReturnType<typeof sparkStore>;\n readonly signer: SparkSigner;\n readonly fetch: typeof globalThis.fetch;\n}) => SparkClient;\n\nexport type SparkControllerOptions = {\n readonly spark: SparkApis;\n readonly fetch: typeof globalThis.fetch;\n readonly random: (length: number) => Uint8Array;\n readonly now: () => number;\n readonly logger: EngineLogger;\n readonly createClient: SparkClientFactory;\n};\n\nconst key = (ref: SparkAccountRef): string => `${ref.walletId}:${ref.groupIndex}:${ref.network}`;\n\n/** TransferId: the client and SO expect a UUIDv7 — mint it from the injected clock+random. */\nconst transferId = (random: (n: number) => Uint8Array, now: () => number): string =>\n uuidv7(random, now);\n\n/** Catch-up sync for one pass: claim every pending transfer, then read balance and identity. */\nasync function resync(\n client: SparkClient,\n log: (transferId: string, error: unknown) => void,\n): Promise<{ balance: number; identity: Uint8Array }> {\n const { failures } = await client.transfers.claimPending();\n for (const failure of failures) {\n log(failure.transferId, failure.error);\n }\n const [balance, identity] = await Promise.all([client.balance(), client.identityPublicKey()]);\n return { balance, identity };\n}\n\n/** Abortable backoff — resolves early when the signal aborts; removes its listener. */\nasync function eventsBackoff(failures: number, signal: AbortSignal): Promise<void> {\n await new Promise<void>((resolve) => {\n const timer = setTimeout(\n () => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n },\n Math.min(2 ** failures, 30) * 1000,\n );\n const onAbort = (): void => {\n clearTimeout(timer);\n resolve();\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\nexport class SparkController extends Controller<SparkControllerState> {\n private readonly options: SparkControllerOptions;\n private engineStore: EngineStore | undefined;\n private readonly accounts = new Map<string, SparkAccountRef>();\n private readonly clients = new Map<string, SparkClient>();\n private readonly recentSeq = new Map<string, number>();\n private readonly aborts = new Map<string, AbortController>();\n\n constructor(options: SparkControllerOptions) {\n super({ name: \"spark\", defaultState: () => ({ accounts: {} }) });\n this.options = options;\n }\n\n /** Engine calls this with the open store on unlock; `undefined` on lock. */\n setStore(store: EngineStore | undefined): void {\n this.engineStore = store;\n }\n\n /**\n * Declarative account set: refs not yet tracked are patched `locked` and started when the store\n * is open; tracked refs no longer listed are stopped and dropped; running refs stay untouched.\n */\n setAccounts(refs: ReadonlyArray<SparkAccountRef>): void {\n const wanted = new Map(refs.map((ref) => [key(ref), ref]));\n for (const k of this.accounts.keys()) {\n if (!wanted.has(k)) {\n this.accounts.delete(k);\n this.stopAccount(k);\n }\n }\n for (const [k, ref] of wanted) {\n if (!this.accounts.has(k)) {\n this.accounts.set(k, ref);\n this.patch(k, { status: \"locked\" });\n }\n if (this.engineStore !== undefined && !this.clients.has(k)) {\n this.startAccount(ref);\n }\n }\n }\n\n async init(): Promise<void> {\n for (const ref of this.accounts.values()) {\n this.startAccount(ref);\n }\n await Promise.resolve();\n }\n\n async destroy(): Promise<void> {\n await this.lockAll();\n }\n\n private stopAccount(k: string): void {\n this.aborts.get(k)?.abort();\n this.aborts.delete(k);\n this.clients.get(k)?.close();\n this.clients.delete(k);\n this.update((s) => {\n if (!(k in s.accounts)) {\n return s;\n }\n const { [k]: _dropped, ...rest } = s.accounts;\n void _dropped;\n return { ...s, accounts: rest };\n });\n }\n\n /** Lock: abort every event loop, close every client, reset state. */\n async lockAll(): Promise<void> {\n for (const [k, client] of this.clients) {\n this.aborts.get(k)?.abort();\n client.close();\n }\n this.aborts.clear();\n this.clients.clear();\n this.engineStore = undefined;\n await Promise.resolve();\n this.update((s) =>\n Object.keys(s.accounts).length === 0\n ? s\n : {\n ...s,\n accounts: Object.fromEntries(\n Object.keys(s.accounts).map((k) => [k, { status: \"locked\" as const }]),\n ),\n },\n );\n }\n\n private startAccount(ref: SparkAccountRef): void {\n const k = key(ref);\n if (this.engineStore === undefined || this.clients.has(k)) {\n return;\n }\n this.patch(k, { status: \"connecting\" });\n try {\n const col = this.engineStore.collection(`spark-exit-chains:${k}`);\n const client = this.options.createClient({\n ref,\n store: sparkStore(col),\n signer: this.options.spark.signer(ref),\n fetch: this.options.fetch,\n });\n this.clients.set(k, client);\n const abort = new AbortController();\n this.aborts.set(k, abort);\n // The initial sync lives in the event loop's catch-up pass: a transient failure at\n // account start retries through the loop's backoff instead of leaving the account dead\n // in \"error\".\n this.runEvents(k, client, abort.signal, ref.network);\n } catch (error) {\n this.patch(k, { status: \"error\", errorCategory: categorize(error) });\n this.options.logger.warn(\"spark account failed to start\", error);\n }\n }\n\n private runEvents(\n k: string,\n client: SparkClient,\n signal: AbortSignal,\n network: SparkAccountRef[\"network\"],\n ): void {\n // Every pass resyncs before streaming: the catch-up claim retries anything a previous\n // pass failed on and covers events missed while disconnected — a failed claim is never\n // lost, only deferred one pass. Any throw or a clean stream end backs off (exponential,\n // abortable) and starts a new pass.\n const loop = async (): Promise<void> => {\n let failures = 0;\n while (!signal.aborted) {\n try {\n // Catch-up: claim pending transfers and refresh the balance snapshot. Per-transfer\n // failures are logged, not fatal — one poisoned transfer must not fail the pass.\n // oxlint-disable-next-line no-await-in-loop -- catch-up sync must precede streaming\n const { balance, identity } = await resync(client, (transferId, error) => {\n this.options.logger.warn(\n `spark catch-up claim failed for ${transferId} (${categorize(error)})`,\n );\n });\n if (signal.aborted) {\n return;\n }\n this.patch(k, {\n balanceSats: balance,\n status: \"ready\",\n identityPublicKey: [...identity].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\"),\n sparkAddress: encodeSparkAddress({\n network,\n identityPublicKey: identity,\n }),\n });\n void this.refreshRecent(k, client);\n const iterator = client.events(signal)[Symbol.asyncIterator]();\n let open = true;\n while (open) {\n // oxlint-disable-next-line no-await-in-loop -- events arrive in stream order\n const item = await iterator.next();\n if (item.done === true) {\n open = false;\n } else {\n const event = item.value;\n if (event.type === \"transfer\") {\n try {\n // oxlint-disable-next-line no-await-in-loop -- claims are ordered per event\n await this.handleTransfer(client, event, signal, k);\n failures = 0;\n } catch (error) {\n // A terminal status (expired, returned…) is not a stream failure — log the\n // transfer and keep consuming the stream.\n if (!(error instanceof SparkInputError)) {\n throw error;\n }\n this.options.logger.warn(\n `spark claim of ${event.transferId} rejected (${categorize(error)})`,\n );\n failures = 0;\n }\n }\n }\n }\n // A clean end is abnormal for a permanent stream — back off like a failure.\n failures += 1;\n this.options.logger.warn(\"spark event stream ended — resubscribing\");\n } catch (error) {\n if (signal.aborted) {\n return;\n }\n failures += 1;\n if (failures === 1) {\n this.patch(k, { status: \"error\", errorCategory: categorize(error) });\n }\n this.options.logger.warn(\"spark event stream failed — resubscribing\", error);\n }\n // oxlint-disable-next-line no-await-in-loop -- the backoff bounds resubscribe pace\n await eventsBackoff(failures, signal);\n }\n };\n void loop();\n }\n\n private async handleTransfer(\n client: SparkClient,\n event: { readonly direction: \"incoming\" | \"outgoing\"; readonly transferId: string },\n signal: AbortSignal,\n k: string,\n ): Promise<void> {\n if (event.direction === \"incoming\") {\n // claim(id) re-queries until the transfer turns claimable — it owns the protocol-level\n // wait for the SSP's claimable window, so no extra delay or pending-list scan here.\n await client.transfers.claim(event.transferId, { signal });\n }\n this.patch(k, { balanceSats: await client.balance() });\n void this.refreshRecent(k, client);\n }\n\n private notesCollection(k: string): EngineCollection | undefined {\n return this.engineStore?.collection(`spark-notes:${k}`);\n }\n\n /** Attach locally written notes to a history page; malformed records warn and drop. */\n private async withNotes(\n k: string,\n payments: ReadonlyArray<SparkPayment>,\n ): Promise<ReadonlyArray<SparkActivity>> {\n const col = this.notesCollection(k);\n if (col === undefined) {\n return payments;\n }\n return Promise.all(\n payments.map(async (payment): Promise<SparkActivity> => {\n const bytes = await col.get(payment.id);\n if (bytes === undefined) {\n return payment;\n }\n let note: PaymentNote | undefined;\n try {\n note = parsePaymentNote(JSON.parse(new TextDecoder().decode(bytes)));\n } catch {\n note = undefined;\n }\n if (note === undefined) {\n this.options.logger.warn(\n `spark note record for ${payment.id} ignored: malformed`,\n new Error(\"malformed payment note\"),\n );\n return payment;\n }\n return { ...payment, note };\n }),\n );\n }\n\n /**\n * Refill `recent` from the first history page. A failure keeps the previous page — it never\n * touches `status`/`errorCategory`. A per-account sequence keeps a slower older refresh from\n * overwriting a newer one.\n */\n private async refreshRecent(k: string, client: SparkClient): Promise<void> {\n const seq = (this.recentSeq.get(k) ?? 0) + 1;\n this.recentSeq.set(k, seq);\n try {\n const { payments } = await client.transfers.history({ limit: 20 });\n const items = await this.withNotes(k, payments);\n // A stale seq or a closed client (lockAll cleared the map) must not write.\n if (this.recentSeq.get(k) === seq && this.clients.get(k) === client) {\n this.patch(k, { recent: items });\n }\n } catch (error) {\n this.options.logger.warn(`spark recent refresh failed for ${k}`, error);\n }\n }\n\n private patch(k: string, delta: Partial<SparkAccountState>): void {\n this.update((s) => ({\n ...s,\n accounts: { ...s.accounts, [k]: { status: \"locked\" as const, ...s.accounts[k], ...delta } },\n }));\n }\n\n private clientFor(ref: SparkAccountRef): SparkClient {\n const client = this.clients.get(key(ref));\n if (client === undefined) {\n throw new SparkControllerError(\"internal\", \"account is not connected\");\n }\n return client;\n }\n\n private async guarded<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n if (error instanceof SparkControllerError) {\n throw error;\n }\n throw new SparkControllerError(categorize(error), \"spark action failed\", error);\n }\n }\n\n /**\n * One-off balance + activity probe for an account that may not be running: builds a temporary\n * client through the same factory on the account's own exit-chain collection (nothing diverges —\n * `balance()`/`transfers.history` never write it), reads, and closes it in `finally`.\n */\n async inspect(ref: SparkAccountRef): Promise<{ balanceSats: number; used: boolean }> {\n return this.guarded(async () => {\n if (this.engineStore === undefined) {\n throw new SparkControllerError(\"internal\", \"engine store is not open\");\n }\n const k = key(ref);\n const running = this.clients.get(k);\n if (running !== undefined) {\n const [balance, page] = await Promise.all([\n running.balance(),\n running.transfers.history({ limit: 1 }),\n ]);\n return { balanceSats: balance, used: balance > 0 || page.payments.length > 0 };\n }\n const client = this.options.createClient({\n ref,\n store: sparkStore(this.engineStore.collection(`spark-exit-chains:${k}`)),\n signer: this.options.spark.signer(ref),\n fetch: this.options.fetch,\n });\n try {\n const [balance, page] = await Promise.all([\n client.balance(),\n client.transfers.history({ limit: 1 }),\n ]);\n return { balanceSats: balance, used: balance > 0 || page.payments.length > 0 };\n } finally {\n client.close();\n }\n });\n }\n\n /** History for one account: a client page merged with locally written notes by id. */\n async history(\n ref: SparkAccountRef,\n options?: {\n readonly limit?: number;\n readonly offset?: number;\n },\n ): Promise<{\n readonly items: ReadonlyArray<SparkActivity>;\n readonly nextOffset: number | undefined;\n }> {\n return this.guarded(async () => {\n const client = this.clientFor(ref);\n const { payments, nextOffset } = await client.transfers.history({\n ...(options?.limit === undefined ? {} : { limit: options.limit }),\n ...(options?.offset === undefined ? {} : { offset: options.offset }),\n });\n return { items: await this.withNotes(key(ref), payments), nextOffset };\n });\n }\n\n async send(\n ref: SparkAccountRef,\n params: {\n receiver: string;\n amountSats: number;\n verify: UnlockFactor;\n },\n ): Promise<SparkTransfer> {\n return this.guarded(async () => {\n const client = this.clientFor(ref);\n const receiver = decodeSparkAddress(params.receiver);\n if (receiver.network !== ref.network) {\n throw new SparkControllerError(\"rejected\", \"receiver address is on a different network\");\n }\n const identity = receiver.identityPublicKey;\n await this.options.spark.approve({\n account: ref,\n intent: {\n kind: \"transfer\",\n receivers: [{ identityPublicKey: identity, amountSats: params.amountSats }],\n },\n verify: params.verify,\n });\n const transfer = await client.transfers.send({\n receiver: params.receiver,\n amountSats: params.amountSats,\n transferId: transferId(this.options.random, this.options.now),\n });\n void this.refreshRecent(key(ref), client);\n return transfer;\n });\n }\n\n async registerLightningAddress(\n ref: SparkAccountRef,\n params: { serverUrl: string; domain: string; username: string; description: string },\n ): Promise<{ lnurl: string; lightningAddress: string }> {\n const signer = this.options.spark.signer(ref);\n try {\n return await registerLightningAddress({ ...params, fetch: this.options.fetch, signer });\n } catch (error) {\n throw error instanceof SparkControllerError\n ? error\n : new SparkControllerError(\"internal\", \"registration failed\");\n }\n }\n\n async unregisterLightningAddress(\n ref: SparkAccountRef,\n params: { serverUrl: string; domain: string; username: string },\n ): Promise<void> {\n const signer = this.options.spark.signer(ref);\n try {\n await unregisterLightningAddress({ ...params, fetch: this.options.fetch, signer });\n } catch (error) {\n throw error instanceof SparkControllerError\n ? error\n : new SparkControllerError(\"internal\", \"unregistration failed\");\n }\n }\n\n async payInvoice(\n ref: SparkAccountRef,\n params: {\n invoice: string;\n amountSats?: number;\n maxFeeSats: number;\n verify: UnlockFactor;\n /** Local annotation written under the payment's transfer id after it succeeds. */\n note?: PaymentNote;\n },\n ): Promise<LightningPayment> {\n return this.guarded(async () => {\n const client = this.clientFor(ref);\n await this.options.spark.approve({\n account: ref,\n intent: {\n kind: \"lightning\",\n invoice: params.invoice,\n ...(params.amountSats === undefined ? {} : { amountSats: params.amountSats }),\n maxFeeSats: params.maxFeeSats,\n },\n verify: params.verify,\n });\n const payment = await client.lightning.pay({\n invoice: params.invoice,\n maxFeeSats: params.maxFeeSats,\n ...(params.amountSats === undefined ? {} : { amountSats: params.amountSats }),\n transferId: transferId(this.options.random, this.options.now),\n });\n if (params.note !== undefined) {\n try {\n await this.notesCollection(key(ref))?.put(\n payment.transferId,\n encodePaymentNote(params.note),\n );\n } catch (error) {\n // The payment already succeeded — a lost annotation is a warning, not a failure.\n this.options.logger.warn(\"spark note write failed\", error);\n }\n }\n void this.refreshRecent(key(ref), client);\n return payment;\n });\n }\n\n /**\n * Pays a Spark invoice address. The approval intent mirrors `send`: receiver identity and amount\n * come from the parsed invoice (the supplied `amountSats` fills an open invoice). Then\n * `client.invoices.pay` executes it.\n */\n async paySparkInvoice(\n ref: SparkAccountRef,\n params: { invoice: string; amountSats?: number; verify: UnlockFactor },\n ): Promise<SparkTransfer> {\n return this.guarded(async () => {\n const client = this.clientFor(ref);\n const parsed = parseSparkInvoice(params.invoice, {\n network: ref.network,\n now: this.options.now(),\n });\n const invoicePayment = parsed.fields.payment;\n if (invoicePayment !== undefined && invoicePayment.type !== \"sats\") {\n throw new SparkControllerError(\n \"rejected\",\n \"spark invoice: only sats invoices are supported\",\n );\n }\n if (\n invoicePayment?.type === \"sats\" &&\n invoicePayment.amount !== undefined &&\n params.amountSats !== undefined &&\n params.amountSats !== invoicePayment.amount\n ) {\n throw new SparkControllerError(\n \"rejected\",\n \"spark invoice: amountSats conflicts with the invoice amount\",\n );\n }\n const amountSats =\n invoicePayment?.type === \"sats\" && invoicePayment.amount !== undefined\n ? invoicePayment.amount\n : params.amountSats;\n if (amountSats === undefined) {\n throw new SparkControllerError(\n \"rejected\",\n \"spark invoice: amountless invoice requires amountSats\",\n );\n }\n await this.options.spark.approve({\n account: ref,\n intent: {\n kind: \"transfer\",\n receivers: [{ identityPublicKey: parsed.receiverIdentityPublicKey, amountSats }],\n },\n verify: params.verify,\n });\n const result = await client.invoices.pay(params.invoice, {\n amount: amountSats,\n transferId: transferId(this.options.random, this.options.now),\n });\n void this.refreshRecent(key(ref), client);\n // invoices.pay returns a string for token invoices — unreachable after the pre-approval\n // sats check above, kept as the internal guard.\n if (typeof result === \"string\") {\n throw new SparkControllerError(\"internal\", \"unexpected token invoice result\");\n }\n return result;\n });\n }\n\n async createInvoice(\n ref: SparkAccountRef,\n params: { amountSats: number; memo?: string },\n ): Promise<LightningInvoice> {\n return this.guarded(async () =>\n this.clientFor(ref).lightning.createInvoice({\n amountSats: params.amountSats,\n ...(params.memo === undefined ? {} : { memo: params.memo }),\n }),\n );\n }\n\n async receiveAddress(ref: SparkAccountRef): Promise<string | undefined> {\n const state = this.getState().accounts[key(ref)];\n await Promise.resolve();\n return state?.sparkAddress;\n }\n\n /**\n * Cooperative exit to an L1 address. The client exits `amountSats` of leaves and the payout is\n * `amountSats - fee`, so the approval intent carries the PAYOUT: `amountSats: exit - fee` and\n * `maxFeeSats: fee` — the kernel matches the exit output against the intent, not the leaf total.\n */\n async withdraw(\n ref: SparkAccountRef,\n params: {\n address: string;\n amountSats?: number;\n speed: \"FAST\" | \"MEDIUM\" | \"SLOW\";\n maxFeeSats?: number;\n verify: UnlockFactor;\n },\n ): Promise<CooperativeExitResult> {\n return this.guarded(async () => {\n const client = this.clientFor(ref);\n try {\n bitcoinAddressScript(params.address, ref.network);\n } catch {\n throw new SparkControllerError(\"rejected\", \"withdrawal address is not on this network\");\n }\n const exitAmount = params.amountSats ?? (await client.balance());\n const quote = await client.withdrawals.quoteCooperativeExit({\n address: params.address,\n amountSats: exitAmount,\n });\n const fee =\n quote.fees[\n params.speed === \"FAST\" ? \"fast\" : params.speed === \"MEDIUM\" ? \"medium\" : \"slow\"\n ];\n if (params.maxFeeSats !== undefined && params.maxFeeSats < fee) {\n throw new SparkControllerError(\"rejected\", \"maxFeeSats below the quoted fee\");\n }\n if (fee >= exitAmount) {\n throw new SparkControllerError(\n \"insufficient-funds\",\n \"exit fee meets or exceeds the amount\",\n );\n }\n await this.options.spark.approve({\n account: ref,\n intent: {\n kind: \"exit\",\n address: params.address,\n amountSats: exitAmount - fee,\n maxFeeSats: fee,\n },\n verify: params.verify,\n });\n const exit = await client.withdrawals.cooperativeExit({\n address: params.address,\n speed: params.speed,\n maxFeeSats: fee,\n amountSats: exitAmount,\n transferId: transferId(this.options.random, this.options.now),\n });\n void this.refreshRecent(key(ref), client);\n return exit;\n });\n }\n}\n","/** Bitcoin route: scan → coin-select → PSBT → sign → broadcast, plus esplora status poll. */\nimport { hex } from \"@scure/base\";\nimport { Address, OutScript, Transaction } from \"@scure/btc-signer\";\n\nimport {\n decodeBitcoinPsbt,\n bitcoinNetwork,\n bitcoinPubkeyFromXpub,\n} from \"@qntx/wallet-chains/bitcoin\";\nimport { chains } from \"@qntx/wallet/chains\";\nimport type { ChainTemplate } from \"@qntx/wallet/protocol\";\n\nimport { BtcUtxoStore, scanChain, scanUtxos, scriptPubKey } from \"../chains/bitcoin-scan.ts\";\nimport type { ScanAddress, ScanUtxo } from \"../chains/bitcoin-scan.ts\";\nimport { BitcoinChainAdapter, feeTiers } from \"../chains/bitcoin.ts\";\nimport type { NetworkController } from \"../networks/controller.ts\";\nimport { errorMessage, newId } from \"./route.ts\";\nimport type { SignParams, RouteContext, SendParams, TrackedTransaction, TxState } from \"./route.ts\";\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null;\n\ntype BtcStash = {\n readonly inputs: ReadonlyArray<Parameters<BitcoinChainAdapter[\"buildPsbt\"]>[0][number]>;\n readonly allUtxos: ReadonlyArray<{\n readonly txid: string;\n readonly vout: number;\n readonly value: number;\n readonly address: string;\n readonly height: number;\n }>;\n readonly pathOf: (u: { readonly address: string; readonly txid?: string }) => number[];\n readonly pubkeyOf: (u: { readonly address: string; readonly txid?: string }) => Uint8Array;\n readonly scriptOf: (u: { readonly address: string }) => Uint8Array;\n readonly changeAddresses: ReadonlyArray<string>;\n readonly tier: string;\n readonly template: ChainTemplate;\n readonly network: string;\n readonly fp: number;\n};\n\nconst fetchRawTxes = async (\n es: { readonly get: (path: string) => Promise<unknown> },\n utxos: ReadonlyArray<{ readonly txid: string }>,\n): Promise<Map<string, Uint8Array>> => {\n const out = new Map<string, Uint8Array>();\n await Promise.all(\n utxos.map(async (u) => {\n const raw = await es.get(`/tx/${u.txid}/hex`);\n if (typeof raw !== \"string\") {\n throw new TypeError(`esplora /tx/${u.txid}/hex: not a string`);\n }\n const bytes = hex.decode(raw);\n if (Transaction.fromRaw(bytes, { allowUnknownInputs: true }).id !== u.txid) {\n throw new Error(`esplora /tx/${u.txid}/hex: txid mismatch`);\n }\n out.set(u.txid, bytes);\n }),\n );\n return out;\n};\n\n/** The account-relative full path `purpose'/coin'/group'/change/index` for a PSBT entry. */\nconst accountPath = (accountPath: string): ReadonlyArray<number> =>\n accountPath\n .replace(/^m\\//, \"\")\n .split(\"/\")\n .map((p) => {\n const hardened = p.endsWith(\"'\");\n const n = Number(hardened ? p.slice(0, -1) : p);\n return hardened ? n + 0x80000000 : n;\n });\n\nconst poll = async (ctx: RouteContext, tx: TrackedTransaction): Promise<TxState | undefined> => {\n if (tx.hash === undefined) {\n return \"failed\";\n }\n const es = ctx.options.networks.esplora(tx.network);\n const status: unknown = await es.get(`/tx/${tx.hash}/status`);\n const confirmed = isObject(status) && status[\"confirmed\"] === true;\n if (!confirmed) {\n return undefined;\n }\n return \"confirmed\";\n};\n\n/** Per-controller route — the UTXO store and the build stash are engine state. */\nexport const createBitcoinRoute = (): BitcoinRoute => {\n const bitcoin = new BitcoinChainAdapter();\n const bitcoinUtxos = new BtcUtxoStore();\n const pending = new Map<string, BtcStash>();\n\n const send = async (ctx: RouteContext, params: SendParams): Promise<TrackedTransaction> => {\n const { account, network, to, amount, fee, verify } = params;\n if (account.kind !== \"hd\") {\n throw new Error(\"imported accounts are not yet supported\");\n }\n const es = ctx.options.networks.esplora(network);\n const apis = ctx.options.chains ?? chains(ctx.options.wallet);\n const template =\n ([\"btc.bip44\", \"btc.bip49\", \"btc.bip84\", \"btc.bip86\"] as const).find(\n (x) => x === account.template,\n ) ?? \"btc.bip84\";\n const btcAccount = await apis.account({\n walletId: account.walletId,\n groupIndex: account.groupIndex,\n template,\n network,\n });\n if (!(\"xpub\" in btcAccount) || btcAccount.xpub === undefined) {\n throw new Error(\"bitcoin account carries no xpub\");\n }\n const { xpub, fingerprint, path } = btcAccount as {\n xpub: string;\n fingerprint: string;\n path: string;\n };\n const fp = Number.parseInt(fingerprint, 16);\n const net = bitcoinNetwork(network);\n const tap = template === \"btc.bip86\";\n const rawTxOf = (u: { readonly txid: string }): Uint8Array | undefined => rawTxes.get(u.txid);\n\n const receive = await scanChain(es, xpub, template, network, net.params, 0);\n const change = await scanChain(es, xpub, template, network, net.params, 1);\n const addresses: ScanAddress[] = [...receive, ...change];\n const scannedUtxos: ReadonlyArray<ScanUtxo> = await scanUtxos(es, addresses, net.params);\n const utxos = scannedUtxos.map((u) => ({\n txid: u.txid,\n vout: u.vout,\n value: u.value,\n address: u.address,\n status: \"confirmed\" as const,\n height: u.height,\n }));\n const byAddr = new Map(addresses.map((a) => [a.address, a]));\n const base = accountPath(path);\n const rawTxes =\n template === \"btc.bip44\" ? await fetchRawTxes(es, utxos) : new Map<string, Uint8Array>();\n const inputs = bitcoin.toInputs(\n utxos,\n fp,\n (u) => {\n const a = byAddr.get(u.address);\n return a === undefined ? [] : [...base, a.chain, a.index];\n },\n (u) => {\n const a = byAddr.get(u.address);\n if (a === undefined) {\n throw new Error(`utxo ${u.txid} on an unknown address`);\n }\n return bitcoinPubkeyFromXpub(xpub, template, network, a.chain, a.index);\n },\n (u) => scriptPubKey(u.address, net.params),\n template,\n template === \"btc.bip44\" ? rawTxOf : undefined,\n );\n // bip49/bip44 are spend-only — their change goes on the group's bip84 chain.\n let changeAddr = change.find((a) => !a.used)?.address;\n if (template === \"btc.bip49\" || template === \"btc.bip44\") {\n const acct84 = await apis.account({\n walletId: account.walletId,\n groupIndex: account.groupIndex,\n template: \"btc.bip84\",\n network,\n });\n const xpub84 = \"xpub\" in acct84 ? acct84.xpub : undefined;\n if (xpub84 === undefined) {\n throw new Error(\"no bip84 account for the legacy-template change chain\");\n }\n const change84 = await scanChain(es, xpub84, \"btc.bip84\", network, net.params, 1);\n changeAddr = change84.find((a) => !a.used)?.address;\n }\n if (changeAddr === undefined) {\n throw new Error(\"no unused change address\");\n }\n const quotes = await feeTiers(es);\n const quote =\n quotes.find(\n (q: { tier: string }) =>\n q.tier === (fee === \"fast\" ? \"fast\" : fee === \"slow\" ? \"slow\" : \"normal\"),\n ) ?? quotes[1];\n if (quote === undefined) {\n throw new Error(\"no fee quote\");\n }\n const { psbt, inputs: selected } = bitcoin.buildPsbt(\n inputs,\n to,\n amount,\n BigInt(quote.satPerByte),\n changeAddr,\n net.params,\n );\n const selectedKeys = new Set(\n selected.map((i) => `${String(i.txid ?? \"\")}:${String(i.index ?? 0)}`),\n );\n const selectedUtxos = utxos.filter((u) => selectedKeys.has(`${u.txid}:${u.vout}`));\n const txP = Transaction.fromPSBT(psbt);\n const ownScripts = new Set(\n change.filter((a) => !a.used).map((a) => hex.encode(scriptPubKey(a.address, net.params))),\n );\n const request = {\n kind: \"bitcoin.psbt\" as const,\n network,\n account,\n psbt,\n sign: Array.from({ length: txP.inputsLength }, (_, i) => i),\n };\n const intent = decodeBitcoinPsbt(request, ownScripts);\n const vsize = Math.ceil(\n 10.5 + txP.inputsLength * (tap ? 57.5 : 68) + txP.outputsLength * (tap ? 43 : 31),\n );\n const outValues = Array.from({ length: txP.outputsLength }, (_, i) => {\n const o = txP.getOutput(i);\n const scriptHex =\n \"script\" in o && o.script instanceof Uint8Array ? o.script : new Uint8Array();\n const address =\n scriptHex.length > 0 ? Address(net.params).encode(OutScript.decode(scriptHex)) : \"\";\n return { address, value: Number(o.amount ?? 0n), own: false };\n });\n for (const o of outValues) {\n if (o.address !== \"\" && ownScripts.has(hex.encode(scriptPubKey(o.address, net.params)))) {\n (o as { own: boolean }).own = true;\n }\n }\n const inTotal = selectedUtxos.reduce((a, u) => a + u.value, 0);\n const outTotal = outValues.reduce((a, o) => a + o.value, 0);\n const id0 = newId(ctx.options.random);\n pending.set(id0, {\n inputs,\n allUtxos: utxos,\n pathOf: (u) => {\n const a = byAddr.get(u.address);\n return a === undefined ? [] : [...base, a.chain, a.index];\n },\n pubkeyOf: (u) => {\n const a = byAddr.get(u.address);\n if (a === undefined) {\n throw new Error(`utxo ${String(u.txid)} on an unknown address`);\n }\n return bitcoinPubkeyFromXpub(xpub, template, network, a.chain, a.index);\n },\n scriptOf: (u) => scriptPubKey(u.address, net.params),\n changeAddresses: change.filter((a) => !a.used).map((a) => a.address),\n fp,\n tier: fee === \"fast\" ? \"fast\" : fee === \"slow\" ? \"slow\" : \"normal\",\n template,\n network,\n });\n let tx: TrackedTransaction = {\n id: id0,\n family: \"bitcoin\",\n network,\n account: account.walletId,\n hash: undefined,\n state: \"draft\",\n intent,\n nonce: 0,\n btc: {\n inputs: selectedUtxos.map((u) => ({\n txid: u.txid,\n vout: u.vout,\n value: u.value,\n address: u.address,\n })),\n outputs: outValues,\n vsize,\n fee: inTotal - outTotal,\n feeRate: Math.ceil((inTotal - outTotal) / vsize),\n },\n submittedAt: ctx.options.now(),\n error: undefined,\n };\n tx = await ctx.transition(tx, {});\n try {\n const result = await apis.sign({ request, verify });\n tx = await ctx.transition(tx, { state: \"signed\" });\n if (result.kind !== \"bitcoin.psbt\" || !(result.signedPsbt instanceof Uint8Array)) {\n throw new Error(\"unexpected bitcoin sign result\");\n }\n bitcoinUtxos.lock(selectedUtxos, tx.id);\n const signed = Transaction.fromPSBT(result.signedPsbt);\n signed.finalize();\n const raw = signed.extract();\n const hash = String(await es.post(\"/tx\", hex.encode(raw)));\n tx = await ctx.transition(tx, {\n state: \"submitted\",\n hash,\n submittedAt: ctx.options.now(),\n });\n ctx.track(tx.id, hash);\n return tx;\n } catch (error) {\n const failed = tx.state === \"signed\" ? \"failed\" : \"rejected\";\n await ctx.transition(tx, { state: failed, error: errorMessage(error) });\n throw error;\n }\n };\n\n /** Esplora `/tx/:txid/status` → terminal state or `undefined` to keep polling. */\n\n const finish = async (\n ctx: RouteContext,\n stash: BtcStash,\n es: ReturnType<NetworkController[\"esplora\"]>,\n account: SignParams[\"request\"][\"account\"],\n old: TrackedTransaction,\n psbt: Uint8Array,\n record: NonNullable<TrackedTransaction[\"btc\"]>,\n link: { readonly replaces?: string; readonly parentId?: string },\n verify: SendParams[\"verify\"],\n ): Promise<TrackedTransaction> => {\n const apis = ctx.options.chains ?? chains(ctx.options.wallet);\n const txP = Transaction.fromPSBT(psbt);\n const request = {\n kind: \"bitcoin.psbt\" as const,\n network: old.network,\n account,\n psbt,\n sign: Array.from({ length: txP.inputsLength }, (_, i) => i),\n };\n const ownScripts = new Set(\n stash.changeAddresses.map((a) =>\n hex.encode(scriptPubKey(a, bitcoinNetwork(stash.network).params)),\n ),\n );\n const intent = decodeBitcoinPsbt(request, ownScripts);\n let tx: TrackedTransaction = {\n id: newId(ctx.options.random),\n family: \"bitcoin\",\n network: old.network,\n account: old.account,\n hash: undefined,\n state: \"draft\",\n intent,\n nonce: 0,\n btc: record,\n submittedAt: ctx.options.now(),\n error: undefined,\n ...link,\n };\n tx = await ctx.transition(tx, {});\n try {\n const result = await apis.sign({ request, verify });\n tx = await ctx.transition(tx, { state: \"signed\" });\n if (result.kind !== \"bitcoin.psbt\" || !(result.signedPsbt instanceof Uint8Array)) {\n throw new Error(\"unexpected bitcoin sign result\");\n }\n bitcoinUtxos.endTx(old.id, \"dropped\");\n const signed = Transaction.fromPSBT(result.signedPsbt);\n signed.finalize();\n const raw = signed.extract();\n const hash = String(await es.post(\"/tx\", hex.encode(raw)));\n bitcoinUtxos.lock(\n record.inputs.map((i) => ({ ...i, status: \"confirmed\" as const, height: 0 })),\n tx.id,\n );\n tx = await ctx.transition(tx, { state: \"submitted\", hash, submittedAt: ctx.options.now() });\n ctx.track(tx.id, hash);\n return tx;\n } catch (error) {\n const failed = tx.state === \"signed\" ? \"failed\" : \"rejected\";\n await ctx.transition(tx, { state: failed, error: errorMessage(error) });\n throw error;\n }\n };\n\n const replace = async (\n ctx: RouteContext,\n old: TrackedTransaction,\n mode: \"speed-up\" | \"cancel\",\n verify: SendParams[\"verify\"],\n ): Promise<TrackedTransaction> => {\n const stash = pending.get(old.id);\n const { btc } = old;\n if (stash === undefined || btc === undefined) {\n throw new Error(\"the original build context is gone — cannot replace after restart\");\n }\n const es = ctx.options.networks.esplora(old.network);\n const apis = ctx.options.chains ?? chains(ctx.options.wallet);\n const { template } = stash;\n const btcAccount = await apis.account({\n walletId: old.account,\n groupIndex: 0,\n template,\n network: old.network,\n });\n if (!(\"xpub\" in btcAccount)) {\n throw new Error(\"bitcoin account carries no xpub\");\n }\n const account = { kind: \"hd\" as const, walletId: old.account, groupIndex: 0, template };\n const tiers = await feeTiers(es);\n const tierQuote = tiers.find((t) => t.tier === stash.tier) ?? tiers[1];\n const rate = tierQuote === undefined ? 1 : tierQuote.satPerByte;\n const newFee = Math.max(btc.fee + btc.vsize, Math.ceil(btc.vsize * rate));\n const [changeAddr] = stash.changeAddresses;\n if (changeAddr === undefined) {\n throw new Error(\"no unused change address\");\n }\n const net = bitcoinNetwork(old.network);\n const inTotal = btc.inputs.reduce((a, i) => a + i.value, 0);\n const dust = 546;\n const payee = btc.outputs\n .filter((o) => !o.own)\n .map((o) => ({ address: o.address, amount: BigInt(o.value) }));\n const usedKeys = new Set(btc.inputs.map((i) => `${i.txid}:${i.vout}`));\n const spare = stash.allUtxos.filter((u) => !usedKeys.has(`${u.txid}:${u.vout}`));\n const extraInputs: ReturnType<typeof bitcoin.toInputs> = [];\n const extraUtxos: typeof spare = [];\n const feeNeeded = (o: ReadonlyArray<{ amount: bigint }>): bigint =>\n BigInt(newFee) -\n (BigInt(inTotal) +\n extraUtxos.reduce((a, u) => a + BigInt(u.value), 0n) -\n o.reduce((a, x) => a + x.amount, 0n));\n let outputs: ReadonlyArray<{ readonly address: string; readonly amount: bigint }>;\n if (mode === \"cancel\") {\n outputs = [{ address: changeAddr, amount: BigInt(inTotal - newFee) }];\n } else {\n const shrunk = btc.outputs.find((o) => o.own);\n const changeAfter = shrunk === undefined ? 0 : shrunk.value - (newFee - btc.fee);\n outputs =\n changeAfter >= dust\n ? [...payee, { address: changeAddr, amount: BigInt(changeAfter) }]\n : payee;\n while (feeNeeded(outputs) > 0n && spare.length > extraUtxos.length) {\n const next = spare[extraUtxos.length];\n if (next === undefined) {\n break;\n }\n extraUtxos.push(next);\n extraInputs.push(\n ...bitcoin.toInputs(\n [{ ...next, status: \"confirmed\" as const }],\n stash.fp,\n stash.pathOf,\n stash.pubkeyOf,\n stash.scriptOf,\n stash.template,\n ),\n );\n }\n if (feeNeeded(outputs) > 0n) {\n const keepChange = [...outputs, { address: changeAddr, amount: BigInt(dust) }];\n while (feeNeeded(keepChange) > 0n && spare.length > extraUtxos.length) {\n const next = spare[extraUtxos.length];\n if (next === undefined) {\n break;\n }\n extraUtxos.push(next);\n extraInputs.push(\n ...bitcoin.toInputs(\n [{ ...next, status: \"confirmed\" as const }],\n 0,\n stash.pathOf,\n stash.pubkeyOf,\n stash.scriptOf,\n stash.template,\n ),\n );\n }\n if (feeNeeded(keepChange) > 0n) {\n throw new Error(\"insufficient confirmed utxo to fund the replacement fee\");\n }\n const changeValue =\n inTotal +\n extraUtxos.reduce((a, u) => a + u.value, 0) -\n payee.reduce((a, o) => a + Number(o.amount), 0) -\n newFee;\n outputs = [...payee, { address: changeAddr, amount: BigInt(changeValue) }];\n } else {\n const changeValue =\n inTotal +\n extraUtxos.reduce((a, u) => a + u.value, 0) -\n payee.reduce((a, o) => a + Number(o.amount), 0) -\n newFee;\n if (changeValue >= dust) {\n outputs = [...payee, { address: changeAddr, amount: BigInt(changeValue) }];\n }\n }\n }\n const allInputs = [...stash.inputs, ...extraInputs];\n const { psbt, vsize } = bitcoin.buildExactPsbt(allInputs, outputs, net.params);\n const record = {\n inputs: [\n ...btc.inputs,\n ...extraUtxos.map((u) => ({\n txid: u.txid,\n vout: u.vout,\n value: u.value,\n address: u.address,\n })),\n ],\n outputs: outputs.map((o) => ({\n address: o.address,\n value: Number(o.amount),\n own: o.address === changeAddr,\n })),\n vsize,\n fee: newFee,\n feeRate: Math.ceil(newFee / vsize),\n };\n return finish(ctx, stash, es, account, old, psbt, record, { replaces: old.id }, verify);\n };\n\n const bumpChild = async (\n ctx: RouteContext,\n old: TrackedTransaction,\n targetRate: number,\n verify: SendParams[\"verify\"],\n ): Promise<TrackedTransaction> => {\n const stash = pending.get(old.id);\n const { btc } = old;\n if (stash === undefined || btc === undefined) {\n throw new Error(\"the parent build context is gone — cannot bump after restart\");\n }\n const es = ctx.options.networks.esplora(old.network);\n const { template } = stash;\n const account = { kind: \"hd\" as const, walletId: old.account, groupIndex: 0, template };\n const own = btc.outputs.flatMap((o, vout) => (o.own ? [{ ...o, vout }] : []));\n if (own.length === 0) {\n throw new Error(\"parent has no own outputs to bump\");\n }\n const childInputs = bitcoin.toInputs(\n own.map((o) => ({\n txid: old.hash ?? \"\",\n vout: o.vout,\n value: o.value,\n address: o.address,\n status: \"confirmed\" as const,\n height: 0,\n })),\n stash.fp,\n stash.pathOf,\n stash.pubkeyOf,\n stash.scriptOf,\n stash.template,\n );\n const [changeAddr] = stash.changeAddresses;\n if (changeAddr === undefined) {\n throw new Error(\"no unused change address\");\n }\n const net = bitcoinNetwork(old.network);\n const inTotal = own.reduce((a, o) => a + o.value, 0);\n const probe = bitcoin.buildExactPsbt(\n childInputs,\n [{ address: changeAddr, amount: BigInt(inTotal) }],\n net.params,\n );\n const childFee = Math.max(\n Math.ceil(targetRate * (btc.vsize + probe.vsize)) - btc.fee,\n probe.vsize,\n );\n const { psbt, vsize } = bitcoin.buildExactPsbt(\n childInputs,\n [{ address: changeAddr, amount: BigInt(inTotal - childFee) }],\n net.params,\n );\n const record = {\n inputs: own.map((o, i) => ({\n txid: old.hash ?? \"\",\n vout: i,\n value: o.value,\n address: o.address,\n })),\n outputs: [{ address: changeAddr, value: inTotal - childFee, own: true }],\n vsize,\n fee: childFee,\n feeRate: Math.ceil(childFee / vsize),\n };\n return finish(ctx, stash, es, account, old, psbt, record, { parentId: old.id }, verify);\n };\n\n return { send, poll, replace, bumpChild };\n};\n\nexport type BitcoinRoute = {\n readonly send: (ctx: RouteContext, params: SendParams) => Promise<TrackedTransaction>;\n readonly poll: (ctx: RouteContext, tx: TrackedTransaction) => Promise<TxState | undefined>;\n readonly replace: (\n ctx: RouteContext,\n old: TrackedTransaction,\n mode: \"speed-up\" | \"cancel\",\n verify: SendParams[\"verify\"],\n ) => Promise<TrackedTransaction>;\n readonly bumpChild: (\n ctx: RouteContext,\n old: TrackedTransaction,\n targetRate: number,\n verify: SendParams[\"verify\"],\n ) => Promise<TrackedTransaction>;\n};\n","/** EVM route: native/ERC-20 send build → fee → decode → sign → broadcast, plus status poll. */\nimport { decodeEvm } from \"@qntx/wallet-chains/evm\";\nimport { chains } from \"@qntx/wallet/chains\";\n\nimport { EvmChainAdapter } from \"../chains/evm.ts\";\nimport { errorMessage, newId } from \"./route.ts\";\nimport type { RouteContext, SendParams, TrackedTransaction, TxState } from \"./route.ts\";\n\ntype PendingBuild = {\n readonly unsigned: Awaited<ReturnType<EvmChainAdapter[\"build\"]>>;\n readonly request: Parameters<ReturnType<typeof chains>[\"sign\"]>[0][\"request\"];\n readonly quote: { readonly tier: string };\n readonly chainId: number;\n};\n\nconst bump = (v: bigint): bigint => (v * 11n + 9n) / 10n;\n\nexport type EvmRoute = {\n readonly send: (ctx: RouteContext, params: SendParams) => Promise<TrackedTransaction>;\n readonly poll: (ctx: RouteContext, tx: TrackedTransaction) => Promise<TxState | undefined>;\n readonly replace: (\n ctx: RouteContext,\n old: TrackedTransaction,\n mode: \"speed-up\" | \"cancel\",\n verify: SendParams[\"verify\"],\n ) => Promise<TrackedTransaction>;\n};\n\n/** Per-controller route — the adapter's nonce queue and the replace stash are engine state. */\nexport const createEvmRoute = (): EvmRoute => {\n const evm = new EvmChainAdapter();\n /** In-memory build context keyed by tx id — the inputs a replace rebuilds from. */\n const pending = new Map<string, PendingBuild>();\n\n const send = async (ctx: RouteContext, params: SendParams): Promise<TrackedTransaction> => {\n const { account, network, to, amount, fee, verify } = params;\n const { networks } = ctx.options;\n if (account.kind !== \"hd\") {\n throw new Error(\"imported accounts are not yet supported\");\n }\n const info = networks.info(network);\n const client = networks.client(network);\n const apis = ctx.options.chains ?? chains(ctx.options.wallet);\n const evmAccount = await apis.account({\n walletId: account.walletId,\n groupIndex: account.groupIndex,\n template: \"evm.bip44\",\n network,\n });\n const from = \"address\" in evmAccount ? evmAccount.address : \"\";\n const unsigned = await evm.build(\n client,\n network,\n from,\n params.token === undefined\n ? { kind: \"native\", to, value: amount }\n : { kind: \"erc20\", token: params.token, to, value: amount },\n );\n const quotes = await evm.estimateFee(client);\n const quote = quotes.find((q) => q.tier === fee) ?? quotes[1];\n if (quote === undefined) {\n throw new Error(\"no fee quote\");\n }\n const feed = evm.applyFee(unsigned, quote);\n const request = evm.toSignRequest(feed, account, info.chainId);\n const intent = decodeEvm(request);\n const id = newId(ctx.options.random);\n pending.set(id, { unsigned: feed, request, quote, chainId: info.chainId });\n let tx: TrackedTransaction = {\n id,\n family: \"evm\",\n network,\n account: account.walletId,\n hash: undefined,\n state: \"draft\",\n intent,\n nonce: unsigned.nonce,\n submittedAt: ctx.options.now(),\n error: undefined,\n };\n tx = await ctx.transition(tx, {});\n let signed: Awaited<ReturnType<ReturnType<typeof chains>[\"sign\"]>>;\n try {\n const result = await apis.sign({ request, verify });\n tx = await ctx.transition(tx, { state: \"signed\" });\n signed = result;\n } catch (error) {\n await ctx.transition(tx, { state: \"rejected\", error: errorMessage(error) });\n throw error;\n }\n try {\n const raw = evm.finalize(feed, signed);\n const hash = await evm.broadcast(client, raw);\n tx = await ctx.transition(tx, {\n state: \"submitted\",\n hash,\n submittedAt: ctx.options.now(),\n });\n ctx.track(tx.id, hash);\n return tx;\n } catch (error) {\n await ctx.transition(tx, { state: \"failed\", error: errorMessage(error) });\n throw error;\n }\n };\n\n /**\n * EVM speed-up/cancel — replaces a pending tx at the same nonce with a bumped fee (cancel = a\n * 0-value transfer to self). The new tx carries `replaces` and needs a fresh signature; a\n * rejected one never reaches the network and leaves the original.\n */\n const replace = async (\n ctx: RouteContext,\n old: TrackedTransaction,\n mode: \"speed-up\" | \"cancel\",\n verify: SendParams[\"verify\"],\n ): Promise<TrackedTransaction> => {\n const stash = pending.get(old.id);\n if (stash === undefined) {\n throw new Error(\"the original build context is gone — cannot replace after restart\");\n }\n const { networks } = ctx.options;\n const client = networks.client(old.network);\n const apis = ctx.options.chains ?? chains(ctx.options.wallet);\n const { tier } = stash.quote;\n const estimates = await evm.estimateFee(client);\n const estimate = estimates.find((q) => q.tier === tier) ?? estimates[1];\n if (estimate === undefined) {\n throw new Error(\"no fee quote\");\n }\n const oldFee = stash.unsigned;\n const bumpedFee = bump(oldFee.maxFeePerGas ?? oldFee.gasPrice ?? 0n);\n const maxFeePerGas = bumpedFee > estimate.maxFeePerGas ? bumpedFee : estimate.maxFeePerGas;\n const priorityBump =\n oldFee.maxPriorityFeePerGas === undefined && estimate.maxPriorityFeePerGas === undefined\n ? undefined\n : bump(oldFee.maxPriorityFeePerGas ?? 0n) > (estimate.maxPriorityFeePerGas ?? 0n)\n ? bump(oldFee.maxPriorityFeePerGas ?? 0n)\n : (estimate.maxPriorityFeePerGas ?? 0n);\n const feeFields =\n priorityBump === undefined\n ? { maxFeePerGas }\n : { maxFeePerGas, maxPriorityFeePerGas: priorityBump };\n const unsigned =\n mode === \"cancel\"\n ? {\n ...stash.unsigned,\n to: stash.unsigned.from,\n value: 0n,\n data: \"0x\" as const,\n gas: 21000n,\n ...feeFields,\n }\n : { ...stash.unsigned, ...feeFields };\n const request = evm.toSignRequest(unsigned, stash.request.account, stash.chainId);\n const intent = decodeEvm(request);\n const id = newId(ctx.options.random);\n pending.set(id, { unsigned, request, quote: stash.quote, chainId: stash.chainId });\n let tx: TrackedTransaction = {\n id,\n family: \"evm\",\n network: old.network,\n account: old.account,\n hash: undefined,\n state: \"draft\",\n intent,\n nonce: old.nonce,\n replaces: old.id,\n submittedAt: ctx.options.now(),\n error: undefined,\n };\n tx = await ctx.transition(tx, {});\n let signed: Awaited<ReturnType<ReturnType<typeof chains>[\"sign\"]>>;\n try {\n const result = await apis.sign({ request, verify });\n tx = await ctx.transition(tx, { state: \"signed\" });\n signed = result;\n } catch (error) {\n await ctx.transition(tx, { state: \"rejected\", error: errorMessage(error) });\n throw error;\n }\n try {\n const raw = evm.finalize(unsigned, signed);\n const hash = await evm.broadcast(client, raw);\n tx = await ctx.transition(tx, {\n state: \"submitted\",\n hash,\n submittedAt: ctx.options.now(),\n });\n ctx.track(tx.id, hash);\n return tx;\n } catch (error) {\n await ctx.transition(tx, { state: \"failed\", error: errorMessage(error) });\n throw error;\n }\n };\n\n /** Returns the terminal state once the receipt lands, or `undefined` to keep polling. */\n const poll = async (ctx: RouteContext, tx: TrackedTransaction): Promise<TxState | undefined> => {\n if (tx.hash === undefined) {\n return \"failed\";\n }\n const state = await evm.status(ctx.options.networks.client(tx.network), tx.hash);\n if (state === \"pending\") {\n return undefined;\n }\n pending.delete(tx.id);\n return state === \"finalized\" ? \"confirmed\" : state;\n };\n\n return { send, poll, replace };\n};\n","import { base64 } from \"@scure/base\";\nimport {\n getSetComputeUnitLimitInstruction,\n getSetComputeUnitPriceInstruction,\n} from \"@solana-program/compute-budget\";\nimport { getTransferSolInstruction } from \"@solana-program/system\";\nimport {\n findAssociatedTokenPda,\n getCreateAssociatedTokenIdempotentInstruction,\n getTransferCheckedInstruction,\n TOKEN_PROGRAM_ADDRESS,\n} from \"@solana-program/token\";\n/**\n * Solana chain adapter — native SOL and SPL-token transfers as v0 messages without lookup tables.\n * Compute-unit headroom is simulated-units x 1.1; the priority fee comes from\n * getRecentPrioritizationFees percentiles (p50/p75/p90) over the writable accounts. Broadcast is\n * sendTransaction(skipPreflight:false, maxRetries:0) re-sent every 2 s while the blockhash is live;\n * an expired lastValidBlockHeight without confirmation is `dropped`. A 1232-byte compiled message\n * is rejected before signing.\n */\nimport {\n address,\n appendTransactionMessageInstructions,\n blockhash,\n compileTransactionMessage,\n createNoopSigner,\n createTransactionMessage,\n getCompiledTransactionMessageEncoder,\n setTransactionMessageFeePayer,\n setTransactionMessageLifetimeUsingBlockhash,\n} from \"@solana/kit\";\nimport type { Instruction } from \"@solana/kit\";\n\nimport { PROGRAM_IDS } from \"@qntx/wallet-chains/solana\";\n\nimport type { SolanaRpc } from \"../networks/controller.ts\";\n\n/** Token-2022 program id — the mint's owner for extension mints. */\nexport const TOKEN_2022_PROGRAM: string = PROGRAM_IDS.token2022;\n\nconst MAX_MESSAGE_BYTES = 1232;\nconst CU_SIMULATE_LIMIT = 1_400_000;\n\nexport type SolanaIntent =\n | { readonly kind: \"sol\"; readonly to: string; readonly lamports: bigint }\n | {\n readonly kind: \"spl\";\n readonly mint: string;\n readonly to: string;\n readonly amount: bigint;\n readonly decimals: number;\n /** Token-2022 mints carry the TokenzQd owner — defaults to the classic SPL program. */\n readonly tokenProgram?: string;\n };\n\nexport type SolanaFeeTier = \"slow\" | \"normal\" | \"fast\";\n\nexport type SolanaFeeQuote = {\n readonly tier: SolanaFeeTier;\n /** Micro-lamports per compute unit. */\n readonly microLamportsPerCu: bigint;\n};\n\nexport type SolanaUnsignedTransaction = {\n readonly family: \"solana\";\n readonly network: string;\n readonly from: string;\n readonly instructions: ReadonlyArray<Instruction>;\n readonly writable: ReadonlyArray<string>;\n readonly unitsConsumed: number;\n readonly blockhash: string;\n readonly lastValidBlockHeight: bigint;\n};\n\ntype Compiled = {\n readonly messageBytes: Uint8Array;\n readonly instructions: ReadonlyArray<Instruction>;\n};\n\nconst b64 = (bytes: Uint8Array): string => base64.encode(bytes);\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null;\n\nconst obj = (v: unknown): Record<string, unknown> | undefined => (isObject(v) ? v : undefined);\n\nconst str = (v: unknown, fallback = \"0\"): string => {\n if (typeof v === \"string\") {\n return v;\n }\n return typeof v === \"number\" || typeof v === \"bigint\" ? String(v) : fallback;\n};\n\nexport class SolanaChainAdapter {\n private async rpc(rpc: SolanaRpc, method: string, params: unknown[]): Promise<unknown> {\n return rpc.call(method, params);\n }\n\n private async instructions(\n rpc: SolanaRpc,\n from: string,\n intent: SolanaIntent,\n ): Promise<ReadonlyArray<Instruction>> {\n if (intent.kind === \"sol\") {\n return [\n getTransferSolInstruction({\n source: createNoopSigner(address(from)),\n destination: address(intent.to),\n amount: intent.lamports,\n }),\n ];\n }\n const tokenProgram =\n intent.tokenProgram === undefined ? TOKEN_PROGRAM_ADDRESS : address(intent.tokenProgram);\n const [sourceAta] = await findAssociatedTokenPda({\n mint: address(intent.mint),\n owner: address(from),\n tokenProgram,\n });\n const [destAta] = await findAssociatedTokenPda({\n mint: address(intent.mint),\n owner: address(intent.to),\n tokenProgram,\n });\n const ixs: Instruction[] = [];\n const destInfo = await this.rpc(rpc, \"getAccountInfo\", [\n destAta,\n { encoding: \"base64\", commitment: \"confirmed\" },\n ]);\n if (obj(obj(destInfo)?.[\"value\"]) === undefined) {\n ixs.push(\n getCreateAssociatedTokenIdempotentInstruction({\n ata: destAta,\n mint: address(intent.mint),\n owner: address(intent.to),\n payer: createNoopSigner(address(from)),\n tokenProgram,\n }),\n );\n }\n ixs.push(\n getTransferCheckedInstruction(\n {\n source: sourceAta,\n mint: address(intent.mint),\n destination: destAta,\n authority: address(from),\n amount: intent.amount,\n decimals: intent.decimals,\n },\n { programAddress: tokenProgram },\n ),\n );\n return ixs;\n }\n\n /** Instruction set, simulated compute units, and a fresh blockhash — fee fields come later. */\n async build(\n rpc: SolanaRpc,\n network: string,\n from: string,\n intent: SolanaIntent,\n ): Promise<SolanaUnsignedTransaction> {\n const instructions = await this.instructions(rpc, from, intent);\n const hashResult = obj(\n await this.rpc(rpc, \"getLatestBlockhash\", [{ commitment: \"confirmed\" }]),\n );\n const value = obj(hashResult?.[\"value\"]);\n const blockhashValue = typeof value?.[\"blockhash\"] === \"string\" ? value[\"blockhash\"] : \"\";\n const lastValidBlockHeight = BigInt(str(value?.[\"lastValidBlockHeight\"], \"0\"));\n const compiled = this.compile(from, instructions, blockhashValue, lastValidBlockHeight);\n const units = await this.simulate(rpc, compiled.messageBytes);\n return {\n family: \"solana\",\n network,\n from,\n instructions,\n writable: this.writableAccounts(instructions),\n unitsConsumed: units,\n blockhash: blockhashValue,\n lastValidBlockHeight,\n };\n }\n\n private writableAccounts(instructions: ReadonlyArray<Instruction>): ReadonlyArray<string> {\n const out = new Set<string>();\n for (const ix of instructions) {\n const accounts = obj(ix)?.[\"accounts\"];\n if (!Array.isArray(accounts)) {\n continue;\n }\n for (const a of accounts) {\n const record = obj(a);\n const role = Number(record?.[\"role\"] ?? 0);\n if (typeof record?.[\"address\"] === \"string\" && role >= 2) {\n out.add(record[\"address\"]);\n }\n }\n }\n return [...out];\n }\n\n /** Unsigned wire bytes: shortvec(1) sig count + 64-byte zero sig + message (for simulate). */\n private wireBytes(messageBytes: Uint8Array): Uint8Array {\n const out = new Uint8Array(1 + 64 + messageBytes.length);\n out[0] = 1;\n out.set(messageBytes, 65);\n return out;\n }\n\n private async simulate(rpc: SolanaRpc, messageBytes: Uint8Array): Promise<number> {\n const result = obj(\n await this.rpc(rpc, \"simulateTransaction\", [\n b64(this.wireBytes(messageBytes)),\n { encoding: \"base64\", sigVerify: false, replaceRecentBlockhash: false },\n ]),\n );\n const value = obj(result?.[\"value\"]);\n const units = Number(value?.[\"unitsConsumed\"] ?? 0);\n return units > 0 ? units : CU_SIMULATE_LIMIT;\n }\n\n private compile(\n from: string,\n instructions: ReadonlyArray<Instruction>,\n blockhashValue: string,\n lastValidBlockHeight: bigint,\n ): Compiled {\n const message = createTransactionMessage({ version: 0 });\n const withPayer = setTransactionMessageFeePayer(address(from), message);\n const withLifetime = setTransactionMessageLifetimeUsingBlockhash(\n { blockhash: blockhash(blockhashValue), lastValidBlockHeight },\n withPayer,\n );\n const withIxs = appendTransactionMessageInstructions([...instructions], withLifetime);\n const compiled = compileTransactionMessage(withIxs);\n const messageBytes = new Uint8Array(getCompiledTransactionMessageEncoder().encode(compiled));\n if (messageBytes.length > MAX_MESSAGE_BYTES) {\n throw new Error(\n `compiled message is ${messageBytes.length} bytes (max ${MAX_MESSAGE_BYTES})`,\n );\n }\n return { messageBytes, instructions };\n }\n\n /** Percentile-tiered prioritization fees over the writable accounts of this transaction. */\n async estimateFee(\n rpc: SolanaRpc,\n writable: ReadonlyArray<string>,\n ): Promise<ReadonlyArray<SolanaFeeQuote>> {\n const result = await this.rpc(rpc, \"getRecentPrioritizationFees\", [[...writable]]);\n const fees = (Array.isArray(result) ? result : [])\n .flatMap((r: unknown) => {\n const fee = obj(r)?.[\"prioritizationFee\"];\n return fee === undefined ? [] : [Number(fee)];\n })\n .sort((a, b) => a - b);\n const pick = (p: number): bigint =>\n BigInt(fees[Math.min(fees.length - 1, Math.floor((fees.length * p) / 100))] ?? 0);\n return [\n { tier: \"slow\", microLamportsPerCu: pick(50) },\n { tier: \"normal\", microLamportsPerCu: pick(75) },\n { tier: \"fast\", microLamportsPerCu: pick(90) },\n ];\n }\n\n /** Prepend CU-limit + CU-price budget instructions; returns message bytes for the sign request. */\n applyFee(tx: SolanaUnsignedTransaction, fee: SolanaFeeQuote): Uint8Array {\n const units = Math.ceil((tx.unitsConsumed === 0 ? CU_SIMULATE_LIMIT : tx.unitsConsumed) * 1.1);\n const compiled = this.compile(\n tx.from,\n [\n getSetComputeUnitLimitInstruction({ units }),\n getSetComputeUnitPriceInstruction({ microLamports: fee.microLamportsPerCu }),\n ...tx.instructions,\n ],\n tx.blockhash,\n tx.lastValidBlockHeight,\n );\n return compiled.messageBytes;\n }\n\n /** Wire transaction bytes — sigCount shortvec + each 64-byte sig + message. */\n finalize(messageBytes: Uint8Array, signatures: ReadonlyArray<Uint8Array>): Uint8Array {\n for (const sig of signatures) {\n if (sig.length !== 64) {\n throw new Error(`solana signature must be 64 bytes, got ${sig.length}`);\n }\n }\n const out = new Uint8Array(1 + 64 * signatures.length + messageBytes.length);\n out[0] = signatures.length;\n for (const [i, sig] of signatures.entries()) {\n out.set(sig, 1 + 64 * i);\n }\n out.set(messageBytes, 1 + 64 * signatures.length);\n return out;\n }\n\n async broadcast(rpc: SolanaRpc, wireBytes: Uint8Array): Promise<string> {\n const result = await this.rpc(rpc, \"sendTransaction\", [\n b64(wireBytes),\n { encoding: \"base64\", skipPreflight: false, maxRetries: 0, preflightCommitment: \"confirmed\" },\n ]);\n if (typeof result !== \"string\") {\n throw new TypeError(\"sendTransaction returned a malformed signature\");\n }\n return result;\n }\n\n /** Processed → confirmed → finalized; an error on the status means the tx failed on-chain. */\n async status(\n rpc: SolanaRpc,\n signature: string,\n ): Promise<\"pending\" | \"confirmed\" | \"finalized\" | \"failed\"> {\n const result = obj(\n await this.rpc(rpc, \"getSignatureStatuses\", [\n [signature],\n { searchTransactionHistory: true },\n ]),\n );\n const entry = Array.isArray(result?.[\"value\"]) ? obj(result[\"value\"][0]) : undefined;\n if (entry === undefined) {\n return \"pending\";\n }\n if (entry[\"err\"] !== null && entry[\"err\"] !== undefined) {\n return \"failed\";\n }\n const c = entry[\"confirmationStatus\"];\n return c === \"finalized\" ? \"finalized\" : c === \"confirmed\" ? \"confirmed\" : \"pending\";\n }\n\n async blockHeight(rpc: SolanaRpc): Promise<bigint> {\n const result = await this.rpc(rpc, \"getBlockHeight\", [{ commitment: \"confirmed\" }]);\n return BigInt(str(result, \"0\"));\n }\n}\n","import { base64 } from \"@scure/base\";\n\nimport {\n decodeSolana,\n netAfterTransferFee,\n parseMintExtensions,\n PROGRAM_IDS,\n} from \"@qntx/wallet-chains/solana\";\nimport type { MintExtensionSummary } from \"@qntx/wallet-chains/solana\";\n/** Solana route: SOL/SPL send → sign → broadcast, plus status poll with rebroadcast/drop. */\nimport { chains } from \"@qntx/wallet/chains\";\n\nimport { SolanaChainAdapter } from \"../chains/solana.ts\";\nimport type {\n DisplayIntent,\n RouteContext,\n SendParams,\n TrackedTransaction,\n TxState,\n} from \"./route.ts\";\nimport { errorMessage, newId } from \"./route.ts\";\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null;\nconst obj = (v: unknown): Record<string, unknown> | undefined => (isObject(v) ? v : undefined);\nconst arr = (v: unknown): unknown[] | undefined => (Array.isArray(v) ? v : undefined);\n\nconst solana = new SolanaChainAdapter();\n\n/** Signed wire transactions kept for re-broadcast until the tx confirms or drops. */\nconst wires = new Map<string, Uint8Array>();\n\nexport const sendSolana = async (\n ctx: RouteContext,\n params: SendParams,\n): Promise<TrackedTransaction> => {\n const { account, network, to, amount, fee, verify } = params;\n if (account.kind !== \"hd\") {\n throw new Error(\"imported accounts are not yet supported\");\n }\n const rpc = ctx.options.networks.solanaRpc(network);\n const apis = ctx.options.chains ?? chains(ctx.options.wallet);\n const solAccount = await apis.account({\n walletId: account.walletId,\n groupIndex: account.groupIndex,\n template: \"solana.bip44-change\",\n network,\n });\n const from = \"address\" in solAccount ? solAccount.address : \"\";\n // For an SPL transfer, resolve the mint's owner (Token vs Token-2022) and reject the\n // extension combinations the wallet cannot carry before any signing or broadcast.\n let tokenProgram: string | undefined;\n let ext: MintExtensionSummary | undefined;\n if (params.token !== undefined) {\n const mintInfo = await rpc.call(\"getAccountInfo\", [\n params.token,\n { encoding: \"base64\", commitment: \"confirmed\" },\n ]);\n const owner = obj(mintInfo)?.[\"value\"];\n if (obj(owner)?.[\"owner\"] === PROGRAM_IDS.token2022) {\n tokenProgram = PROGRAM_IDS.token2022;\n const mintBytes = arr(obj(owner)?.[\"data\"])?.[0];\n const raw = typeof mintBytes === \"string\" ? base64.decode(mintBytes) : undefined;\n if (raw !== undefined && raw.length > 166) {\n const epoch = obj(await rpc.call(\"getEpochInfo\", []))?.[\"epoch\"];\n ext = parseMintExtensions(raw, BigInt(typeof epoch === \"number\" ? epoch : 0));\n if (ext.nonTransferable === true) {\n throw new Error(\"token is non-transferable\");\n }\n if (ext.confidential === true) {\n throw new Error(\"confidential transfer extensions are not supported\");\n }\n }\n }\n }\n const unsigned = await solana.build(\n rpc,\n network,\n from,\n params.token === undefined\n ? { kind: \"sol\", to, lamports: amount }\n : {\n kind: \"spl\",\n mint: params.token,\n to,\n amount,\n decimals: params.decimals ?? 0,\n ...(tokenProgram === undefined ? {} : { tokenProgram }),\n },\n );\n const quotes = await solana.estimateFee(rpc, unsigned.writable);\n const quote = quotes.find((q) => q.tier === fee) ?? quotes[1];\n if (quote === undefined) {\n throw new Error(\"no fee quote\");\n }\n const messageBytes = solana.applyFee(unsigned, quote);\n const request = {\n kind: \"solana.transaction\" as const,\n network,\n account,\n message: messageBytes,\n };\n const intent =\n ext === undefined || params.token === undefined\n ? decodeSolana(request, from)\n : token2022Intent(decodeSolana(request, from), ext, params.token, amount);\n const id = newId(ctx.options.random);\n let tx: TrackedTransaction = {\n id,\n family: \"solana\",\n network,\n account: account.walletId,\n hash: undefined,\n state: \"draft\",\n intent,\n nonce: 0,\n lastValidBlockHeight: Number(unsigned.lastValidBlockHeight),\n submittedAt: ctx.options.now(),\n error: undefined,\n };\n tx = await ctx.transition(tx, {});\n try {\n const result = await apis.sign({ request, verify });\n tx = await ctx.transition(tx, { state: \"signed\" });\n if (result.kind !== \"solana.transaction\" || !(result.signature instanceof Uint8Array)) {\n throw new Error(\"unexpected solana sign result\");\n }\n const wire = solana.finalize(messageBytes, [result.signature]);\n const hash = await solana.broadcast(rpc, wire);\n wires.set(id, wire);\n tx = await ctx.transition(tx, {\n state: \"submitted\",\n hash,\n submittedAt: ctx.options.now(),\n });\n ctx.track(tx.id, hash);\n return tx;\n } catch (error) {\n const failed = tx.state === \"signed\" ? \"failed\" : \"rejected\";\n await ctx.transition(tx, { state: failed, error: errorMessage(error) });\n throw error;\n }\n};\n\n/** Returns the terminal state, `dropped` on blockhash expiry, or `undefined` to keep polling. */\nexport const pollSolana = async (\n ctx: RouteContext,\n tx: TrackedTransaction,\n): Promise<TxState | undefined> => {\n if (tx.hash === undefined) {\n return \"failed\";\n }\n const rpc = ctx.options.networks.solanaRpc(tx.network);\n const state = await solana.status(rpc, tx.hash);\n if (state !== \"pending\") {\n wires.delete(tx.id);\n return state === \"finalized\" ? \"confirmed\" : state;\n }\n if (\n tx.lastValidBlockHeight !== undefined &&\n (await solana.blockHeight(rpc)) > BigInt(tx.lastValidBlockHeight)\n ) {\n wires.delete(tx.id);\n return \"dropped\";\n }\n const wire = wires.get(tx.id);\n if (wire !== undefined) {\n await solana.broadcast(rpc, wire).catch(() => \"\");\n }\n return undefined;\n};\n\n/**\n * Folds Token-2022 mint extensions into the decoded intent: a TransferFee mint shows the\n * recipient's net amount (amount − min(amount×bps/10000, maximum)); a TransferHook or\n * PermanentDelegate marks the intent `partial` with a warning. The mint's extension data is not\n * part of the message, so the route attaches what it fetched — decode alone cannot see it.\n */\nexport const token2022Intent = (\n intent: DisplayIntent,\n ext: MintExtensionSummary,\n mint: string,\n amount: bigint,\n): DisplayIntent => {\n const warnings = [...intent.warnings];\n let { outflows } = intent;\n if (ext.transferFee !== undefined) {\n const net = netAfterTransferFee(\n amount,\n ext.transferFee.basisPoints,\n ext.transferFee.maximumFee,\n );\n const withheld = amount - net;\n warnings.push({\n kind: \"token-2022-transfer-fee\",\n message: `transfer fee withheld ${withheld.toString(10)} base units`,\n });\n outflows = outflows.map((o) =>\n o.amount.asset === mint ? { ...o, amount: { ...o.amount, amount: net.toString(10) } } : o,\n );\n }\n if (ext.transferHook !== undefined || ext.permanentDelegate !== undefined) {\n warnings.push({\n kind: \"token-2022-extension\",\n message: \"mint carries a transfer-hook or permanent-delegate extension\",\n });\n return { ...intent, outflows, warnings, verifiability: \"partial\" };\n }\n return { ...intent, outflows, warnings };\n};\n","/**\n * Transaction controller: orchestrates lifecycle, persistence and polling; each chain family routes\n * through its own module (`evm.ts`, `solana.ts`, `bitcoin.ts`). A rejected signature (wrong\n * password, cancelled presence) never broadcasts.\n */\nimport { Controller } from \"../controller.ts\";\nimport type { EngineStore } from \"../store/port.ts\";\nimport { createBitcoinRoute } from \"./bitcoin.ts\";\nimport { createEvmRoute } from \"./evm.ts\";\nimport type {\n DisplayIntent,\n Options,\n RouteContext,\n SendParams,\n TrackedTransaction,\n TxState,\n} from \"./route.ts\";\nimport { newId } from \"./route.ts\";\nimport { pollSolana, sendSolana } from \"./solana.ts\";\n\nexport type { SendParams, TrackedTransaction, TxState } from \"./route.ts\";\nexport type { Options } from \"./route.ts\";\n\nexport type TransactionControllerState = {\n readonly txs: Record<string, TrackedTransaction>;\n};\n\nconst encode = (tx: TrackedTransaction): Uint8Array => new TextEncoder().encode(JSON.stringify(tx));\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null;\n\nconst TX_STATES: ReadonlySet<string> = new Set([\n \"draft\",\n \"signed\",\n \"submitted\",\n \"pending\",\n \"confirmed\",\n \"failed\",\n \"rejected\",\n \"dropped\",\n \"replaced\",\n]);\n\nconst isTxState = (v: unknown): v is TxState => typeof v === \"string\" && TX_STATES.has(v);\n\ntype BtcRecord = NonNullable<TrackedTransaction[\"btc\"]>;\nconst isBtcRecord = (v: unknown): v is BtcRecord => {\n if (!isObject(v)) {\n return false;\n }\n const { inputs, outputs, vsize, fee, feeRate } = v;\n return (\n Array.isArray(inputs) &&\n Array.isArray(outputs) &&\n typeof vsize === \"number\" &&\n typeof fee === \"number\" &&\n typeof feeRate === \"number\" &&\n inputs.every(\n (i) =>\n isObject(i) &&\n typeof i[\"txid\"] === \"string\" &&\n typeof i[\"vout\"] === \"number\" &&\n typeof i[\"value\"] === \"number\" &&\n typeof i[\"address\"] === \"string\",\n ) &&\n outputs.every(\n (o) =>\n isObject(o) &&\n typeof o[\"address\"] === \"string\" &&\n typeof o[\"value\"] === \"number\" &&\n typeof o[\"own\"] === \"boolean\",\n )\n );\n};\n\nconst isIntent = (v: unknown): v is DisplayIntent =>\n isObject(v) &&\n typeof v[\"summary\"] === \"string\" &&\n Array.isArray(v[\"outflows\"]) &&\n typeof v[\"verifiability\"] === \"string\";\n\nconst decode = (raw: Uint8Array): TrackedTransaction | undefined => {\n const parsed: unknown = JSON.parse(new TextDecoder().decode(raw));\n if (!isObject(parsed)) {\n return undefined;\n }\n const {\n id,\n family,\n network,\n account,\n hash,\n state,\n intent,\n nonce,\n replaces,\n parentId,\n btc,\n submittedAt,\n error,\n } = parsed;\n if (\n typeof id !== \"string\" ||\n (family !== \"evm\" && family !== \"solana\" && family !== \"bitcoin\") ||\n typeof network !== \"string\" ||\n typeof account !== \"string\" ||\n !isTxState(state) ||\n typeof nonce !== \"number\" ||\n typeof submittedAt !== \"number\"\n ) {\n return undefined;\n }\n return {\n id,\n family,\n network,\n account,\n hash: typeof hash === \"string\" ? hash : undefined,\n state,\n intent: isIntent(intent) ? intent : undefined,\n nonce,\n ...(typeof replaces === \"string\" ? { replaces } : {}),\n ...(typeof parentId === \"string\" ? { parentId } : {}),\n ...(isBtcRecord(btc) ? { btc } : {}),\n submittedAt,\n error: typeof error === \"string\" ? error : undefined,\n };\n};\n\nexport class TransactionController extends Controller<TransactionControllerState> {\n private readonly options: Options;\n private engineStore?: EngineStore | undefined;\n private readonly timers = new Map<string, () => void>();\n private evmRoute = createEvmRoute();\n private readonly bitcoinRoute = createBitcoinRoute();\n private locked = true;\n\n constructor(options: Options) {\n super({ name: \"transactions\", defaultState: () => ({ txs: {} }) });\n this.options = options;\n }\n\n async init(): Promise<void> {\n this.locked = false;\n this.engineStore = await this.options.openStore();\n const collection = this.engineStore.collection(\"transactions\");\n const keys = await collection.list();\n const rows = await Promise.all(keys.map(async (key) => collection.get(key)));\n for (const raw of rows) {\n const tx = raw === undefined ? undefined : decode(raw);\n if (tx === undefined) {\n continue;\n }\n this.update((s) => ({ ...s, txs: { ...s.txs, [tx.id]: tx } }));\n if ((tx.state === \"submitted\" || tx.state === \"pending\") && tx.hash !== undefined) {\n this.track(tx.id, tx.hash);\n }\n }\n }\n\n async destroy(): Promise<void> {\n this.lock();\n await Promise.resolve();\n }\n\n lock(): void {\n this.locked = true;\n for (const stop of this.timers.values()) {\n stop();\n }\n this.timers.clear();\n this.engineStore = undefined;\n this.evmRoute = createEvmRoute();\n }\n\n private async persist(tx: TrackedTransaction): Promise<void> {\n const store = this.engineStore;\n if (store !== undefined) {\n await store.collection(\"transactions\").put(tx.id, encode(tx));\n }\n }\n\n private async transition(\n tx: TrackedTransaction,\n next: Partial<TrackedTransaction>,\n ): Promise<TrackedTransaction> {\n const updated: TrackedTransaction = { ...tx, ...next };\n this.update((s) => ({ ...s, txs: { ...s.txs, [tx.id]: updated } }));\n await this.persist(updated);\n return updated;\n }\n\n private routeCtx(): RouteContext {\n return {\n options: this.options,\n transition: async (tx, next) => this.transition(tx, next),\n track: (id, hash) => this.track(id, hash),\n newId: () => newId(this.options.random),\n };\n }\n\n async send(params: SendParams): Promise<TrackedTransaction> {\n if (this.locked) {\n throw new Error(\"transactions require an unlocked vault\");\n }\n const { account, network } = params;\n const info = this.options.networks.info(network);\n if (account.kind !== \"hd\") {\n throw new Error(\"imported accounts are not yet supported\");\n }\n const ctx = this.routeCtx();\n if (info.family === \"solana\") {\n return sendSolana(ctx, params);\n }\n if (info.family === \"bitcoin\") {\n return this.bitcoinRoute.send(ctx, params);\n }\n return this.evmRoute.send(ctx, params);\n }\n\n /**\n * Speed up or cancel a pending/submitted EVM transaction at the same nonce — a fresh signature is\n * required and a rejection leaves the original untouched.\n */\n async replace(\n id: string,\n mode: \"speed-up\" | \"cancel\",\n verify: SendParams[\"verify\"],\n ): Promise<TrackedTransaction> {\n if (this.locked) {\n throw new Error(\"transactions require an unlocked vault\");\n }\n const old = this.getState().txs[id];\n if (old === undefined) {\n throw new Error(`unknown transaction ${id}`);\n }\n if (old.family === \"bitcoin\") {\n return this.bitcoinRoute.replace(this.routeCtx(), old, mode, verify);\n }\n if (old.family !== \"evm\") {\n throw new Error(\"replace is EVM-only in this layer\");\n }\n if (old.state !== \"pending\" && old.state !== \"submitted\") {\n throw new Error(`cannot replace a ${old.state} transaction`);\n }\n return this.evmRoute.replace(this.routeCtx(), old, mode, verify);\n }\n\n /**\n * CPFP — spend an unconfirmed tx's own outputs into a higher-fee child so the package mines.\n * Bitcoin only; the child is linked via `parentId`.\n */\n async bumpChild(\n id: string,\n targetRate: number,\n verify: SendParams[\"verify\"],\n ): Promise<TrackedTransaction> {\n if (this.locked) {\n throw new Error(\"transactions require an unlocked vault\");\n }\n const old = this.getState().txs[id];\n if (old === undefined) {\n throw new Error(`unknown transaction ${id}`);\n }\n if (old.family !== \"bitcoin\") {\n throw new Error(\"bumpChild is Bitcoin-only in this layer\");\n }\n if (old.state !== \"pending\" && old.state !== \"submitted\") {\n throw new Error(`cannot bump a ${old.state} transaction`);\n }\n return this.bitcoinRoute.bumpChild(this.routeCtx(), old, targetRate, verify);\n }\n\n private track(id: string, hash: string): void {\n if (this.timers.has(id) || hash === \"\") {\n return;\n }\n const poll = this.options.pollMs ?? 4000;\n const stop = this.options.setTimer(poll, async () => {\n if (this.locked) {\n return;\n }\n try {\n const tx = this.getState().txs[id];\n if (tx === undefined) {\n return;\n }\n const ctx = this.routeCtx();\n const next =\n tx.family === \"solana\"\n ? await pollSolana(ctx, tx)\n : tx.family === \"bitcoin\"\n ? await this.bitcoinRoute.poll(ctx, tx)\n : await this.evmRoute.poll(ctx, tx);\n if (next === undefined) {\n return;\n }\n const updated = await this.transition(tx, { state: next });\n this.timers.delete(id);\n stop();\n // When one of a replace pair confirms, the sibling is `replaced`.\n const siblings = Object.values(this.getState().txs).filter(\n (t) =>\n t.id !== updated.id &&\n t.hash !== undefined &&\n t.state !== \"replaced\" &&\n ((updated.replaces !== undefined && t.id === updated.replaces) ||\n (t.replaces !== undefined && t.replaces === updated.id)) &&\n (t.state === \"submitted\" || t.state === \"pending\"),\n );\n await Promise.all(\n siblings.map(async (sibling) => {\n await this.transition(sibling, { state: \"replaced\" });\n const siblingStop = this.timers.get(sibling.id);\n this.timers.delete(sibling.id);\n siblingStop?.();\n }),\n );\n } catch (error) {\n this.options.logger.warn(\"tx status poll failed\", error);\n }\n });\n this.timers.set(id, stop);\n }\n}\n","/**\n * Composition root: wires the Wallet's lock state to the SparkController's lifecycle. Unlocked →\n * open the EngineStore and start every declared account; locked → abort event loops, close every\n * client, close the store and reset account state. Transitions are serialized on one promise chain,\n * so an unlock→lock flip can never overlap a still-opening store.\n */\nimport { createSparkClient } from \"@qntx/spark\";\nimport type { LightningPayment, SparkNetwork } from \"@qntx/spark\";\nimport type { Wallet } from \"@qntx/wallet\";\nimport { nostr } from \"@qntx/wallet/nostr\";\nimport type { SparkAccountRef } from \"@qntx/wallet/protocol\";\nimport { spark } from \"@qntx/wallet/spark\";\n\nimport { AccountTreeController } from \"./accounts/controller.ts\";\nimport { AssetsController } from \"./assets/controller.ts\";\nimport { BackupController } from \"./backup/controller.ts\";\nimport type { CloudStore } from \"./backup/port.ts\";\nimport type { EngineLogger } from \"./events.ts\";\nimport { MetaSyncController } from \"./meta/controller.ts\";\nimport type { MetaSyncConfig } from \"./meta/controller.ts\";\nimport { NetworkController } from \"./networks/controller.ts\";\nimport { parsePayment } from \"./payments/parse.ts\";\nimport type { PaymentParse } from \"./payments/parse.ts\";\nimport { pay as runPay } from \"./payments/pay.ts\";\nimport type { PayParams, PayResult } from \"./payments/pay.ts\";\nimport { resolvePayment } from \"./payments/resolve.ts\";\nimport { payZap, prepareZap } from \"./payments/zap.ts\";\nimport type { PrepareZapParams, PreparedZap, PayZapOptions } from \"./payments/zap.ts\";\nimport { SparkController } from \"./spark/controller.ts\";\nimport type { SparkControllerOptions } from \"./spark/controller.ts\";\nimport type { EngineStore } from \"./store/port.ts\";\nimport { TransactionController } from \"./transactions/controller.ts\";\n\nexport type EngineOptions = {\n readonly wallet: Wallet;\n /** Every Spark account the engine touches lives on this network. */\n readonly sparkNetwork: SparkNetwork;\n readonly fetch: typeof globalThis.fetch;\n readonly random: (length: number) => Uint8Array;\n readonly now: () => number;\n readonly logger: EngineLogger;\n readonly openStore: () => Promise<EngineStore>;\n /** Cloud file transport for the backup controller; absent → `unavailable`. */\n readonly cloud?: CloudStore;\n /** RPC endpoints per network (CAIP-2), ordered by preference for the viem fallback transport. */\n readonly rpc?: Readonly<Record<string, ReadonlyArray<string>>>;\n /** Injected timer for transaction polling; defaults to setTimeout. */\n readonly setTimer?: (ms: number, fn: () => void) => () => void;\n /** Kind-30078 wallet-metadata sync; absent → every wallet reports `unavailable`. */\n readonly metaSync?: MetaSyncConfig;\n /** Test seam — defaults to the wallet's real spark proxy. */\n readonly sparkApis?: SparkControllerOptions[\"spark\"];\n};\n\nexport type WalletEngine = {\n readonly networks: NetworkController;\n readonly assets: AssetsController;\n readonly transactions: TransactionController;\n readonly spark: SparkController;\n readonly accounts: AccountTreeController;\n readonly metaSync: MetaSyncController;\n readonly backup: BackupController;\n readonly zaps: {\n readonly prepare: (params: PrepareZapParams) => Promise<PreparedZap>;\n readonly pay: (\n account: SparkAccountRef,\n prepared: PreparedZap,\n options: Omit<PayZapOptions, \"now\">,\n ) => Promise<LightningPayment>;\n };\n readonly payments: {\n readonly parse: (input: string, network: SparkNetwork) => PaymentParse;\n readonly resolve: (input: string, network: SparkNetwork) => Promise<PaymentParse>;\n readonly pay: (params: PayParams) => Promise<PayResult>;\n };\n readonly unsubscribe: () => void;\n};\n\nexport function createWalletEngine(options: EngineOptions): WalletEngine {\n const backup = new BackupController({\n wallet: options.wallet,\n cloud: options.cloud,\n now: options.now,\n logger: options.logger,\n });\n\n const controller = new SparkController({\n spark: options.sparkApis ?? spark(options.wallet),\n fetch: options.fetch,\n random: options.random,\n now: options.now,\n logger: options.logger,\n createClient: ({ ref, store, signer, fetch }) =>\n createSparkClient({\n network: ref.network,\n signer,\n store,\n fetch,\n }),\n });\n\n const networks = new NetworkController({\n fetch: options.fetch,\n rpc: options.rpc ?? {},\n openStore: options.openStore,\n logger: options.logger,\n });\n\n const assets = new AssetsController({\n networks,\n openStore: options.openStore,\n setTimer:\n options.setTimer ??\n ((ms, fn) => {\n const id = setTimeout(() => {\n void fn();\n }, ms);\n return () => clearTimeout(id);\n }),\n logger: options.logger,\n });\n\n const transactions = new TransactionController({\n wallet: options.wallet,\n networks,\n openStore: options.openStore,\n random: options.random,\n setTimer:\n options.setTimer ??\n ((ms, fn) => {\n const id = setTimeout(() => {\n void fn();\n }, ms);\n return () => clearTimeout(id);\n }),\n now: options.now,\n logger: options.logger,\n });\n\n const accounts = new AccountTreeController({\n wallet: options.wallet,\n spark: controller,\n sparkNetwork: options.sparkNetwork,\n networks,\n logger: options.logger,\n now: options.now,\n });\n\n const metaSync = new MetaSyncController({\n wallet: options.wallet,\n accounts,\n nostr: { signer: (ref) => nostr(options.wallet).signer(ref) },\n metaSync: options.metaSync,\n logger: options.logger,\n now: options.now,\n });\n\n // The transition chain: every status change queues behind the previous one, so a late lock\n // always observes the snapshot left by a settled unlock (and vice versa).\n let chain: Promise<void> = Promise.resolve();\n let store: EngineStore | undefined;\n let started = false;\n\n const transition = async (): Promise<void> => {\n const unlocked = options.wallet.getSnapshot().vault === \"unlocked\";\n if (unlocked && !started) {\n started = true;\n try {\n store = await options.openStore();\n } catch (error) {\n // No store, no clients — reset so the next status event retries cleanly.\n started = false;\n store = undefined;\n options.logger.warn(\"engine store failed to open\", error);\n return;\n }\n controller.setStore(store);\n backup.setStore(store);\n accounts.setStore(store);\n backup.trigger(); // reconcile — never awaited on the transition chain\n // Load + reconcile + drive the selected account through spark.setAccounts.\n await accounts.init();\n await controller.init();\n // Pull → merge → maybe publish for every wallet with a group-0 identity.\n await metaSync.init();\n await networks.init();\n await assets.init();\n await transactions.init();\n } else if (!unlocked && started) {\n started = false;\n transactions.lock();\n assets.lock();\n networks.lock();\n // Lock: cancel sync write-backs, tree → locked, spark.setAccounts([]), totals flush.\n await metaSync.lock();\n await accounts.lock();\n await controller.lockAll();\n controller.setStore(undefined);\n const s = store;\n store = undefined;\n await s?.close();\n }\n };\n\n const snapshotListener = (): void => {\n // Every snapshot change while unlocked nudges the reconcile; the lock transition is\n // handled inside transition() and bumps the backup generation.\n if (options.wallet.getSnapshot().vault === \"unlocked\") {\n backup.trigger();\n accounts.reconcile();\n metaSync.reconcile();\n } else {\n backup.lock();\n }\n };\n\n const schedule = (): void => {\n const previous = chain;\n chain = (async () => {\n try {\n await previous;\n await transition();\n } catch (error) {\n options.logger.warn(\"engine lock transition failed\", error);\n }\n })();\n };\n const unsubscribe = options.wallet.subscribe(() => {\n schedule();\n snapshotListener();\n });\n schedule();\n return {\n networks,\n assets,\n transactions,\n spark: controller,\n accounts,\n metaSync,\n backup,\n zaps: {\n prepare: async (params) => prepareZap(params, { fetch: options.fetch, now: options.now }),\n pay: async (account, prepared, payOptions) =>\n payZap(controller, account, prepared, { ...payOptions, now: options.now }),\n },\n payments: {\n parse: (input, network) => parsePayment(input, { network, now: options.now() }),\n resolve: async (input, network) =>\n resolvePayment(input, { network, now: options.now(), fetch: options.fetch }),\n pay: async (params) =>\n runPay({ spark: controller, fetch: options.fetch, now: options.now }, params),\n },\n unsubscribe,\n };\n}\n","import type { CloudStore } from \"./port.ts\";\n\nconst tick = Promise.resolve();\n\n/** In-memory CloudStore for tests and the playground; swap the Map for cross-engine sharing. */\nexport function createMemoryCloudStore(backing?: Map<string, string>): CloudStore {\n const files = backing ?? new Map<string, string>();\n let reachable = true;\n const store: CloudStore & { readonly setReachable: (v: boolean) => void } = {\n available: async () => {\n await tick;\n return reachable;\n },\n list: async () => {\n await tick;\n return [...files.keys()].sort();\n },\n read: async (name) => {\n await tick;\n return files.get(name);\n },\n write: async (name, text) => {\n await tick;\n files.set(name, text);\n },\n delete: async (name) => {\n await tick;\n files.delete(name);\n },\n setReachable: (v) => {\n reachable = v;\n },\n };\n return store;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,IAAsB,aAAtB,MAAoE;CAClE;CACA;CAEA,YAAsB,SAA+B;EACnD,KAAK,OAAO,QAAQ;EACpB,KAAK,QAAQ,YAAe,QAAQ,YAAY;CAClD;CAEA,WAAc;EACZ,OAAO,KAAK,MAAM,SAAS;CAC7B;CAEA,OAAiB,QAA+B;EAC9C,KAAK,MAAM,UAAU,UAAU,OAAO,KAAK,CAAC;CAC9C;AAIF;;;ACrBA,SAAgB,eAAkB,QAAmC;CACnE,MAAM,4BAAY,IAAI,IAA8C;CACpE,OAAO;EACL,KAAwB,MAAS,SAAqB;GACpD,MAAM,MAAM,UAAU,IAAI,IAAI;GAC9B,IAAI,QAAQ,KAAA,GACV;GAEF,KAAK,MAAM,YAAY,KACrB,IAAI;IACF,SAAS,OAAO;GAClB,SAAS,OAAO;IACd,OAAO,KAAK,wBAAwB,KAAK;GAC3C;EAEJ;EACA,GAAsB,MAAS,UAA+C;GAC5E,IAAI,MAAM,UAAU,IAAI,IAAI;GAC5B,IAAI,QAAQ,KAAA,GAAW;IACrB,sBAAM,IAAI,IAAI;IACd,UAAU,IAAI,MAAM,GAAG;GACzB;GAGA,MAAM,SAAS;GACf,IAAI,IAAI,MAAM;GACd,aAAa;IACX,IAAI,OAAO,MAAM;GACnB;EACF;CACF;AACF;;;;ACvCA,IAAa,mBAAb,cAAsC,MAAM;CAC1C;CAEA,YAAY,MAAuB,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