@qntx/wallet-engine 0.5.2 → 0.7.0
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.
- package/README.md +21 -0
- package/dist/contract-CEsgLme3.mjs +277 -0
- package/dist/contract-CEsgLme3.mjs.map +1 -0
- package/dist/gateway-contract.d.mts +285 -0
- package/dist/gateway-contract.mjs +1 -0
- package/dist/idb.d.mts +0 -4
- package/dist/idb.mjs +3 -6
- package/dist/idb.mjs.map +1 -1
- package/dist/index.d.mts +976 -499
- package/dist/index.mjs +2971 -965
- package/dist/index.mjs.map +1 -1
- package/dist/registry-LcFSPrE1.d.mts +23 -0
- package/package.json +14 -8
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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,IAAs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S,UAAU,eAC7B,OAAO,YAAY,SAAS,UAAU;IAAE,GAAG;IAAY,KAAK,QAAQ;GAAI,CAAC;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;;;AC5PA,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":["COLLECTION","addressOf","isObject","errorMessage","COLLECTION","isObject","isObject","NAME_MAX","isObject","isNonNegativeInt","COLLECTION","isObject","str","NAME_MAX","isNonNegativeInt","KNOWN_GROUP_KEYS","KNOWN_WALLET_KEYS","PUBKEY_RE","errorMessage","hex","obj","isObject","arr","COLLECTION","key","isObject","isObject","isObject","isObject","isObject","isObject","errorMessage","isObject","obj","isObject"],"sources":["../src/controller.ts","../src/events.ts","../src/errors.ts","../src/store/guard.ts","../src/store/memory.ts","../src/connect/errors.ts","../src/connect/controller.ts","../src/addresses/normalize.ts","../src/spark/errors.ts","../src/payments/action.ts","../src/payments/errors.ts","../src/payments/pay.ts","../src/payments/zap.ts","../src/spark/l1.ts","../src/transactions/route.ts","../src/requests/checks.ts","../src/requests/risk.ts","../src/requests/sign-log.ts","../src/requests/controller.ts","../src/connect/eip1193.ts","../src/addresses/errors.ts","../src/addresses/record.ts","../src/addresses/merge.ts","../src/addresses/controller.ts","../src/chains/bitcoin-scan.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/controller.ts","../src/payments/parse.ts","../src/payments/resolve.ts","../src/spark/notes.ts","../src/spark/exit-chain-codec.ts","../src/spark/store.ts","../src/spark/controller.ts","../src/spark/deposit-claim.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","/** EIP-1193 / EIP-1474 / EIP-3326 error: `code` is what the page's promise rejects with. */\nexport class ProviderError extends Error {\n readonly code: number;\n\n constructor(code: number, message: string) {\n super(message);\n this.name = \"ProviderError\";\n this.code = code;\n }\n}\n\nexport const userRejectedRequest = (message = \"user rejected the request\"): ProviderError =>\n new ProviderError(4001, message);\n\nexport const unauthorized = (message = \"not authorized\"): ProviderError =>\n new ProviderError(4100, message);\n\nexport const unsupportedMethod = (method: string): ProviderError =>\n new ProviderError(4200, `${method} is not supported`);\n\nexport const unrecognizedChain = (message = \"unrecognized chain\"): ProviderError =>\n new ProviderError(4902, message);\n\nexport const invalidParams = (message: string): ProviderError => new ProviderError(-32602, message);\n\nexport const requestPending = (message: string): ProviderError =>\n new ProviderError(-32002, message);\n\nexport const internalError = (message: string): ProviderError => new ProviderError(-32603, message);\n","/**\n * DApp connections (CAIP-25 style sessions): one session per origin, authorization by network,\n * account and method, persisted in the engine store and cleared from memory on lock. A connection\n * is approved from a pending queue, by id, like any other request; locking rejects all of it.\n */\nimport { Controller } from \"../controller.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport type { EngineStore } from \"../store/port.ts\";\nimport {\n internalError,\n invalidParams,\n requestPending,\n unauthorized,\n userRejectedRequest,\n} from \"./errors.ts\";\n\nexport type ConnectionOrigin = { readonly kind: \"browser\"; readonly origin: string };\n\nexport type ConnectionScope = {\n /** CAIP-10 */\n readonly accounts: ReadonlyArray<string>;\n readonly methods: ReadonlyArray<string>;\n readonly notifications: ReadonlyArray<string>;\n};\n\nexport type ConnectionSession = {\n readonly id: string;\n readonly origin: ConnectionOrigin;\n /** Keyed by CAIP-2. */\n readonly scopes: Readonly<Record<string, ConnectionScope>>;\n /** The session's current EVM network; only dApp sessions have one. */\n readonly currentNetwork: string;\n readonly createdAt: number;\n readonly lastUsedAt: number;\n};\n\n/** `connect` asks for accounts; `network` asks to add a network the session does not cover. */\nexport type PendingConnection = {\n readonly id: string;\n readonly origin: ConnectionOrigin;\n readonly kind: \"connect\" | \"network\";\n readonly network?: string;\n readonly createdAt: number;\n};\n\nexport type AccountGroup = { readonly walletId: string; readonly groupIndex: number };\n\nexport type ConnectionState = {\n readonly sessions: Readonly<Record<string, ConnectionSession>>;\n readonly pending: Readonly<Record<string, PendingConnection>>;\n};\n\nexport type ConnectionControllerOptions = {\n readonly openStore: () => Promise<EngineStore>;\n readonly random: (n: number) => Uint8Array;\n readonly now: () => number;\n readonly logger: EngineLogger;\n /** Development builds also accept `http://localhost`. */\n readonly allowLocalhost: boolean;\n /** The group the app currently shows; sessions are bound to it. */\n readonly selectedGroup: () => AccountGroup | undefined;\n /** The group's EVM address on `network`. */\n readonly evmAddress: (group: AccountGroup, network: string) => Promise<string>;\n readonly enabledNetworks: () => ReadonlyArray<string>;\n /** Voids a page's unfinished requests (revoked, or its network changed). */\n readonly invalidate: (origin: string) => void;\n};\n\nconst COLLECTION = \"connections\";\n\n/** Sessions unused for this long are dropped when the vault unlocks. */\nexport const SESSION_TTL_MS = 90 * 24 * 60 * 60 * 1000;\n\n/** `lastUsedAt` is rewritten at most this often. */\nconst TOUCH_INTERVAL_MS = 60_000;\n\n/** Granted for every network a session covers. */\nexport const SESSION_METHODS: ReadonlyArray<string> = [\n \"eth_sendTransaction\",\n \"personal_sign\",\n \"eth_signTypedData_v4\",\n];\nexport const SESSION_NOTIFICATIONS: ReadonlyArray<string> = [\"accountsChanged\", \"chainChanged\"];\n\n/** `eip155:1` → 1; `undefined` for anything that is not an EVM network. */\nexport const evmChainId = (network: string): number | undefined => {\n const match = /^eip155:(\\d+)$/.exec(network);\n const id = match?.[1] === undefined ? undefined : Number(match[1]);\n return id !== undefined && Number.isSafeInteger(id) ? id : undefined;\n};\n\nconst caip10 = (network: string, address: string): string => `${network}:${address}`;\n\nconst addressOf = (account: string): string => account.slice(account.lastIndexOf(\":\") + 1);\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null;\n\nconst isSession = (value: unknown): value is ConnectionSession => {\n if (!isObject(value) || !isObject(value[\"origin\"]) || !isObject(value[\"scopes\"])) {\n return false;\n }\n return (\n typeof value[\"id\"] === \"string\" &&\n value[\"origin\"][\"kind\"] === \"browser\" &&\n typeof value[\"origin\"][\"origin\"] === \"string\" &&\n typeof value[\"currentNetwork\"] === \"string\" &&\n typeof value[\"createdAt\"] === \"number\" &&\n typeof value[\"lastUsedAt\"] === \"number\"\n );\n};\n\ntype Waiter = {\n readonly resolve: (session: ConnectionSession) => void;\n readonly reject: (error: Error) => void;\n};\n\nexport class ConnectionController extends Controller<ConnectionState> {\n private readonly options: ConnectionControllerOptions;\n private engineStore: EngineStore | undefined;\n private readonly waiters = new Map<string, Waiter>();\n private group: AccountGroup | undefined;\n\n constructor(options: ConnectionControllerOptions) {\n super({ name: \"connections\", defaultState: () => ({ sessions: {}, pending: {} }) });\n this.options = options;\n }\n\n async init(): Promise<void> {\n const store = await this.options.openStore();\n this.engineStore = store;\n this.group = undefined;\n const collection = store.collection(COLLECTION);\n const keys = await collection.list();\n const rows = await Promise.all(keys.map(async (key) => collection.get(key)));\n const now = this.options.now();\n const sessions: Record<string, ConnectionSession> = {};\n const expired: string[] = [];\n for (const [index, raw] of rows.entries()) {\n const key = keys[index];\n if (raw === undefined || key === undefined) {\n continue;\n }\n const parsed: unknown = JSON.parse(new TextDecoder().decode(raw));\n if (!isSession(parsed)) {\n this.options.logger.warn(\"connection session skipped: malformed\");\n expired.push(key);\n } else if (now - parsed.lastUsedAt > SESSION_TTL_MS) {\n expired.push(key);\n } else {\n sessions[parsed.id] = parsed;\n }\n }\n await Promise.all(expired.map(async (key) => collection.delete(key)));\n this.update(() => ({ sessions, pending: {} }));\n }\n\n async destroy(): Promise<void> {\n this.lock();\n await Promise.resolve();\n }\n\n /** Locking is not consent: every pending connection is rejected. */\n lock(): void {\n this.engineStore = undefined;\n this.group = undefined;\n for (const waiter of this.waiters.values()) {\n waiter.reject(userRejectedRequest(\"the wallet was locked\"));\n }\n this.waiters.clear();\n this.update(() => ({ sessions: {}, pending: {} }));\n }\n\n /** Throws `4100` unless `origin` is `https://host[:port]` (or localhost in development). */\n checkOrigin(origin: string): ConnectionOrigin {\n let url: URL;\n try {\n url = new URL(origin);\n } catch {\n throw unauthorized(\"invalid origin\");\n }\n const localhost = url.protocol === \"http:\" && url.hostname === \"localhost\";\n if (\n url.origin !== origin ||\n (url.protocol !== \"https:\" && !(localhost && this.options.allowLocalhost))\n ) {\n throw unauthorized(\"origin not allowed\");\n }\n return { kind: \"browser\", origin };\n }\n\n session(origin: string): ConnectionSession | undefined {\n return Object.values(this.getState().sessions).find((s) => s.origin.origin === origin);\n }\n\n pending(): ReadonlyArray<PendingConnection> {\n return Object.values(this.getState().pending);\n }\n\n /** The group sessions are bound to: the host's last `setActiveGroup`, else the app's selection. */\n activeGroup(): AccountGroup | undefined {\n return this.group ?? this.options.selectedGroup();\n }\n\n /** Whether `network` is an EVM network the wallet has enabled. */\n isEnabled(network: string): boolean {\n return this.options.enabledNetworks().includes(network);\n }\n\n /** The origin's authorized addresses on its current network; empty when not connected. */\n accounts(origin: string): ReadonlyArray<string> {\n const session = this.session(origin);\n return session?.scopes[session.currentNetwork]?.accounts.map(addressOf) ?? [];\n }\n\n /** Throws `4100` unless the origin's session covers `method` on `network`. */\n authorize(origin: string, network: string, method: string): ConnectionSession {\n const session = this.session(origin);\n const scope = session?.scopes[network];\n if (session === undefined || scope === undefined || !scope.methods.includes(method)) {\n throw unauthorized();\n }\n return session;\n }\n\n /** Resolves with the session once the host approves; rejects with `4001` when it refuses. */\n async request(\n origin: string,\n kind: PendingConnection[\"kind\"],\n network?: string,\n ): Promise<ConnectionSession> {\n const store = this.engineStore;\n if (store === undefined) {\n throw userRejectedRequest(\"the wallet is locked\");\n }\n if (this.pending().some((p) => p.origin.origin === origin)) {\n throw requestPending(\"a connection request is already pending\");\n }\n const id = `conn-${[...this.options.random(8)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\")}`;\n const entry: PendingConnection = {\n id,\n origin: { kind: \"browser\", origin },\n kind,\n ...(network === undefined ? {} : { network }),\n createdAt: this.options.now(),\n };\n return new Promise<ConnectionSession>((resolve, reject) => {\n this.waiters.set(id, { resolve, reject });\n this.update((s) => ({ ...s, pending: { ...s.pending, [id]: entry } }));\n });\n }\n\n /**\n * The host's approval, by id: the accounts granted (EVM addresses of the active group) and the\n * network.\n */\n async approveConnection(\n id: string,\n grant: { readonly accounts: ReadonlyArray<string>; readonly network: string },\n ): Promise<ConnectionSession> {\n const store = this.requireStore();\n const entry = this.getState().pending[id];\n const waiter = this.waiters.get(id);\n if (entry === undefined || waiter === undefined) {\n throw new Error(`unknown connection request ${id}`);\n }\n if (entry.kind === \"network\" && entry.network !== grant.network) {\n throw new Error(`connection request ${id} is for ${String(entry.network)}`);\n }\n const chainId = evmChainId(grant.network);\n if (chainId === undefined || !this.options.enabledNetworks().includes(grant.network)) {\n throw invalidParams(`${grant.network} is not an enabled EVM network`);\n }\n const group = this.activeGroup();\n if (group === undefined) {\n throw new Error(\"no account group is selected\");\n }\n const derived = await this.options.evmAddress(group, grant.network);\n const own = derived.toLowerCase();\n if (grant.accounts.length === 0 || grant.accounts.some((a) => a.toLowerCase() !== own)) {\n throw invalidParams(\"only the active group's account can be granted\");\n }\n if (this.getState().pending[id] === undefined) {\n throw new Error(`connection request ${id} is no longer pending`);\n }\n const now = this.options.now();\n const existing = this.session(entry.origin.origin);\n const scope: ConnectionScope = {\n accounts: [caip10(grant.network, own)],\n methods: SESSION_METHODS,\n notifications: SESSION_NOTIFICATIONS,\n };\n const session: ConnectionSession = {\n id:\n existing?.id ??\n `session-${[...this.options.random(8)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\")}`,\n origin: entry.origin,\n scopes: { ...existing?.scopes, [grant.network]: scope },\n currentNetwork: grant.network,\n createdAt: existing?.createdAt ?? now,\n lastUsedAt: now,\n };\n await this.persist(store, session);\n this.dropPending(id);\n if (existing !== undefined && existing.currentNetwork !== grant.network) {\n this.options.invalidate(entry.origin.origin);\n }\n waiter.resolve(session);\n return session;\n }\n\n rejectConnection(id: string): void {\n const waiter = this.waiters.get(id);\n if (this.getState().pending[id] === undefined || waiter === undefined) {\n throw new Error(`unknown connection request ${id}`);\n }\n this.dropPending(id);\n waiter.reject(userRejectedRequest());\n }\n\n /** Ends the origin's session; its pending connection and unfinished requests are void. */\n async revoke(origin: string): Promise<void> {\n const store = this.requireStore();\n for (const p of this.pending().filter((x) => x.origin.origin === origin)) {\n const waiter = this.waiters.get(p.id);\n this.dropPending(p.id);\n waiter?.reject(userRejectedRequest(\"the connection was revoked\"));\n }\n const session = this.session(origin);\n if (session !== undefined) {\n await store.collection(COLLECTION).delete(session.id);\n this.update((s) => {\n const { [session.id]: _gone, ...sessions } = s.sessions;\n return { ...s, sessions };\n });\n }\n this.options.invalidate(origin);\n }\n\n /** Switches within the session's scope; the origin's unfinished requests are void. */\n async setCurrentNetwork(origin: string, network: string): Promise<void> {\n const store = this.requireStore();\n const session = this.session(origin);\n if (session === undefined || session.scopes[network] === undefined) {\n throw unauthorized();\n }\n await this.persist(store, { ...session, currentNetwork: network });\n this.options.invalidate(origin);\n }\n\n async touch(origin: string): Promise<void> {\n const store = this.engineStore;\n const session = this.session(origin);\n const now = this.options.now();\n if (\n store === undefined ||\n session === undefined ||\n now - session.lastUsedAt < TOUCH_INTERVAL_MS\n ) {\n return;\n }\n await this.persist(store, { ...session, lastUsedAt: now });\n }\n\n /**\n * The host switched account group: every session's accounts become the new group's addresses. A\n * session that cannot get one (no address derivable) is left with an empty list and has to be\n * authorized again.\n */\n async setActiveGroup(walletId: string, groupIndex: number): Promise<void> {\n const store = this.requireStore();\n const group = { walletId, groupIndex };\n this.group = group;\n await Promise.all(\n Object.values(this.getState().sessions).map(async (session) => {\n const entries = await Promise.all(\n Object.entries(session.scopes).map(\n async ([network, scope]): Promise<[string, ConnectionScope]> => {\n if (scope.accounts.length === 0) {\n return [network, scope];\n }\n try {\n const address = await this.options.evmAddress(group, network);\n return [network, { ...scope, accounts: [caip10(network, address.toLowerCase())] }];\n } catch (error) {\n this.options.logger.warn(\"connection account unavailable in the new group\", error);\n return [network, { ...scope, accounts: [] }];\n }\n },\n ),\n );\n await this.persist(store, { ...session, scopes: Object.fromEntries(entries) });\n }),\n );\n }\n\n private dropPending(id: string): void {\n this.waiters.delete(id);\n this.update((s) => {\n const { [id]: _gone, ...pending } = s.pending;\n return { ...s, pending };\n });\n }\n\n private async persist(store: EngineStore, session: ConnectionSession): Promise<void> {\n try {\n await store\n .collection(COLLECTION)\n .put(session.id, new TextEncoder().encode(JSON.stringify(session)));\n } catch (error) {\n throw internalError(error instanceof Error ? error.message : String(error));\n }\n this.update((s) => ({ ...s, sessions: { ...s.sessions, [session.id]: session } }));\n }\n\n private requireStore(): EngineStore {\n if (this.engineStore === undefined) {\n throw userRejectedRequest(\"the wallet is locked\");\n }\n return this.engineStore;\n }\n}\n","import { Address } from \"@scure/btc-signer\";\n\nimport { decodeSparkAddress, encodeSparkAddress } from \"@qntx/spark\";\nimport { BITCOIN_NETWORKS } from \"@qntx/wallet-chains/bitcoin\";\nimport { checksumEvmAddress, isEvmAddress } from \"@qntx/wallet-chains/evm\";\nimport { isSolanaAddress } from \"@qntx/wallet-chains/solana\";\n\nexport type AddressFamily = \"evm\" | \"solana\" | \"bitcoin\" | \"spark\";\n\n/**\n * The canonical form of `address` for its family — EIP-55 for EVM, the re-encoded form for bitcoin\n * (accepted on any known bitcoin network, since a contact is not tied to the wallet's network) and\n * Spark (identity key only, no invoice fields) — or `undefined` when it is not a valid address.\n */\nexport function normalizeAddress(family: AddressFamily, address: string): string | undefined {\n try {\n if (family === \"evm\") {\n return isEvmAddress(address) ? checksumEvmAddress(address) : undefined;\n }\n if (family === \"solana\") {\n return isSolanaAddress(address) ? address : undefined;\n }\n if (family === \"spark\") {\n const decoded = decodeSparkAddress(address);\n return encodeSparkAddress({\n network: decoded.network,\n identityPublicKey: decoded.identityPublicKey,\n });\n }\n for (const network of Object.values(BITCOIN_NETWORKS)) {\n try {\n const codec = Address(network.params);\n return codec.encode(codec.decode(address));\n } catch {\n // not an address of this network; try the next\n }\n }\n return undefined;\n } catch {\n return undefined;\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","import type {\n CooperativeExitResult,\n LightningPayment,\n SparkNetwork,\n SparkTransfer,\n} from \"@qntx/spark\";\nimport type { UnlockFactor } from \"@qntx/wallet\";\n\nimport type { RequestCheckCode } from \"../requests/checks.ts\";\nimport type { SparkController } from \"../spark/controller.ts\";\n\n/**\n * What the host shows for a Spark, Lightning or exit request; `family` tells it apart from a chain\n * intent.\n */\nexport type SparkDisplay = {\n readonly family: \"spark\";\n readonly network: SparkNetwork;\n readonly kind: \"transfer\" | \"lightning\" | \"exit\";\n readonly amountSats: number;\n readonly maxFeeSats?: number;\n /** Spark address, Lightning payee public key (hex) or bitcoin address. */\n readonly receiver: string;\n /** Invoice description or the LNURL metadata text. */\n readonly description?: string;\n};\n\nexport type SparkResult =\n | { readonly kind: \"spark\"; readonly transfer: SparkTransfer }\n | { readonly kind: \"lightning\"; readonly payment: LightningPayment }\n | { readonly kind: \"withdraw\"; readonly exit: CooperativeExitResult };\n\n/**\n * A validated, fixed Spark payment: everything that does not need the user's verification has\n * happened (including any LNURL invoice fetch), so approval only re-checks expiry and executes.\n */\nexport type PreparedSparkAction = {\n readonly display: SparkDisplay;\n readonly checks: ReadonlyArray<RequestCheckCode>;\n /** Why the action can no longer be paid at `now` (an expiring invoice), if so. */\n readonly staleReason: (now: number) => string | undefined;\n /** Runs the controller's approve-first payment call. */\n readonly execute: (spark: SparkController, verify: UnlockFactor) => Promise<SparkResult>;\n};\n\n/** An invoice must have more than this much life left when approved. */\nexport const INVOICE_EXPIRY_GRACE_MS = 60_000;\n\nexport const feeCheck = (\n amountSats: number,\n maxFeeSats: number | undefined,\n): ReadonlyArray<RequestCheckCode> =>\n maxFeeSats !== undefined && maxFeeSats >= amountSats ? [\"fee-exceeds-amount\"] : [];\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 { bytesToHex } from \"@noble/hashes/utils.js\";\n\nimport { decodeBolt11, encodeSparkAddress, parseSparkInvoice } from \"@qntx/spark\";\nimport type { LightningInvoice } from \"@qntx/spark\";\nimport { requestInvoice, submitWithdraw } from \"@qntx/spark/lnurl\";\nimport type { SparkAccountRef } from \"@qntx/wallet/protocol\";\n\nimport type { SparkController } from \"../spark/controller.ts\";\nimport { SparkControllerError } from \"../spark/errors.ts\";\nimport { INVOICE_EXPIRY_GRACE_MS, feeCheck } from \"./action.ts\";\nimport type { PreparedSparkAction } from \"./action.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};\n\nexport type PayContext = {\n readonly fetch: typeof globalThis.fetch;\n readonly now: () => number;\n};\n\nconst lightningDetails = (\n invoice: string,\n): { readonly payee: string; readonly expiresAt: number } => {\n const decoded = decodeBolt11(invoice);\n return {\n payee: bytesToHex(decoded.payee),\n expiresAt: (decoded.timestamp + decoded.expirySeconds) * 1000,\n };\n};\n\n/**\n * Validates one parsed payment option and fixes everything the approval needs — including the\n * LNURL-pay invoice, fetched here exactly once. Every input validation happens before the approval\n * round, so a `PaymentError` here never consumed a verification. `lnurl-withdraw` receives funds\n * and has its own entry, {@link withdrawLnurl}.\n */\nexport async function preparePay(\n context: PayContext,\n params: PayParams,\n): Promise<PreparedSparkAction> {\n const ref = params.account;\n const { network } = ref;\n if (params.option.kind === \"lnurl-withdraw\") {\n throw new PaymentError(\n \"invalid-input\",\n \"lnurl-withdraw receives funds: use payments.withdrawLnurl\",\n );\n }\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 { address } = params.option;\n const { amountSats } = params;\n return {\n display: { family: \"spark\", network, kind: \"transfer\", amountSats, receiver: address },\n checks: [],\n staleReason: () => undefined,\n execute: async (spark, verify) => ({\n kind: \"spark\",\n transfer: await spark.send(ref, { receiver: address, amountSats, verify }),\n }),\n };\n }\n case \"spark-invoice\": {\n const { option } = params;\n if (option.expiresAt !== undefined && option.expiresAt <= context.now()) {\n throw new PaymentError(\"rejected\", \"spark invoice expired\");\n }\n if (\n option.amountSats !== undefined &&\n params.amountSats !== undefined &&\n params.amountSats !== option.amountSats\n ) {\n throw new PaymentError(\n \"invalid-input\",\n \"spark invoice: amountSats conflicts with the invoice amount\",\n );\n }\n const amountSats = option.amountSats ?? params.amountSats;\n if (amountSats === undefined) {\n throw new PaymentError(\n \"invalid-input\",\n \"spark invoice: amountless invoice requires amountSats\",\n );\n }\n // A fixed-amount invoice derives the amount itself — only an open one takes the caller's.\n const openAmount = option.amountSats === undefined ? params.amountSats : undefined;\n const parsed = parseSparkInvoice(option.invoice, { network, now: context.now() });\n const { expiresAt } = option;\n return {\n display: {\n family: \"spark\",\n network,\n kind: \"transfer\",\n amountSats,\n receiver: encodeSparkAddress({\n network,\n identityPublicKey: parsed.receiverIdentityPublicKey,\n }),\n ...(option.memo === undefined ? {} : { description: option.memo }),\n },\n checks: [],\n staleReason: (now) =>\n expiresAt !== undefined && expiresAt <= now ? \"spark invoice expired\" : undefined,\n execute: async (spark, verify) => ({\n kind: \"spark\",\n transfer: await spark.paySparkInvoice(ref, {\n invoice: option.invoice,\n ...(openAmount === undefined ? {} : { amountSats: openAmount }),\n verify,\n }),\n }),\n };\n }\n case \"lightning\": {\n const { option } = params;\n if (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 if (option.expiresAt <= context.now() + INVOICE_EXPIRY_GRACE_MS) {\n throw new PaymentError(\"rejected\", \"lightning invoice expired\");\n }\n if (\n option.amountSats !== undefined &&\n params.amountSats !== undefined &&\n params.amountSats !== option.amountSats\n ) {\n throw new PaymentError(\"invalid-input\", \"amountSats conflicts with the invoice amount\");\n }\n const { maxFeeSats } = params;\n // amountSats is only for amountless invoices — a fixed-amount invoice must not carry it.\n const openAmount = option.amountSats === undefined ? params.amountSats : undefined;\n const amountSats = option.amountSats ?? params.amountSats ?? 0;\n const { payee } = lightningDetails(option.invoice);\n const { expiresAt } = option;\n return {\n display: {\n family: \"spark\",\n network,\n kind: \"lightning\",\n amountSats,\n maxFeeSats,\n receiver: payee,\n ...(option.description === undefined ? {} : { description: option.description }),\n },\n checks: feeCheck(amountSats, maxFeeSats),\n staleReason: (now) =>\n expiresAt <= now + INVOICE_EXPIRY_GRACE_MS ? \"lightning invoice expired\" : undefined,\n execute: async (spark, verify) => ({\n kind: \"lightning\",\n payment: await spark.payInvoice(ref, {\n invoice: option.invoice,\n maxFeeSats,\n ...(openAmount === undefined ? {} : { amountSats: openAmount }),\n verify,\n }),\n }),\n };\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 { amountSats, maxFeeSats } = params;\n const amountMsat = 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,\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 { invoice } = requested;\n const { payee, expiresAt } = lightningDetails(invoice);\n return {\n display: {\n family: \"spark\",\n network,\n kind: \"lightning\",\n amountSats,\n maxFeeSats,\n receiver: payee,\n description: request.description,\n },\n checks: feeCheck(amountSats, maxFeeSats),\n staleReason: (now) =>\n expiresAt <= now + INVOICE_EXPIRY_GRACE_MS ? \"lightning invoice expired\" : undefined,\n execute: async (spark, verify) => ({\n kind: \"lightning\",\n payment: await spark.payInvoice(ref, { invoice, maxFeeSats, verify }),\n }),\n };\n }\n default: {\n if (params.amountSats === undefined) {\n throw new PaymentError(\"invalid-input\", \"bitcoin payment: amountSats is required\");\n }\n const { address } = params.option;\n const { amountSats, maxFeeSats } = params;\n const speed = params.speed ?? \"MEDIUM\";\n return {\n display: {\n family: \"spark\",\n network,\n kind: \"exit\",\n amountSats,\n ...(maxFeeSats === undefined ? {} : { maxFeeSats }),\n receiver: address,\n },\n checks: feeCheck(amountSats, maxFeeSats),\n staleReason: () => undefined,\n execute: async (spark, verify) => ({\n kind: \"withdraw\",\n exit: await spark.withdraw(ref, {\n address,\n speed,\n verify,\n amountSats,\n ...(maxFeeSats === undefined ? {} : { maxFeeSats }),\n }),\n }),\n };\n }\n }\n}\n\nexport type WithdrawLnurlParams = {\n readonly account: SparkAccountRef;\n readonly option: Extract<PaymentOption, { kind: \"lnurl-withdraw\" }>;\n readonly amountSats: number;\n};\n\n/**\n * LNURL-withdraw: asks the service to pay an invoice this wallet creates. It receives funds, so it\n * needs no verification factor and does not go through the request pipeline.\n */\nexport async function withdrawLnurl(\n context: PayContext & { readonly spark: SparkController },\n params: WithdrawLnurlParams,\n): Promise<{ readonly kind: \"lnurl-withdraw\"; readonly invoice: LightningInvoice }> {\n const { request } = params.option;\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 context.spark.createInvoice(params.account, {\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 return { kind: \"lnurl-withdraw\", invoice };\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 { SparkNetwork } from \"@qntx/spark\";\nimport { encodeLnurl, lightningAddressUrl, requestInvoice, resolveLnurl } from \"@qntx/spark/lnurl\";\nimport type { SparkAccountRef } from \"@qntx/wallet/protocol\";\n\nimport { categorize } from \"../spark/errors.ts\";\nimport { INVOICE_EXPIRY_GRACE_MS, feeCheck } from \"./action.ts\";\nimport type { PreparedSparkAction } from \"./action.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\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() + INVOICE_EXPIRY_GRACE_MS) {\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 * Fixes a prepared zap for approval: the invoice (fetched by {@link prepareZap}) is paid as-is, and\n * the zap note is written under the payment's transfer id afterwards. A nearly-expired invoice is\n * refused here and again at approval — the user may sit on the confirm screen.\n */\nexport function prepareZapAction(\n account: SparkAccountRef,\n prepared: PreparedZap,\n options: { readonly maxFeeSats: number; readonly now: () => number },\n): PreparedSparkAction {\n if (prepared.expiresAt <= options.now() + INVOICE_EXPIRY_GRACE_MS) {\n throw new PaymentError(\"rejected\", \"zap invoice expired\");\n }\n const { maxFeeSats } = options;\n const { payee } = lightningInvoiceDetails(prepared.invoice);\n return {\n display: {\n family: \"spark\",\n network: account.network,\n kind: \"lightning\",\n amountSats: prepared.amountSats,\n maxFeeSats,\n receiver: payee,\n ...(prepared.comment === undefined ? {} : { description: prepared.comment }),\n },\n checks: feeCheck(prepared.amountSats, maxFeeSats),\n staleReason: (now) =>\n prepared.expiresAt <= now + INVOICE_EXPIRY_GRACE_MS ? \"zap invoice expired\" : undefined,\n execute: async (spark, verify) => ({\n kind: \"lightning\",\n payment: await spark.payInvoice(account, {\n invoice: prepared.invoice,\n maxFeeSats,\n 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 };\n}\n\nconst lightningInvoiceDetails = (invoice: string): { readonly payee: string } => ({\n payee: bytesToHex(decodeBolt11(invoice).payee),\n});\n\nfunction categorizePayment(error: unknown): \"network\" | \"rejected\" {\n const category = categorize(error);\n return category === \"network\" ? \"network\" : \"rejected\";\n}\n","import type { SparkNetwork } from \"@qntx/spark\";\n\n/** The bitcoin network each Spark network settles on; deposits and exits must agree with it. */\nexport const SPARK_L1_NETWORK: Readonly<Record<SparkNetwork, string>> = {\n mainnet: \"bip122:000000000019d6689c085ae165831e93\",\n regtest: \"bip122:0f9188f13cb7b2c71f2a335e3a4fc328\",\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 { SparkNetwork } from \"@qntx/spark\";\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 { RequestCheckCode } from \"../requests/checks.ts\";\nimport type { EngineStore } from \"../store/port.ts\";\n\nexport type ChainApis = ReturnType<typeof chains>;\nexport type SignParams = Parameters<ChainApis[\"sign\"]>[0];\nexport type SignResult = Awaited<ReturnType<ChainApis[\"sign\"]>>;\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\n/** A bitcoin transaction that funds the wallet's own Spark account; it is claimed once confirmed. */\nexport type SparkDepositTag = {\n readonly walletId: string;\n readonly groupIndex: number;\n readonly network: SparkNetwork;\n readonly claimed?: boolean;\n};\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 /** Set on a Spark deposit; `claimed` flips once the deposit is credited on Spark. */\n readonly sparkDeposit?: SparkDepositTag;\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 PrepareParams = Omit<SendParams, \"verify\">;\n\nexport type ChainRequestMethod = \"send\" | \"speed-up\" | \"cancel\" | \"cpfp\";\n\n/** What a request asks for; replacements and CPFP name the original transaction. */\nexport type ChainRequestInput =\n | ({ readonly method: \"send\" } & PrepareParams)\n | { readonly method: \"speed-up\" | \"cancel\"; readonly txId: string }\n | { readonly method: \"cpfp\"; readonly txId: string; readonly feeRate: number };\n\n/**\n * A fully built, estimated and cross-checked send that has not been signed. The unsigned content\n * lives in the closures and cannot change after `prepare` returns.\n */\nexport type PreparedRequest = {\n /** Id of the tracked transaction `submit` creates. */\n readonly txId: string;\n readonly account: AccountRef;\n readonly network: string;\n /** The transaction being replaced or accelerated; absent for a plain send. */\n readonly target?: string;\n readonly intent: DisplayIntent;\n readonly checks: ReadonlyArray<RequestCheckCode>;\n /** Why the build can no longer be signed (nonce taken, blockhash expired), if so. */\n readonly staleReason: () => string | undefined | Promise<string | undefined>;\n /** Signs, finalizes, broadcasts and hands the transaction to tracking. */\n readonly submit: (verify: SendParams[\"verify\"]) => Promise<TrackedTransaction>;\n /** Frees what `prepare` reserved; safe to call more than once. */\n readonly release: () => void;\n};\n\nexport type SignatureResult = {\n readonly kind: \"evm.personal-message\" | \"evm.typed-data\";\n readonly signature: Uint8Array;\n};\n\n/** A prepared message signature: nothing is broadcast or tracked, `submit` returns the signature. */\nexport type PreparedMessage = Omit<PreparedRequest, \"submit\" | \"txId\"> & {\n readonly submit: (verify: SendParams[\"verify\"]) => Promise<SignatureResult>;\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 /** Every tracked transaction, for approval-time checks on a replacement's original. */\n readonly txs: () => Readonly<Record<string, TrackedTransaction>>;\n readonly newId: () => string;\n};\n\nconst hexId = (prefix: string, random: (n: number) => Uint8Array): string =>\n `${prefix}-${[...random(8)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\")}`;\n\nexport const newId = (random: (n: number) => Uint8Array): string => hexId(\"tx\", random);\n\nexport const newRequestId = (random: (n: number) => Uint8Array): string => hexId(\"req\", random);\n\nexport const errorMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\nconst LIVE_REPLACEMENT_STATES: ReadonlySet<TxState> = new Set([\n \"draft\",\n \"signed\",\n \"submitted\",\n \"pending\",\n]);\n\n/**\n * Approval-time check for a replacement: the original must still be unconfirmed and no other\n * replacement of it may already be on its way.\n */\nexport const replacementStaleReason = (\n ctx: RouteContext,\n originalId: string,\n): string | undefined => {\n const txs = ctx.txs();\n const original = txs[originalId];\n if (original?.state !== \"submitted\" && original?.state !== \"pending\") {\n return \"original transaction already finished — nothing to replace\";\n }\n const replaced = Object.values(txs).some(\n (t) => t.replaces === originalId && LIVE_REPLACEMENT_STATES.has(t.state),\n );\n return replaced ? \"original transaction was already replaced — start over\" : undefined;\n};\n\nexport const submitTx = async (\n ctx: RouteContext,\n tx: TrackedTransaction,\n hash: string,\n): Promise<TrackedTransaction> => {\n const tracked = await ctx.transition(tx, {\n state: \"submitted\",\n hash,\n submittedAt: ctx.options.now(),\n });\n ctx.track(tracked.id, hash);\n return tracked;\n};\n\nexport const failTx = async (\n ctx: RouteContext,\n tx: TrackedTransaction,\n error: unknown,\n): Promise<void> => {\n const failed = tx.state === \"signed\" ? \"failed\" : \"rejected\";\n await ctx.transition(tx, { state: failed, error: errorMessage(error) });\n};\n","/**\n * Pure rules of the request pipeline: merging the gateway's and the independent endpoint's\n * pre-signing reads, and the fee ceilings. Taking the lower fee means a lying gateway can at most\n * slow a transaction down, never make the user overpay.\n */\nimport type { EvmFeeQuote } from \"../chains/evm.ts\";\nimport type { SolanaFeeQuote } from \"../chains/solana.ts\";\n\nexport type RequestCheckCode =\n | \"decode-partial\"\n | \"nonce-mismatch\"\n | \"fee-mismatch\"\n | \"reads-unverified\"\n | \"fee-above-network\"\n | \"fee-exceeds-amount\";\n\n/** Two reads of one fee differ by more than this share of the smaller one. */\nexport const FEE_MISMATCH_PERCENT = 25n;\n\n/** A fee ceiling above this multiple of the independent estimate is flagged. */\nexport const FEE_CAP_MULTIPLIER = 2n;\n\n/**\n * `|a − b| / min(a, b)` is strictly above {@link FEE_MISMATCH_PERCENT}; a zero against a non-zero\n * always is.\n */\nexport const feesDiffer = (a: bigint, b: bigint): boolean => {\n const low = a < b ? a : b;\n const high = a < b ? b : a;\n return (high - low) * 100n > low * FEE_MISMATCH_PERCENT;\n};\n\n/**\n * The final ceiling exceeds {@link FEE_CAP_MULTIPLIER} times the independent estimate of the same\n * tier.\n */\nexport const exceedsNetworkCap = (final: bigint, independent: bigint): boolean =>\n final > independent * FEE_CAP_MULTIPLIER;\n\n/** The worst-case fee is not below the amount sent (native-asset sends only). */\nexport const feeReachesAmount = (maxFee: bigint, amount: bigint): boolean => maxFee >= amount;\n\nconst min = (a: bigint, b: bigint): bigint => (a < b ? a : b);\nconst max = (a: bigint, b: bigint): bigint => (a > b ? a : b);\n\n/** EIP-1559 quotes are `maxFee = baseFee × 2 + priority`; this recovers the base fee. */\nconst baseFeeOf = (quote: EvmFeeQuote): bigint =>\n (quote.maxFeePerGas - (quote.maxPriorityFeePerGas ?? 0n)) / 2n;\n\n/**\n * EIP-1559: priority fee is the lower of the two, `maxFeePerGas = max(baseFee) × 2 + priority` (a\n * high ceiling only prevents a stuck transaction, the base fee actually paid is the chain's).\n * Legacy: the lower gas price. Two different shapes cannot be merged — the independent quote wins.\n */\nexport const mergeEvmQuote = (\n primary: EvmFeeQuote,\n independent: EvmFeeQuote,\n): { readonly quote: EvmFeeQuote; readonly mismatch: boolean } => {\n const a = primary.maxPriorityFeePerGas;\n const b = independent.maxPriorityFeePerGas;\n if (a !== undefined && b !== undefined) {\n const priority = min(a, b);\n const maxFeePerGas = max(baseFeeOf(primary), baseFeeOf(independent)) * 2n + priority;\n return {\n quote: {\n tier: primary.tier,\n wei: maxFeePerGas,\n maxFeePerGas,\n maxPriorityFeePerGas: priority,\n },\n mismatch: feesDiffer(a, b) || feesDiffer(baseFeeOf(primary), baseFeeOf(independent)),\n };\n }\n if (a === undefined && b === undefined) {\n const price = min(primary.maxFeePerGas, independent.maxFeePerGas);\n return {\n quote: {\n tier: primary.tier,\n wei: price,\n maxFeePerGas: price,\n maxPriorityFeePerGas: undefined,\n },\n mismatch: feesDiffer(primary.maxFeePerGas, independent.maxFeePerGas),\n };\n }\n return { quote: independent, mismatch: true };\n};\n\nexport const mergeSolanaQuote = (\n primary: SolanaFeeQuote,\n independent: SolanaFeeQuote,\n): { readonly quote: SolanaFeeQuote; readonly mismatch: boolean } => ({\n quote: {\n tier: primary.tier,\n microLamportsPerCu: min(primary.microLamportsPerCu, independent.microLamportsPerCu),\n },\n mismatch: feesDiffer(primary.microLamportsPerCu, independent.microLamportsPerCu),\n});\n\n/** Bitcoin fee rates (sat/vB) per confirmation target. */\nexport const mergeSatPerByte = (\n primary: number,\n independent: number,\n): { readonly rate: number; readonly mismatch: boolean } => ({\n rate: Math.min(primary, independent),\n mismatch: feesDiffer(BigInt(Math.ceil(primary)), BigInt(Math.ceil(independent))),\n});\n\n/** The checks a prepared build carries, in a stable order and without duplicates. */\nexport const collectChecks = (\n flags: ReadonlyArray<RequestCheckCode | undefined>,\n): ReadonlyArray<RequestCheckCode> => [\n ...new Set(flags.filter((f): f is RequestCheckCode => f !== undefined)),\n];\n","/**\n * Recipient risk, pure: a recipient the wallet has never paid or saved is a `warning`; one that\n * looks like a known address (same first and last four characters, different address) is a `danger`\n * — the shape of an address-poisoning lookalike. Both can apply to one recipient.\n */\nexport type RiskFinding = {\n readonly code: \"first-recipient\" | \"address-poisoning\";\n readonly level: \"warning\" | \"danger\";\n};\n\n/** Characters compared at each end of an address. */\nexport const POISONING_EDGE = 4;\n\n/** EVM addresses compare without the `0x` prefix and case-insensitively. */\nexport const comparable = (family: string, address: string): string =>\n family === \"evm\" ? address.replace(/^0x/i, \"\").toLowerCase() : address;\n\nconst looksLike = (a: string, b: string): boolean =>\n a !== b &&\n a.length >= POISONING_EDGE * 2 &&\n b.length >= POISONING_EDGE * 2 &&\n a.slice(0, POISONING_EDGE) === b.slice(0, POISONING_EDGE) &&\n a.slice(-POISONING_EDGE) === b.slice(-POISONING_EDGE);\n\n/** Findings for every recipient of one request, deduplicated, `danger` first. */\nexport function assessRecipients(\n family: string,\n recipients: ReadonlyArray<string>,\n known: ReadonlyArray<string>,\n): ReadonlyArray<RiskFinding> {\n const knownSet = new Set(known.map((a) => comparable(family, a)));\n const found = new Map<RiskFinding[\"code\"], RiskFinding>();\n for (const recipient of recipients) {\n const candidate = comparable(family, recipient);\n if (knownSet.has(candidate)) {\n continue;\n }\n found.set(\"first-recipient\", { code: \"first-recipient\", level: \"warning\" });\n if ([...knownSet].some((k) => looksLike(candidate, k))) {\n found.set(\"address-poisoning\", { code: \"address-poisoning\", level: \"danger\" });\n }\n }\n return [...found.values()].sort(\n (a, b) => Number(b.level === \"danger\") - Number(a.level === \"danger\"),\n );\n}\n","/**\n * The signature record: one entry per request that reached a final stage, newest 1000 kept in the\n * engine store. Entries carry a summary only — never signature bytes or the full signable content.\n */\nimport type { SparkAccountRef } from \"@qntx/wallet/protocol\";\n\nimport type { EngineLogger } from \"../events.ts\";\nimport type { EngineStore } from \"../store/port.ts\";\nimport type { AccountRef } from \"../transactions/route.ts\";\nimport type { RequestCheckCode } from \"./checks.ts\";\nimport type { RiskFinding } from \"./risk.ts\";\nimport type { RequestMethod, RequestOrigin } from \"./types.ts\";\n\nexport type SignLogOutcome = \"submitted\" | \"rejected\" | \"failed\" | \"expired\" | \"invalidated\";\n\nexport type SignLogEntry = {\n readonly id: string;\n readonly at: number;\n readonly origin: RequestOrigin;\n readonly method: RequestMethod;\n readonly account: AccountRef | SparkAccountRef;\n readonly network: string;\n readonly summary: string;\n readonly verification: \"verified\" | \"unverifiable\";\n readonly checks: ReadonlyArray<RequestCheckCode>;\n readonly risk: ReadonlyArray<RiskFinding>;\n readonly outcome: SignLogOutcome;\n readonly error?: string;\n};\n\nexport const SIGN_LOG_LIMIT = 1000;\nconst COLLECTION = \"sign-log\";\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null;\n\nconst METHODS: ReadonlySet<unknown> = new Set([\n \"send\",\n \"speed-up\",\n \"cancel\",\n \"cpfp\",\n \"pay\",\n \"zap\",\n \"evm-sign\",\n \"spark-deposit\",\n \"spark-exit\",\n]);\nconst OUTCOMES: ReadonlySet<unknown> = new Set([\n \"submitted\",\n \"rejected\",\n \"failed\",\n \"expired\",\n \"invalidated\",\n]);\nconst FAMILIES: ReadonlySet<unknown> = new Set([\"evm\", \"solana\", \"bitcoin\"]);\n\nconst isAccount = (value: unknown): value is AccountRef | SparkAccountRef => {\n if (!isObject(value)) {\n return false;\n }\n if (value[\"kind\"] === \"hd\") {\n return (\n typeof value[\"walletId\"] === \"string\" &&\n typeof value[\"groupIndex\"] === \"number\" &&\n typeof value[\"template\"] === \"string\"\n );\n }\n if (value[\"kind\"] === \"imported\") {\n return typeof value[\"keyId\"] === \"string\" && FAMILIES.has(value[\"family\"]);\n }\n return (\n value[\"kind\"] === undefined &&\n typeof value[\"walletId\"] === \"string\" &&\n typeof value[\"groupIndex\"] === \"number\" &&\n typeof value[\"network\"] === \"string\"\n );\n};\n\nconst isOrigin = (value: unknown): boolean =>\n isObject(value) &&\n (value[\"kind\"] === \"internal\" ||\n (value[\"kind\"] === \"browser\" && typeof value[\"origin\"] === \"string\"));\n\nconst isEntry = (value: unknown): value is SignLogEntry =>\n isObject(value) &&\n typeof value[\"id\"] === \"string\" &&\n typeof value[\"at\"] === \"number\" &&\n isOrigin(value[\"origin\"]) &&\n METHODS.has(value[\"method\"]) &&\n OUTCOMES.has(value[\"outcome\"]) &&\n isAccount(value[\"account\"]);\n\n/** Sortable key: time first, request id as the tiebreak. */\nconst keyOf = (entry: SignLogEntry): string => `${String(entry.at).padStart(16, \"0\")}-${entry.id}`;\n\nexport type SignLog = {\n readonly open: (store: EngineStore) => void;\n /** Stops writing; entries that arrive afterwards are dropped with a warning. */\n readonly close: () => void;\n readonly append: (entry: SignLogEntry) => Promise<void>;\n /** Newest first. */\n readonly list: () => Promise<ReadonlyArray<SignLogEntry>>;\n readonly clear: () => Promise<void>;\n};\n\nexport function createSignLog(logger: EngineLogger): SignLog {\n let store: EngineStore | undefined;\n\n return {\n open: (next) => {\n store = next;\n },\n close: () => {\n store = undefined;\n },\n append: async (entry) => {\n const current = store;\n if (current === undefined) {\n logger.warn(\n `sign log entry for request ${entry.id} (${entry.outcome}) not written: vault locked`,\n );\n return;\n }\n const collection = current.collection(COLLECTION);\n await collection.put(keyOf(entry), new TextEncoder().encode(JSON.stringify(entry)));\n const keys = [...(await collection.list())].sort();\n await Promise.all(\n keys\n .slice(0, Math.max(0, keys.length - SIGN_LOG_LIMIT))\n .map(async (k) => collection.delete(k)),\n );\n },\n list: async () => {\n if (store === undefined) {\n return [];\n }\n const collection = store.collection(COLLECTION);\n const keys = [...(await collection.list())].sort();\n const rows = await Promise.all(keys.map(async (k) => collection.get(k)));\n const entries: SignLogEntry[] = [];\n for (const raw of rows) {\n if (raw === undefined) {\n continue;\n }\n const parsed: unknown = JSON.parse(new TextDecoder().decode(raw));\n if (isEntry(parsed)) {\n entries.push(parsed);\n }\n }\n return entries.reverse();\n },\n clear: async () => {\n if (store === undefined) {\n return;\n }\n const collection = store.collection(COLLECTION);\n const keys = [...(await collection.list())].sort();\n await Promise.all(keys.map(async (k) => collection.delete(k)));\n },\n };\n}\n","import { WalletError } from \"@qntx/wallet\";\n/**\n * Request pipeline for internal sends, speed-ups, cancellations and CPFP: `prepare` builds,\n * estimates and cross-checks without signing; `approve(id, method, verify)` is the only way to\n * sign, and only for a live, unexpired request of the right method; locking invalidates everything\n * that has not finished. The unsigned content stays in a private table, never in the state\n * snapshot, and cannot change after prepare.\n */\nimport type { SignRequest } from \"@qntx/wallet-chains\";\nimport type { SparkAccountRef } from \"@qntx/wallet/protocol\";\n\nimport type { AddressBookController } from \"../addresses/controller.ts\";\nimport { normalizeAddress } from \"../addresses/normalize.ts\";\nimport { Controller } from \"../controller.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport type { PreparedSparkAction, SparkDisplay, SparkResult } from \"../payments/action.ts\";\nimport { preparePay } from \"../payments/pay.ts\";\nimport type { PayParams } from \"../payments/pay.ts\";\nimport { prepareZapAction } from \"../payments/zap.ts\";\nimport type { PreparedZap } from \"../payments/zap.ts\";\nimport type { SparkController } from \"../spark/controller.ts\";\nimport { SPARK_L1_NETWORK } from \"../spark/l1.ts\";\nimport type { EngineStore } from \"../store/port.ts\";\nimport type { TransactionController } from \"../transactions/controller.ts\";\nimport type {\n AccountRef,\n ChainRequestInput,\n ChainRequestMethod,\n DisplayIntent,\n PrepareParams,\n SendParams,\n SignatureResult,\n TrackedTransaction,\n} from \"../transactions/route.ts\";\nimport { newRequestId } from \"../transactions/route.ts\";\nimport { collectChecks } from \"./checks.ts\";\nimport type { RequestCheckCode } from \"./checks.ts\";\nimport { assessRecipients } from \"./risk.ts\";\nimport type { RiskFinding } from \"./risk.ts\";\nimport { createSignLog } from \"./sign-log.ts\";\nimport type { SignLog, SignLogEntry, SignLogOutcome } from \"./sign-log.ts\";\nimport type { BrowserOrigin, RequestMethod, RequestOrigin } from \"./types.ts\";\n\nexport type { BrowserOrigin, RequestMethod, RequestOrigin } from \"./types.ts\";\n\nexport type { RequestCheckCode } from \"./checks.ts\";\nexport type { RiskFinding } from \"./risk.ts\";\nexport type { SignLogEntry, SignLogOutcome } from \"./sign-log.ts\";\nexport type { SignatureResult } from \"../transactions/route.ts\";\nexport type { SparkDisplay, SparkResult } from \"../payments/action.ts\";\n\n/** A Spark, Lightning (including LNURL-pay and lightning addresses) or cooperative-exit payment. */\nexport type PayInput = { readonly method: \"pay\" } & PayParams;\n\n/** A prepared zap; its invoice was fetched by `engine.zaps.prepare` and is paid as-is. */\nexport type ZapInput = {\n readonly method: \"zap\";\n readonly account: SparkAccountRef;\n readonly zap: PreparedZap;\n readonly maxFeeSats: number;\n};\n\n/**\n * A dApp's EVM request: a transaction (rebuilt here with fresh nonce and fees), a personal message\n * or EIP-712 typed data.\n */\nexport type EvmSignInput = {\n readonly method: \"evm-sign\";\n readonly origin: BrowserOrigin;\n readonly account: AccountRef;\n readonly network: string;\n readonly request: SignRequest;\n};\n\n/**\n * Funds the wallet's own Spark account from a bitcoin account of the same wallet; the transaction\n * is an ordinary bitcoin send to a fresh Spark deposit address and is claimed once confirmed.\n */\nexport type SparkDepositInput = {\n readonly method: \"spark-deposit\";\n readonly account: SparkAccountRef;\n readonly from: AccountRef;\n readonly amountSats: number;\n readonly fee: PrepareParams[\"fee\"];\n};\n\n/** A cooperative exit to the group's own next unused `btc.bip84` receive address. */\nexport type SparkExitInput = {\n readonly method: \"spark-exit\";\n readonly account: SparkAccountRef;\n readonly amountSats: number;\n readonly maxFeeSats: number;\n readonly speed?: \"FAST\" | \"MEDIUM\" | \"SLOW\";\n};\n\nexport type RequestInput =\n | ChainRequestInput\n | PayInput\n | ZapInput\n | EvmSignInput\n | SparkDepositInput\n | SparkExitInput;\n\n/** A request that ended without a result: `stage` says how, `message` is the failure if any. */\nexport class RequestEndedError extends Error {\n readonly stage: \"rejected\" | \"failed\" | \"expired\" | \"invalidated\";\n constructor(stage: RequestEndedError[\"stage\"], message: string | undefined) {\n super(message ?? `request ${stage}`);\n this.name = \"RequestEndedError\";\n this.stage = stage;\n }\n}\n\n/** The origin already has a request in flight; a dApp gets one at a time. */\nexport class OriginBusyError extends Error {\n constructor(origin: string) {\n super(`${origin} already has an unfinished request`);\n this.name = \"OriginBusyError\";\n }\n}\n\nexport type RequestStage =\n | \"awaiting-approval\"\n | \"signing\"\n | \"submitted\"\n | \"rejected\"\n | \"failed\"\n | \"expired\"\n | \"invalidated\";\n\nexport type PendingRequest = {\n readonly id: string;\n readonly origin: RequestOrigin;\n readonly method: RequestMethod;\n readonly account: AccountRef | SparkAccountRef;\n readonly network: string;\n readonly stage: RequestStage;\n /** Decoded locally from the exact content that will be signed; `family` tells the shapes apart. */\n readonly display: DisplayIntent | SparkDisplay;\n /** `unverifiable` as soon as any check is recorded; the host must ask for explicit confirmation. */\n readonly verification: \"verified\" | \"unverifiable\";\n readonly checks: ReadonlyArray<RequestCheckCode>;\n /**\n * Recipient risk; independent of `verification`. A `danger` needs the user's explicit\n * acknowledgement.\n */\n readonly risk: ReadonlyArray<RiskFinding>;\n readonly createdAt: number;\n readonly expiresAt: number;\n /** The transaction being replaced or accelerated; absent for a plain send. */\n readonly target?: string;\n /** The tracked transaction once submitted. */\n readonly txId?: string;\n readonly error?: string;\n};\n\nexport type RequestControllerState = {\n readonly requests: Record<string, PendingRequest>;\n};\n\nexport type RequestControllerOptions = {\n readonly transactions: TransactionController;\n /** The full controller: its payment methods are reachable only through this pipeline. */\n readonly spark: SparkController;\n readonly addressBook: AddressBookController;\n readonly openStore: () => Promise<EngineStore>;\n readonly fetch: typeof globalThis.fetch;\n readonly random: (n: number) => Uint8Array;\n readonly now: () => number;\n readonly setTimer: (ms: number, fn: () => unknown) => () => void;\n readonly logger: EngineLogger;\n};\n\n/** Requests expire this long after creation. */\nexport const REQUEST_TTL_MS = 10 * 60 * 1000;\n\n/** What approval needs from a prepared request, whichever kind it is. */\ntype Run = {\n /** The tracked transaction `submit` creates (chain requests only). */\n readonly txId?: string;\n readonly staleReason: () => string | undefined | Promise<string | undefined>;\n readonly submit: (\n verify: SendParams[\"verify\"],\n ) => Promise<TrackedTransaction | SparkResult | SignatureResult>;\n readonly release: () => void;\n};\n\ntype Built = {\n readonly account: AccountRef | SparkAccountRef;\n readonly network: string;\n readonly display: DisplayIntent | SparkDisplay;\n readonly checks: ReadonlyArray<RequestCheckCode>;\n readonly risk: ReadonlyArray<RiskFinding>;\n readonly run: Run;\n};\n\ntype Settler = {\n readonly promise: Promise<TrackedTransaction | SparkResult | SignatureResult>;\n readonly resolve: (value: TrackedTransaction | SparkResult | SignatureResult) => void;\n readonly reject: (error: Error) => void;\n};\n\ntype Entry = {\n readonly prepared: Run;\n readonly stopTimer: () => void;\n};\n\nconst originKey = (origin: BrowserOrigin): string => `origin:${origin.origin}`;\n\nconst LIVE: ReadonlySet<RequestStage> = new Set([\"awaiting-approval\", \"signing\"]);\n\nconst errorMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\nexport class RequestController extends Controller<RequestControllerState> {\n private readonly options: RequestControllerOptions;\n private readonly entries = new Map<string, Entry>();\n private readonly log: SignLog;\n private readonly settlers = new Map<string, Settler>();\n /** Original transaction id → the unfinished request replacing or accelerating it. */\n private readonly targets = new Map<string, string>();\n private locked = true;\n /** Bumped on every unlock and lock so work that outlives a session never touches the next one. */\n private session = 0;\n\n constructor(options: RequestControllerOptions) {\n super({ name: \"requests\", defaultState: () => ({ requests: {} }) });\n this.options = options;\n this.log = createSignLog(options.logger);\n }\n\n async init(): Promise<void> {\n this.session += 1;\n this.locked = false;\n this.entries.clear();\n this.targets.clear();\n this.settlers.clear();\n this.update(() => ({ requests: {} }));\n this.log.open(await this.options.openStore());\n }\n\n async destroy(): Promise<void> {\n this.lock();\n await Promise.resolve();\n }\n\n /** Locking is not consent: every unfinished request becomes `invalidated` and frees its resources. */\n lock(): void {\n this.session += 1;\n this.locked = true;\n for (const [id, request] of Object.entries(this.getState().requests)) {\n if (LIVE.has(request.stage)) {\n this.finish(id, \"invalidated\");\n }\n }\n this.log.close();\n }\n\n /** A page navigated away, was revoked or changed network: its unfinished requests are void. */\n invalidateOrigin(origin: string): void {\n for (const [id, request] of Object.entries(this.getState().requests)) {\n if (\n LIVE.has(request.stage) &&\n request.origin.kind === \"browser\" &&\n request.origin.origin === origin\n ) {\n this.finish(id, \"invalidated\");\n }\n }\n }\n\n /** The signature record, newest first. */\n async signLog(): Promise<ReadonlyArray<SignLogEntry>> {\n return this.log.list();\n }\n\n async clearSignLog(): Promise<void> {\n await this.log.clear();\n }\n\n async prepare(input: RequestInput): Promise<PendingRequest> {\n if (this.locked) {\n throw new Error(\"requests require an unlocked vault\");\n }\n const { session } = this;\n const id = newRequestId(this.options.random);\n // A transaction can have one unfinished replacement at a time; claimed synchronously so two\n // concurrent prepares cannot both pass.\n const target = \"txId\" in input ? input.txId : undefined;\n if (input.method === \"evm-sign\") {\n const key = originKey(input.origin);\n if (this.targets.has(key)) {\n throw new OriginBusyError(input.origin.origin);\n }\n this.targets.set(key, id);\n }\n if (target !== undefined) {\n if (this.targets.has(target)) {\n throw new Error(`transaction ${target} already has an unfinished replacement request`);\n }\n this.targets.set(target, id);\n }\n let built: Built;\n try {\n built = await this.build(input, id);\n } catch (error) {\n this.unclaim(id);\n throw error;\n }\n if (session !== this.session) {\n built.run.release();\n this.unclaim(id);\n throw new Error(\"the vault was locked while the request was being prepared\");\n }\n const { checks } = built;\n const createdAt = this.options.now();\n const request: PendingRequest = {\n id,\n origin: input.method === \"evm-sign\" ? input.origin : { kind: \"internal\" },\n method: input.method,\n account: built.account,\n network: built.network,\n ...(target === undefined ? {} : { target }),\n stage: \"awaiting-approval\",\n display: built.display,\n verification: checks.length > 0 ? \"unverifiable\" : \"verified\",\n checks,\n risk: built.risk,\n createdAt,\n expiresAt: createdAt + REQUEST_TTL_MS,\n };\n const stopTimer = this.options.setTimer(REQUEST_TTL_MS, () => {\n if (this.getState().requests[id]?.stage === \"awaiting-approval\") {\n this.finish(id, \"expired\");\n }\n });\n this.entries.set(id, { prepared: built.run, stopTimer });\n this.put(request);\n this.openSettler(id);\n return request;\n }\n\n /**\n * Resolves with what `approve` returned, or rejects with `RequestEndedError` when the request\n * ends any other way — how a dApp's pending call learns the outcome.\n */\n async outcome(id: string): Promise<TrackedTransaction | SparkResult | SignatureResult> {\n const settler = this.settlers.get(id);\n if (settler === undefined) {\n throw new Error(`unknown request ${id}`);\n }\n return settler.promise;\n }\n\n private openSettler(id: string): void {\n const holder: { resolve?: Settler[\"resolve\"]; reject?: Settler[\"reject\"] } = {};\n const promise = new Promise<TrackedTransaction | SparkResult | SignatureResult>(\n (resolve, reject) => {\n holder.resolve = resolve;\n holder.reject = reject;\n },\n );\n // The caller may never ask; marking it observed keeps a rejection from surfacing.\n void Promise.allSettled([promise]);\n this.settlers.set(id, {\n promise,\n resolve: (value) => holder.resolve?.(value),\n reject: (error) => holder.reject?.(error),\n });\n }\n\n private settle(\n id: string,\n result: TrackedTransaction | SparkResult | SignatureResult | Error,\n ): void {\n const settler = this.settlers.get(id);\n if (settler === undefined) {\n return;\n }\n if (result instanceof Error) {\n settler.reject(result);\n } else {\n settler.resolve(result);\n }\n }\n\n /** The bitcoin network `account`'s Spark network settles on; any other pairing is refused. */\n private l1Network(account: SparkAccountRef): string {\n const network = SPARK_L1_NETWORK[account.network] as string | undefined;\n if (network === undefined) {\n throw new Error(`unknown Spark network ${account.network}`);\n }\n return network;\n }\n\n private sparkBuilt(account: SparkAccountRef, action: PreparedSparkAction): Built {\n return {\n account,\n network: action.display.network,\n display: action.display,\n checks: collectChecks(action.checks),\n risk: this.sparkRisk(action.display),\n run: {\n staleReason: () => action.staleReason(this.options.now()),\n submit: async (verify) => action.execute(this.options.spark, verify),\n release: () => undefined,\n },\n };\n }\n\n private async build(input: RequestInput, id: string): Promise<Built> {\n if (input.method === \"pay\" || input.method === \"zap\") {\n const action: PreparedSparkAction =\n input.method === \"pay\"\n ? await preparePay({ fetch: this.options.fetch, now: this.options.now }, input)\n : prepareZapAction(input.account, input.zap, {\n maxFeeSats: input.maxFeeSats,\n now: this.options.now,\n });\n return this.sparkBuilt(input.account, action);\n }\n if (input.method === \"spark-deposit\") {\n const l1 = this.l1Network(input.account);\n if (input.from.kind !== \"hd\" || input.from.walletId !== input.account.walletId) {\n throw new Error(\"a Spark deposit must come from the same wallet\");\n }\n const to = await this.options.spark.newDepositAddress(input.account);\n const prepared = await this.options.transactions.prepareSend(\n { account: input.from, network: l1, to, amount: BigInt(input.amountSats), fee: input.fee },\n id,\n {\n walletId: input.account.walletId,\n groupIndex: input.account.groupIndex,\n network: input.account.network,\n },\n );\n return {\n account: prepared.account,\n network: prepared.network,\n display: prepared.intent,\n checks: collectChecks([\n prepared.intent.verifiability === \"full\" ? undefined : \"decode-partial\",\n ...prepared.checks,\n ]),\n risk: [],\n run: prepared,\n };\n }\n if (input.method === \"spark-exit\") {\n const l1 = this.l1Network(input.account);\n const address = await this.options.transactions.nextReceiveAddress(\n input.account.walletId,\n input.account.groupIndex,\n l1,\n );\n const action = await preparePay(\n { fetch: this.options.fetch, now: this.options.now },\n {\n account: input.account,\n option: { kind: \"bitcoin\", address },\n amountSats: input.amountSats,\n maxFeeSats: input.maxFeeSats,\n ...(input.speed === undefined ? {} : { speed: input.speed }),\n },\n );\n return this.sparkBuilt(input.account, action);\n }\n if (input.method === \"evm-sign\") {\n const prepared = await this.options.transactions.prepareDapp(input.account, input.request);\n const isTransaction = input.request.kind === \"evm.transaction\";\n return {\n account: prepared.account,\n network: prepared.network,\n display: prepared.intent,\n checks: collectChecks([\n isTransaction && prepared.intent.verifiability !== \"full\" ? \"decode-partial\" : undefined,\n ...prepared.checks,\n ]),\n risk: isTransaction ? this.chainRisk(prepared.intent) : [],\n run: prepared,\n };\n }\n const prepared =\n input.method === \"send\"\n ? await this.options.transactions.prepareSend(input, id)\n : await this.options.transactions.prepareReplacement(input, id);\n return {\n account: prepared.account,\n network: prepared.network,\n display: prepared.intent,\n checks: collectChecks([\n prepared.intent.verifiability === \"full\" ? undefined : \"decode-partial\",\n ...prepared.checks,\n ]),\n risk: input.method === \"send\" ? this.chainRisk(prepared.intent) : [],\n run: prepared,\n };\n }\n\n /**\n * Signs and submits a request. Anything but a live, unexpired `send` request with this id throws\n * before any signing; a stale build (nonce taken, blockhash expired) fails without signing.\n */\n async approve(\n id: string,\n method: ChainRequestMethod | \"spark-deposit\",\n verify: SendParams[\"verify\"],\n ): Promise<TrackedTransaction>;\n async approve(\n id: string,\n method: \"pay\" | \"zap\" | \"spark-exit\",\n verify: SendParams[\"verify\"],\n ): Promise<SparkResult>;\n async approve(\n id: string,\n method: \"evm-sign\",\n verify: SendParams[\"verify\"],\n ): Promise<TrackedTransaction | SignatureResult>;\n async approve(\n id: string,\n method: RequestMethod,\n verify: SendParams[\"verify\"],\n ): Promise<TrackedTransaction | SparkResult | SignatureResult> {\n const request = this.getState().requests[id];\n if (request === undefined) {\n throw new Error(`unknown request ${id}`);\n }\n if (request.method !== method) {\n throw new Error(`request ${id} is a ${request.method} request, not ${method}`);\n }\n const entry = this.entries.get(id);\n if (request.stage !== \"awaiting-approval\" || entry === undefined) {\n throw new Error(`request ${id} is ${request.stage}, not awaiting approval`);\n }\n if (this.options.now() >= request.expiresAt) {\n this.finish(id, \"expired\");\n throw new Error(`request ${id} expired`);\n }\n const { session } = this;\n this.put({ ...request, stage: \"signing\" });\n\n let stale: string | undefined;\n try {\n stale = await entry.prepared.staleReason();\n } catch (error) {\n stale = errorMessage(error);\n }\n if (session !== this.session) {\n throw new Error(`request ${id} was invalidated`);\n }\n if (stale !== undefined) {\n this.finish(id, \"failed\", stale);\n throw new Error(stale);\n }\n try {\n const result = await entry.prepared.submit(verify);\n if (session === this.session) {\n entry.stopTimer();\n this.entries.delete(id);\n this.unclaim(id);\n const done: PendingRequest = {\n ...this.requireRequest(id),\n stage: \"submitted\",\n ...(\"id\" in result ? { txId: result.id } : {}),\n };\n this.put(done);\n this.record(done, \"submitted\");\n } else {\n this.record(request, \"submitted\");\n }\n this.settle(id, result);\n return result;\n } catch (error) {\n if (session === this.session) {\n this.finish(id, this.failureStage(entry.prepared, error), errorMessage(error));\n } else {\n this.record(request, \"failed\", errorMessage(error));\n }\n throw error;\n }\n }\n\n /**\n * A cancelled or refused verification is `rejected`; anything after it is `failed`. Chain\n * requests record which step failed on the tracked transaction; for Spark, the approval round is\n * the only source of `WalletError`.\n */\n private failureStage(run: Run, error: unknown): \"rejected\" | \"failed\" {\n if (run.txId === undefined) {\n return error instanceof WalletError ? \"rejected\" : \"failed\";\n }\n return this.options.transactions.getState().txs[run.txId]?.state === \"rejected\"\n ? \"rejected\"\n : \"failed\";\n }\n\n reject(id: string): void {\n const request = this.getState().requests[id];\n if (request === undefined) {\n throw new Error(`unknown request ${id}`);\n }\n if (request.stage !== \"awaiting-approval\") {\n throw new Error(`request ${id} is ${request.stage}, not awaiting approval`);\n }\n this.finish(id, \"rejected\");\n }\n\n private requireRequest(id: string): PendingRequest {\n const request = this.getState().requests[id];\n if (request === undefined) {\n throw new Error(`unknown request ${id}`);\n }\n return request;\n }\n\n private put(request: PendingRequest): void {\n this.update((s) => ({ ...s, requests: { ...s.requests, [request.id]: request } }));\n }\n\n private unclaim(requestId: string): void {\n for (const [target, holder] of this.targets) {\n if (holder === requestId) {\n this.targets.delete(target);\n }\n }\n }\n\n /** Ends a request in a terminal stage and frees what it reserved. */\n private finish(\n id: string,\n stage: \"rejected\" | \"failed\" | \"expired\" | \"invalidated\",\n error?: string,\n ): void {\n this.unclaim(id);\n const entry = this.entries.get(id);\n if (entry !== undefined) {\n entry.stopTimer();\n this.entries.delete(id);\n try {\n entry.prepared.release();\n } catch (releaseError) {\n this.options.logger.warn(\"request release failed\", releaseError);\n }\n }\n const request = this.getState().requests[id];\n if (request !== undefined) {\n const ended: PendingRequest = {\n ...request,\n stage,\n ...(error === undefined ? {} : { error }),\n };\n this.put(ended);\n this.record(ended, stage, error);\n this.settle(id, new RequestEndedError(stage, error));\n }\n }\n\n /** Appends the final stage to the signature record; a failed write is a warning, not an error. */\n private record(request: PendingRequest, outcome: SignLogOutcome, error?: string): void {\n const { display } = request;\n const entry: SignLogEntry = {\n id: request.id,\n at: this.options.now(),\n origin: request.origin,\n method: request.method,\n account: request.account,\n network: request.network,\n summary: \"summary\" in display ? display.summary : `${display.kind} ${display.amountSats}`,\n verification: request.verification,\n checks: request.checks,\n risk: request.risk,\n outcome,\n ...(error === undefined ? {} : { error }),\n };\n void this.appendLog(entry);\n }\n\n private async appendLog(entry: SignLogEntry): Promise<void> {\n try {\n await this.log.append(entry);\n } catch (error) {\n this.options.logger.warn(\"sign log write failed\", error);\n }\n }\n\n /**\n * Addresses the wallet already knows for a family: contacts, plus recipients of tracked chain\n * sends (Spark payments are not tracked).\n */\n private knownAddresses(family: string): ReadonlyArray<string> {\n const contacts = Object.values(this.options.addressBook.getState().entries)\n .filter((e) => e.family === family)\n .map((e) => e.address);\n if (family === \"spark\") {\n return contacts;\n }\n const paid = Object.values(this.options.transactions.getState().txs)\n .filter(\n (tx) =>\n tx.family === family &&\n (tx.state === \"submitted\" || tx.state === \"pending\" || tx.state === \"confirmed\"),\n )\n .flatMap((tx) => tx.intent?.outflows.map((o) => o.to) ?? []);\n return [...contacts, ...paid];\n }\n\n private chainRisk(intent: DisplayIntent): ReadonlyArray<RiskFinding> {\n return assessRecipients(\n intent.family,\n intent.outflows.map((o) => o.to),\n this.knownAddresses(intent.family),\n );\n }\n\n /** Only a Spark transfer has a recipient to check; Lightning and exits are not assessed. */\n private sparkRisk(display: SparkDisplay): ReadonlyArray<RiskFinding> {\n if (display.kind !== \"transfer\") {\n return [];\n }\n const receiver = normalizeAddress(\"spark\", display.receiver) ?? display.receiver;\n return assessRecipients(\"spark\", [receiver], this.knownAddresses(\"spark\"));\n }\n}\n","import { bytesToHex, hexToBytes } from \"@noble/hashes/utils.js\";\n\n/**\n * Platform-neutral EIP-1193 provider logic: it knows nothing about WebViews. The host hands it a\n * page's origin (computed from the WebView's top-level URL, never from the page) and a JSON-RPC\n * call; signing goes through the request pipeline and waits for the host's approval by id.\n */\nimport { ChainError } from \"@qntx/wallet-chains\";\nimport type { SignRequest } from \"@qntx/wallet-chains\";\n\nimport { EVM_RPC_METHODS } from \"../gateway/contract/rpc.ts\";\nimport type { NetworkController } from \"../networks/controller.ts\";\nimport { OriginBusyError, RequestEndedError } from \"../requests/controller.ts\";\nimport type { RequestController } from \"../requests/controller.ts\";\nimport type { AccountGroup, ConnectionController, ConnectionSession } from \"./controller.ts\";\nimport { evmChainId } from \"./controller.ts\";\nimport {\n ProviderError,\n internalError,\n invalidParams,\n unauthorized,\n unrecognizedChain,\n unsupportedMethod,\n userRejectedRequest,\n} from \"./errors.ts\";\n\nexport type Eip1193Request = { readonly method: string; readonly params?: unknown };\n\nexport type Eip1193Event =\n | { readonly name: \"connect\"; readonly origin: string; readonly chainId: string }\n | {\n readonly name: \"accountsChanged\";\n readonly origin: string;\n readonly accounts: ReadonlyArray<string>;\n }\n | { readonly name: \"chainChanged\"; readonly origin: string; readonly chainId: string }\n | { readonly name: \"disconnect\"; readonly origin: string };\n\nexport type Eip1193HandlerOptions = {\n readonly connections: ConnectionController;\n readonly requests: RequestController;\n readonly networks: NetworkController;\n /** The network an unconnected page sees. */\n readonly defaultNetwork: () => string;\n};\n\n/** Refused outright, whatever the session. */\nconst REFUSED: ReadonlySet<string> = new Set([\n \"eth_sign\",\n \"eth_signTypedData\",\n \"eth_signTypedData_v3\",\n \"eth_signTransaction\",\n \"eth_sendRawTransaction\",\n]);\n\n/** Planned for later layers; answered `4200` until then. */\nconst DEFERRED: ReadonlySet<string> = new Set([\n \"wallet_addEthereumChain\",\n \"wallet_watchAsset\",\n \"wallet_sendCalls\",\n \"wallet_getCallsStatus\",\n \"wallet_getCapabilities\",\n \"wallet_showCallsStatus\",\n]);\n\nconst READ_ONLY: ReadonlySet<string> = new Set(\n EVM_RPC_METHODS.filter((m) => m !== \"eth_sendRawTransaction\" && m !== \"eth_chainId\"),\n);\n\nconst hexChainId = (network: string): string => `0x${(evmChainId(network) ?? 0).toString(16)}`;\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\nconst paramList = (params: unknown): ReadonlyArray<unknown> => {\n if (params === undefined) {\n return [];\n }\n if (!Array.isArray(params)) {\n throw invalidParams(\"params must be an array\");\n }\n return params;\n};\n\nconst textBytes = (value: unknown): Uint8Array => {\n if (typeof value !== \"string\") {\n throw invalidParams(\"message must be a string\");\n }\n if (/^0x(?:[0-9a-fA-F]{2})*$/.test(value)) {\n const bytes = hexToBytes(value.slice(2));\n try {\n new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch {\n throw new ProviderError(4200, \"blind signing is not enabled: the message is not UTF-8 text\");\n }\n return bytes;\n }\n return new TextEncoder().encode(value);\n};\n\nconst quantityOf = (value: unknown, field: string, fallback: string): string => {\n if (value === undefined) {\n return fallback;\n }\n if (typeof value !== \"string\" || !/^0x[0-9a-fA-F]+$/.test(value)) {\n throw invalidParams(`${field} must be a 0x quantity`);\n }\n return value;\n};\n\nexport class Eip1193Handler {\n private readonly options: Eip1193HandlerOptions;\n private readonly listeners = new Set<(event: Eip1193Event) => void>();\n private unsubscribe: (() => void) | undefined;\n\n constructor(options: Eip1193HandlerOptions) {\n this.options = options;\n }\n\n /** Events for the host to forward to pages; derived from changes to the sessions. */\n subscribe(listener: (event: Eip1193Event) => void): () => void {\n this.listeners.add(listener);\n if (this.unsubscribe === undefined) {\n let previous = this.options.connections.getState().sessions;\n this.unsubscribe = this.options.connections.store.subscribe((state) => {\n for (const event of diffSessions(previous, state.sessions)) {\n for (const l of this.listeners) {\n l(event);\n }\n }\n previous = state.sessions;\n });\n }\n return () => {\n this.listeners.delete(listener);\n if (this.listeners.size === 0) {\n this.unsubscribe?.();\n this.unsubscribe = undefined;\n }\n };\n }\n\n async handle(origin: string, request: Eip1193Request): Promise<unknown> {\n const { connections } = this.options;\n connections.checkOrigin(origin);\n const { method } = request;\n const params = paramList(request.params);\n if (REFUSED.has(method) || DEFERRED.has(method)) {\n throw unsupportedMethod(method);\n }\n switch (method) {\n case \"eth_accounts\":\n return connections.accounts(origin);\n case \"eth_chainId\":\n return hexChainId(\n connections.session(origin)?.currentNetwork ?? this.options.defaultNetwork(),\n );\n case \"eth_requestAccounts\":\n return this.requestAccounts(origin);\n case \"wallet_requestPermissions\":\n await this.requestAccounts(origin);\n return this.permissions(origin);\n case \"wallet_getPermissions\":\n return this.permissions(origin);\n case \"wallet_revokePermissions\":\n await connections.revoke(origin);\n return null;\n case \"wallet_switchEthereumChain\":\n return this.switchChain(origin, params[0]);\n case \"personal_sign\":\n return this.personalSign(origin, params);\n case \"eth_signTypedData_v4\":\n return this.typedData(origin, params);\n case \"eth_sendTransaction\":\n return this.sendTransaction(origin, params[0]);\n default:\n break;\n }\n if (READ_ONLY.has(method)) {\n return this.read(origin, method, params);\n }\n throw new ProviderError(-32601, `${method} does not exist`);\n }\n\n private async requestAccounts(origin: string): Promise<ReadonlyArray<string>> {\n const { connections } = this.options;\n if (connections.accounts(origin).length === 0) {\n await connections.request(origin, \"connect\");\n }\n await connections.touch(origin);\n return connections.accounts(origin);\n }\n\n private permissions(origin: string): ReadonlyArray<unknown> {\n const accounts = this.options.connections.accounts(origin);\n if (accounts.length === 0) {\n return [];\n }\n return [\n {\n parentCapability: \"eth_accounts\",\n invoker: origin,\n caveats: [{ type: \"restrictReturnedAccounts\", value: accounts }],\n },\n ];\n }\n\n private async switchChain(origin: string, arg: unknown): Promise<unknown> {\n const { connections } = this.options;\n const chainId = isObject(arg) ? arg[\"chainId\"] : undefined;\n if (typeof chainId !== \"string\" || !/^0x[0-9a-fA-F]+$/.test(chainId)) {\n throw invalidParams(\"chainId must be a 0x quantity\");\n }\n const network = `eip155:${Number.parseInt(chainId, 16)}`;\n if (!connections.isEnabled(network)) {\n throw unrecognizedChain(`chain ${chainId} is not enabled`);\n }\n const session = connections.session(origin);\n if (session === undefined) {\n throw unauthorized();\n }\n if (session.scopes[network] === undefined) {\n await connections.request(origin, \"network\", network);\n } else if (session.currentNetwork !== network) {\n await connections.setCurrentNetwork(origin, network);\n }\n return null;\n }\n\n private authorizedAccount(session: ConnectionSession, address: unknown): string {\n const accounts = this.options.connections.accounts(session.origin.origin);\n const wanted = typeof address === \"string\" ? address.toLowerCase() : accounts[0];\n if (wanted === undefined || !accounts.some((a) => a.toLowerCase() === wanted.toLowerCase())) {\n throw unauthorized(\"account not authorized\");\n }\n return wanted;\n }\n\n private async personalSign(origin: string, params: ReadonlyArray<unknown>): Promise<string> {\n const session = this.signingSession(origin, \"personal_sign\");\n this.authorizedAccount(session, params[1]);\n const message = textBytes(params[0]);\n return this.sign(origin, session, (account) => ({\n kind: \"evm.personal-message\",\n network: session.currentNetwork,\n account,\n message,\n }));\n }\n\n private async typedData(origin: string, params: ReadonlyArray<unknown>): Promise<string> {\n const session = this.signingSession(origin, \"eth_signTypedData_v4\");\n this.authorizedAccount(session, params[0]);\n const [, source] = params;\n const typedData = typeof source === \"string\" ? source : JSON.stringify(source);\n return this.sign(origin, session, (account) => ({\n kind: \"evm.typed-data\",\n network: session.currentNetwork,\n account,\n typedData,\n }));\n }\n\n private async sendTransaction(origin: string, arg: unknown): Promise<string> {\n const session = this.signingSession(origin, \"eth_sendTransaction\");\n if (!isObject(arg)) {\n throw invalidParams(\"transaction must be an object\");\n }\n this.authorizedAccount(session, arg[\"from\"]);\n const chainId = evmChainId(session.currentNetwork);\n if (chainId === undefined) {\n throw internalError(\"session network is not an EVM network\");\n }\n if (arg[\"chainId\"] !== undefined && Number(arg[\"chainId\"]) !== chainId) {\n throw invalidParams(\"transaction chainId does not match the session network\");\n }\n const data = arg[\"data\"] ?? arg[\"input\"] ?? \"0x\";\n if (typeof data !== \"string\") {\n throw invalidParams(\"data must be a hex string\");\n }\n const { to } = arg;\n if (to !== undefined && typeof to !== \"string\") {\n throw invalidParams(\"to must be an address\");\n }\n // Only to, value, data and gas survive; nonce and fees are placeholders the pipeline replaces.\n return this.sign(origin, session, (account) => ({\n kind: \"evm.transaction\",\n network: session.currentNetwork,\n account,\n tx: {\n type: \"eip1559\",\n chainId,\n nonce: 0,\n gas: quantityOf(arg[\"gas\"], \"gas\", \"0x0\"),\n value: quantityOf(arg[\"value\"], \"value\", \"0x0\"),\n data,\n ...(to === undefined ? {} : { to }),\n accessList: [],\n maxFeePerGas: \"0x0\",\n maxPriorityFeePerGas: \"0x0\",\n },\n }));\n }\n\n private signingSession(origin: string, method: string): ConnectionSession {\n const { connections } = this.options;\n const session = connections.session(origin);\n if (session === undefined) {\n throw unauthorized();\n }\n return connections.authorize(origin, session.currentNetwork, method);\n }\n\n private async sign(\n origin: string,\n session: ConnectionSession,\n build: (account: SignRequest[\"account\"]) => SignRequest,\n ): Promise<string> {\n const { connections, requests } = this.options;\n const group: AccountGroup | undefined = connections.activeGroup();\n if (group === undefined) {\n throw internalError(\"no account group is selected\");\n }\n const account = { kind: \"hd\", ...group, template: \"evm.bip44\" } as const;\n try {\n const pending = await requests.prepare({\n method: \"evm-sign\",\n origin: { kind: \"browser\", origin },\n account,\n network: session.currentNetwork,\n request: build(account),\n });\n const result = await requests.outcome(pending.id);\n await connections.touch(origin);\n if (\"signature\" in result && result.signature instanceof Uint8Array) {\n return `0x${bytesToHex(result.signature)}`;\n }\n if (!(\"hash\" in result) || typeof result.hash !== \"string\") {\n throw internalError(\"the transaction has no hash\");\n }\n return result.hash;\n } catch (error) {\n throw toProviderError(error);\n }\n }\n\n private async read(\n origin: string,\n method: string,\n params: ReadonlyArray<unknown>,\n ): Promise<unknown> {\n const { connections, networks } = this.options;\n const network = connections.session(origin)?.currentNetwork ?? this.options.defaultNetwork();\n try {\n return await networks.client(network).transport.request({ method, params: [...params] });\n } catch (error) {\n throw toProviderError(error);\n }\n }\n}\n\nfunction toProviderError(error: unknown): ProviderError {\n if (error instanceof ProviderError) {\n return error;\n }\n if (error instanceof OriginBusyError) {\n return userRejectedRequest(error.message);\n }\n if (error instanceof RequestEndedError) {\n return error.stage === \"failed\"\n ? internalError(error.message)\n : userRejectedRequest(error.message);\n }\n if (error instanceof ChainError) {\n return invalidParams(error.message);\n }\n return internalError(error instanceof Error ? error.message : String(error));\n}\n\nfunction currentAccounts(session: ConnectionSession): ReadonlyArray<string> {\n return (\n session.scopes[session.currentNetwork]?.accounts.map((a) => a.slice(a.lastIndexOf(\":\") + 1)) ??\n []\n );\n}\n\nconst byOrigin = (sessions: Readonly<Record<string, ConnectionSession>>) =>\n new Map(Object.values(sessions).map((s) => [s.origin.origin, s]));\n\nfunction diffSessions(\n before: Readonly<Record<string, ConnectionSession>>,\n after: Readonly<Record<string, ConnectionSession>>,\n): ReadonlyArray<Eip1193Event> {\n const events: Eip1193Event[] = [];\n const prev = byOrigin(before);\n const next = byOrigin(after);\n for (const [origin, session] of prev) {\n const now = next.get(origin);\n if (now === undefined) {\n events.push({ name: \"disconnect\", origin });\n continue;\n }\n if (now.currentNetwork !== session.currentNetwork) {\n events.push({ name: \"chainChanged\", origin, chainId: hexChainId(now.currentNetwork) });\n }\n const was = currentAccounts(session).join(\",\");\n const is = currentAccounts(now).join(\",\");\n if (was !== is) {\n events.push({ name: \"accountsChanged\", origin, accounts: currentAccounts(now) });\n }\n }\n for (const [origin, session] of next) {\n if (!prev.has(origin)) {\n events.push({ name: \"connect\", origin, chainId: hexChainId(session.currentNetwork) });\n }\n }\n return events;\n}\n","export type AddressBookErrorCategory =\n | \"invalid-input\"\n | \"duplicate\"\n | \"not-found\"\n | \"locked\"\n | \"limit\";\n\nexport class AddressBookError extends Error {\n readonly category: AddressBookErrorCategory;\n\n constructor(category: AddressBookErrorCategory, message: string) {\n super(message);\n this.name = \"AddressBookError\";\n this.category = category;\n }\n}\n","/**\n * The address-book record shared by the controller, the sync merge and the metadata document: a\n * live entry, or a tombstone that carries a deletion to the other devices.\n */\nimport { normalizeAddress } from \"./normalize.ts\";\nimport type { AddressFamily } from \"./normalize.ts\";\n\nexport type AddressBookEntry = {\n readonly id: string;\n readonly name: string;\n readonly family: AddressFamily;\n readonly address: string;\n readonly note?: string;\n readonly createdAt: number;\n readonly updatedAt: number;\n};\n\nexport type AddressBookTombstone = {\n readonly id: string;\n readonly deleted: true;\n readonly updatedAt: number;\n};\n\nexport type AddressBookRecord = AddressBookEntry | AddressBookTombstone;\n\nexport const isTombstone = (record: AddressBookRecord): record is AddressBookTombstone =>\n \"deleted\" in record;\n\nexport const NAME_MAX = 32;\nexport const NOTE_MAX = 120;\n\nconst isFamily = (v: unknown): v is AddressFamily =>\n v === \"evm\" || v === \"solana\" || v === \"bitcoin\" || v === \"spark\";\nconst ENTRY_KEYS: ReadonlySet<string> = new Set([\n \"id\",\n \"name\",\n \"family\",\n \"address\",\n \"note\",\n \"createdAt\",\n \"updatedAt\",\n]);\nconst TOMBSTONE_KEYS: ReadonlySet<string> = new Set([\"id\", \"deleted\", \"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\n/** Trimmed name, or `undefined` when it is not 1 to {@link NAME_MAX} characters. */\nexport const cleanName = (raw: string): string | undefined => {\n const name = raw.trim();\n return name.length > 0 && name.length <= NAME_MAX ? name : undefined;\n};\n\n/** Trimmed note; an empty one means no note. `undefined` return with `ok: false` when too long. */\nexport const cleanNote = (\n raw: string | undefined,\n): { readonly ok: true; readonly note: string | undefined } | { readonly ok: false } => {\n const note = raw?.trim();\n if (note === undefined || note.length === 0) {\n return { ok: true, note: undefined };\n }\n return note.length <= NOTE_MAX ? { ok: true, note } : { ok: false };\n};\n\nconst hasOnly = (value: Record<string, unknown>, keys: ReadonlySet<string>): boolean =>\n Object.keys(value).every((k) => keys.has(k));\n\n/**\n * Strict decode with the controller's rules; the address is re-normalized. Anything else is\n * `undefined`.\n */\nexport function decodeRecord(value: unknown): AddressBookRecord | undefined {\n if (\n !isObject(value) ||\n typeof value[\"id\"] !== \"string\" ||\n !isNonNegativeInt(value[\"updatedAt\"])\n ) {\n return undefined;\n }\n if (\"deleted\" in value) {\n return value[\"deleted\"] === true && hasOnly(value, TOMBSTONE_KEYS)\n ? { id: value[\"id\"], deleted: true, updatedAt: value[\"updatedAt\"] }\n : undefined;\n }\n const { family, name, address, note } = value;\n if (\n !hasOnly(value, ENTRY_KEYS) ||\n !isFamily(family) ||\n typeof name !== \"string\" ||\n typeof address !== \"string\" ||\n !isNonNegativeInt(value[\"createdAt\"]) ||\n (note !== undefined && typeof note !== \"string\")\n ) {\n return undefined;\n }\n const cleanedName = cleanName(name);\n const normalized = normalizeAddress(family, address);\n const cleanedNote = cleanNote(note);\n // A stored note is never empty: an empty string was already dropped when it was written.\n if (\n cleanedName === undefined ||\n normalized === undefined ||\n !cleanedNote.ok ||\n (note !== undefined && cleanedNote.note === undefined)\n ) {\n return undefined;\n }\n return {\n id: value[\"id\"],\n name: cleanedName,\n family,\n address: normalized,\n ...(cleanedNote.note === undefined ? {} : { note: cleanedNote.note }),\n createdAt: value[\"createdAt\"],\n updatedAt: value[\"updatedAt\"],\n };\n}\n","/**\n * Address-book sync rules, pure: last-writer-wins per id, deterministic ties, tombstone expiry and\n * the record cap. Time is always passed in.\n */\nimport { isTombstone } from \"./record.ts\";\nimport type { AddressBookRecord } from \"./record.ts\";\n\n/** Entries plus tombstones never exceed this many records. */\nexport const ADDRESS_BOOK_LIMIT = 128;\n\n/** A tombstone older than this is dropped at merge time. */\nexport const TOMBSTONE_TTL_MS = 90 * 24 * 60 * 60 * 1000;\n\nconst serialized = (record: AddressBookRecord): string => JSON.stringify(record);\n\n/** The winner of two versions of one id: larger `updatedAt`, then the larger serialization. */\nexport function pickWinner(a: AddressBookRecord, b: AddressBookRecord): AddressBookRecord {\n if (a.updatedAt !== b.updatedAt) {\n return a.updatedAt > b.updatedAt ? a : b;\n }\n return serialized(a) >= serialized(b) ? a : b;\n}\n\nexport const pruneTombstones = (\n records: ReadonlyArray<AddressBookRecord>,\n now: number,\n): ReadonlyArray<AddressBookRecord> =>\n records.filter((r) => !isTombstone(r) || now - r.updatedAt <= TOMBSTONE_TTL_MS);\n\n/** Newest first, id as the tiebreak, so every device orders (and truncates) the same way. */\nconst newestFirst = (a: AddressBookRecord, b: AddressBookRecord): number =>\n b.updatedAt - a.updatedAt || (a.id < b.id ? -1 : 1);\n\n/** Drops the oldest tombstones until at most `max` records remain, or no tombstone is left. */\nexport function evictTombstones(\n records: ReadonlyArray<AddressBookRecord>,\n max: number,\n): ReadonlyArray<AddressBookRecord> {\n const excess = records.length - max;\n if (excess <= 0) {\n return records;\n }\n const oldest = new Set(\n records\n .filter(isTombstone)\n .sort((a, b) => a.updatedAt - b.updatedAt || (a.id < b.id ? -1 : 1))\n .slice(0, excess)\n .map((r) => r.id),\n );\n return records.filter((r) => !oldest.has(r.id));\n}\n\n/**\n * Merges two record sets: one winner per id, tombstones past their TTL dropped, two live entries\n * for the same (family, address) reduced to the winner, then tombstones evicted (and, only if live\n * entries alone exceed the cap, the oldest entries) down to {@link ADDRESS_BOOK_LIMIT}.\n */\nexport function mergeRecords(\n local: ReadonlyArray<AddressBookRecord>,\n remote: ReadonlyArray<AddressBookRecord>,\n now: number,\n): ReadonlyArray<AddressBookRecord> {\n return mergeWithReport(local, remote, now).records;\n}\n\n/** {@link mergeRecords}, also counting the live entries the cap forced out. */\nexport function mergeWithReport(\n local: ReadonlyArray<AddressBookRecord>,\n remote: ReadonlyArray<AddressBookRecord>,\n now: number,\n): { readonly records: ReadonlyArray<AddressBookRecord>; readonly droppedLive: number } {\n const byId = new Map<string, AddressBookRecord>();\n for (const record of [...local, ...remote]) {\n const existing = byId.get(record.id);\n byId.set(record.id, existing === undefined ? record : pickWinner(existing, record));\n }\n const live = new Map<string, AddressBookRecord>();\n const kept: AddressBookRecord[] = [];\n for (const record of [...pruneTombstones([...byId.values()], now)].sort(newestFirst)) {\n if (isTombstone(record)) {\n kept.push(record);\n continue;\n }\n const key = `${record.family}:${record.address}`;\n if (!live.has(key)) {\n live.set(key, record);\n kept.push(record);\n }\n }\n const evicted = evictTombstones(kept, ADDRESS_BOOK_LIMIT);\n const bounded = evicted.slice(0, ADDRESS_BOOK_LIMIT);\n return {\n records: [...bounded].sort((a, b) => (a.id < b.id ? -1 : 1)),\n droppedLive: evicted.slice(ADDRESS_BOOK_LIMIT).filter((r) => !isTombstone(r)).length,\n };\n}\n","/**\n * Address book: named recipients, validated and normalized per chain family, persisted in the\n * engine store and cleared from memory on lock. Deletions are kept as tombstones so they reach the\n * other devices; `syncEntries`/`merge` are the whole surface the metadata sync needs. Request risk\n * checks treat its addresses as known.\n */\nimport { Controller } from \"../controller.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport type { EngineStore } from \"../store/port.ts\";\nimport { AddressBookError } from \"./errors.ts\";\nimport { ADDRESS_BOOK_LIMIT, evictTombstones, mergeWithReport } from \"./merge.ts\";\nimport { normalizeAddress } from \"./normalize.ts\";\nimport type { AddressFamily } from \"./normalize.ts\";\nimport { cleanName, cleanNote, decodeRecord, isTombstone, NAME_MAX, NOTE_MAX } from \"./record.ts\";\nimport type { AddressBookEntry, AddressBookRecord } from \"./record.ts\";\n\nexport type { AddressFamily } from \"./normalize.ts\";\nexport type { AddressBookEntry, AddressBookRecord, AddressBookTombstone } from \"./record.ts\";\n\nexport type AddressBookState = {\n /** Live entries only; tombstones stay internal. */\n readonly entries: Record<string, AddressBookEntry>;\n};\n\nexport type AddressBookOptions = {\n readonly openStore: () => Promise<EngineStore>;\n readonly random: (n: number) => Uint8Array;\n readonly now: () => number;\n readonly logger: EngineLogger;\n};\n\nconst COLLECTION = \"contacts\";\n\nconst entriesOf = (records: ReadonlyArray<AddressBookRecord>): Record<string, AddressBookEntry> =>\n Object.fromEntries(records.flatMap((r) => (isTombstone(r) ? [] : [[r.id, r] as const])));\n\nexport class AddressBookController extends Controller<AddressBookState> {\n private readonly options: AddressBookOptions;\n private engineStore: EngineStore | undefined;\n /** Every record, tombstones included, by id. */\n private records = new Map<string, AddressBookRecord>();\n\n constructor(options: AddressBookOptions) {\n super({ name: \"address-book\", defaultState: () => ({ entries: {} }) });\n this.options = options;\n }\n\n async init(): Promise<void> {\n const store = await this.options.openStore();\n this.engineStore = store;\n const collection = store.collection(COLLECTION);\n const keys = await collection.list();\n const rows = await Promise.all(keys.map(async (key) => collection.get(key)));\n const records = new Map<string, AddressBookRecord>();\n for (const raw of rows) {\n if (raw === undefined) {\n continue;\n }\n const record = decodeRecord(JSON.parse(new TextDecoder().decode(raw)));\n if (record === undefined) {\n this.options.logger.warn(\"address book record skipped: malformed\");\n } else {\n records.set(record.id, record);\n }\n }\n this.records = records;\n this.update(() => ({ entries: entriesOf([...records.values()]) }));\n }\n\n async destroy(): Promise<void> {\n this.lock();\n await Promise.resolve();\n }\n\n lock(): void {\n this.engineStore = undefined;\n this.records = new Map();\n this.update(() => ({ entries: {} }));\n }\n\n /** Entries and tombstones, for the metadata document. */\n syncEntries(): ReadonlyArray<AddressBookRecord> {\n return [...this.records.values()].sort((a, b) => (a.id < b.id ? -1 : 1));\n }\n\n /**\n * Merges records from another device (last writer wins, tombstones win over older entries).\n * Returns whether anything local changed and whether the merged set holds something `remote`\n * lacks, i.e. whether the remote copy needs a newer publish.\n */\n async merge(\n remote: ReadonlyArray<AddressBookRecord>,\n ): Promise<{ readonly changed: boolean; readonly localNewer: boolean }> {\n const store = this.requireStore();\n const before = JSON.stringify(this.syncEntries());\n const { records: merged, droppedLive } = mergeWithReport(\n this.syncEntries(),\n remote,\n this.options.now(),\n );\n if (droppedLive > 0) {\n this.options.logger.warn(\n `address book sync: ${droppedLive} contacts dropped, over the ${ADDRESS_BOOK_LIMIT}-record cap`,\n );\n }\n const remoteSorted = JSON.stringify([...remote].sort((a, b) => (a.id < b.id ? -1 : 1)));\n const localNewer = JSON.stringify(merged) !== remoteSorted;\n if (JSON.stringify(merged) === before) {\n return { changed: false, localNewer };\n }\n const collection = store.collection(COLLECTION);\n const next = new Map(merged.map((r) => [r.id, r]));\n await Promise.all([\n ...merged.map(async (r) => collection.put(r.id, new TextEncoder().encode(JSON.stringify(r)))),\n ...[...this.records.keys()]\n .filter((id) => !next.has(id))\n .map(async (id) => collection.delete(id)),\n ]);\n this.records = next;\n this.update(() => ({ entries: entriesOf(merged) }));\n return { changed: true, localNewer };\n }\n\n async add(params: {\n readonly name: string;\n readonly family: AddressFamily;\n readonly address: string;\n readonly note?: string;\n }): Promise<AddressBookEntry> {\n const store = this.requireStore();\n const name = cleanName(params.name);\n if (name === undefined) {\n throw new AddressBookError(\"invalid-input\", `name must be 1 to ${NAME_MAX} characters`);\n }\n const note = this.checkedNote(params.note);\n const address = normalizeAddress(params.family, params.address.trim());\n if (address === undefined) {\n throw new AddressBookError(\"invalid-input\", `not a valid ${params.family} address`);\n }\n const duplicate = Object.values(this.getState().entries).some(\n (e) => e.family === params.family && e.address === address,\n );\n if (duplicate) {\n throw new AddressBookError(\"duplicate\", \"this address is already in the address book\");\n }\n if (this.records.size >= ADDRESS_BOOK_LIMIT) {\n const kept = evictTombstones([...this.records.values()], ADDRESS_BOOK_LIMIT - 1);\n if (kept.length >= ADDRESS_BOOK_LIMIT) {\n throw new AddressBookError(\n \"limit\",\n `the address book holds at most ${ADDRESS_BOOK_LIMIT} contacts`,\n );\n }\n const keptIds = new Set(kept.map((r) => r.id));\n await Promise.all(\n [...this.records.keys()]\n .filter((id) => !keptIds.has(id))\n .map(async (id) => store.collection(COLLECTION).delete(id)),\n );\n this.records = new Map(kept.map((r) => [r.id, r]));\n }\n const now = this.options.now();\n const id = `contact-${[...this.options.random(8)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\")}`;\n const entry: AddressBookEntry = {\n id,\n name,\n family: params.family,\n address,\n ...(note === undefined ? {} : { note }),\n createdAt: now,\n updatedAt: now,\n };\n await this.persist(store, entry);\n return entry;\n }\n\n async rename(id: string, name: string): Promise<AddressBookEntry> {\n const store = this.requireStore();\n const existing = this.requireEntry(id);\n const cleaned = cleanName(name);\n if (cleaned === undefined) {\n throw new AddressBookError(\"invalid-input\", `name must be 1 to ${NAME_MAX} characters`);\n }\n const entry: AddressBookEntry = { ...existing, name: cleaned, updatedAt: this.options.now() };\n await this.persist(store, entry);\n return entry;\n }\n\n /** Sets or clears (empty or `undefined`) the note. */\n async setNote(id: string, note: string | undefined): Promise<AddressBookEntry> {\n const store = this.requireStore();\n const existing = this.requireEntry(id);\n const cleaned = this.checkedNote(note);\n const { note: _previous, ...rest } = existing;\n const entry: AddressBookEntry = {\n ...rest,\n ...(cleaned === undefined ? {} : { note: cleaned }),\n updatedAt: this.options.now(),\n };\n await this.persist(store, entry);\n return entry;\n }\n\n /** Removes the entry, leaving a tombstone so other devices drop it too. */\n async remove(id: string): Promise<void> {\n const store = this.requireStore();\n this.requireEntry(id);\n await this.persist(store, { id, deleted: true, updatedAt: this.options.now() });\n }\n\n private checkedNote(note: string | undefined): string | undefined {\n const cleaned = cleanNote(note);\n if (!cleaned.ok) {\n throw new AddressBookError(\"invalid-input\", `note must be at most ${NOTE_MAX} characters`);\n }\n return cleaned.note;\n }\n\n private requireEntry(id: string): AddressBookEntry {\n const entry = this.getState().entries[id];\n if (entry === undefined) {\n throw new AddressBookError(\"not-found\", `unknown contact ${id}`);\n }\n return entry;\n }\n\n private async persist(store: EngineStore, record: AddressBookRecord): Promise<void> {\n await store\n .collection(COLLECTION)\n .put(record.id, new TextEncoder().encode(JSON.stringify(record)));\n this.records.set(record.id, record);\n this.update(() => ({ entries: entriesOf([...this.records.values()]) }));\n }\n\n private requireStore(): EngineStore {\n if (this.engineStore === undefined) {\n throw new AddressBookError(\"locked\", \"the address book requires an unlocked vault\");\n }\n return this.engineStore;\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 /** True while a pending request or an unconfirmed transaction holds this output. */\n isLocked(u: { txid: string; vout: number }): boolean {\n return this.utxos.get(BtcUtxoStore.key(u))?.status === \"locked\";\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","/** 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 { MetaDocGroup, MetaDocTree } 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): MetaDocTree {\n this.mustWallet(walletId);\n const s = this.getState();\n const w = s.wallets.find((x) => x.walletId === walletId);\n const wallet: MetaDocTree[\"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 { 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: MetaDocTree): { 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). The next nonce is read on a per-(network, from) serial queue as max(pending count,\n * last broadcast + 1) and is only recorded once a broadcast succeeds. Finalization uses the\n * `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\nconst evmRpc = async (client: PublicClient, method: string, params: unknown[]): Promise<unknown> =>\n client.transport.request({ method, params });\n\nexport const evmRpcHex = async (\n client: PublicClient,\n method: string,\n params: unknown[],\n): Promise<string> => {\n const result: unknown = await evmRpc(client, method, params);\n if (typeof result !== \"string\") {\n throw new TypeError(`${method} returned a malformed result`);\n }\n return result;\n};\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 /** The endpoint's pending transaction count for `from`. */\n async pendingCount(client: PublicClient, from: string): Promise<number> {\n return Number(await evmRpcHex(client, \"eth_getTransactionCount\", [from, \"pending\"]));\n }\n\n /**\n * The next nonce for (network, from): the larger of the endpoint's pending count and one past the\n * highest nonce this engine already broadcast. Reading it reserves nothing — only\n * {@link commitNonce} after a successful broadcast advances the local record.\n */\n async nextNonce(client: PublicClient, network: string, from: string): Promise<number> {\n const key = `${network}:${from}`;\n return this.serial(key, async () => {\n const pending = await this.pendingCount(client, from);\n const local = this.lastNonce.get(key);\n return Math.max(pending, local === undefined ? 0 : local + 1);\n });\n }\n\n /** True once a broadcast at `nonce` or later is recorded for (network, from). */\n nonceConsumed(network: string, from: string, nonce: number): boolean {\n const local = this.lastNonce.get(`${network}:${from}`);\n return local !== undefined && local >= nonce;\n }\n\n commitNonce(network: string, from: string, nonce: number): void {\n const key = `${network}:${from}`;\n this.lastNonce.set(key, Math.max(this.lastNonce.get(key) ?? nonce, nonce));\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 | {\n /** An arbitrary call from a dApp; `minGas` is its own gas figure, a floor under ours. */\n readonly kind: \"call\";\n readonly to: string;\n readonly value: bigint;\n readonly data: string;\n readonly minGas?: bigint;\n },\n nonceOverride?: number,\n ): Promise<EvmUnsignedTransaction> {\n const nonce = nonceOverride ?? (await this.nextNonce(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 : intent.kind === \"call\"\n ? intent.data\n : \"0x\";\n const estimate = BigInt(\n await evmRpcHex(client, \"eth_estimateGas\", [{ from, to, value: hex(value), data }]),\n );\n const scale = erc20 ? 11n : 12n;\n const buffered = (estimate * scale) / 10n + ((estimate * scale) % 10n === 0n ? 0n : 1n);\n const minGas = intent.kind === \"call\" ? (intent.minGas ?? 0n) : 0n;\n const gas = buffered > minGas ? buffered : minGas;\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 evmRpc(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 evmRpcHex(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 evmRpcHex(client, \"eth_sendRawTransaction\", [raw]);\n }\n\n async status(client: PublicClient, hash: string): Promise<ChainTxStatus> {\n const receipt: unknown = await evmRpc(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 evmRpc(client, \"eth_getBlockByNumber\", [\"finalized\", false]);\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, evmRpcHex } 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 evmRpcHex(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.callToken(client, t.address, \"symbol\")) ?? \"?\",\n decimals: (await this.callToken(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 evmRpcHex(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 evmRpcHex(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 callToken(\n client: PublicClient,\n token: string,\n fn: \"symbol\",\n ): Promise<string | undefined>;\n private async callToken(\n client: PublicClient,\n token: string,\n fn: \"decimals\",\n ): Promise<number | undefined>;\n private async callToken(\n client: PublicClient,\n token: string,\n fn: \"symbol\" | \"decimals\",\n ): Promise<string | number | undefined> {\n const data = encodeFunctionData({ abi: ERC20_ABI, functionName: fn });\n const result = await evmRpcHex(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.callToken(client, address, \"symbol\");\n await this.callToken(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 /** 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 };\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};\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 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)) {\n return undefined;\n }\n return { id, digest, uploadedAt, walletIds };\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 });\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 walletIds = wallets\n .map((w) => w.walletId)\n .filter((id) => !covered || !record.walletIds.includes(id));\n return { walletIds: sorted(walletIds) };\n }\n\n private coverage(snapshot: WalletSnapshot): {\n readonly walletIds: ReadonlyArray<string>;\n } {\n return {\n walletIds: sorted(snapshot.wallets.map((w) => w.walletId)),\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 };\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 ) {\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 };\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: [] },\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","import { ADDRESS_BOOK_LIMIT } from \"../addresses/merge.ts\";\nimport { decodeRecord } from \"../addresses/record.ts\";\nimport type { AddressBookRecord } from \"../addresses/record.ts\";\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\n/** The per-wallet part of the document: this wallet's name and account groups. */\nexport type MetaDocTree = {\n readonly wallet: MetaDocWallet;\n readonly groups: ReadonlyArray<MetaDocGroup>;\n};\n\n/** Every wallet's document also carries the whole address book, which is shared across wallets. */\nexport type MetaDoc = MetaDocTree & {\n readonly v: 2;\n readonly contacts: ReadonlyArray<AddressBookRecord>;\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\", \"contacts\"]);\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/**\n * Strict decode — any malformed shape, unknown key, duplicate index or id, or invalid contact\n * returns `undefined`; only `v: 2` is read.\n */\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\"] !== 2) {\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 { contacts } = value;\n if (!Array.isArray(contacts) || contacts.length > ADDRESS_BOOK_LIMIT) {\n return undefined;\n }\n const records = new Map<string, AddressBookRecord>();\n for (const item of contacts) {\n const record = decodeRecord(item);\n if (record === undefined || records.has(record.id)) {\n return undefined;\n }\n records.set(record.id, record);\n }\n const name = trimmedName(wallet[\"name\"]);\n return {\n v: 2,\n contacts: [...records.values()].sort((a, b) => (a.id < b.id ? -1 : 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 { WalletSyncSigner } from \"@qntx/wallet/nostr\";\n\nimport type { AccountTreeController } from \"../accounts/controller.ts\";\nimport type { AddressBookRecord } from \"../addresses/record.ts\";\nimport { Controller } from \"../controller.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport { decodeMetaDocBytes, encodeMetaDoc } from \"./doc.ts\";\nimport type { MetaDoc } 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: \"syncing\" | \"synced\" | \"error\";\n readonly error?: MetaSyncErrorCategory;\n};\n\nexport type MetaSyncState = {\n readonly wallets: Readonly<Record<string, MetaSyncWalletStatus>>;\n};\n\n/** What the sync needs from the address book: its records, a merge, and a change subscription. */\nexport type AddressBookSync = {\n readonly syncEntries: () => ReadonlyArray<AddressBookRecord>;\n readonly merge: (\n remote: ReadonlyArray<AddressBookRecord>,\n ) => Promise<{ readonly changed: boolean; readonly localNewer: boolean }>;\n readonly store: { readonly subscribe: (listener: () => void) => () => void };\n};\n\nexport type MetaSyncControllerOptions = {\n readonly wallet: Wallet;\n readonly accounts: AccountTreeController;\n readonly addressBook: AddressBookSync;\n /** `nostr(wallet).syncSigner` — each wallet signs metadata with its dedicated sync key. */\n readonly nostr: { readonly syncSigner: (walletId: string) => WalletSyncSigner };\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 dedicated sync key (WD-070). Pull always precedes publish in an unlock\n * session — replaceable events would otherwise let a stale local tree overwrite a newer remote\n * document. Debounced publishes are per wallet; a generation counter cancels in-flight write-backs\n * 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 private addressBookUnsubscribe: (() => 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 this.addressBookUnsubscribe = this.options.addressBook.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 this.addressBookUnsubscribe?.();\n this.addressBookUnsubscribe = 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 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.options.nostr.syncSigner(walletId);\n this.inflight.add(walletId);\n this.setStatus(walletId, { status: \"syncing\" });\n try {\n const pubkey = await signer.getPublicKey();\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.exportDoc(walletId);\n const hasEdits =\n local.wallet.updatedAt > 0 ||\n local.groups.some((g) => g.updatedAt > 0) ||\n local.contacts.length > 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 plaintext = await signer.decrypt(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 const contacts = await this.options.addressBook.merge(doc.contacts);\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 || contacts.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 /** The wallet's tree plus the shared address book — every wallet's document carries both. */\n private exportDoc(walletId: string): MetaDoc {\n return {\n v: 2,\n ...this.options.accounts.exportMeta(walletId),\n contacts: this.options.addressBook.syncEntries(),\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 this.lastExported.set(walletId, JSON.stringify(this.exportDoc(walletId)));\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.exportDoc(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.options.nostr.syncSigner(walletId);\n try {\n const bytes = encodeMetaDoc(this.exportDoc(walletId));\n if (bytes === undefined) {\n throw new MetaSyncError(\"internal\", \"meta doc exceeds 64 KB\");\n }\n const pubkey = await signer.getPublicKey();\n const content = await signer.encrypt(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 2 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 > 2\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 // `pubkeyOf` already returns the x-only internal key for bip86.\n entry.tapInternalKey = pub;\n entry.tapBip32Derivation = [[pub, { hashes: [], der: { fingerprint, path: pathOf(u) } }]];\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","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 {\n INSTALL_ID_HEADER,\n parseWith,\n esploraBasePath,\n networksPath,\n rpcPath,\n servedNetworksResponse,\n} from \"../gateway/contract/index.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\n/** Bound on the unlock-time `/v1/networks` read so a dead gateway cannot stall unlocking. */\nconst GATEWAY_PROBE_TIMEOUT_MS = 5000;\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\n/**\n * A host-endpoint-only client for cross-checking pre-signing reads. `not-needed`: the gateway is\n * not this network's first endpoint, so the primary reads already come from the host.\n * `unavailable`: a cross-check is needed but the network has no host endpoint.\n */\nexport type Independent<T> =\n | { readonly kind: \"not-needed\" }\n | { readonly kind: \"unavailable\" }\n | { readonly kind: \"available\"; readonly client: T };\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 readonly gateway?: { readonly url: string; readonly installId: string } | undefined;\n};\n\nconst makeClient = (\n info: NetworkInfo,\n urls: ReadonlyArray<string>,\n fetchFn: typeof globalThis.fetch,\n): PublicClient =>\n 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 }))),\n batch: { multicall: true },\n });\n\nconst esploraClient = (urls: ReadonlyArray<string>, fetchFn: typeof globalThis.fetch): Esplora =>\n esplora(\n urls,\n async (url, init) => {\n const r = await fetchFn(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\nconst solanaCaller = (\n urls: ReadonlyArray<string>,\n fetchFn: typeof globalThis.fetch,\n): SolanaRpc => ({\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 ? last : new Error(typeof last === \"string\" ? last : method);\n }\n try {\n const res = await fetchFn(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\nexport class NetworkController extends Controller<NetworkControllerState> {\n private readonly options: Options;\n private engineStore?: StoreOrUndefined;\n private readonly clients = new Map<string, PublicClient>();\n private readonly gatewayBase: string | undefined;\n private readonly gatewayOrigin: string | undefined;\n /** Networks the gateway reported at unlock; empty while locked or when the read failed. */\n private gatewayServed: ReadonlySet<string> = new Set();\n\n constructor(options: Options) {\n super({ name: \"networks\", defaultState: () => ({ customRpc: {} }) });\n this.options = options;\n if (options.gateway !== undefined) {\n this.gatewayBase = options.gateway.url.replace(/\\/+$/, \"\");\n this.gatewayOrigin = new URL(options.gateway.url).origin;\n }\n }\n\n async init(): Promise<void> {\n this.engineStore = await this.options.openStore();\n await this.loadCustomRpc(this.engineStore);\n await this.loadGatewayNetworks();\n }\n\n private async loadCustomRpc(store: EngineStore): Promise<void> {\n const raw = await store.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 /** Reads the gateway's served networks; any failure leaves the gateway unused until next unlock. */\n private async loadGatewayNetworks(): Promise<void> {\n if (this.gatewayBase === undefined) {\n return;\n }\n const url = `${this.gatewayBase}${networksPath}`;\n try {\n const res = await this.gatewayFetch(url, {\n signal: AbortSignal.timeout(GATEWAY_PROBE_TIMEOUT_MS),\n });\n if (!res.ok) {\n throw new Error(`status ${res.status}`);\n }\n const body: unknown = await res.json();\n const served = parseWith(servedNetworksResponse, body);\n if (served === undefined) {\n throw new Error(\"malformed response\");\n }\n this.gatewayServed = new Set(served.networks);\n } catch {\n this.gatewayServed = new Set();\n this.options.logger.warn(`gateway unavailable, not used for this session: ${url}`);\n }\n }\n\n /** `fetch` that adds the install id to requests bound for the gateway's origin only. */\n private readonly gatewayFetch: typeof globalThis.fetch = async (input, init) => {\n const { gateway } = this.options;\n const target = input instanceof Request ? input.url : String(input);\n if (gateway === undefined || new URL(target).origin !== this.gatewayOrigin) {\n return this.options.fetch(input, init);\n }\n const headers = new Headers(init?.headers);\n headers.set(INSTALL_ID_HEADER, gateway.installId);\n return this.options.fetch(input, { ...init, headers });\n };\n\n async destroy(): Promise<void> {\n this.lock();\n await Promise.resolve();\n }\n\n lock(): void {\n this.gatewayServed = new Set();\n this.clients.clear();\n this.engineStore = undefined;\n }\n\n /**\n * Ordered endpoints: a network with custom endpoints uses custom → host and never the gateway;\n * otherwise a gateway-served network uses gateway → host; else host only.\n */\n endpoints(network: string): ReadonlyArray<string> {\n const custom = this.getState().customRpc[network] ?? [];\n const host = this.options.rpc[network] ?? [];\n if (custom.length > 0) {\n return [...custom, ...host];\n }\n if (this.gatewayBase !== undefined && this.gatewayServed.has(network)) {\n const path =\n networkById(network)?.family === \"bitcoin\" ? esploraBasePath(network) : rpcPath(network);\n return [`${this.gatewayBase}${path}`, ...host];\n }\n return host;\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 = makeClient(info, urls, this.gatewayFetch);\n this.clients.set(network, client);\n return client;\n }\n\n /** True when the gateway heads this network's endpoint list (no custom endpoints, gateway-served). */\n private gatewayFirst(network: string): boolean {\n return (\n (this.getState().customRpc[network] ?? []).length === 0 &&\n this.gatewayBase !== undefined &&\n this.gatewayServed.has(network)\n );\n }\n\n private independent<T>(\n network: string,\n make: (hosts: ReadonlyArray<string>) => T,\n ): Independent<T> {\n if (!this.gatewayFirst(network)) {\n return { kind: \"not-needed\" };\n }\n const hosts = this.options.rpc[network] ?? [];\n return hosts.length === 0\n ? { kind: \"unavailable\" }\n : { kind: \"available\", client: make(hosts) };\n }\n\n /** Host-endpoint EVM client for cross-checking reads; never sends the install id. */\n independentClient(network: string): Independent<PublicClient> {\n return this.independent(network, (hosts) =>\n makeClient(this.info(network), hosts, this.options.fetch),\n );\n }\n\n independentSolanaRpc(network: string): Independent<SolanaRpc> {\n return this.independent(network, (hosts) => solanaCaller(hosts, this.options.fetch));\n }\n\n independentEsplora(network: string): Independent<Esplora> {\n return this.independent(network, (hosts) => esploraClient(hosts, this.options.fetch));\n }\n\n /** Networks with at least one configured endpoint or served by the gateway, 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 ...this.gatewayServed,\n ]);\n return [...ids].filter((id) => {\n const info = networkById(id);\n return info !== undefined && info.family === family;\n });\n }\n\n /** Solana JSON-RPC over the ordered endpoint list — kit's transport is single-endpoint. */\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 solanaCaller(urls, this.gatewayFetch);\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 esploraClient(urls, this.gatewayFetch);\n }\n\n /** Validate a custom endpoint's reported chain id, then persist it first in the list. */\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","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 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. */\nexport async 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 /** A fresh single-use L1 deposit address (with the SO's proof of possession). */\n async newDepositAddress(ref: SparkAccountRef): Promise<string> {\n return this.guarded(async () => this.clientFor(ref).deposits.newAddress());\n }\n\n /** Claims a confirmed L1 deposit paying one of the account's unused deposit addresses. */\n async claimDeposit(ref: SparkAccountRef, transaction: Uint8Array): Promise<void> {\n await this.guarded(async () => this.clientFor(ref).deposits.claim({ transaction }));\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 * Claims Spark deposits: once a transaction tagged `sparkDeposit` is confirmed, its raw bytes are\n * read from Esplora and handed to the Spark account's `deposits.claim`. Claiming too early (the SO\n * wants enough confirmations) just fails and is retried with backoff; locking stops everything.\n * Works only from the transaction state, so a restart resumes whatever is confirmed and unclaimed.\n */\nimport { hex } from \"@scure/base\";\n\nimport type { EngineLogger } from \"../events.ts\";\nimport type { NetworkController } from \"../networks/controller.ts\";\nimport type { TransactionController } from \"../transactions/controller.ts\";\nimport type { TrackedTransaction } from \"../transactions/route.ts\";\nimport { eventsBackoff } from \"./controller.ts\";\nimport type { SparkController } from \"./controller.ts\";\n\nexport type DepositClaimerOptions = {\n readonly transactions: TransactionController;\n readonly spark: SparkController;\n readonly networks: NetworkController;\n readonly logger: EngineLogger;\n};\n\nconst pending = (tx: TrackedTransaction): boolean =>\n tx.sparkDeposit !== undefined && tx.state === \"confirmed\" && tx.sparkDeposit.claimed !== true;\n\nexport class DepositClaimer {\n private readonly options: DepositClaimerOptions;\n private readonly active = new Map<string, AbortController>();\n private unsubscribe: (() => void) | undefined;\n\n constructor(options: DepositClaimerOptions) {\n this.options = options;\n }\n\n /** Starts watching; every confirmed, unclaimed deposit already in the state is picked up. */\n start(): void {\n this.stop();\n this.unsubscribe = this.options.transactions.store.subscribe(() => {\n this.scan();\n });\n this.scan();\n }\n\n stop(): void {\n this.unsubscribe?.();\n this.unsubscribe = undefined;\n for (const abort of this.active.values()) {\n abort.abort();\n }\n this.active.clear();\n }\n\n private scan(): void {\n for (const tx of Object.values(this.options.transactions.getState().txs)) {\n if (pending(tx) && !this.active.has(tx.id)) {\n const abort = new AbortController();\n this.active.set(tx.id, abort);\n void this.claim(tx.id, abort.signal);\n }\n }\n }\n\n private async claim(id: string, signal: AbortSignal): Promise<void> {\n for (let failures = 0; !signal.aborted; failures += 1) {\n const tx = this.options.transactions.getState().txs[id];\n if (tx === undefined || !pending(tx) || tx.sparkDeposit === undefined) {\n break;\n }\n const { walletId, groupIndex, network: sparkNetwork } = tx.sparkDeposit;\n try {\n if (tx.hash === undefined) {\n throw new Error(\"the deposit has no transaction id\");\n }\n // oxlint-disable-next-line eslint/no-await-in-loop -- one attempt at a time, then backoff\n const raw = await this.options.networks.esplora(tx.network).get(`/tx/${tx.hash}/hex`);\n if (typeof raw !== \"string\") {\n throw new TypeError(\"esplora returned a malformed transaction\");\n }\n // oxlint-disable-next-line eslint/no-await-in-loop\n await this.options.spark.claimDeposit(\n { walletId, groupIndex, network: sparkNetwork },\n hex.decode(raw.trim()),\n );\n if (signal.aborted) {\n break;\n }\n // oxlint-disable-next-line eslint/no-await-in-loop\n await this.options.transactions.markDepositClaimed(id);\n break;\n } catch (error) {\n this.options.logger.warn(`spark deposit ${id} not claimed yet`, error);\n // oxlint-disable-next-line eslint/no-await-in-loop\n await eventsBackoff(failures, signal);\n }\n }\n if (this.active.get(id)?.signal === signal) {\n this.active.delete(id);\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 {\n BitcoinScanStore,\n BtcUtxoStore,\n scanChain,\n scanUtxos,\n scriptPubKey,\n} 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 {\n collectChecks,\n exceedsNetworkCap,\n feeReachesAmount,\n mergeSatPerByte,\n} from \"../requests/checks.ts\";\nimport type { RequestCheckCode } from \"../requests/checks.ts\";\nimport type { EngineStore } from \"../store/port.ts\";\nimport { failTx, newId, replacementStaleReason, submitTx } from \"./route.ts\";\nimport type {\n PrepareParams,\n PreparedRequest,\n RouteContext,\n SendParams,\n AccountRef,\n SignResult,\n SparkDepositTag,\n TrackedTransaction,\n TxState,\n} 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 broadcastPsbt = async (\n es: { post: (path: string, body: string) => Promise<unknown> },\n result: SignResult,\n): Promise<string> => {\n if (result.kind !== \"bitcoin.psbt\" || !(result.signedPsbt instanceof Uint8Array)) {\n throw new Error(\"unexpected bitcoin sign result\");\n }\n const signed = Transaction.fromPSBT(result.signedPsbt);\n signed.finalize();\n const raw = signed.extract();\n return String(await es.post(\"/tx\", hex.encode(raw)));\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\nconst nextReceiveAddress = async (\n ctx: RouteContext,\n walletId: string,\n groupIndex: number,\n network: string,\n): Promise<string> => {\n const apis = ctx.options.chains ?? chains(ctx.options.wallet);\n const account = await apis.account({ walletId, groupIndex, template: \"btc.bip84\", network });\n if (!(\"xpub\" in account) || account.xpub === undefined) {\n throw new Error(\"bitcoin account carries no xpub\");\n }\n const receive = await scanChain(\n ctx.options.networks.esplora(network),\n account.xpub,\n \"btc.bip84\",\n network,\n bitcoinNetwork(network).params,\n 0,\n );\n const next = new BitcoinScanStore().nextUnused(\n { addresses: receive, utxos: [], scannedAt: ctx.options.now() },\n 0,\n );\n if (next === undefined) {\n throw new Error(\"no unused receive address\");\n }\n return next.address;\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 * Outputs held by a request that has not been broadcast yet (\"txid:vout\" → request id). Memory\n * only: the request queue is not persisted, so a crash must not leave anything locked. The\n * persistent lock (keyed by tx id) is written only once a broadcast succeeds.\n */\n const reserved = new Map<string, string>();\n const isHeld = (key: string): boolean => {\n const [txid = \"\", vout = \"0\"] = key.split(\":\");\n return reserved.has(key) || bitcoinUtxos.isLocked({ txid, vout: Number(vout) });\n };\n const releaseReservation = (requestId: string): void => {\n for (const [key, holder] of reserved) {\n if (holder === requestId) {\n reserved.delete(key);\n }\n }\n };\n\n const prepare = async (\n ctx: RouteContext,\n params: PrepareParams,\n requestId: string,\n sparkDeposit?: SparkDepositTag,\n ): Promise<PreparedRequest> => {\n const { account, network, to, amount, fee } = 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 independent = ctx.options.networks.independentEsplora(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 flags: Array<RequestCheckCode | undefined> = [\n independent.kind === \"unavailable\" ? \"reads-unverified\" : undefined,\n ];\n let rate = quote.satPerByte;\n let independentRate: number | undefined;\n if (independent.kind === \"available\") {\n try {\n const others = await feeTiers(independent.client);\n independentRate = others.find((q) => q.tier === quote.tier)?.satPerByte;\n if (independentRate === undefined) {\n flags.push(\"reads-unverified\");\n } else {\n const merged = mergeSatPerByte(quote.satPerByte, independentRate);\n ({ rate } = merged);\n flags.push(merged.mismatch ? \"fee-mismatch\" : undefined);\n }\n } catch {\n flags.push(\"reads-unverified\");\n }\n }\n // Selection and reservation run with no await between them, so concurrent prepares cannot\n // pick the same output.\n const free = inputs.filter((i) => !isHeld(`${String(i.txid ?? \"\")}:${String(i.index ?? 0)}`));\n const { psbt, inputs: selected } = bitcoin.buildPsbt(\n free,\n to,\n amount,\n BigInt(rate),\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 for (const key of selectedKeys) {\n reserved.set(key, requestId);\n }\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 const stash: BtcStash = {\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 const record = {\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 if (independentRate !== undefined) {\n flags.push(\n exceedsNetworkCap(BigInt(record.feeRate), BigInt(Math.ceil(independentRate)))\n ? \"fee-above-network\"\n : undefined,\n );\n }\n flags.push(feeReachesAmount(BigInt(record.fee), amount) ? \"fee-exceeds-amount\" : undefined);\n\n const submit = async (verify: SendParams[\"verify\"]): Promise<TrackedTransaction> => {\n pending.set(id0, stash);\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: record,\n ...(sparkDeposit === undefined ? {} : { sparkDeposit }),\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 const hash = await broadcastPsbt(es, result);\n bitcoinUtxos.lock(selectedUtxos, tx.id);\n releaseReservation(requestId);\n return await submitTx(ctx, tx, hash);\n } catch (error) {\n await failTx(ctx, tx, error);\n throw error;\n }\n };\n\n return {\n txId: id0,\n account,\n network,\n intent,\n checks: collectChecks(flags),\n staleReason: () => undefined,\n submit,\n release: () => {\n releaseReservation(requestId);\n },\n };\n };\n\n /** Esplora `/tx/:txid/status` → terminal state or `undefined` to keep polling. */\n\n /**\n * Builds the approval-ready request for a replacement or CPFP child. `held` are the extra outputs\n * it spends beyond the original's own inputs; they are reserved in memory here and only locked\n * persistently, under the new transaction id, once the broadcast succeeds.\n */\n const prepareFinish = (\n ctx: RouteContext,\n stash: BtcStash,\n es: ReturnType<NetworkController[\"esplora\"]>,\n account: AccountRef,\n old: TrackedTransaction,\n psbt: Uint8Array,\n record: NonNullable<TrackedTransaction[\"btc\"]>,\n link: { readonly replaces?: string; readonly parentId?: string },\n requestId: string,\n held: ReadonlyArray<string>,\n flags: ReadonlyArray<RequestCheckCode | undefined>,\n ): PreparedRequest => {\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 const txId = newId(ctx.options.random);\n for (const key of held) {\n reserved.set(key, requestId);\n }\n\n const submit = async (verify: SendParams[\"verify\"]): Promise<TrackedTransaction> => {\n let tx: TrackedTransaction = {\n id: txId,\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 const hash = await broadcastPsbt(es, result);\n if (link.replaces !== undefined) {\n bitcoinUtxos.endTx(old.id, \"dropped\");\n }\n bitcoinUtxos.lock(\n record.inputs.map((i) => ({ ...i, status: \"confirmed\" as const, height: 0 })),\n tx.id,\n );\n releaseReservation(requestId);\n return await submitTx(ctx, tx, hash);\n } catch (error) {\n await failTx(ctx, tx, error);\n throw error;\n }\n };\n\n return {\n txId,\n account,\n network: old.network,\n target: old.id,\n intent,\n checks: collectChecks(flags),\n staleReason: () =>\n link.replaces === undefined ? undefined : replacementStaleReason(ctx, old.id),\n submit,\n release: () => {\n releaseReservation(requestId);\n },\n };\n };\n\n const prepareReplace = async (\n ctx: RouteContext,\n old: TrackedTransaction,\n mode: \"speed-up\" | \"cancel\",\n requestId: string,\n ): Promise<PreparedRequest> => {\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 independent = ctx.options.networks.independentEsplora(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 let rate = tierQuote === undefined ? 1 : tierQuote.satPerByte;\n const flags: Array<RequestCheckCode | undefined> = [\n independent.kind === \"unavailable\" ? \"reads-unverified\" : undefined,\n ];\n let independentRate: number | undefined;\n if (independent.kind === \"available\") {\n try {\n const others = await feeTiers(independent.client);\n independentRate = others.find((q) => q.tier === tierQuote?.tier)?.satPerByte;\n if (independentRate === undefined) {\n flags.push(\"reads-unverified\");\n } else {\n const merged = mergeSatPerByte(rate, independentRate);\n ({ rate } = merged);\n flags.push(merged.mismatch ? \"fee-mismatch\" : undefined);\n }\n } catch {\n flags.push(\"reads-unverified\");\n }\n }\n // The BIP-125 floor (rule 4: pay for the replacement's own relay) applies after the merge, so\n // a low quote cannot push the replacement under it.\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(\n (u) => !usedKeys.has(`${u.txid}:${u.vout}`) && !isHeld(`${u.txid}:${u.vout}`),\n );\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 if (independentRate !== undefined) {\n flags.push(\n exceedsNetworkCap(BigInt(record.feeRate), BigInt(Math.ceil(independentRate)))\n ? \"fee-above-network\"\n : undefined,\n );\n }\n return prepareFinish(\n ctx,\n stash,\n es,\n account,\n old,\n psbt,\n record,\n { replaces: old.id },\n requestId,\n extraUtxos.map((u) => `${u.txid}:${u.vout}`),\n flags,\n );\n };\n\n const prepareCpfp = async (\n ctx: RouteContext,\n old: TrackedTransaction,\n targetRate: number,\n requestId: string,\n ): Promise<PreparedRequest> => {\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 independent = ctx.options.networks.independentEsplora(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 parentKeys = own.map((o) => `${old.hash ?? \"\"}:${o.vout}`);\n if (parentKeys.some((key) => isHeld(key))) {\n throw new Error(\"the parent's outputs are already reserved by another request\");\n }\n const flags: Array<RequestCheckCode | undefined> = [\n independent.kind === \"unavailable\" ? \"reads-unverified\" : undefined,\n ];\n if (independent.kind === \"available\") {\n try {\n const others = await feeTiers(independent.client);\n const fastest = others.find((q) => q.tier === \"fast\");\n flags.push(\n fastest === undefined\n ? \"reads-unverified\"\n : exceedsNetworkCap(\n BigInt(Math.ceil(targetRate)),\n BigInt(Math.ceil(fastest.satPerByte)),\n )\n ? \"fee-above-network\"\n : undefined,\n );\n } catch {\n flags.push(\"reads-unverified\");\n }\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) => ({\n txid: old.hash ?? \"\",\n vout: o.vout,\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 prepareFinish(\n ctx,\n stash,\n es,\n account,\n old,\n psbt,\n record,\n { parentId: old.id },\n requestId,\n parentKeys,\n flags,\n );\n };\n\n const pollAndRelease = async (\n ctx: RouteContext,\n tx: TrackedTransaction,\n ): Promise<TxState | undefined> => {\n const state = await poll(ctx, tx);\n if (state === \"confirmed\") {\n bitcoinUtxos.endTx(tx.id, \"confirmed\");\n }\n return state;\n };\n\n return {\n prepare,\n nextReceiveAddress,\n poll: pollAndRelease,\n prepareReplace,\n prepareCpfp,\n unlock: async (store) => bitcoinUtxos.unlock(store),\n lock: () => {\n reserved.clear();\n bitcoinUtxos.lockStore();\n },\n };\n};\n\nexport type BitcoinRoute = {\n readonly prepare: (\n ctx: RouteContext,\n params: PrepareParams,\n requestId: string,\n sparkDeposit?: SparkDepositTag,\n ) => Promise<PreparedRequest>;\n /** The group's next unused `btc.bip84` receive address. */\n readonly nextReceiveAddress: (\n ctx: RouteContext,\n walletId: string,\n groupIndex: number,\n network: string,\n ) => Promise<string>;\n readonly poll: (ctx: RouteContext, tx: TrackedTransaction) => Promise<TxState | undefined>;\n readonly prepareReplace: (\n ctx: RouteContext,\n old: TrackedTransaction,\n mode: \"speed-up\" | \"cancel\",\n requestId: string,\n ) => Promise<PreparedRequest>;\n readonly unlock: (store: EngineStore) => Promise<void>;\n readonly lock: () => void;\n readonly prepareCpfp: (\n ctx: RouteContext,\n old: TrackedTransaction,\n targetRate: number,\n requestId: string,\n ) => Promise<PreparedRequest>;\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 {\n collectChecks,\n exceedsNetworkCap,\n feeReachesAmount,\n mergeEvmQuote,\n} from \"../requests/checks.ts\";\nimport type { RequestCheckCode } from \"../requests/checks.ts\";\nimport { errorMessage, newId, replacementStaleReason } from \"./route.ts\";\nimport type {\n ChainApis,\n PrepareParams,\n PreparedRequest,\n RouteContext,\n SendParams,\n SignParams,\n SignResult,\n TrackedTransaction,\n TxState,\n} from \"./route.ts\";\n\ntype PendingBuild = {\n readonly unsigned: Awaited<ReturnType<EvmChainAdapter[\"build\"]>>;\n readonly request: SignParams[\"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 prepare: (ctx: RouteContext, params: PrepareParams) => Promise<PreparedRequest>;\n readonly prepareCall: (\n ctx: RouteContext,\n request: {\n readonly account: PrepareParams[\"account\"];\n readonly network: string;\n readonly tx: {\n readonly to?: string;\n readonly value: string;\n readonly data: string;\n readonly gas: string;\n };\n },\n ) => Promise<PreparedRequest>;\n readonly poll: (ctx: RouteContext, tx: TrackedTransaction) => Promise<TxState | undefined>;\n readonly prepareReplace: (\n ctx: RouteContext,\n old: TrackedTransaction,\n mode: \"speed-up\" | \"cancel\",\n ) => Promise<PreparedRequest>;\n};\n\nconst signSubmit = async (\n ctx: RouteContext,\n tx: TrackedTransaction,\n apis: ChainApis,\n request: SignParams[\"request\"],\n verify: SignParams[\"verify\"],\n broadcast: (signed: SignResult) => Promise<string>,\n): Promise<TrackedTransaction> => {\n let signed: SignResult;\n let tracked = tx;\n try {\n const result = await apis.sign({ request, verify });\n tracked = await ctx.transition(tracked, { state: \"signed\" });\n signed = result;\n } catch (error) {\n await ctx.transition(tracked, { state: \"rejected\", error: errorMessage(error) });\n throw error;\n }\n try {\n const hash = await broadcast(signed);\n tracked = await ctx.transition(tracked, {\n state: \"submitted\",\n hash,\n submittedAt: ctx.options.now(),\n });\n ctx.track(tracked.id, hash);\n return tracked;\n } catch (error) {\n await ctx.transition(tracked, { state: \"failed\", error: errorMessage(error) });\n throw error;\n }\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 type BuildIntent = Parameters<EvmChainAdapter[\"build\"]>[3];\n type PrepareSpec = {\n readonly account: PrepareParams[\"account\"];\n readonly network: string;\n readonly intent: BuildIntent;\n readonly fee: PrepareParams[\"fee\"];\n /** Native value moved; the worst-case fee reaching it is flagged. */\n readonly nativeValue: bigint | undefined;\n };\n\n const prepareSpec = async (ctx: RouteContext, spec: PrepareSpec): Promise<PreparedRequest> => {\n const { account, network, fee } = spec;\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 independent = networks.independentClient(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 flags: Array<RequestCheckCode | undefined> = [\n independent.kind === \"unavailable\" ? \"reads-unverified\" : undefined,\n ];\n\n let nonce = await evm.nextNonce(client, network, from);\n if (independent.kind === \"available\") {\n try {\n const [primary, other] = await Promise.all([\n evm.pendingCount(client, from),\n evm.pendingCount(independent.client, from),\n ]);\n nonce = Math.max(nonce, other);\n flags.push(primary === other ? undefined : \"nonce-mismatch\");\n } catch {\n flags.push(\"reads-unverified\");\n }\n }\n const unsigned = await evm.build(client, network, from, spec.intent, nonce);\n const quotes = await evm.estimateFee(client);\n let quote = quotes.find((q) => q.tier === fee) ?? quotes[1];\n if (quote === undefined) {\n throw new Error(\"no fee quote\");\n }\n if (independent.kind === \"available\") {\n try {\n const others = await evm.estimateFee(independent.client);\n const other = others.find((q) => q.tier === quote?.tier);\n if (other === undefined) {\n flags.push(\"reads-unverified\");\n } else {\n const merged = mergeEvmQuote(quote, other);\n ({ quote } = merged);\n flags.push(\n merged.mismatch ? \"fee-mismatch\" : undefined,\n exceedsNetworkCap(quote.maxFeePerGas, other.maxFeePerGas)\n ? \"fee-above-network\"\n : undefined,\n );\n }\n } catch {\n flags.push(\"reads-unverified\");\n }\n }\n const feed = evm.applyFee(unsigned, quote);\n if (\n spec.nativeValue !== undefined &&\n feeReachesAmount(feed.gas * (feed.maxFeePerGas ?? feed.gasPrice ?? 0n), spec.nativeValue)\n ) {\n flags.push(\"fee-exceeds-amount\");\n }\n const request = evm.toSignRequest(feed, account, info.chainId);\n const intent = decodeEvm(request);\n const txId = newId(ctx.options.random);\n const chosen = quote;\n\n const submit = async (verify: SendParams[\"verify\"]): Promise<TrackedTransaction> => {\n pending.set(txId, { unsigned: feed, request, quote: chosen, chainId: info.chainId });\n let tx: TrackedTransaction = {\n id: txId,\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 return signSubmit(ctx, tx, apis, request, verify, async (signed) => {\n const raw = evm.finalize(feed, signed);\n const hash = await evm.broadcast(client, raw);\n evm.commitNonce(network, from, unsigned.nonce);\n return hash;\n });\n };\n\n return {\n txId,\n account,\n network,\n intent,\n checks: collectChecks(flags),\n staleReason: () =>\n evm.nonceConsumed(network, from, unsigned.nonce)\n ? \"nonce already used by a newer transaction — start over\"\n : undefined,\n submit,\n release: () => undefined,\n };\n };\n\n const prepare = async (ctx: RouteContext, params: PrepareParams): Promise<PreparedRequest> =>\n prepareSpec(ctx, {\n account: params.account,\n network: params.network,\n fee: params.fee,\n intent:\n params.token === undefined\n ? { kind: \"native\", to: params.to, value: params.amount }\n : { kind: \"erc20\", token: params.token, to: params.to, value: params.amount },\n nativeValue: params.token === undefined ? params.amount : undefined,\n });\n\n /**\n * A dApp transaction, already normalized: only `to`, `value` and `data` are kept; nonce and fees\n * are read again and the dApp's `gas` only raises the floor under our own estimate.\n */\n const prepareCall = async (\n ctx: RouteContext,\n request: {\n readonly account: PrepareParams[\"account\"];\n readonly network: string;\n readonly tx: {\n readonly to?: string;\n readonly value: string;\n readonly data: string;\n readonly gas: string;\n };\n },\n ): Promise<PreparedRequest> => {\n const { tx } = request;\n if (tx.to === undefined) {\n throw new Error(\"contract creation is not supported\");\n }\n const value = BigInt(tx.value);\n return prepareSpec(ctx, {\n account: request.account,\n network: request.network,\n fee: \"normal\",\n intent: { kind: \"call\", to: tx.to, value, data: tx.data, minGas: BigInt(tx.gas) },\n nativeValue: value > 0n ? value : undefined,\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 fee is cross-checked and merged first, then the replacement\n * floor (+10% on both fee fields, never below the merged estimate) is applied on top, so a low\n * quote can never push the replacement under the node's replacement rule. A rejected signature\n * never reaches the network and leaves the original.\n */\n const prepareReplace = async (\n ctx: RouteContext,\n old: TrackedTransaction,\n mode: \"speed-up\" | \"cancel\",\n ): Promise<PreparedRequest> => {\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 independent = networks.independentClient(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 let estimate = estimates.find((q) => q.tier === tier) ?? estimates[1];\n if (estimate === undefined) {\n throw new Error(\"no fee quote\");\n }\n const flags: Array<RequestCheckCode | undefined> = [\n independent.kind === \"unavailable\" ? \"reads-unverified\" : undefined,\n ];\n let independentCap: bigint | undefined;\n if (independent.kind === \"available\") {\n try {\n const others = await evm.estimateFee(independent.client);\n const other = others.find((q) => q.tier === estimate?.tier);\n if (other === undefined) {\n flags.push(\"reads-unverified\");\n } else {\n const merged = mergeEvmQuote(estimate, other);\n ({ quote: estimate } = merged);\n independentCap = other.maxFeePerGas;\n flags.push(merged.mismatch ? \"fee-mismatch\" : undefined);\n }\n } catch {\n flags.push(\"reads-unverified\");\n }\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 if (independentCap !== undefined) {\n flags.push(exceedsNetworkCap(maxFeePerGas, independentCap) ? \"fee-above-network\" : undefined);\n }\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 txId = newId(ctx.options.random);\n\n const submit = async (verify: SendParams[\"verify\"]): Promise<TrackedTransaction> => {\n pending.set(txId, { unsigned, request, quote: stash.quote, chainId: stash.chainId });\n let tx: TrackedTransaction = {\n id: txId,\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 return signSubmit(ctx, tx, apis, request, verify, async (signed) =>\n evm.broadcast(client, evm.finalize(unsigned, signed)),\n );\n };\n\n return {\n txId,\n account: stash.request.account,\n network: old.network,\n target: old.id,\n intent,\n checks: collectChecks(flags),\n staleReason: () => replacementStaleReason(ctx, old.id),\n submit,\n release: () => undefined,\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 { prepare, prepareCall, poll, prepareReplace };\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 {\n collectChecks,\n exceedsNetworkCap,\n feeReachesAmount,\n mergeSolanaQuote,\n} from \"../requests/checks.ts\";\nimport type { RequestCheckCode } from \"../requests/checks.ts\";\nimport type {\n DisplayIntent,\n PrepareParams,\n PreparedRequest,\n RouteContext,\n SendParams,\n TrackedTransaction,\n TxState,\n} from \"./route.ts\";\nimport { newId, failTx, submitTx } from \"./route.ts\";\n\n/** The network's base signature fee, lamports per signature. */\nconst BASE_FEE_LAMPORTS = 5000n;\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 prepareSolana = async (\n ctx: RouteContext,\n params: PrepareParams,\n): Promise<PreparedRequest> => {\n const { account, network, to, amount, fee } = 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 independent = ctx.options.networks.independentSolanaRpc(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 let quote = quotes.find((q) => q.tier === fee) ?? quotes[1];\n if (quote === undefined) {\n throw new Error(\"no fee quote\");\n }\n const flags: Array<RequestCheckCode | undefined> = [\n independent.kind === \"unavailable\" ? \"reads-unverified\" : undefined,\n ];\n if (independent.kind === \"available\") {\n try {\n const others = await solana.estimateFee(independent.client, unsigned.writable);\n const other = others.find((q) => q.tier === quote?.tier);\n if (other === undefined) {\n flags.push(\"reads-unverified\");\n } else {\n const merged = mergeSolanaQuote(quote, other);\n ({ quote } = merged);\n flags.push(\n merged.mismatch ? \"fee-mismatch\" : undefined,\n exceedsNetworkCap(quote.microLamportsPerCu, other.microLamportsPerCu)\n ? \"fee-above-network\"\n : undefined,\n );\n }\n } catch {\n flags.push(\"reads-unverified\");\n }\n }\n if (params.token === undefined) {\n const units = BigInt(\n Math.ceil((unsigned.unitsConsumed === 0 ? 1_400_000 : unsigned.unitsConsumed) * 1.1),\n );\n const maxFee = BASE_FEE_LAMPORTS + (units * quote.microLamportsPerCu + 999_999n) / 1_000_000n;\n flags.push(feeReachesAmount(maxFee, amount) ? \"fee-exceeds-amount\" : undefined);\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\n const submit = async (verify: SendParams[\"verify\"]): Promise<TrackedTransaction> => {\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 return await submitTx(ctx, tx, hash);\n } catch (error) {\n await failTx(ctx, tx, error);\n throw error;\n }\n };\n\n return {\n txId: id,\n account,\n network,\n intent,\n checks: collectChecks(flags),\n staleReason: async () =>\n (await solana.blockHeight(rpc)) > unsigned.lastValidBlockHeight\n ? \"blockhash expired — start over\"\n : undefined,\n submit,\n release: () => undefined,\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 type { SignRequest } from \"@qntx/wallet-chains\";\nimport { decodeEvm, normalizeEvm } from \"@qntx/wallet-chains/evm\";\nimport { chains } from \"@qntx/wallet/chains\";\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 AccountRef,\n DisplayIntent,\n Options,\n PrepareParams,\n PreparedMessage,\n PreparedRequest,\n ChainRequestInput,\n RouteContext,\n SparkDepositTag,\n TrackedTransaction,\n TxState,\n} from \"./route.ts\";\nimport { newId } from \"./route.ts\";\nimport { pollSolana, prepareSolana } from \"./solana.ts\";\n\nexport type {\n AccountRef,\n PrepareParams,\n PreparedRequest,\n ChainRequestInput,\n ChainRequestMethod,\n SendParams,\n TrackedTransaction,\n TxState,\n} 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 isSparkDeposit = (v: unknown): v is SparkDepositTag =>\n isObject(v) &&\n typeof v[\"walletId\"] === \"string\" &&\n typeof v[\"groupIndex\"] === \"number\" &&\n (v[\"network\"] === \"mainnet\" || v[\"network\"] === \"regtest\") &&\n (v[\"claimed\"] === undefined || typeof v[\"claimed\"] === \"boolean\");\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 sparkDeposit,\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 ...(isSparkDeposit(sparkDeposit) ? { sparkDeposit } : {}),\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 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 await this.bitcoinRoute.unlock(this.engineStore);\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 this.bitcoinRoute.lock();\n this.bitcoinRoute = createBitcoinRoute();\n }\n\n private async persist(tx: TrackedTransaction): Promise<void> {\n const store = this.engineStore;\n if (store === undefined) {\n this.options.logger.warn(`transaction ${tx.id} (${tx.state}) not persisted: vault locked`);\n return;\n }\n await store.collection(\"transactions\").put(tx.id, encode(tx));\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 txs: () => this.getState().txs,\n newId: () => newId(this.options.random),\n };\n }\n\n /**\n * Internal entry for the request pipeline: builds, estimates and cross-checks a send without\n * signing it. Bitcoin outputs it selects stay locked under `requestId` until the returned\n * `release` runs or the broadcast moves them to the transaction.\n */\n async prepareSend(\n params: PrepareParams,\n requestId: string,\n sparkDeposit?: SparkDepositTag,\n ): Promise<PreparedRequest> {\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 prepareSolana(ctx, params);\n }\n if (info.family === \"bitcoin\") {\n return this.bitcoinRoute.prepare(ctx, params, requestId, sparkDeposit);\n }\n return this.evmRoute.prepare(ctx, params);\n }\n\n /** The group's next unused `btc.bip84` receive address on a bitcoin `network`. */\n async nextReceiveAddress(walletId: string, groupIndex: number, network: string): Promise<string> {\n if (this.locked) {\n throw new Error(\"transactions require an unlocked vault\");\n }\n return this.bitcoinRoute.nextReceiveAddress(this.routeCtx(), walletId, groupIndex, network);\n }\n\n /** Records that a Spark deposit was credited; persisted with the transaction. */\n async markDepositClaimed(id: string): Promise<void> {\n const tx = this.getState().txs[id];\n if (tx?.sparkDeposit === undefined) {\n throw new Error(`transaction ${id} is not a Spark deposit`);\n }\n await this.transition(tx, { sparkDeposit: { ...tx.sparkDeposit, claimed: true } });\n }\n\n /**\n * Internal entry for a dApp's EVM signature request: the request is normalized first, a\n * transaction is rebuilt with fresh nonce and fees (the dApp's own are discarded), and a message\n * is decoded and signed as is.\n */\n async prepareDapp(\n account: AccountRef,\n request: SignRequest,\n ): Promise<PreparedRequest | PreparedMessage> {\n if (this.locked) {\n throw new Error(\"transactions require an unlocked vault\");\n }\n const normalized = normalizeEvm(request);\n if (account.kind !== \"hd\") {\n throw new Error(\"imported accounts are not yet supported\");\n }\n if (normalized.kind === \"evm.transaction\") {\n return this.evmRoute.prepareCall(this.routeCtx(), {\n account,\n network: normalized.network,\n tx: normalized.tx,\n });\n }\n if (normalized.kind !== \"evm.personal-message\" && normalized.kind !== \"evm.typed-data\") {\n throw new Error(`unsupported dApp request ${normalized.kind}`);\n }\n const { kind, network } = normalized;\n const apis = this.options.chains ?? chains(this.options.wallet);\n return {\n account,\n network,\n intent: decodeEvm(normalized),\n checks: [],\n staleReason: () => undefined,\n release: () => undefined,\n submit: async (verify) => {\n const result = await apis.sign({\n request:\n normalized.kind === \"evm.personal-message\"\n ? { kind: normalized.kind, network, account, message: normalized.message }\n : { kind: normalized.kind, network, account, typedData: normalized.typedData },\n verify,\n });\n if (result.kind !== kind || !(\"signature\" in result)) {\n throw new Error(\"unexpected sign result\");\n }\n return { kind, signature: result.signature };\n },\n };\n }\n\n /**\n * Internal entry for replacements and CPFP: builds, cross-checks and reserves what the\n * replacement needs without signing it. The original must be `submitted` or `pending`.\n */\n async prepareReplacement(\n input: Exclude<ChainRequestInput, { method: \"send\" }>,\n requestId: string,\n ): Promise<PreparedRequest> {\n if (this.locked) {\n throw new Error(\"transactions require an unlocked vault\");\n }\n const old = this.getState().txs[input.txId];\n if (old === undefined) {\n throw new Error(`unknown transaction ${input.txId}`);\n }\n if (old.state !== \"pending\" && old.state !== \"submitted\") {\n throw new Error(`cannot ${input.method} a ${old.state} transaction`);\n }\n const ctx = this.routeCtx();\n if (input.method === \"cpfp\") {\n if (old.family !== \"bitcoin\") {\n throw new Error(\"cpfp is Bitcoin-only\");\n }\n return this.bitcoinRoute.prepareCpfp(ctx, old, input.feeRate, requestId);\n }\n if (old.family === \"bitcoin\") {\n return this.bitcoinRoute.prepareReplace(ctx, old, input.method, requestId);\n }\n if (old.family === \"evm\") {\n return this.evmRoute.prepareReplace(ctx, old, input.method);\n }\n throw new Error(`${input.method} is EVM and Bitcoin only`);\n }\n\n private track(id: string, hash: string): void {\n if (this.locked) {\n this.options.logger.warn(\n `transaction ${id} was broadcast after the vault locked; it is neither persisted nor tracked`,\n );\n return;\n }\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 { LightningInvoice, SparkNetwork } from \"@qntx/spark\";\nimport type { Wallet } from \"@qntx/wallet\";\nimport { chains } from \"@qntx/wallet/chains\";\nimport { nostr } from \"@qntx/wallet/nostr\";\nimport { spark } from \"@qntx/wallet/spark\";\n\nimport { AccountTreeController } from \"./accounts/controller.ts\";\nimport { AddressBookController } from \"./addresses/controller.ts\";\nimport { AssetsController } from \"./assets/controller.ts\";\nimport { BackupController } from \"./backup/controller.ts\";\nimport type { CloudStore } from \"./backup/port.ts\";\nimport { ConnectionController } from \"./connect/controller.ts\";\nimport { Eip1193Handler } from \"./connect/eip1193.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 { withdrawLnurl } from \"./payments/pay.ts\";\nimport type { WithdrawLnurlParams } from \"./payments/pay.ts\";\nimport { resolvePayment } from \"./payments/resolve.ts\";\nimport { prepareZap } from \"./payments/zap.ts\";\nimport type { PrepareZapParams, PreparedZap } from \"./payments/zap.ts\";\nimport { RequestController } from \"./requests/controller.ts\";\nimport { SparkController } from \"./spark/controller.ts\";\nimport type { SparkControllerOptions } from \"./spark/controller.ts\";\nimport { DepositClaimer } from \"./spark/deposit-claim.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 /**\n * Host endpoints per network (CAIP-2), ordered by preference, for all three chain families: EVM\n * and Solana JSON-RPC URLs, and for Bitcoin the Esplora base URL.\n */\n readonly rpc?: Readonly<Record<string, ReadonlyArray<string>>>;\n /**\n * The wallet gateway: tried first for the networks it serves (read at each unlock) unless a\n * network has custom endpoints. The install id is sent only to the gateway's origin.\n */\n readonly gateway?: { readonly url: string; readonly installId: string };\n /** Injected timer for transaction polling; defaults to setTimeout. */\n /** Development builds: also accept `http://localhost` as a dApp origin. */\n readonly allowLocalhostOrigins?: boolean;\n readonly setTimer?: (ms: number, fn: () => void) => () => void;\n /** Kind-30078 wallet-metadata sync; absent → no wallet metadata is synced. */\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 requests: RequestController;\n readonly addressBook: AddressBookController;\n readonly connections: ConnectionController;\n readonly eip1193: Eip1193Handler;\n /** Read and receive surface; every payment goes through `requests`. */\n readonly spark: Omit<SparkController, \"send\" | \"payInvoice\" | \"paySparkInvoice\" | \"withdraw\">;\n readonly accounts: AccountTreeController;\n readonly metaSync: MetaSyncController;\n readonly backup: BackupController;\n readonly zaps: {\n readonly prepare: (params: PrepareZapParams) => Promise<PreparedZap>;\n };\n readonly payments: {\n readonly parse: (input: string, network: SparkNetwork) => PaymentParse;\n readonly resolve: (input: string, network: SparkNetwork) => Promise<PaymentParse>;\n /** Receives funds from an LNURL-withdraw service; needs no verification factor. */\n readonly withdrawLnurl: (\n params: WithdrawLnurlParams,\n ) => Promise<{ readonly kind: \"lnurl-withdraw\"; readonly invoice: LightningInvoice }>;\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 gateway: options.gateway,\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 addressBook = new AddressBookController({\n openStore: options.openStore,\n random: options.random,\n now: options.now,\n logger: options.logger,\n });\n\n const requests = new RequestController({\n transactions,\n addressBook,\n openStore: options.openStore,\n spark: controller,\n fetch: options.fetch,\n random: options.random,\n now: options.now,\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 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 addressBook,\n nostr: { syncSigner: (walletId) => nostr(options.wallet).syncSigner(walletId) },\n metaSync: options.metaSync,\n logger: options.logger,\n now: options.now,\n });\n\n const depositClaimer = new DepositClaimer({\n transactions,\n spark: controller,\n networks,\n logger: options.logger,\n });\n const connections = new ConnectionController({\n openStore: options.openStore,\n random: options.random,\n now: options.now,\n logger: options.logger,\n allowLocalhost: options.allowLocalhostOrigins ?? false,\n selectedGroup: () => accounts.getState().selected ?? undefined,\n evmAddress: async (group, network) => {\n const account = await chains(options.wallet).account({\n ...group,\n template: \"evm.bip44\",\n network,\n });\n if (!(\"address\" in account)) {\n throw new Error(\"no EVM address for the group\");\n }\n return account.address;\n },\n enabledNetworks: () => networks.enabled(\"evm\"),\n invalidate: (origin) => {\n requests.invalidateOrigin(origin);\n },\n });\n const eip1193 = new Eip1193Handler({\n connections,\n requests,\n networks,\n defaultNetwork: () => networks.enabled(\"evm\")[0] ?? \"eip155:1\",\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 addressBook.init();\n await metaSync.init();\n await networks.init();\n await assets.init();\n await transactions.init();\n await requests.init();\n await connections.init();\n depositClaimer.start();\n } else if (!unlocked && started) {\n started = false;\n depositClaimer.stop();\n connections.lock();\n requests.lock();\n addressBook.lock();\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 requests,\n addressBook,\n connections,\n eip1193,\n spark: controller,\n accounts,\n metaSync,\n backup,\n zaps: {\n prepare: async (params) => prepareZap(params, { fetch: options.fetch, 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 withdrawLnurl: async (params) =>\n withdrawLnurl({ 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;C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