@qntx/wallet-engine 0.13.0 → 0.14.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 +1057 -20
- package/dist/apps-fiat24.d.mts +202 -0
- package/dist/apps-fiat24.mjs +1378 -0
- package/dist/apps-fiat24.mjs.map +1 -0
- package/dist/apps-hyperliquid.d.mts +549 -0
- package/dist/apps-hyperliquid.mjs +2742 -0
- package/dist/apps-hyperliquid.mjs.map +1 -0
- package/dist/apps-polymarket.d.mts +729 -0
- package/dist/apps-polymarket.mjs +3786 -0
- package/dist/apps-polymarket.mjs.map +1 -0
- package/dist/apps.d.mts +136 -0
- package/dist/apps.mjs +535 -0
- package/dist/apps.mjs.map +1 -0
- package/dist/connect-BY1C5ZRI.mjs +210 -0
- package/dist/connect-BY1C5ZRI.mjs.map +1 -0
- package/dist/connect.d.mts +17 -9
- package/dist/connect.mjs +3 -185
- package/dist/{errors-CQnlTc1i.d.mts → controller-DpNVHVsj.d.mts} +1093 -758
- package/dist/controller-rMnaxKAH.mjs +46 -0
- package/dist/controller-rMnaxKAH.mjs.map +1 -0
- package/dist/decimal-COJ4g8qy.mjs +38 -0
- package/dist/decimal-COJ4g8qy.mjs.map +1 -0
- package/dist/eligibility-BfM9ybYZ.mjs +48 -0
- package/dist/eligibility-BfM9ybYZ.mjs.map +1 -0
- package/dist/engine-Dic_kkEr.d.mts +1829 -0
- package/dist/errors-B8W-hoYW.d.mts +7 -0
- package/dist/errors-horUy5k1.mjs +24 -0
- package/dist/errors-horUy5k1.mjs.map +1 -0
- package/dist/gateway-contract.d.mts +3 -608
- package/dist/gateway-contract.mjs +1467 -161
- package/dist/gateway-contract.mjs.map +1 -1
- package/dist/idb.d.mts +5 -0
- package/dist/idb.mjs +122 -46
- package/dist/idb.mjs.map +1 -1
- package/dist/index-vBgfOFIh.d.mts +2227 -0
- package/dist/index.d.mts +58 -618
- package/dist/index.mjs +21963 -6836
- package/dist/index.mjs.map +1 -1
- package/dist/json-BDwV38cj.mjs +15 -0
- package/dist/json-BDwV38cj.mjs.map +1 -0
- package/dist/link-Ceq8Dggp.mjs +139 -0
- package/dist/link-Ceq8Dggp.mjs.map +1 -0
- package/dist/primitives-DbSHLZKq.mjs +31 -0
- package/dist/primitives-DbSHLZKq.mjs.map +1 -0
- package/dist/push-message-AQuzoNFY.d.mts +84 -0
- package/dist/push-message-kbnH1A5w.mjs +142 -0
- package/dist/push-message-kbnH1A5w.mjs.map +1 -0
- package/dist/push.d.mts +13 -0
- package/dist/push.mjs +70 -0
- package/dist/push.mjs.map +1 -0
- package/dist/qr.d.mts +292 -0
- package/dist/qr.mjs +1725 -0
- package/dist/qr.mjs.map +1 -0
- package/dist/registry-CbtwcxkX.mjs +374 -0
- package/dist/registry-CbtwcxkX.mjs.map +1 -0
- package/dist/risk-DyABgg4W.mjs +757 -0
- package/dist/risk-DyABgg4W.mjs.map +1 -0
- package/dist/session-CNJFLarP.mjs +18 -0
- package/dist/session-CNJFLarP.mjs.map +1 -0
- package/dist/socket-ChG9JRT_.mjs +110 -0
- package/dist/socket-ChG9JRT_.mjs.map +1 -0
- package/dist/spi-BrTw5s98.d.mts +3 -0
- package/dist/timer-Cdk5rGM2.mjs +43 -0
- package/dist/timer-Cdk5rGM2.mjs.map +1 -0
- package/dist/types-BpvioFGo.d.mts +258 -0
- package/dist/types-DbftVZ3I.mjs +90 -0
- package/dist/types-DbftVZ3I.mjs.map +1 -0
- package/dist/walletconnect.d.mts +86 -0
- package/dist/walletconnect.mjs +1507 -0
- package/dist/walletconnect.mjs.map +1 -0
- package/dist/webln-BgrtPXpG.mjs +2593 -0
- package/dist/webln-BgrtPXpG.mjs.map +1 -0
- package/dist/webln-Bllk_xJ2.d.mts +666 -0
- package/package.json +92 -19
- package/dist/connect.mjs.map +0 -1
- package/dist/registry-DwguKWvt.d.mts +0 -27
- package/dist/registry-oorLoGtz.mjs +0 -120
- package/dist/registry-oorLoGtz.mjs.map +0 -1
- package/dist/webln-DKqCnqx1.mjs +0 -3677
- package/dist/webln-DKqCnqx1.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"webln-BgrtPXpG.mjs","names":["toProviderError","isObject","diffSessions","toProviderError","isBytesEnvelope","bytesOf","byOrigin","isObject","checkString","diffSessions","toProviderError","isBytesEnvelope","byOrigin","isObject"],"sources":["../src/phishing/status.ts","../src/connect/errors.ts","../src/connect/controller.ts","../src/transactions/route.ts","../src/connect/subscription.ts","../src/transactions/broadcast.ts","../src/connect/text.ts","../src/connect/bitcoin.ts","../src/connect/nip07.ts","../src/connect/siws.ts","../src/connect/solana.ts","../src/connect/tron.ts","../src/payments/parse.ts","../src/connect/webln.ts"],"sourcesContent":["/**\n * `blocked`: on the list. `trusted`: on the list, but the user trusts that origin. `clear`: not on\n * the list, or not a web page. `unchecked`: no list has been loaded yet.\n */\nexport type PhishingStatus = \"blocked\" | \"trusted\" | \"clear\" | \"unchecked\";\n\nexport const PHISHING_BLOCKED_MESSAGE = \"origin is on the phishing list\";\n","import { ChainError } from \"@qntx/wallet-chains\";\n\nimport {\n InvalidTokenError,\n OriginBusyError,\n RequestEndedError,\n SignInOriginError,\n} from \"../requests/types.ts\";\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\n/** EIP-1474 \"limit exceeded\": the request is valid but asks for more than the wallet serves. */\nexport const limitExceeded = (message: string): ProviderError => new ProviderError(-32005, message);\n\nexport const internalError = (message: string): ProviderError => new ProviderError(-32603, message);\n\nexport function toProviderError(error: unknown): ProviderError {\n if (error instanceof ProviderError) {\n return error;\n }\n if (error instanceof InvalidTokenError || error instanceof SignInOriginError) {\n return invalidParams(error.message);\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\n/** JSON-RPC implementation-defined server error (outside EIP-1474's assigned codes). */\nexport const PAYMENT_PENDING_CODE = -32010;\n\n/**\n * The payment may have been made — it may still settle, or settled without a usable answer — never\n * an error the page can safely retry: an lnurl dApp that retries on failure would fetch a new\n * invoice and pay twice.\n */\nexport const paymentPending = (message: string): ProviderError =>\n new ProviderError(PAYMENT_PENDING_CODE, message);\n\n/**\n * A batch send that stopped at `stopped.index` (never the first: a first failure fails the request\n * instead). `reason` is `\"refused\"` only when the node itself rejected those bytes — the stopped\n * input and everything after it never went out — while anything else means a local failure kept it\n * from being sent at all. The message lists the ids already submitted so the page does not resubmit\n * them.\n */\nexport const batchStopped = (\n stopped: {\n readonly index: number;\n readonly reason: \"refused\" | \"not-sent\";\n readonly error: string;\n },\n submitted: ReadonlyArray<string>,\n): ProviderError => {\n const head =\n stopped.reason === \"refused\"\n ? `the network refused transaction ${String(stopped.index)}`\n : `transaction ${String(stopped.index)} was not sent`;\n return internalError(\n `${head}: ${stopped.error} — it and every later transaction were not sent; already ` +\n `submitted, do not resubmit: ${submitted.join(\", \")}`,\n );\n};\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 type { NostrKeyRef } from \"@qntx/wallet\";\n\nimport { Controller } from \"../controller.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport type { PhishingController } from \"../phishing/controller.ts\";\nimport { PHISHING_BLOCKED_MESSAGE } from \"../phishing/status.ts\";\nimport { dappUrl, isDappOrigin, walletConnectKey } from \"../requests/types.ts\";\nimport type { DappOrigin, WalletConnectOrigin } from \"../requests/types.ts\";\nimport { readJson } from \"../store/json.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 = DappOrigin;\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 /**\n * The group whose keys sign for every chain scope (`eip155:*`, `solana:*`, `bip122:*`) and\n * `lightning`; absent until such a scope is granted.\n */\n readonly group?: AccountGroup;\n /** The identity whose key signs for the `nostr` scope; present with a non-empty nostr scope. */\n readonly identity?: NostrKeyRef;\n /** The session's current EVM network; only dApp sessions have one. */\n readonly currentNetwork: string;\n /** The session's current TRON network; set when a `tron` namespace is granted. */\n readonly tronNetwork?: string;\n /** The origin's Nostr policy — set when the host approves a `nostr` connection. */\n readonly nostrPolicy?: NostrPolicy;\n /** The origin's Lightning policy — set when the host approves a `lightning` connection. */\n readonly lightningPolicy?: LightningPolicy;\n readonly createdAt: number;\n readonly lastUsedAt: number;\n};\n\n/**\n * How much a `nostr` session may do without per-call approval: `signing` is `\"ask\"` (every\n * `signEvent` goes through the pipeline), `\"always\"` (any kind signs directly), or a kind list (`{\n * kinds }` — only those kinds sign directly, the rest ask); `decrypt` gates `nip04/nip44 .decrypt`.\n * Kinds `0`, `3` and `5` and every replaceable, ephemeral or addressable event (10000–39999) always\n * ask regardless.\n */\nexport type NostrPolicy = {\n readonly signing: \"ask\" | \"always\" | { readonly kinds: ReadonlyArray<number> };\n readonly decrypt: boolean;\n};\n\n/**\n * How much a `lightning` session may do without per-call approval: `balance` gates `getBalance`\n * (WebLN). Sending and invoicing always go through their own approvals.\n */\nexport type LightningPolicy = {\n readonly balance: boolean;\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 /**\n * Which namespace the connection is for — `eip155` (EVM), `nostr` (NIP-07) or `lightning`\n * (WebLN).\n */\n readonly namespace: \"eip155\" | \"nostr\" | \"lightning\" | \"solana\" | \"bip122\" | \"tron\";\n readonly network?: string;\n /** `false` for a `network` request that adds the network without making it current. */\n readonly activate?: boolean;\n readonly createdAt: number;\n};\n\n/** What a connection request asks for; `namespace` defaults to `eip155`, `activate` to `true`. */\nexport type ConnectionRequest = {\n readonly kind: PendingConnection[\"kind\"];\n readonly namespace?: PendingConnection[\"namespace\"];\n readonly network?: string;\n readonly activate?: boolean;\n};\n\n/** Pending connection requests held at once; a further request is refused. */\nexport const MAX_PENDING_CONNECTIONS = 64;\n\n/** A pending connection request that nobody answers is rejected after this long. */\nexport const CONNECTION_REQUEST_TTL_MS = 10 * 60 * 1000;\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 /** Whether the session store is open and loaded. */\n readonly ready: boolean;\n};\n\nexport type ConnectionControllerOptions = {\n /** The session EngineStore — the engine opens it once per unlock and closes it on lock. */\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 /** The group's Solana address on `network` (a CAIP-2 `solana:<genesis>` chain). */\n readonly solanaAddress: (group: AccountGroup, network: string) => Promise<string>;\n /** The group's TRON address (base58) on `network` (a `tron:<chain>` CAIP-2 chain). */\n readonly tronAddress: (group: AccountGroup, network: string) => Promise<string>;\n /** The group's fixed dApp-facing Bitcoin address of `purpose` on `network` (`bip122:<genesis>`). */\n readonly bitcoinAddress: (\n group: AccountGroup,\n network: string,\n purpose: BitcoinPurpose,\n ) => Promise<string>;\n readonly enabledNetworks: () => ReadonlyArray<string>;\n /** A Nostr identity's public key — `nostr(wallet).signer(ref).getPublicKey()`. */\n readonly nostrPubkey: (ref: NostrKeyRef) => Promise<string>;\n /** Voids a page's unfinished requests (revoked, or its network changed). */\n readonly invalidate: (origin: string) => void;\n /** Called when the app's group selection changes; returns an unsubscribe. */\n readonly onSelectedGroup: (listener: () => void) => () => void;\n /**\n * Voids every unfinished request — locking, unlocking and switching account group void every\n * unfinished request (requests.mdx invariant 1).\n */\n readonly invalidateAll: () => void;\n readonly phishing: Pick<PhishingController, \"check\">;\n readonly setTimer: (ms: number, fn: () => unknown) => () => 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 \"wallet_watchAsset\",\n \"wallet_getCapabilities\",\n \"wallet_sendCalls\",\n \"wallet_getCallsStatus\",\n \"wallet_showCallsStatus\",\n];\nexport const SESSION_NOTIFICATIONS: ReadonlyArray<string> = [\"accountsChanged\", \"chainChanged\"];\n/** The `nostr` namespace scope's granted methods — the NIP-07 surface. */\nexport const NOSTR_METHODS: ReadonlyArray<string> = [\n \"getPublicKey\",\n \"signEvent\",\n \"nip04.encrypt\",\n \"nip04.decrypt\",\n \"nip44.encrypt\",\n \"nip44.decrypt\",\n];\n\n/** The `lightning` namespace scope's granted methods — the WebLN surface. */\nexport const LIGHTNING_METHODS: ReadonlyArray<string> = [\n \"enable\",\n \"getInfo\",\n \"sendPayment\",\n \"makeInvoice\",\n \"lnurl\",\n \"getBalance\",\n];\n\n/** The `solana` namespace scope's granted methods — the Wallet Standard surface. */\nexport const SOLANA_METHODS: ReadonlyArray<string> = [\n \"standard:connect\",\n \"standard:disconnect\",\n \"standard:events\",\n \"solana:signTransaction\",\n \"solana:signAndSendTransaction\",\n \"solana:signMessage\",\n \"solana:signIn\",\n];\n\n/** The `bip122` namespace scope's granted methods — the Bitcoin Wallet Standard surface. */\nexport const BITCOIN_METHODS: ReadonlyArray<string> = [\n \"bitcoin:connect\",\n \"standard:disconnect\",\n \"bitcoin:events\",\n \"bitcoin:signMessage\",\n \"bitcoin:signTransaction\",\n \"bitcoin:signAndSendTransaction\",\n];\n\n/** `payment` is the group's `btc.bip84` address, `ordinals` its `btc.bip86` one. */\nexport type BitcoinPurpose = \"payment\" | \"ordinals\";\n\n/** The `tron` namespace scope's granted methods — the TronLink surface. */\nexport const TRON_METHODS: ReadonlyArray<string> = [\n \"eth_requestAccounts\",\n \"tron_requestAccounts\",\n \"wallet_switchEthereumChain\",\n \"wallet_watchAsset\",\n \"tron_signTransaction\",\n \"tron_sendRawTransaction\",\n \"tron_signMessageV2\",\n \"tron_signTypedData\",\n];\n\n/** The `tron` namespace scope's notifications. */\nexport const TRON_NOTIFICATIONS: ReadonlyArray<string> = [\"accountsChanged\", \"chainChanged\"];\n\n/** The order of a `bip122` scope's two accounts. */\nexport const BITCOIN_PURPOSES: ReadonlyArray<BitcoinPurpose> = [\"payment\", \"ordinals\"];\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 isGroup = (value: unknown): value is AccountGroup =>\n isObject(value) &&\n typeof value[\"walletId\"] === \"string\" &&\n typeof value[\"groupIndex\"] === \"number\" &&\n Number.isSafeInteger(value[\"groupIndex\"]) &&\n value[\"groupIndex\"] >= 0;\n\nconst isIdentity = (value: unknown): value is NostrKeyRef =>\n isObject(value) &&\n value[\"kind\"] === \"derived\" &&\n typeof value[\"walletId\"] === \"string\" &&\n typeof value[\"index\"] === \"number\" &&\n Number.isSafeInteger(value[\"index\"]) &&\n value[\"index\"] >= 0;\n\nexport const isSession = (value: unknown): value is ConnectionSession => {\n if (!isObject(value) || !isObject(value[\"scopes\"])) {\n return false;\n }\n const { origin } = value;\n return (\n typeof value[\"id\"] === \"string\" &&\n isDappOrigin(origin) &&\n (origin.kind !== \"walletconnect\" || origin.origin === walletConnectKey(origin.topic)) &&\n typeof value[\"currentNetwork\"] === \"string\" &&\n (value[\"tronNetwork\"] === undefined || typeof value[\"tronNetwork\"] === \"string\") &&\n typeof value[\"createdAt\"] === \"number\" &&\n typeof value[\"lastUsedAt\"] === \"number\" &&\n (value[\"group\"] === undefined || isGroup(value[\"group\"])) &&\n (value[\"identity\"] === undefined || isIdentity(value[\"identity\"])) &&\n (value[\"nostrPolicy\"] === undefined || isNostrPolicy(value[\"nostrPolicy\"])) &&\n (value[\"lightningPolicy\"] === undefined || isLightningPolicy(value[\"lightningPolicy\"]))\n );\n};\n\nconst isLightningPolicy = (value: unknown): value is LightningPolicy =>\n isObject(value) && typeof value[\"balance\"] === \"boolean\";\n\nconst isNostrPolicy = (value: unknown): value is NostrPolicy =>\n isObject(value) &&\n typeof value[\"decrypt\"] === \"boolean\" &&\n (value[\"signing\"] === \"ask\" ||\n value[\"signing\"] === \"always\" ||\n (isObject(value[\"signing\"]) &&\n Array.isArray(value[\"signing\"][\"kinds\"]) &&\n (value[\"signing\"][\"kinds\"] as unknown[]).every((k) => typeof k === \"number\")));\n\n/**\n * What a session authorized on one network: the addresses the page may see and the group whose keys\n * sign for them.\n */\nexport type SessionAccounts = {\n readonly group: AccountGroup;\n readonly addresses: ReadonlyArray<string>;\n};\n\n/** `undefined` unless the session covers `network` with at least one account and has a group. */\nexport const sessionAccounts = (\n session: ConnectionSession | undefined,\n network: string,\n): SessionAccounts | undefined => {\n const scope = session?.scopes[network];\n if (session?.group === undefined || scope === undefined || scope.accounts.length === 0) {\n return undefined;\n }\n return { group: session.group, addresses: scope.accounts.map(addressOf) };\n};\n\n/** The identity and pubkey a session bound to its `nostr` scope; `undefined` when it has neither. */\nexport const sessionIdentity = (\n session: ConnectionSession | undefined,\n): { readonly ref: NostrKeyRef; readonly pubkey: string } | undefined => {\n const account = session?.scopes[\"nostr\"]?.accounts[0];\n if (session?.identity === undefined || account === undefined) {\n return undefined;\n }\n return { ref: session.identity, pubkey: addressOf(account) };\n};\n\nconst sameGroup = (a: AccountGroup | undefined, b: AccountGroup | undefined): boolean =>\n a === undefined || b === undefined\n ? a === b\n : a.walletId === b.walletId && a.groupIndex === b.groupIndex;\n\n/** A scope a group signs for — chain networks and `lightning`; `nostr` belongs to the identity. */\nconst isChainScope = (network: string): boolean =>\n network === \"lightning\" ||\n network.startsWith(\"eip155:\") ||\n network.startsWith(\"solana:\") ||\n network.startsWith(\"bip122:\") ||\n network.startsWith(\"tron:\");\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 readonly expiries = new Map<string, () => void>();\n private identity: NostrKeyRef | undefined;\n private unsubscribeSelection: (() => void) | undefined;\n private writeQueue: Promise<void> = Promise.resolve();\n\n constructor(options: ConnectionControllerOptions) {\n super({\n name: \"connections\",\n defaultState: () => ({ sessions: {}, pending: {}, ready: false }),\n });\n this.options = options;\n }\n\n async init(): Promise<void> {\n const store = await this.options.openStore();\n this.engineStore = store;\n this.identity = 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 = readJson(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: {}, ready: true }));\n this.unsubscribeSelection = this.options.onSelectedGroup(() => {\n this.options.invalidateAll();\n void this.repointQueued();\n });\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.unsubscribeSelection?.();\n this.unsubscribeSelection = undefined;\n this.engineStore = undefined;\n for (const waiter of this.waiters.values()) {\n waiter.reject(userRejectedRequest(\"the wallet was locked\"));\n }\n this.waiters.clear();\n for (const cancel of this.expiries.values()) {\n cancel();\n }\n this.expiries.clear();\n this.update(() => ({ sessions: {}, pending: {}, ready: false }));\n }\n\n /**\n * A page navigated away (or the bridge is being disposed): the origin's pending connection\n * requests are rejected and its unfinished pipeline requests voided — the live session survives\n * (a refresh is not a revocation).\n */\n invalidateOrigin(origin: string): void {\n for (const entry of this.pending()) {\n if (entry.origin.origin !== origin) {\n continue;\n }\n this.waiters.get(entry.id)?.reject(userRejectedRequest(\"the page navigated away\"));\n this.dropPending(entry.id);\n }\n this.options.invalidate(origin);\n }\n\n /**\n * Throws `4100` unless `origin` is `https://host[:port]` (or localhost in development) and not on\n * the phishing list. A WalletConnect peer instead passes its origin object: an established\n * session must carry the same session key and topic, and its unverified peer URL must not be on\n * the phishing list.\n */\n checkOrigin(origin: string | WalletConnectOrigin): ConnectionOrigin {\n if (typeof origin !== \"string\") {\n const session = Object.values(this.getState().sessions).find(\n (s) =>\n s.origin.kind === \"walletconnect\" &&\n s.origin.origin === origin.origin &&\n s.origin.topic === origin.topic,\n );\n if (session === undefined) {\n throw unauthorized();\n }\n if (this.options.phishing.check(origin.url) === \"blocked\") {\n throw unauthorized(PHISHING_BLOCKED_MESSAGE);\n }\n return origin;\n }\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 if (this.options.phishing.check(origin) === \"blocked\") {\n throw unauthorized(PHISHING_BLOCKED_MESSAGE);\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 /** What the origin's session authorized on `network` — `undefined` when nothing. */\n sessionAccounts(origin: string, network: string): SessionAccounts | undefined {\n return sessionAccounts(this.session(origin), network);\n }\n\n /**\n * The selected group's accounts on `network` as a grant would bind them — a preview for callers\n * that sign before a session exists; nothing is persisted. `undefined` when no group is selected\n * or the account cannot be derived.\n */\n async previewAccounts(network: string): Promise<SessionAccounts | undefined> {\n const group = this.options.selectedGroup();\n if (group === undefined) {\n return undefined;\n }\n const bound = await this.repointScopes(\n { [network]: { accounts: [], methods: [], notifications: [] } },\n group,\n );\n const scope = bound[network];\n if (scope === undefined || scope.accounts.length === 0) {\n return undefined;\n }\n return { group, addresses: scope.accounts.map(addressOf) };\n }\n\n /** The identity the origin's `nostr` scope is bound to, with the pubkey the page sees. */\n nostrIdentity(\n origin: string,\n ): { readonly ref: NostrKeyRef; readonly pubkey: string } | undefined {\n return sessionIdentity(this.session(origin));\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 /** 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, namespace = \"eip155\", network, activate = true }: ConnectionRequest,\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 if (this.pending().length >= MAX_PENDING_CONNECTIONS) {\n throw requestPending(\"too many pending connection requests\");\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: this.session(origin)?.origin ?? { kind: \"browser\", origin },\n kind,\n namespace,\n ...(network === undefined ? {} : { network }),\n ...(activate ? {} : { activate }),\n createdAt: this.options.now(),\n };\n return new Promise<ConnectionSession>((resolve, reject) => {\n this.waiters.set(id, { resolve, reject });\n this.expiries.set(\n id,\n this.options.setTimer(CONNECTION_REQUEST_TTL_MS, () => {\n this.waiters.get(id)?.reject(userRejectedRequest(\"the connection request expired\"));\n this.dropPending(id);\n }),\n );\n this.update((s) => ({ ...s, pending: { ...s.pending, [id]: entry } }));\n });\n }\n\n /**\n * The host's approval, by id: the accounts granted (of the app's selected group for a\n * chain/lightning grant, of the active identity for `nostr`) and the network. The whole\n * derivation, merge and persist runs inside the session write queue, so a concurrent group switch\n * cannot interleave.\n */\n async approveConnection(\n id: string,\n grant: {\n readonly accounts: ReadonlyArray<string>;\n readonly network: string;\n /** The `nostr` namespace's grant: the identity's pubkey and the origin's policy. */\n readonly nostr?: { readonly pubkey: string; readonly policy: NostrPolicy };\n /** The `lightning` namespace's grant: the origin's policy. */\n readonly lightning?: { readonly policy: LightningPolicy };\n },\n ): Promise<ConnectionSession> {\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 (this.options.phishing.check(dappUrl(entry.origin)) === \"blocked\") {\n const blocked = unauthorized(PHISHING_BLOCKED_MESSAGE);\n this.dropPending(id);\n waiter.reject(blocked);\n throw blocked;\n }\n if (entry.kind === \"network\" && entry.network !== grant.network) {\n throw new Error(`connection request ${id} is for ${String(entry.network)}`);\n }\n return this.serial(async () => {\n const store = this.requireStore();\n const { scopes, group, identity, tronNetwork } = await this.grantScopes(entry, grant);\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 /*\n * A grant binds to the current group: merging into a session bound to another re-points the\n * existing chain/lightning scopes in the same write — a session never mixes groups.\n */\n const repointed =\n group !== undefined && existing !== undefined && !sameGroup(existing.group, group);\n const merged = repointed\n ? await this.repointScopes(existing.scopes, group)\n : { ...existing?.scopes };\n const sessionGroup = group ?? existing?.group;\n const sessionIdentity = identity ?? existing?.identity;\n const sessionTronNetwork = tronNetwork ?? existing?.tronNetwork;\n /* A later grant (e.g. an added network) keeps the policies an earlier grant set. */\n const nostrPolicy = grant.nostr?.policy ?? existing?.nostrPolicy;\n const lightningPolicy = grant.lightning?.policy ?? existing?.lightningPolicy;\n const session: ConnectionSession = {\n id: existing?.id ?? this.newSessionId(),\n origin: entry.origin,\n scopes: { ...merged, ...scopes },\n currentNetwork:\n entry.activate === false && existing !== undefined\n ? existing.currentNetwork\n : grant.network,\n ...(sessionGroup === undefined ? {} : { group: sessionGroup }),\n ...(sessionIdentity === undefined ? {} : { identity: sessionIdentity }),\n ...(sessionTronNetwork === undefined ? {} : { tronNetwork: sessionTronNetwork }),\n ...(nostrPolicy === undefined ? {} : { nostrPolicy }),\n ...(lightningPolicy === undefined ? {} : { lightningPolicy }),\n createdAt: existing?.createdAt ?? now,\n lastUsedAt: now,\n };\n await this.persist(store, session);\n this.dropPending(id);\n if (\n repointed ||\n (existing !== undefined && existing.currentNetwork !== session.currentNetwork)\n ) {\n this.options.invalidate(entry.origin.origin);\n }\n waiter.resolve(session);\n return session;\n });\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 /**\n * Establishes a WalletConnect peer's session inside the session write queue: each network's scope\n * is bound to the selected group's accounts, `settle` receives the bound scopes and settles the\n * peer on the relay, returning its origin, and the session is persisted under that origin — a\n * group switch cannot interleave between the accounts the peer is given and the ones recorded.\n * Nothing is persisted when `settle` throws.\n */\n async establishWalletConnect(\n scopes: Readonly<Record<string, Omit<ConnectionScope, \"accounts\">>>,\n settle: (scopes: Readonly<Record<string, ConnectionScope>>) => Promise<WalletConnectOrigin>,\n ): Promise<ConnectionSession> {\n return this.serial(async () => {\n const store = this.requireStore();\n const group = this.options.selectedGroup();\n if (group === undefined) {\n throw userRejectedRequest(\"no account group is selected\");\n }\n const enabled = this.options.enabledNetworks();\n const boundable = (network: string): boolean =>\n (network.startsWith(\"eip155:\") ||\n network.startsWith(\"solana:\") ||\n network.startsWith(\"bip122:\")) &&\n enabled.includes(network);\n const requested = Object.keys(scopes);\n const [first] = requested;\n if (first === undefined || !requested.every(boundable)) {\n throw invalidParams(\"every scope must name an enabled eip155, solana or bip122 network\");\n }\n const bound = await this.repointScopes(\n Object.fromEntries(\n Object.entries(scopes).map(([network, scope]) => [network, { ...scope, accounts: [] }]),\n ),\n group,\n );\n if (Object.values(bound).some((scope) => scope.accounts.length === 0)) {\n throw internalError(\"an account could not be derived for a granted network\");\n }\n const origin = await settle(bound);\n const existing = this.session(origin.origin);\n const now = this.options.now();\n const session: ConnectionSession = {\n id: existing?.id ?? this.newSessionId(),\n origin,\n scopes: bound,\n group,\n currentNetwork: requested.find((network) => network.startsWith(\"eip155:\")) ?? first,\n createdAt: existing?.createdAt ?? now,\n lastUsedAt: now,\n };\n await this.persist(store, session);\n return session;\n });\n }\n\n /** Ends the origin's session; its pending connection and unfinished requests are void. */\n async revoke(origin: string): Promise<void> {\n await this.serial(async () => {\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\n /** Switches within the session's scope; the origin's unfinished requests are void. */\n async setCurrentNetwork(origin: string, network: string): Promise<void> {\n await this.serial(async () => {\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\n /** Switches the session's TRON network; the origin's unfinished requests are void. */\n async setTronNetwork(origin: string, network: string): Promise<void> {\n await this.serial(async () => {\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, tronNetwork: network });\n this.options.invalidate(origin);\n });\n }\n\n async touch(origin: string): Promise<void> {\n await this.serial(async () => {\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 active Nostr identity — `undefined` until the host picks one. */\n activeIdentity(): NostrKeyRef | undefined {\n return this.identity;\n }\n\n /** The origin's persisted Nostr policy — `undefined` until it is nostr-authorized. */\n nostrPolicy(origin: string): NostrPolicy | undefined {\n return this.session(origin)?.nostrPolicy;\n }\n\n /** The origin's persisted Lightning policy — `undefined` until it is lightning-authorized. */\n lightningPolicy(origin: string): LightningPolicy | undefined {\n return this.session(origin)?.lightningPolicy;\n }\n\n private async bitcoinScope(group: AccountGroup, network: string): Promise<ConnectionScope> {\n const addresses = await Promise.all(\n BITCOIN_PURPOSES.map(async (purpose) => this.options.bitcoinAddress(group, network, purpose)),\n );\n return {\n accounts: addresses.map((address) => caip10(network, address)),\n methods: BITCOIN_METHODS,\n notifications: [\"change\"],\n };\n }\n\n /**\n * The host's Nostr identity selection: the pubkey is derived first, then every session with a\n * non-empty `nostr` scope is re-pointed — `identity` and the scope's account written together —\n * and the origin's unfinished requests voided. No event — NIP-07 has none.\n */\n async setActiveIdentity(ref: NostrKeyRef | undefined): Promise<void> {\n await this.serial(async () => {\n const store = this.requireStore();\n let pubkey: string | undefined;\n if (ref !== undefined) {\n const raw = await this.options.nostrPubkey(ref);\n pubkey = raw.toLowerCase();\n }\n this.identity = ref;\n for (const session of Object.values(this.getState().sessions)) {\n const scope = session.scopes[\"nostr\"];\n if (scope === undefined || scope.accounts.length === 0) {\n continue;\n }\n const { identity: _gone, ...rest } = session;\n // oxlint-disable-next-line eslint/no-await-in-loop -- session writes are serialized.\n await this.persist(store, {\n ...rest,\n scopes: {\n ...session.scopes,\n nostr: {\n ...scope,\n accounts: pubkey === undefined ? [] : [`nostr:${pubkey}`],\n },\n },\n ...(ref === undefined ? {} : { identity: ref }),\n });\n this.options.invalidate(session.origin.origin);\n }\n });\n }\n\n /**\n * Every session write — a re-point, a grant's merge and persist, a revoke, a network switch, a\n * touch — queues here so one writer runs at a time and reads the latest session at its turn. A\n * failed task does not break the chain.\n */\n private async serial<T>(task: () => Promise<T>): Promise<T> {\n const previous = this.writeQueue;\n let release: (() => void) | undefined;\n this.writeQueue = new Promise<void>((resolve) => {\n release = resolve;\n });\n await previous;\n try {\n return await task();\n } finally {\n release?.();\n }\n }\n\n private async repointQueued(): Promise<void> {\n try {\n await this.serial(async () => this.repoint());\n } catch (error: unknown) {\n this.options.logger.warn(\"connection re-point failed\", error);\n }\n }\n\n /**\n * Re-binds every session's chain/lightning scopes to the app's current group selection: each\n * scope's accounts become the target's (empty when the selection is cleared or a derivation\n * fails), `group` written together with them. The origin's unfinished requests are voided.\n */\n private async repoint(): Promise<void> {\n const store = this.requireStore();\n const target = this.options.selectedGroup();\n for (const session of Object.values(this.getState().sessions)) {\n if (!Object.keys(session.scopes).some(isChainScope) || sameGroup(session.group, target)) {\n continue;\n }\n // oxlint-disable-next-line eslint/no-await-in-loop -- session writes are serialized.\n const scopes = await this.repointScopes(session.scopes, target);\n const { group: _gone, ...rest } = session;\n // oxlint-disable-next-line eslint/no-await-in-loop -- session writes are serialized.\n await this.persist(store, {\n ...rest,\n scopes,\n ...(target === undefined ? {} : { group: target }),\n });\n this.options.invalidate(session.origin.origin);\n }\n }\n\n /**\n * A session's scopes re-computed for `target`: EVM and Solana scope accounts are the group's\n * address, `bip122` its two purpose addresses, `lightning` its `spark:` ref; `nostr` is the\n * identity's and passes through. `target` undefined or a failed derivation → empty accounts.\n */\n private async repointScopes(\n scopes: Readonly<Record<string, ConnectionScope>>,\n target: AccountGroup | undefined,\n ): Promise<Record<string, ConnectionScope>> {\n const entries = await Promise.all(\n Object.entries(scopes).map(async ([network, scope]): Promise<[string, ConnectionScope]> => {\n if (network === \"nostr\") {\n return [network, scope];\n }\n if (target === undefined) {\n return [network, { ...scope, accounts: [] }];\n }\n try {\n if (network === \"lightning\") {\n return [\n network,\n { ...scope, accounts: [`spark:${target.walletId}:${String(target.groupIndex)}`] },\n ];\n }\n if (network.startsWith(\"bip122:\")) {\n const bound = await this.bitcoinScope(target, network);\n return [network, { ...scope, accounts: bound.accounts }];\n }\n if (network.startsWith(\"solana:\")) {\n const address = await this.options.solanaAddress(target, network);\n return [network, { ...scope, accounts: [caip10(network, address)] }];\n }\n if (network.startsWith(\"tron:\")) {\n const address = await this.options.tronAddress(target, network);\n return [network, { ...scope, accounts: [caip10(network, address)] }];\n }\n if (network.startsWith(\"eip155:\")) {\n const address = await this.options.evmAddress(target, network);\n return [network, { ...scope, accounts: [caip10(network, address.toLowerCase())] }];\n }\n return [network, scope];\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 return Object.fromEntries(entries);\n }\n\n /**\n * The scopes a grant produces, bound to the app's selected group (chain/lightning namespaces) or\n * the active identity (`nostr`) — read at write-queue turn, not request time.\n */\n private async grantScopes(\n entry: PendingConnection,\n grant: Parameters<ConnectionController[\"approveConnection\"]>[1],\n ): Promise<{\n readonly scopes: Record<string, ConnectionScope>;\n readonly group?: AccountGroup;\n readonly identity?: NostrKeyRef;\n readonly tronNetwork?: string;\n }> {\n const scopes: Record<string, ConnectionScope> = {};\n if (entry.namespace === \"nostr\") {\n if (grant.nostr === undefined) {\n throw invalidParams(\"a nostr connection needs the identity's pubkey and policy\");\n }\n const identity = this.activeIdentity();\n if (identity === undefined) {\n throw userRejectedRequest(\"no nostr identity is selected\");\n }\n const identityRaw = await this.options.nostrPubkey(identity);\n const identityPubkey = identityRaw.toLowerCase();\n if (grant.nostr.pubkey.toLowerCase() !== identityPubkey) {\n throw invalidParams(\"only the active identity can be granted\");\n }\n scopes[\"nostr\"] = {\n accounts: [`nostr:${identityPubkey}`],\n methods: NOSTR_METHODS,\n notifications: [],\n };\n return { scopes, identity };\n }\n if (entry.namespace === \"lightning\") {\n if (grant.lightning === undefined) {\n throw invalidParams(\"a lightning connection needs the origin's policy\");\n }\n const group = this.options.selectedGroup();\n if (group === undefined) {\n throw new Error(\"no account group is selected\");\n }\n scopes[\"lightning\"] = {\n accounts: [`spark:${group.walletId}:${String(group.groupIndex)}`],\n methods: LIGHTNING_METHODS,\n notifications: [],\n };\n return { scopes, group };\n }\n const group = this.options.selectedGroup();\n if (group === undefined) {\n throw new Error(\"no account group is selected\");\n }\n if (entry.namespace === \"solana\") {\n const solanaNetworks = this.options.enabledNetworks().filter((n) => n.startsWith(\"solana:\"));\n const solanaEntries = await Promise.all(\n solanaNetworks.map(async (network): Promise<[string, ConnectionScope]> => {\n const address = await this.options.solanaAddress(group, network);\n return [\n network,\n {\n accounts: [caip10(network, address)],\n methods: SOLANA_METHODS,\n notifications: [\"change\"],\n },\n ];\n }),\n );\n Object.assign(scopes, Object.fromEntries(solanaEntries));\n return { scopes, group };\n }\n if (entry.namespace === \"tron\") {\n const tronNetworks = this.options.enabledNetworks().filter((n) => n.startsWith(\"tron:\"));\n if (!tronNetworks.includes(grant.network)) {\n throw invalidParams(`${grant.network} is not an enabled TRON network`);\n }\n const tronEntries = await Promise.all(\n tronNetworks.map(async (network): Promise<[string, ConnectionScope]> => {\n const address = await this.options.tronAddress(group, network);\n return [\n network,\n {\n accounts: [caip10(network, address)],\n methods: TRON_METHODS,\n notifications: TRON_NOTIFICATIONS,\n },\n ];\n }),\n );\n Object.assign(scopes, Object.fromEntries(tronEntries));\n return { scopes, group, tronNetwork: grant.network };\n }\n if (entry.namespace === \"bip122\") {\n const bitcoinNetworks = this.options.enabledNetworks().filter((n) => n.startsWith(\"bip122:\"));\n const bitcoinEntries = await Promise.all(\n bitcoinNetworks.map(async (network): Promise<[string, ConnectionScope]> => [\n network,\n await this.bitcoinScope(group, network),\n ]),\n );\n Object.assign(scopes, Object.fromEntries(bitcoinEntries));\n return { scopes, group };\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 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 selected group's account can be granted\");\n }\n scopes[grant.network] = {\n accounts: [caip10(grant.network, own)],\n methods: SESSION_METHODS,\n notifications: SESSION_NOTIFICATIONS,\n };\n return { scopes, group };\n }\n\n private newSessionId(): string {\n return `session-${[...this.options.random(8)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\")}`;\n }\n\n private dropPending(id: string): void {\n this.expiries.get(id)?.();\n this.expiries.delete(id);\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","/**\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 { ChainError } from \"@qntx/wallet-chains\";\nimport type { BitcoinAccountTemplate } from \"@qntx/wallet-chains/bitcoin\";\nimport type { decodeEvm } from \"@qntx/wallet-chains/evm\";\nimport type { chains, ChainsApi } from \"@qntx/wallet/chains\";\n\nimport type { EvmFeeTier } from \"../chains/evm.ts\";\nimport type { SolanaFeeTier } from \"../chains/solana.ts\";\nimport type { TronFeeQuote } from \"../chains/tron.ts\";\nimport { errorMessage } from \"../errors.ts\";\nimport type { EngineLogger } from \"../events.ts\";\nimport type { NetworkController } from \"../networks/controller.ts\";\nimport type { NetworkInfo } from \"../networks/registry.ts\";\nimport type { RequestCheckCode } from \"../requests/checks.ts\";\nimport type { RiskFinding } from \"../requests/risk.ts\";\nimport type { SimulationOutcome } from \"../requests/simulation.ts\";\nimport type { DappOrigin } from \"../requests/types.ts\";\nimport type { EngineStore } from \"../store/port.ts\";\nimport type { AcrossBridgeQuote } from \"../swaps/bridge.ts\";\nimport type { JupiterSwapQuote, ZeroExSwapQuote } from \"../swaps/index.ts\";\n\n/* The engine's sign widens the wallet API with the hardware acknowledgement: routes pass it once\n the `bitcoin-unconfirmed-output` danger finding was acknowledged at approve. Software wallets\n and the card path ignore it — their material is always confirmed. */\nexport type ChainApis = Omit<ReturnType<typeof chains>, \"sign\"> & {\n readonly sign: (\n params: Parameters<ChainsApi[\"sign\"]>[0] & { readonly acknowledgeUnconfirmed?: true },\n ) => ReturnType<ChainsApi[\"sign\"]>;\n};\nexport type SignParams = Parameters<ChainApis[\"sign\"]>[0];\nexport type SignResult = Awaited<ReturnType<ChainApis[\"sign\"]>>;\nexport type AccountRef = Exclude<SignParams[\"request\"], { kind: \"bitcoin.psbt\" }>[\"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/** Where an on-chain transaction sits, as its tracker last saw it. */\nexport type TxBlock = {\n /** Block hash; absent on Solana, whose status answer names only the slot. */\n readonly hash?: string;\n /** Block number (EVM), height (Bitcoin) or slot (Solana). */\n readonly height: number;\n};\n\n/**\n * What one status poll established; a poll returning `undefined` changes nothing. `included` is a\n * transaction in a block — kept tracked until `final`; `reorged` is its block leaving the chain;\n * `ended` is a terminal answer the tracker stops on. `waiting` is still live: its `error` says why\n * the transaction cannot land yet, `undefined` clears an earlier note; `stuck` marks a row no\n * endpoint has known for `STUCK_AFTER_MS` — a live mark, never terminal.\n */\nexport type TxPoll =\n | {\n readonly kind: \"included\";\n readonly state: \"confirmed\" | \"failed\";\n readonly block: TxBlock;\n readonly final: boolean;\n /** An on-chain failure's reason (receipt result plus burned fee), persisted on the row. */\n readonly error?: string;\n }\n | { readonly kind: \"reorged\" }\n | { readonly kind: \"ended\"; readonly state: \"failed\" | \"dropped\" | \"replaced\" }\n | {\n readonly kind: \"waiting\";\n readonly error: string | undefined;\n /** Set only when the mark is on; an absent `stuck` clears it — see `TrackedTransaction.stuck`. */\n readonly stuck?: boolean;\n };\n\n/** In a block but not final yet: tracked at the finality interval. */\nexport const awaitingFinality = (tx: TrackedTransaction): boolean =>\n tx.block !== undefined &&\n tx.final !== true &&\n (tx.state === \"confirmed\" || tx.state === \"failed\");\n\n/**\n * The recheck answer for a transaction already in `tx.block`: `undefined` when state, block and\n * finality are unchanged. Hashes compare lowercase.\n */\nexport const includedPoll = (\n tx: TrackedTransaction,\n state: \"confirmed\" | \"failed\",\n block: TxBlock,\n final: boolean,\n error?: string,\n): TxPoll | undefined =>\n tx.state === state &&\n tx.final === final &&\n tx.block?.height === block.height &&\n tx.block.hash?.toLowerCase() === block.hash?.toLowerCase()\n ? undefined\n : { kind: \"included\", state, block, final, ...(error === undefined ? {} : { error }) };\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\" | \"tron\";\n readonly network: string;\n /** The signer's identity label — `walletId` for HD accounts, `keyId` for imported keys. */\n readonly account: string;\n readonly hash: string | undefined;\n readonly state: TxState;\n readonly intent: DisplayIntent | undefined;\n readonly nonce: number;\n /**\n * The block a `confirmed` or on-chain `failed` transaction is in; cleared when a reorg returns it\n * to `submitted`.\n */\n readonly block?: TxBlock | undefined;\n /**\n * Past the network's finality rule (EVM `finalized` tag, 6 Bitcoin confirmations, Solana\n * `finalized`): never changes again, no longer polled.\n */\n readonly final?: boolean | undefined;\n /** Solana only — the blockhash expiry that turns an unconfirmed tx `dropped`. */\n readonly lastValidBlockHeight?: number;\n /**\n * Solana only — a durable-nonce transaction has no block-height expiry: `account` is the nonce\n * account and `value` the nonce its first instruction advances, read back on each poll. `account`\n * is undefined when the message loads it from a lookup table: nothing to read on it, so the\n * transaction is never dropped — only resolved by landing.\n */\n readonly durableNonce?: { readonly account: string | undefined; readonly value: string };\n /**\n * TRON build record — `raw_data.expiration` bounds drop proofs (past it the network can never\n * include the transaction); `from` is the sender, for group membership like `evm.from`.\n * `dappSignature` is set on a dApp-observed entry: the wallet-signed signature (lowercase hex)\n * `submitDappTron` later matches against the bytes the dApp broadcasts.\n */\n readonly tron?: {\n readonly expiration: number;\n readonly from: string;\n readonly dappSignature?: string;\n };\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 /**\n * Absent: the tracker may rebroadcast the persisted bytes while the network does not know them.\n * `false`: recovered from a broadcast whose outcome never settled — it may have been refused — so\n * the bytes are watched but never resent; a speed-up or cancel is the remedy.\n */\n readonly rebroadcast?: false;\n /**\n * EVM and Bitcoin: neither endpoint has known this transaction for `STUCK_AFTER_MS`. It stays\n * `submitted`, still holds its nonce or inputs and is polled at the finality interval; offer\n * speed-up or cancel.\n */\n readonly stuck?: boolean | undefined;\n /**\n * The signed transaction exactly as broadcast — EVM and Bitcoin hex, Solana base64 wire —\n * persisted with `hash` before it leaves, so an unknown outcome is rebroadcast, even after a\n * restart. Cleared when the node refuses it.\n */\n readonly raw?: string | undefined;\n /** EVM build record persisted with `raw`, for drop detection and replacement. */\n readonly evm?: { readonly from: string; readonly account: AccountRef };\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 /** The account shape the transaction was built from — needed to rebuild it after a restart. */\n readonly template: BitcoinAccountTemplate;\n readonly groupIndex: number;\n readonly tier: \"fast\" | \"normal\" | \"slow\";\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 /**\n * Bitcoin only — the exact outpoints (`txid:vout`) this send spends; omit for automatic\n * selection. Naming an inscription-protected output opts into spending it.\n */\n readonly inputs?: ReadonlyArray<string>;\n /** TRON only — the `raw_data.data` memo; refused on every other family. */\n readonly memo?: string;\n readonly verify: SignParams[\"verify\"];\n};\n\nexport type PrepareParams = Omit<SendParams, \"verify\">;\n\nexport type { ChainRequestMethod } from \"../requests/types.ts\";\n\n/** One standing EVM approval to remove. */\nexport type EvmRevokeTarget =\n | { readonly kind: \"erc20\"; readonly token: string; readonly spender: string }\n | { readonly kind: \"permit2\"; readonly token: string; readonly spender: string }\n | { readonly kind: \"operator\"; readonly contract: string; readonly operator: string }\n | { readonly kind: \"nft\"; readonly contract: string; readonly tokenId: bigint };\n\n/** What a request asks for; replacements and CPFP name the original transaction. */\nexport type ChainRequestInput =\n | ({ readonly method: \"send\"; readonly origin?: DappOrigin } & PrepareParams)\n | { readonly method: \"speed-up\" | \"cancel\"; readonly txId: string }\n | { readonly method: \"cpfp\"; readonly txId: string; readonly feeRate: number }\n | {\n readonly method: \"evm-delegation\";\n readonly account: AccountRef;\n readonly network: string;\n readonly action: \"upgrade\" | \"revoke\";\n readonly fee: PrepareParams[\"fee\"];\n }\n | {\n readonly method: \"evm-batch\";\n readonly account: AccountRef;\n readonly network: string;\n readonly calls: ReadonlyArray<{\n readonly to: string;\n readonly value: bigint;\n readonly data: string;\n }>;\n readonly fee: PrepareParams[\"fee\"];\n /** A page asking for the batch (`wallet_sendCalls`); absent means the wallet itself. */\n readonly origin?: DappOrigin;\n }\n | {\n readonly method: \"evm-approve\";\n readonly account: AccountRef;\n readonly network: string;\n readonly token: string;\n readonly spender: string;\n readonly amount: bigint;\n readonly fee: PrepareParams[\"fee\"];\n }\n | {\n readonly method: \"evm-revoke\";\n readonly account: AccountRef;\n readonly network: string;\n /**\n * 1..EVM_BATCH_LIMIT distinct targets; more than one needs the account delegated to the\n * wallet's delegator.\n */\n readonly targets: ReadonlyArray<EvmRevokeTarget>;\n readonly fee: PrepareParams[\"fee\"];\n }\n | {\n /** The Hyperliquid CCTP deposit — `depositForBurnWithHook` on the route's messenger. */\n readonly method: \"evm-cctp\";\n readonly account: AccountRef;\n readonly network: string;\n readonly amount: bigint;\n readonly dex: \"perps\" | \"spot\";\n /** The Circle forward fee bound — strictly below `amount`. */\n readonly maxFee: bigint;\n readonly fee: PrepareParams[\"fee\"];\n }\n | {\n readonly method: \"evm-swap\";\n readonly account: AccountRef;\n readonly network: string;\n readonly quote: ZeroExSwapQuote;\n readonly fee: PrepareParams[\"fee\"];\n }\n | {\n readonly method: \"evm-bridge\";\n readonly account: AccountRef;\n readonly network: string;\n readonly quote: AcrossBridgeQuote;\n readonly fee: PrepareParams[\"fee\"];\n }\n | {\n readonly method: \"evm-nft-send\";\n readonly account: AccountRef;\n readonly network: string;\n /** The ERC-721 or ERC-1155 contract. */\n readonly contract: string;\n /** The ids sent — one for ERC-721, up to `EVM_BATCH_LIMIT` for ERC-1155. */\n readonly items: ReadonlyArray<{ readonly tokenId: bigint; readonly amount?: bigint }>;\n readonly to: string;\n readonly fee: PrepareParams[\"fee\"];\n }\n | {\n readonly method: \"solana-nft-send\";\n readonly account: AccountRef;\n readonly network: string;\n /** The SPL mint or Core asset account. */\n readonly asset: string;\n readonly to: string;\n readonly fee: PrepareParams[\"fee\"];\n }\n | {\n readonly method: \"solana-swap\";\n readonly account: AccountRef;\n readonly network: string;\n readonly quote: JupiterSwapQuote;\n readonly fee: PrepareParams[\"fee\"];\n }\n | {\n readonly method: \"evm-lido\";\n readonly account: AccountRef;\n readonly network: string;\n readonly action:\n | { readonly kind: \"stake\"; readonly amount: bigint }\n | { readonly kind: \"request\"; readonly amount: bigint }\n | { readonly kind: \"claim\"; readonly requestIds: ReadonlyArray<bigint> };\n readonly fee: PrepareParams[\"fee\"];\n }\n | {\n readonly method: \"solana-revoke\";\n readonly account: AccountRef;\n readonly network: string;\n /** 1..10 distinct token accounts the signer owns whose delegate is removed — one Revoke each. */\n readonly tokenAccounts: ReadonlyArray<string>;\n readonly fee: PrepareParams[\"fee\"];\n }\n | {\n readonly method: \"solana-stake\";\n readonly account: AccountRef;\n readonly network: string;\n readonly action:\n | { readonly kind: \"delegate\"; readonly lamports: bigint; readonly vote: string }\n | { readonly kind: \"deactivate\"; readonly stakeAccount: string }\n | {\n readonly kind: \"withdraw\";\n readonly stakeAccount: string;\n readonly lamports: bigint;\n };\n readonly fee: PrepareParams[\"fee\"];\n }\n | {\n readonly method: \"tron-stake\";\n readonly account: AccountRef;\n readonly network: string;\n readonly action:\n | {\n readonly kind: \"freeze\" | \"unfreeze\";\n readonly amount: bigint;\n readonly resource: \"bandwidth\" | \"energy\";\n }\n | { readonly kind: \"withdraw-expired\" }\n | { readonly kind: \"cancel-unfreeze\" }\n | {\n readonly kind: \"delegate\";\n readonly receiver: string;\n readonly amount: bigint;\n readonly resource: \"bandwidth\" | \"energy\";\n /** Lock the delegation for this many blocks (1..getMaxDelegateLockPeriod). */\n readonly lockBlocks?: number;\n }\n | {\n readonly kind: \"undelegate\";\n readonly receiver: string;\n readonly amount: bigint;\n readonly resource: \"bandwidth\" | \"energy\";\n }\n | {\n readonly kind: \"vote\";\n readonly votes: ReadonlyArray<{ readonly witness: string; readonly count: bigint }>;\n }\n | { readonly kind: \"claim-rewards\" };\n }\n | {\n readonly method: \"tron-approve\";\n readonly account: AccountRef;\n readonly network: string;\n readonly token: string;\n readonly spender: string;\n /** The new allowance in token units; 0 revokes. */\n readonly amount: bigint;\n };\n\n/** At most this many calls per batch — one approval stays reviewable. */\nexport const EVM_BATCH_LIMIT = 10;\n\n/**\n * One `wallet_sendCalls` bundle: the tracked transactions it produced so `wallet_getCallsStatus`\n * can aggregate them, retained alongside those transactions.\n */\nexport type BatchRecord = {\n readonly origin: string;\n readonly id: string;\n readonly network: string;\n readonly atomic: boolean;\n readonly txIds: ReadonlyArray<string>;\n readonly expected: number;\n readonly createdAt: number;\n};\n\n/** The account's EIP-7702 delegation state: `supported` follows the registry hash entry. */\nexport type DelegationStatus = {\n readonly supported: boolean;\n readonly state: \"none\" | \"ours\" | \"other\";\n readonly address?: string;\n};\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 /** The address the route resolved for `account` — what recipient risk calls self. */\n readonly signer?: string;\n readonly checks: ReadonlyArray<RequestCheckCode>;\n /** Findings a route can only see on-chain (contract recipient, empty token balance). */\n readonly risk?: ReadonlyArray<RiskFinding>;\n /** The TRON fee quote — the intent's fee field carries only `fee_limit`. */\n readonly tronFee?: TronFeeQuote;\n /** Absent when the request is not simulated (replacements, Bitcoin). */\n readonly simulation?: SimulationOutcome;\n /** Re-runs the same simulated call at approval; absent when there is nothing to re-run. */\n readonly resimulate?: () => Promise<SimulationOutcome>;\n /** Why the build can no longer be signed (nonce taken, blockhash expired), if so. */\n readonly staleReason: () => string | undefined | Promise<string | undefined>;\n /**\n * Signs, finalizes, broadcasts and hands the transaction to tracking. `commit` must run\n * immediately (no await in between) before the network send; a throw there means nothing may be\n * sent.\n */\n readonly submit: (\n verify: SendParams[\"verify\"],\n commit: () => void,\n ) => 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:\n | \"evm.personal-message\"\n | \"evm.fiat24-session\"\n | \"evm.typed-data\"\n | \"tron.message\"\n | \"tron.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 /** The address that will sign. */\n readonly signer: string;\n readonly submit: (verify: SendParams[\"verify\"]) => Promise<SignatureResult>;\n};\n\n/** A transaction signed for a counterpart that broadcasts it itself — nothing is tracked or sent. */\nexport type SignedTransactionResult =\n | { readonly kind: \"evm.signed-transaction\"; readonly signedTransaction: Uint8Array }\n | { readonly kind: \"tron.signed-transaction\"; readonly signature: Uint8Array };\n\n/**\n * A prepared QR transaction signature: all of `PreparedRequest`'s checks without its tracking —\n * `submit` signs the request's own bytes, `commit()`s before returning, and hands back the signed\n * material for the counterpart to broadcast.\n */\nexport type PreparedQrSign = Omit<PreparedRequest, \"submit\" | \"txId\"> & {\n /** The address that will sign. */\n readonly signer: string;\n readonly submit: (\n verify: SendParams[\"verify\"],\n commit: () => void,\n ) => Promise<SignedTransactionResult>;\n};\n\nexport type Options = {\n readonly wallet: Wallet;\n readonly networks: NetworkController;\n /** The session EngineStore — the engine opens it once per unlock and closes it on lock. */\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 /** The engine's signing path — `signers.apis`: custody dispatch lives in the signers module. */\n readonly chains: ReturnType<typeof chains>;\n /** A card wallet still waiting on a member card holds no groups — its addresses do not exist. */\n readonly isWalletIncomplete?: (walletId: string) => boolean;\n};\n\nexport type RouteContext = {\n readonly options: Options;\n /**\n * Applies `next` to `tx` and persists the row. A locked vault keeps the row out of state but\n * retains it for replay at the next unlock — unless `durable`, which throws instead: signed bytes\n * must be on disk before they leave. Only a durable call may throw on a store failure: a failed\n * non-durable write is retained and landed by the controller's own retry loop, since the bytes it\n * describes may already be out. The context belongs to the session that created it: after a\n * lock→unlock its calls are ignored (`durable` still throws), so a stale async result never\n * writes into the new session.\n */\n readonly transition: (\n tx: TrackedTransaction,\n next: Partial<TrackedTransaction>,\n durable?: boolean,\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\n/** The account's address; signer-dependent checks fail closed when an account carries none. */\nexport const accountAddress = (account: Readonly<Record<string, unknown>>): string => {\n const { address } = account;\n if (typeof address !== \"string\" || address === \"\") {\n throw new Error(\"account carries no address\");\n }\n return address;\n};\n\nexport const newRequestId = (random: (n: number) => Uint8Array): string => hexId(\"req\", random);\n\n/**\n * The chain binding of signed bytes (a TRON reference block, a Solana recent blockhash) is the only\n * thing keeping a transaction off the wrong chain. On a mainnet the binding needs no second source:\n * a binding from another chain makes the signature invalid on the mainnet, so nothing of more value\n * than the user chose can move — the build goes ahead flagged `reads-unverified`. On a testnet the\n * same attack inverts: a binding taken from the mainnet produces a signature valid on the mainnet\n * and moves real value, so a gateway-only testnet build is refused and a host endpoint must be\n * configured.\n */\nexport const assertGatewayOnlyBinding = (info: NetworkInfo, binding: string): void => {\n if (info.testnet) {\n throw new ChainError(\"invalid-request\", gatewayOnlyBindingMessage(info, binding));\n }\n};\n\n/** The refusal {@link assertGatewayOnlyBinding} throws — shared by typed binding errors. */\nexport const gatewayOnlyBindingMessage = (info: NetworkInfo, binding: string): string =>\n `only the gateway vouches for the ${binding} on ${info.id}; on a testnet a signature over another network's ${binding} could be valid there — configure a host endpoint in EngineOptions.rpc[\"${info.id}\"]`;\n\nconst TEMPLATE_FAMILY = {\n \"evm.bip44\": \"evm\",\n \"solana.bip44-change\": \"solana\",\n \"tron.bip44\": \"tron\",\n} as const;\n\n/**\n * The signer address for a send/sign account ref: HD refs derive through the chains proxy; an\n * imported ref resolves its stored address from `wallet.keys` — the ref's family and the key's\n * listed family must both match the network's family or the request is refused.\n */\nexport const accountAddressOf = async (\n ctx: RouteContext,\n account: AccountRef,\n template: keyof typeof TEMPLATE_FAMILY,\n network: string,\n): Promise<string> => {\n const family = TEMPLATE_FAMILY[template];\n if (account.kind === \"imported\") {\n if (account.family !== family) {\n throw new ChainError(\n \"invalid-request\",\n `an imported ${account.family} key cannot sign on a ${family} network`,\n );\n }\n const keys = await ctx.options.wallet.keys.list();\n const key = keys.find((entry) => entry.keyId === account.keyId);\n if (key === undefined) {\n throw new ChainError(\"invalid-request\", \"the imported key is not in the vault\");\n }\n if (key.family !== family) {\n throw new ChainError(\n \"invalid-request\",\n `the imported key is a ${key.family} key, not ${family}`,\n );\n }\n return key.address;\n }\n const apis = ctx.options.chains;\n return accountAddress(\n await apis.account({\n walletId: account.walletId,\n groupIndex: account.groupIndex,\n template,\n network,\n }),\n );\n};\n\nexport { errorMessage } from \"../errors.ts\";\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","import type { ConnectionController, ConnectionSession } from \"./controller.ts\";\n\ntype Sessions = Readonly<Record<string, ConnectionSession>>;\n\n/**\n * Fans events derived from session changes out to listeners. The store subscription is created with\n * the first listener and dropped with the last; `derive` may be async (its events are then\n * delivered once it settles).\n */\nexport class SessionEvents<E> {\n private readonly listeners = new Set<(event: E) => void>();\n private unsubscribe: (() => void) | undefined;\n\n private readonly connections: Pick<ConnectionController, \"getState\" | \"store\">;\n private readonly derive: (\n before: Sessions,\n after: Sessions,\n ) => ReadonlyArray<E> | Promise<ReadonlyArray<E>>;\n\n constructor(\n connections: Pick<ConnectionController, \"getState\" | \"store\">,\n derive: (before: Sessions, after: Sessions) => ReadonlyArray<E> | Promise<ReadonlyArray<E>>,\n ) {\n this.connections = connections;\n this.derive = derive;\n }\n\n subscribe(listener: (event: E) => void): () => void {\n this.listeners.add(listener);\n if (this.unsubscribe === undefined) {\n let previous = this.connections.getState().sessions;\n this.unsubscribe = this.connections.store.subscribe((state) => {\n const events = this.derive(previous, state.sessions);\n previous = state.sessions;\n if (Array.isArray(events)) {\n this.emit(events);\n } else {\n void (async () => {\n this.emit(await events);\n })();\n }\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 private emit(events: ReadonlyArray<E>): void {\n for (const event of events) {\n for (const listener of this.listeners) {\n listener(event);\n }\n }\n }\n}\n","/**\n * Broadcast with an outcome that is never guessed. The signed bytes and their locally computed id\n * are persisted, and what the transaction consumes (nonce, inputs) is held, before anything leaves;\n * a failed send then fails the transaction only when the node itself refuses those bytes — and that\n * refusal is persisted durably, so bytes the user was told failed are never broadcast again. Any\n * other failure — transport error, 5xx, timeout, an endpoint naming another id — may have reached\n * the mempool, so the transaction stays `submitted` and the tracker resolves it by id.\n */\nimport { errorMessage, submitTx } from \"./route.ts\";\nimport type { RouteContext, TrackedTransaction } from \"./route.ts\";\n\n/**\n * How long the network may not know a transaction before its row turns `stuck` — never terminal:\n * the bytes may still land, so the nonce or inputs stay held and the poll drops to the finality\n * interval until a chain answer resolves it.\n */\nexport const STUCK_AFTER_MS = 1_800_000;\n/** The note a stuck row carries; its remedies are speed-up and cancel. */\nexport const STUCK_NOTE =\n \"the network has not seen this transaction for 30 minutes — speed up or cancel it\";\n/** Rebroadcast backoff for a transaction the node does not know: base doubling up to the cap. */\nexport const RESUBMIT_BASE_MS = 15_000;\nexport const RESUBMIT_MAX_MS = 600_000;\n\n/** What a node's error says about these exact bytes, when it says anything definite. */\nexport type BroadcastVerdict = \"held\" | \"refused\" | undefined;\n\nexport type BroadcastOutcome =\n | { readonly kind: \"accepted\" }\n | { readonly kind: \"refused\"; readonly error: unknown }\n | { readonly kind: \"unknown\"; readonly error: unknown };\n\nexport type BroadcastAttempt = {\n /** The id computed from the signed bytes: EVM hash, Bitcoin txid, Solana signature. */\n readonly id: string;\n /** Sends the bytes; resolves with the id the endpoint reports. */\n readonly send: () => Promise<string>;\n /** `held`: the node already has these bytes; `refused`: it rejected them for good. */\n readonly verdict: (error: unknown) => BroadcastVerdict;\n /** Whether the network knows `id`, in the pool or on chain. */\n readonly known: () => Promise<boolean>;\n};\n\nexport const broadcastOutcome = async (attempt: BroadcastAttempt): Promise<BroadcastOutcome> => {\n let reported: string;\n try {\n reported = await attempt.send();\n } catch (error) {\n const verdict = attempt.verdict(error);\n if (verdict === \"held\") {\n return { kind: \"accepted\" };\n }\n if (verdict === undefined) {\n return { kind: \"unknown\", error };\n }\n // A retried or failed-over send is refused (nonce too low, inputs spent) when an earlier copy\n // of the same bytes already landed. A failed lookup cannot tell the two apart, so the outcome\n // is ambiguous — never a definite refusal: the bytes may have landed.\n let known: boolean;\n try {\n known = await attempt.known();\n } catch {\n return { kind: \"unknown\", error };\n }\n return known ? { kind: \"accepted\" } : { kind: \"refused\", error };\n }\n return reported === attempt.id\n ? { kind: \"accepted\" }\n : {\n kind: \"unknown\",\n error: new Error(`the endpoint reported ${reported} for ${attempt.id}`),\n };\n};\n\n/**\n * The node refused the signed bytes it was shown: nothing went out, so the request may fail. Every\n * other error `submitSigned` can raise happens before the broadcast.\n */\nexport class BroadcastRefusedError extends Error {\n constructor(nodeError: unknown) {\n super(errorMessage(nodeError), { cause: nodeError });\n this.name = \"BroadcastRefusedError\";\n }\n}\n\nexport type SubmittedBatch = {\n /**\n * Ids of exactly the transactions that went out (accepted or outcome unknown), in input order.\n * The stopped one and everything after it were not sent.\n */\n readonly ids: ReadonlyArray<string>;\n /** Where the batch stopped: `refused` only when the node itself rejected the bytes. */\n readonly stopped?: {\n readonly index: number;\n readonly reason: \"refused\" | \"not-sent\";\n readonly error: string;\n };\n};\n\n/**\n * Submits `count` signed transactions in order; stops at the first that does not go out — a later\n * one may depend on it, so it is never sent, and each is persisted by its own `submitSigned` just\n * before its own send so an unsent later item is never rebroadcast after a restart. Throws that\n * error when the first one does not go out (nothing was sent).\n */\nexport const submitInOrder = async (\n count: number,\n submit: (index: number) => Promise<string>,\n): Promise<SubmittedBatch> => {\n const ids: string[] = [];\n for (let index = 0; index < count; index += 1) {\n try {\n // oxlint-disable-next-line eslint/no-await-in-loop -- submissions are sequential per input.\n ids.push(await submit(index));\n } catch (error) {\n if (index === 0) {\n throw error;\n }\n return {\n ids,\n stopped: {\n index,\n reason: error instanceof BroadcastRefusedError ? \"refused\" : \"not-sent\",\n error: errorMessage(error),\n },\n };\n }\n }\n return { ids };\n};\n\nexport type SignedBroadcast = BroadcastAttempt & {\n /** The signed bytes as persisted for rebroadcast: EVM/Bitcoin hex, Solana base64 wire. */\n readonly raw: string;\n /** Build-record fields persisted with the bytes. */\n readonly record?: Partial<TrackedTransaction>;\n /** Holds what the transaction consumes once its bytes are persisted. */\n readonly hold: () => void;\n /** Frees it again when the node refuses the bytes. */\n readonly release: () => void;\n};\n\n/**\n * Persists the signed bytes and id on `tx` — throwing, with nothing sent, when the vault locked\n * first — holds what it consumes, then broadcasts. Accepted or unknown → `submitted` and tracked;\n * refused → released, `failed` is written durably so the refused bytes can never be recovered as\n * `signed` later — a `signed` row the failed write lost would resurrect them — and a\n * `BroadcastRefusedError` is thrown. A locked vault or failed write cannot block the refusal: the\n * terminal row then lands through the bookkeeping retry like any other. The refusal is the only\n * error allowed out once the send was attempted: anything else happens before bytes leave.\n */\nexport const submitSigned = async (\n ctx: RouteContext,\n tx: TrackedTransaction,\n signed: SignedBroadcast,\n): Promise<TrackedTransaction> => {\n let persisted: TrackedTransaction;\n try {\n persisted = await ctx.transition(\n tx,\n {\n ...signed.record,\n hash: signed.id,\n raw: signed.raw,\n },\n true,\n );\n } catch (error) {\n // Nothing was persisted or sent — a vault that locked first refuses the write — but the\n // caller may already hold what the transaction consumes (an EVM nonce): free it so later\n // sends are not stuck behind a gap.\n signed.release();\n throw error;\n }\n signed.hold();\n const outcome = await broadcastOutcome(signed);\n if (outcome.kind === \"refused\") {\n signed.release();\n const failed: Partial<TrackedTransaction> = {\n state: \"failed\",\n hash: undefined,\n raw: undefined,\n error: errorMessage(outcome.error),\n };\n try {\n await ctx.transition(persisted, failed, true);\n } catch {\n /* The vault locked or the store failed: the refusal still stands, so park the terminal\n row for the bookkeeping retry — a `signed` row left on disk would resurrect the\n refused bytes as `submitted` at the next unlock. */\n await ctx.transition(persisted, failed);\n }\n throw new BroadcastRefusedError(outcome.error);\n }\n if (outcome.kind === \"unknown\") {\n ctx.options.logger.warn(\n `transaction ${tx.id}: broadcast outcome unknown, tracking ${signed.id}`,\n outcome.error,\n );\n }\n return submitTx(ctx, persisted, signed.id);\n};\n","/** What a handler answers with (`4200`) for sign-message bytes that are not UTF-8 text. */\nexport const BLIND_SIGNING_MESSAGE = \"blind signing is not enabled: the message is not UTF-8 text\";\n\nconst decoder = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true });\n\n/** The bytes as UTF-8 text, or `undefined` when they are not valid UTF-8. */\nexport function utf8Text(bytes: Uint8Array): string | undefined {\n try {\n return decoder.decode(bytes);\n } catch {\n return undefined;\n }\n}\n","import { hexToBytes } from \"@noble/hashes/utils.js\";\nimport { base64 } from \"@scure/base\";\n\nimport { BITCOIN_NETWORKS } from \"../networks/registry.ts\";\nimport type { RequestController } from \"../requests/controller.ts\";\nimport type {\n BitcoinAccount,\n BitcoinPsbtInput,\n BitcoinSigHash,\n WalletConnectOrigin,\n} from \"../requests/types.ts\";\nimport type {\n BitcoinPurpose,\n ConnectionController,\n ConnectionOrigin,\n ConnectionSession,\n} from \"./controller.ts\";\nimport { BITCOIN_METHODS, BITCOIN_PURPOSES, sessionAccounts } from \"./controller.ts\";\nimport {\n ProviderError,\n batchStopped,\n internalError,\n invalidParams,\n toProviderError,\n} from \"./errors.ts\";\nimport { SessionEvents } from \"./subscription.ts\";\nimport { BLIND_SIGNING_MESSAGE, utf8Text } from \"./text.ts\";\n\n/**\n * The Bitcoin Wallet Standard (Exodus' `bitcoin:*` features, registered through\n * `@wallet-standard/wallet` like the Solana wallet) handler — the bridge routes `provider:\n * \"bitcoin\"` messages here.\n */\nexport type BitcoinRequest = {\n readonly method: string;\n readonly params?: unknown;\n /**\n * The CAIP-2 network the call targets — a WalletConnect request names it; the in-app-browser\n * bridge never sets it (the page has no say), so its calls use the wallet's default network.\n */\n readonly network?: string;\n};\n\nexport type BitcoinHandler = {\n readonly handle: (\n origin: string | WalletConnectOrigin,\n request: BitcoinRequest,\n ) => Promise<unknown>;\n readonly subscribe: (listener: (event: BitcoinEvent) => void) => () => void;\n};\n\nconst bitcoinId = (name: string): string => {\n const entry = BITCOIN_NETWORKS.find((n) => n.name === name);\n if (entry === undefined) {\n throw new Error(`no bitcoin network named ${name} in the registry`);\n }\n return entry.id;\n};\n\n/**\n * The Bitcoin Wallet Standard chain ids to the registry's CAIP-2 ids: `bitcoin:testnet` is the\n * registry's default test network (Testnet4 — the registry has no Testnet3).\n */\nexport const BITCOIN_CHAIN_IDS: Readonly<Record<string, string>> = Object.freeze({\n \"bitcoin:mainnet\": bitcoinId(\"Bitcoin\"),\n \"bitcoin:testnet\": bitcoinId(\"Bitcoin Testnet4\"),\n});\n\n/** The Wallet Standard chain id of a registry network, or `undefined` when it has none. */\nexport const bitcoinStandardChain = (network: string): string | undefined =>\n Object.entries(BITCOIN_CHAIN_IDS).find(([, id]) => id === network)?.[0];\n\n/** The Wallet Standard `WalletAccount` shape `bitcoin:connect` returns per account. */\nexport type BitcoinWalletAccount = {\n readonly address: string;\n /** `payment`: the compressed key (33 bytes); `ordinals`: the x-only internal key (32 bytes). */\n readonly publicKey: Uint8Array;\n readonly chains: ReadonlyArray<string>;\n readonly features: ReadonlyArray<string>;\n};\n\nexport type BitcoinEvent = {\n readonly name: \"bitcoinAccountsChanged\";\n readonly origin: string;\n readonly accounts: ReadonlyArray<BitcoinWalletAccount>;\n};\n\ntype BitcoinConnections = Pick<\n ConnectionController,\n | \"checkOrigin\"\n | \"session\"\n | \"authorize\"\n | \"sessionAccounts\"\n | \"request\"\n | \"touch\"\n | \"revoke\"\n | \"getState\"\n | \"store\"\n>;\n\ntype BitcoinRequests = Pick<RequestController, \"prepare\" | \"outcome\">;\n\n/** The kernel tags a BIP-322 simple signature `smp` + base64 of the witness. */\nconst SIMPLE_PREFIX = \"smp\";\n\nconst TEMPLATES = { payment: \"btc.bip84\", ordinals: \"btc.bip86\" } as const;\n\ntype Options = {\n readonly connections: BitcoinConnections;\n readonly requests: BitcoinRequests;\n /** The group's address and public key for `purpose` on `network` (receive chain, index 0). */\n readonly bitcoinAccount: (\n group: { readonly walletId: string; readonly groupIndex: number },\n network: string,\n purpose: BitcoinPurpose,\n ) => Promise<{ readonly address: string; readonly publicKey: Uint8Array }>;\n readonly bitcoinNetwork: () => string;\n};\n\n/**\n * The Bitcoin Wallet Standard handler: `bitcoin:connect` authorizes the `bip122` scope (both the\n * `payment` and the `ordinals` account) and returns the requested purposes in order;\n * `bitcoin:signMessage` goes through `bitcoin-sign` (BIP-322 simple); `bitcoinAccountsChanged`\n * carries the re-pointed accounts the bridge forwards as `bitcoin:events` `change` on a group\n * switch.\n */\nexport class BitcoinWalletHandler implements BitcoinHandler {\n readonly options: Options;\n private readonly events: SessionEvents<BitcoinEvent>;\n\n constructor(options: Options) {\n this.options = options;\n this.events = new SessionEvents(options.connections, async (before, after) =>\n Promise.all(\n diffSessions(before, after).map(async ({ origin, session }): Promise<BitcoinEvent> => ({\n name: \"bitcoinAccountsChanged\",\n origin,\n accounts: await this.sessionAccountsChanged(session),\n })),\n ),\n );\n }\n\n subscribe(listener: (event: BitcoinEvent) => void): () => void {\n return this.events.subscribe(listener);\n }\n\n async handle(origin: string | WalletConnectOrigin, request: BitcoinRequest): Promise<unknown> {\n const caller = this.options.connections.checkOrigin(origin);\n if (request.method === \"bitcoin:connect\") {\n return this.connect(caller, request);\n }\n if (request.method === \"standard:disconnect\") {\n await this.options.connections.revoke(caller.origin);\n return {};\n }\n if (request.method === \"bitcoin:signMessage\") {\n return this.signMessage(caller, request);\n }\n if (request.method === \"bitcoin:signTransaction\") {\n return this.signTransactions(caller, request, false);\n }\n if (request.method === \"bitcoin:signAndSendTransaction\") {\n return this.signTransactions(caller, request, true);\n }\n throw invalidParams(`unsupported bitcoin method ${request.method}`);\n }\n\n private async connect(\n caller: ConnectionOrigin,\n request: BitcoinRequest,\n ): Promise<{ accounts: ReadonlyArray<BitcoinWalletAccount> }> {\n const purposes = purposesOf(request.params);\n const network = request.network ?? this.options.bitcoinNetwork();\n let binding = this.options.connections.sessionAccounts(caller.origin, network);\n await (binding === undefined\n ? this.options.connections.request(caller.origin, { kind: \"connect\", namespace: \"bip122\" })\n : this.options.connections.touch(caller.origin));\n binding = this.options.connections.sessionAccounts(caller.origin, network);\n if (binding === undefined) {\n throw new ProviderError(4100, \"the wallet is not connected\");\n }\n const { group } = binding;\n const accounts = await Promise.all(\n purposes.map(async (purpose) => {\n const account = await this.walletAccount(group, network, purpose);\n if (account.address !== binding.addresses[BITCOIN_PURPOSES.indexOf(purpose)]) {\n throw new ProviderError(-32603, \"the session's account does not derive for its group\");\n }\n return account;\n }),\n );\n return { accounts };\n }\n\n private async walletAccount(\n group: { readonly walletId: string; readonly groupIndex: number },\n network: string,\n purpose: BitcoinPurpose,\n ): Promise<BitcoinWalletAccount> {\n const chain = bitcoinStandardChain(network);\n if (chain === undefined) {\n throw new ProviderError(-32603, `network ${network} has no Wallet Standard chain id`);\n }\n const account = await this.options.bitcoinAccount(group, network, purpose);\n return {\n address: account.address,\n publicKey: account.publicKey,\n chains: [chain],\n features: BITCOIN_METHODS.filter((m) => m.startsWith(\"bitcoin:\")),\n };\n }\n\n /**\n * Signs `message` (UTF-8 text only — `bitcoin.message` takes text, so there is no blind path) for\n * one of the session's accounts. The signature is the BIP-322 simple witness serialization\n * (witness item count, then each item length-prefixed) — the kernel's `smp` + base64 string\n * decoded to bytes, which is what MetaMask's Bitcoin Wallet Standard wallet hands out.\n */\n private async signMessage(caller: ConnectionOrigin, request: BitcoinRequest): Promise<unknown> {\n const network = request.network ?? this.options.bitcoinNetwork();\n this.options.connections.authorize(caller.origin, network, \"bitcoin:signMessage\");\n const binding = this.options.connections.sessionAccounts(caller.origin, network);\n if (binding === undefined) {\n throw new ProviderError(4100, \"no bitcoin account for this origin\");\n }\n const { address, message } = signMessageParams(request.params);\n const purpose = BITCOIN_PURPOSES.find(\n (p) => binding.addresses[BITCOIN_PURPOSES.indexOf(p)] === address,\n );\n if (purpose === undefined) {\n throw new ProviderError(4100, \"account is not a connected account\");\n }\n const text = utf8Text(message);\n if (text === undefined) {\n throw new ProviderError(4200, BLIND_SIGNING_MESSAGE);\n }\n const account: BitcoinAccount = { ...binding.group, address, template: TEMPLATES[purpose] };\n let outcome: Awaited<ReturnType<BitcoinRequests[\"outcome\"]>>;\n try {\n const pending = await this.options.requests.prepare({\n method: \"bitcoin-sign\",\n origin: caller,\n account,\n network,\n request: { kind: \"message\", message: text },\n });\n outcome = await this.options.requests.outcome(pending.id);\n } catch (error) {\n throw toProviderError(error);\n }\n if (!(\"kind\" in outcome) || outcome.kind !== \"bitcoin.message\") {\n throw new ProviderError(-32603, \"the bitcoin-sign request settled unexpectedly\");\n }\n if (!outcome.signature.startsWith(SIMPLE_PREFIX)) {\n throw new ProviderError(-32603, \"the kernel returned an unrecognized signature encoding\");\n }\n return {\n signedMessage: message,\n signature: base64.decode(outcome.signature.slice(SIMPLE_PREFIX.length)),\n };\n }\n\n /**\n * Signs (and with `send` broadcasts) a batch of dApp PSBTs under one approval. Every account\n * named must be a session account — inputs of both purposes may mix in one PSBT, each sign entry\n * carries its account's template — and `chain`, when given, must be the session's network.\n */\n private async signTransactions(\n caller: ConnectionOrigin,\n request: BitcoinRequest,\n send: boolean,\n ): Promise<unknown> {\n const network = request.network ?? this.options.bitcoinNetwork();\n this.options.connections.authorize(caller.origin, network, request.method);\n const binding = this.options.connections.sessionAccounts(caller.origin, network);\n if (binding === undefined) {\n throw new ProviderError(4100, \"no bitcoin account for this origin\");\n }\n const inputs = transactionInputs(request.params);\n if (send && inputs.some((input) => input.chain === undefined)) {\n throw invalidParams(\"chain is required for bitcoin:signAndSendTransaction\");\n }\n if (\n inputs.some(\n (input) => input.chain !== undefined && BITCOIN_CHAIN_IDS[input.chain] !== network,\n )\n ) {\n throw invalidParams(\"chain is not the connected network\");\n }\n const templateOf = (address: string): BitcoinAccount[\"template\"] => {\n const purpose = BITCOIN_PURPOSES.find(\n (p) => binding.addresses[BITCOIN_PURPOSES.indexOf(p)] === address,\n );\n if (purpose === undefined) {\n throw new ProviderError(4100, \"account is not a connected account\");\n }\n return TEMPLATES[purpose];\n };\n let outcome: Awaited<ReturnType<BitcoinRequests[\"outcome\"]>>;\n try {\n const pending = await this.options.requests.prepare({\n method: \"bitcoin-sign\",\n origin: caller,\n account: binding.group,\n network,\n request: {\n kind: \"psbt\",\n psbts: inputs.map(({ psbt, inputsToSign }): BitcoinPsbtInput => ({\n psbt,\n sign: inputsToSign.flatMap(({ address, signingIndexes, sigHash }) =>\n signingIndexes.map((index) => ({\n index,\n sigHash,\n template: templateOf(address),\n })),\n ),\n })),\n send,\n },\n });\n outcome = await this.options.requests.outcome(pending.id);\n } catch (error) {\n throw toProviderError(error);\n }\n if (!(\"kind\" in outcome) || outcome.kind !== \"bitcoin.psbts\") {\n throw new ProviderError(-32603, \"the bitcoin-sign request settled unexpectedly\");\n }\n if (send && outcome.stopped !== undefined) {\n throw batchStopped(outcome.stopped, outcome.txids);\n }\n return send\n ? outcome.txids.map((txId, index) => {\n const signedPsbt = outcome.signedPsbts[index];\n if (signedPsbt === undefined) {\n throw internalError(\"a broadcast transaction has no signed PSBT\");\n }\n return { txId, signedPsbt };\n })\n : outcome.signedPsbts.map((signedPsbt) => ({ signedPsbt }));\n }\n\n /**\n * A `change` event's accounts, derived only from the session after the write: the binding's\n * `payment` and `ordinals` accounts — empty when the session is gone or none are bound.\n */\n private async sessionAccountsChanged(\n session: ConnectionSession | undefined,\n ): Promise<BitcoinWalletAccount[]> {\n const network = this.options.bitcoinNetwork();\n const binding = sessionAccounts(session, network);\n if (binding === undefined) {\n return [];\n }\n try {\n const accounts = await Promise.all(\n BITCOIN_PURPOSES.map(async (purpose, index) => {\n const account = await this.walletAccount(binding.group, network, purpose);\n return account.address === binding.addresses[index] ? account : undefined;\n }),\n );\n return accounts.filter((account) => account !== undefined);\n } catch {\n /* A session whose accounts cannot be derived or advertised changes to an empty list. */\n return [];\n }\n }\n}\n\nconst isBytesEnvelope = (v: unknown): v is { __bytes: string } =>\n typeof v === \"object\" && v !== null && typeof (v as { __bytes?: unknown }).__bytes === \"string\";\n\nconst purposesOf = (params: unknown): BitcoinPurpose[] => {\n const raw =\n typeof params === \"object\" && params !== null\n ? (params as { purposes?: unknown }).purposes\n : undefined;\n if (!Array.isArray(raw) || raw.length === 0) {\n throw invalidParams(\"bitcoin:connect needs a non-empty purposes array\");\n }\n return raw.map((purpose) => {\n const found = BITCOIN_PURPOSES.find((p) => p === purpose);\n if (found === undefined) {\n throw invalidParams(\"unknown purpose\");\n }\n return found;\n });\n};\n\nconst signMessageParams = (params: unknown): { address: string; message: Uint8Array } => {\n const { account, message } =\n typeof params === \"object\" && params !== null\n ? (params as { account?: unknown; message?: unknown })\n : {};\n if (typeof account !== \"string\") {\n throw invalidParams(\"bitcoin:signMessage needs the account address\");\n }\n if (message instanceof Uint8Array) {\n return { address: account, message };\n }\n if (isBytesEnvelope(message) && /^(?:[0-9a-fA-F]{2})*$/.test(message.__bytes)) {\n return { address: account, message: hexToBytes(message.__bytes) };\n }\n throw invalidParams(\"bitcoin:signMessage needs Uint8Array message bytes\");\n};\n\ntype TransactionInput = {\n readonly psbt: Uint8Array;\n readonly chain: string | undefined;\n readonly inputsToSign: ReadonlyArray<{\n readonly address: string;\n readonly signingIndexes: ReadonlyArray<number>;\n readonly sigHash: BitcoinSigHash;\n }>;\n};\n\nconst bytesOf = (value: unknown): Uint8Array | undefined => {\n if (value instanceof Uint8Array) {\n return value;\n }\n return isBytesEnvelope(value) && /^(?:[0-9a-fA-F]{2})*$/.test(value.__bytes)\n ? hexToBytes(value.__bytes)\n : undefined;\n};\n\nconst sigHashOf = (value: unknown): BitcoinSigHash => {\n if (value === undefined || value === \"ALL\") {\n return \"ALL\";\n }\n if (value === \"SINGLE|ANYONECANPAY\") {\n return value;\n }\n throw invalidParams(\"sigHash must be ALL or SINGLE|ANYONECANPAY\");\n};\n\n/** The wire shape of `bitcoin:signTransaction` inputs: accounts arrive as their addresses. */\nconst transactionInputs = (params: unknown): ReadonlyArray<TransactionInput> => {\n const raw =\n typeof params === \"object\" && params !== null\n ? (params as { inputs?: unknown }).inputs\n : undefined;\n if (!Array.isArray(raw) || raw.length === 0) {\n throw invalidParams(\"a bitcoin transaction call needs a non-empty inputs array\");\n }\n return raw.map((entry: unknown): TransactionInput => {\n const { psbt, chain, inputsToSign } =\n typeof entry === \"object\" && entry !== null\n ? (entry as { psbt?: unknown; chain?: unknown; inputsToSign?: unknown })\n : {};\n const bytes = bytesOf(psbt);\n if (bytes === undefined || !Array.isArray(inputsToSign) || inputsToSign.length === 0) {\n throw invalidParams(\"each input needs psbt bytes and inputsToSign\");\n }\n if (chain !== undefined && typeof chain !== \"string\") {\n throw invalidParams(\"chain must be a string\");\n }\n return {\n psbt: bytes,\n chain,\n inputsToSign: inputsToSign.map((item: unknown) => {\n const { address, signingIndexes, sigHash } =\n typeof item === \"object\" && item !== null\n ? (item as { address?: unknown; signingIndexes?: unknown; sigHash?: unknown })\n : {};\n if (\n typeof address !== \"string\" ||\n !Array.isArray(signingIndexes) ||\n signingIndexes.length === 0 ||\n !signingIndexes.every((i) => Number.isSafeInteger(i) && i >= 0)\n ) {\n throw invalidParams(\"inputsToSign needs an account and signing indexes\");\n }\n return { address, signingIndexes: signingIndexes.map(Number), sigHash: sigHashOf(sigHash) };\n }),\n };\n });\n};\n\nconst byOrigin = (\n sessions: Readonly<Record<string, ConnectionSession>>,\n): Map<string, ConnectionSession> =>\n new Map(Object.values(sessions).map((s) => [s.origin.origin, s]));\n\nconst bitcoinAccountList = (session: ConnectionSession): ReadonlyArray<string> =>\n Object.entries(session.scopes)\n .filter(([network]) => network.startsWith(\"bip122:\"))\n .flatMap(([, scope]) => scope.accounts.map((a) => a.slice(a.lastIndexOf(\":\") + 1)));\n\n/**\n * The origins whose `bip122` scope's accounts changed between the two snapshots, each with the\n * session after the write (`undefined` when the session is gone).\n */\nfunction diffSessions(\n before: Readonly<Record<string, ConnectionSession>>,\n after: Readonly<Record<string, ConnectionSession>>,\n): ReadonlyArray<{ origin: string; session: ConnectionSession | undefined }> {\n const events: Array<{ origin: string; session: ConnectionSession | undefined }> = [];\n const prev = byOrigin(before);\n const next = byOrigin(after);\n for (const [origin, session] of prev) {\n const now = next.get(origin);\n const was = bitcoinAccountList(session).join(\",\");\n const is = now === undefined ? \"\" : bitcoinAccountList(now).join(\",\");\n if (was !== is) {\n events.push({ origin, session: now });\n }\n }\n for (const [origin, session] of next) {\n if (!prev.has(origin) && bitcoinAccountList(session).length > 0) {\n events.push({ origin, session });\n }\n }\n return events;\n}\n","/**\n * The NIP-07 (`window.nostr`) handler — the bridge routes `provider: \"nostr\"` messages here.\n * `getPublicKey` asks for the active identity (a `nostr` connection approval when the origin is not\n * yet authorized); `signEvent` is policy-gated — an allowed kind signs directly through the\n * identity's signer, anything else (or one of the forced-confirm kinds) goes through the request\n * pipeline's `nostr-sign` for an explicit approval; `nip04`/`nip44` `encrypt` needs authorization\n * and `decrypt` additionally needs the session's `nostrPolicy.decrypt`.\n */\nimport type { Event } from \"@qntx/nostr\";\nimport type { NostrKeyRef } from \"@qntx/wallet\";\nimport type { WalletSigner } from \"@qntx/wallet/nostr\";\n\nimport type { RequestController } from \"../requests/controller.ts\";\nimport type { ConnectionController } from \"./controller.ts\";\nimport { invalidParams, unauthorized } from \"./errors.ts\";\n\n/** A NIP-07 method call from the page. */\nexport type Nip07Request = {\n readonly method: string;\n readonly params?: unknown;\n};\n\nexport type Nip07HandlerOptions = {\n readonly connections: Pick<\n ConnectionController,\n \"checkOrigin\" | \"authorize\" | \"session\" | \"nostrIdentity\" | \"nostrPolicy\" | \"request\" | \"touch\"\n >;\n readonly requests: Pick<RequestController, \"prepare\" | \"outcome\">;\n /** `nostr(wallet).signer(ref)` — the session identity's signer. */\n readonly signerFor: (ref: NostrKeyRef) => WalletSigner;\n};\n\n/**\n * `signEvent` of these kinds always asks for explicit confirmation, whatever the policy allows:\n * metadata/contact-list/deletion plus every replaceable, ephemeral and addressable event —\n * ephemeral events are by convention authentication and remote-control messages, not content.\n */\nconst forcesConfirmation = (kind: number): boolean =>\n kind === 0 || kind === 3 || kind === 5 || (kind >= 10_000 && kind < 40_000);\n\nconst MAX_TAGS = 64;\nconst MAX_TAG_ITEMS = 32;\nconst MAX_TAG_ITEM_LENGTH = 1024;\nconst MAX_CONTENT_LENGTH = 128 * 1024;\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null;\n\n/**\n * Strict event validation: `kind` is an integer 0–65535, `created_at` a safe integer, `tags` a\n * bounded `string[][]`, `content` a bounded string and `pubkey` — when present — a string.\n */\nfunction checkEvent(value: unknown): {\n readonly kind: number;\n readonly content: string;\n readonly created_at: number;\n readonly tags: ReadonlyArray<ReadonlyArray<string>>;\n readonly pubkey?: string;\n} {\n if (!isObject(value)) {\n throw invalidParams(\"event is not an object\");\n }\n const { kind, content, pubkey, tags, created_at: createdAt } = value;\n if (typeof kind !== \"number\" || !Number.isSafeInteger(kind) || kind < 0 || kind > 65_535) {\n throw invalidParams(\"event.kind must be an integer 0–65535\");\n }\n if (typeof content !== \"string\" || content.length > MAX_CONTENT_LENGTH) {\n throw invalidParams(\"event.content must be a string\");\n }\n if (pubkey !== undefined && typeof pubkey !== \"string\") {\n throw invalidParams(\"event.pubkey must be a string\");\n }\n if (typeof createdAt !== \"number\" || !Number.isSafeInteger(createdAt)) {\n throw invalidParams(\"event.created_at must be a safe integer\");\n }\n if (!Array.isArray(tags) || tags.length > MAX_TAGS) {\n throw invalidParams(\"event.tags must be a bounded array of string arrays\");\n }\n const checkedTags: string[][] = [];\n for (const tag of tags) {\n if (!Array.isArray(tag) || tag.length > MAX_TAG_ITEMS) {\n throw invalidParams(\"event.tags items must be bounded string arrays\");\n }\n const checkedTag: string[] = [];\n for (const item of tag) {\n if (typeof item !== \"string\" || item.length > MAX_TAG_ITEM_LENGTH) {\n throw invalidParams(\"event.tags items must contain bounded strings\");\n }\n checkedTag.push(item);\n }\n checkedTags.push(checkedTag);\n }\n return {\n kind,\n content,\n created_at: createdAt,\n tags: checkedTags,\n ...(pubkey === undefined ? {} : { pubkey }),\n };\n}\n\n/** NIP-04/NIP-44 encrypt/decrypt take `[peerPubkey, text]`. */\nfunction peerText(params: unknown): { peer: string; text: string } {\n if (!Array.isArray(params) || typeof params[0] !== \"string\" || typeof params[1] !== \"string\") {\n throw invalidParams(\"expected [peerPubkey, text]\");\n }\n return { peer: params[0], text: params[1] };\n}\n\nexport class Nip07Handler {\n private readonly options: Nip07HandlerOptions;\n\n constructor(options: Nip07HandlerOptions) {\n this.options = options;\n }\n\n async handle(origin: string, request: Nip07Request): Promise<unknown> {\n const { connections } = this.options;\n connections.checkOrigin(origin);\n switch (request.method) {\n case \"getPublicKey\":\n return this.publicKey(origin);\n case \"signEvent\":\n return this.signEvent(origin, request.params);\n case \"nip04.encrypt\":\n case \"nip04.decrypt\":\n case \"nip44.encrypt\":\n case \"nip44.decrypt\": {\n connections.authorize(origin, \"nostr\", request.method);\n const { peer, text } = peerText(request.params);\n return this.crypt(origin, request.method, peer, text);\n }\n default:\n throw unauthorized();\n }\n }\n\n /** The session's bound identity pubkey — a `nostr` connection approval when none yet. */\n private async publicKey(origin: string): Promise<string> {\n const { connections } = this.options;\n if (connections.nostrIdentity(origin) === undefined) {\n await connections.request(origin, { kind: \"connect\", namespace: \"nostr\" });\n }\n await connections.touch(origin);\n const granted = connections.nostrIdentity(origin);\n if (granted === undefined) {\n throw unauthorized();\n }\n return granted.pubkey;\n }\n\n private async signEvent(origin: string, params: unknown): Promise<Event> {\n const { connections, requests, signerFor } = this.options;\n const session = connections.authorize(origin, \"nostr\", \"signEvent\");\n const bound = connections.nostrIdentity(origin);\n if (bound === undefined) {\n throw unauthorized();\n }\n const { pubkey } = bound;\n const event = checkEvent(Array.isArray(params) ? params[0] : params);\n // A page-supplied pubkey must equal the session identity's or be absent.\n if (event.pubkey !== undefined && event.pubkey !== pubkey) {\n throw invalidParams(\"event.pubkey does not match the connected identity\");\n }\n const policy = session.nostrPolicy ?? { signing: \"ask\", decrypt: false };\n const direct =\n policy.signing === \"always\" ||\n (typeof policy.signing === \"object\" && policy.signing.kinds.includes(event.kind));\n const signing = { ...event, pubkey };\n if (direct && !forcesConfirmation(event.kind)) {\n await connections.touch(origin);\n return signerFor(bound.ref).signEvent(signing);\n }\n const pending = await requests.prepare({\n method: \"nostr-sign\",\n origin: { kind: \"browser\", origin },\n ref: bound.ref,\n event: signing,\n });\n const outcome = await requests.outcome(pending.id);\n if (outcome === undefined || !(\"event\" in outcome)) {\n throw unauthorized();\n }\n return outcome.event;\n }\n\n private async crypt(origin: string, method: string, peer: string, text: string): Promise<string> {\n const { connections, signerFor } = this.options;\n if (method.endsWith(\".decrypt\") && connections.nostrPolicy(origin)?.decrypt !== true) {\n throw unauthorized();\n }\n const bound = connections.nostrIdentity(origin);\n if (bound === undefined) {\n throw unauthorized();\n }\n await connections.touch(origin);\n const signer = signerFor(bound.ref);\n const fn =\n method === \"nip04.encrypt\"\n ? signer.nip04Encrypt\n : method === \"nip04.decrypt\"\n ? signer.nip04Decrypt\n : method === \"nip44.encrypt\"\n ? signer.nip44Encrypt\n : signer.nip44Decrypt;\n if (fn === undefined) {\n throw unauthorized();\n }\n return fn(peer, text);\n }\n}\n","import { invalidParams } from \"./errors.ts\";\n\n/** A Sign In With Solana request after validation: `domain` and `address` are resolved. */\nexport type SignInFields = {\n readonly domain: string;\n readonly address: string;\n readonly statement?: string;\n readonly uri?: string;\n readonly version?: string;\n readonly chainId?: string;\n readonly nonce?: string;\n readonly issuedAt?: string;\n readonly expirationTime?: string;\n readonly notBefore?: string;\n readonly requestId?: string;\n readonly resources?: ReadonlyArray<string>;\n};\n\n/** The dApp's input: every field optional. */\nexport type SignInInput = Partial<SignInFields>;\n\nconst STATEMENT_MAX = 1024;\nconst FIELD_MAX = 256;\nconst RESOURCES_MAX = 32;\n\nconst STRING_FIELDS = [\n \"domain\",\n \"address\",\n \"statement\",\n \"uri\",\n \"version\",\n \"chainId\",\n \"nonce\",\n \"issuedAt\",\n \"expirationTime\",\n \"notBefore\",\n \"requestId\",\n] as const;\n\nconst checkString = (name: string, value: unknown, max: number): string => {\n if (typeof value !== \"string\") {\n throw invalidParams(`${name} must be a string`);\n }\n if (value.includes(\"\\n\") || value.includes(\"\\r\")) {\n throw invalidParams(`${name} must not contain line breaks`);\n }\n if (value.length > max) {\n throw invalidParams(`${name} is longer than ${String(max)} characters`);\n }\n return value;\n};\n\n/** Validates a dApp's sign-in input: types, no line breaks, length caps. */\nexport function checkSignInInput(raw: unknown): SignInInput {\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n throw invalidParams(\"the sign-in input must be an object\");\n }\n const record = new Map<string, unknown>(Object.entries(raw));\n const out: Record<string, string | string[]> = {};\n for (const name of STRING_FIELDS) {\n const value = record.get(name);\n if (value !== undefined) {\n out[name] = checkString(name, value, name === \"statement\" ? STATEMENT_MAX : FIELD_MAX);\n }\n }\n const resources = record.get(\"resources\");\n if (resources !== undefined) {\n if (!Array.isArray(resources) || resources.length > RESOURCES_MAX) {\n throw invalidParams(`resources must be an array of at most ${String(RESOURCES_MAX)} strings`);\n }\n out[\"resources\"] = resources.map((resource) => checkString(\"resources\", resource, FIELD_MAX));\n }\n return out;\n}\n\n/**\n * The EIP-4361-style message, byte for byte `createSignInMessageText` of\n * `@solana/wallet-standard-util` 1.2.0 (an empty `resources` array still prints `Resources:`).\n */\nexport function signInMessageText(input: SignInFields): string {\n let message = `${input.domain} wants you to sign in with your Solana account:\\n${input.address}`;\n if (input.statement !== undefined && input.statement !== \"\") {\n message += `\\n\\n${input.statement}`;\n }\n const fields: string[] = [];\n const optional: ReadonlyArray<readonly [string, string | undefined]> = [\n [\"URI\", input.uri],\n [\"Version\", input.version],\n [\"Chain ID\", input.chainId],\n [\"Nonce\", input.nonce],\n [\"Issued At\", input.issuedAt],\n [\"Expiration Time\", input.expirationTime],\n [\"Not Before\", input.notBefore],\n [\"Request ID\", input.requestId],\n ];\n for (const [label, value] of optional) {\n if (value !== undefined && value !== \"\") {\n fields.push(`${label}: ${value}`);\n }\n }\n if (input.resources !== undefined) {\n fields.push(\"Resources:\");\n for (const resource of input.resources) {\n fields.push(`- ${resource}`);\n }\n }\n if (fields.length > 0) {\n message += `\\n\\n${fields.join(\"\\n\")}`;\n }\n return message;\n}\n","import { hexToBytes } from \"@noble/hashes/utils.js\";\nimport { base58 } from \"@scure/base\";\n\nimport { ChainError } from \"@qntx/wallet-chains\";\nimport { decodeSolanaTransaction } from \"@qntx/wallet-chains/solana\";\n\nimport { SOLANA_NETWORKS } from \"../networks/registry.ts\";\nimport type { RequestController } from \"../requests/controller.ts\";\nimport { dappUrl } from \"../requests/types.ts\";\nimport type { WalletConnectOrigin } from \"../requests/types.ts\";\nimport type { ConnectionController, ConnectionOrigin, ConnectionSession } from \"./controller.ts\";\nimport { SOLANA_METHODS, sessionAccounts } from \"./controller.ts\";\nimport { ProviderError, batchStopped, invalidParams, toProviderError } from \"./errors.ts\";\nimport { checkSignInInput, signInMessageText } from \"./siws.ts\";\nimport type { SignInFields } from \"./siws.ts\";\nimport { SessionEvents } from \"./subscription.ts\";\n\n/**\n * The Wallet Standard (`window.solana` / `registerWallet`) handler — the bridge routes `provider:\n * \"solana\"` messages here.\n */\nexport type SolanaRequest = {\n readonly method: string;\n readonly params?: unknown;\n /**\n * The CAIP-2 network the call targets — a WalletConnect request names it; the in-app-browser\n * bridge never sets it (the page has no say), so its calls use the wallet's default network.\n */\n readonly network?: string;\n};\n\nexport type SolanaHandler = {\n readonly handle: (\n origin: string | WalletConnectOrigin,\n request: SolanaRequest,\n ) => Promise<unknown>;\n readonly subscribe: (listener: (event: SolanaEvent) => void) => () => void;\n};\n\nconst solanaId = (name: string): string => {\n const entry = SOLANA_NETWORKS.find((n) => n.name === name);\n if (entry === undefined) {\n throw new Error(`no solana network named ${name} in the registry`);\n }\n return entry.id;\n};\n\n/**\n * The Wallet Standard short chain ids to the registry's CAIP-2 genesis-hash ids, derived from the\n * solana network registry by name.\n */\nexport const SOLANA_CHAIN_IDS: Readonly<Record<string, string>> = Object.freeze({\n \"solana:mainnet\": solanaId(\"Solana\"),\n \"solana:devnet\": solanaId(\"Solana Devnet\"),\n});\n\n/** The Wallet Standard short id of a registry network, or `undefined` when it has none. */\nexport const walletStandardChain = (network: string): string | undefined =>\n Object.entries(SOLANA_CHAIN_IDS).find(([, id]) => id === network)?.[0];\n\n/** The Wallet Standard `WalletAccount` shape `standard:connect` returns per account. */\nexport type SolanaWalletAccount = {\n readonly address: string;\n readonly publicKey: Uint8Array;\n readonly chains: ReadonlyArray<string>;\n readonly features: ReadonlyArray<string>;\n readonly icon?: string;\n readonly label?: string;\n};\n\nexport type SolanaEvent = {\n readonly name: \"solanaAccountsChanged\";\n readonly origin: string;\n readonly accounts: ReadonlyArray<SolanaWalletAccount>;\n};\n\ntype SolanaConnections = Pick<\n ConnectionController,\n | \"checkOrigin\"\n | \"session\"\n | \"authorize\"\n | \"sessionAccounts\"\n | \"request\"\n | \"touch\"\n | \"revoke\"\n | \"getState\"\n | \"store\"\n>;\n\ntype SolanaRequests = Pick<RequestController, \"prepare\" | \"outcome\">;\n\ntype Options = {\n readonly connections: SolanaConnections;\n readonly requests: SolanaRequests;\n /** The group's Solana address + public key on `network` (the `solana.bip44-change` account). */\n readonly solanaAccount: (\n group: { readonly walletId: string; readonly groupIndex: number },\n network: string,\n ) => Promise<{ readonly address: string; readonly publicKey: Uint8Array }>;\n readonly solanaNetwork: () => string;\n};\n\n/**\n * The Wallet Standard handler: `standard:connect` authorizes the `solana` scope, `solana:*` sign\n * requests go through `solana-sign`, `solanaAccountsChanged` returns the re-pointed accounts the\n * bridge forwards as `standard:events` `change` on a group switch.\n */\nexport class SolanaWalletHandler implements SolanaHandler {\n readonly options: Options;\n private readonly events: SessionEvents<SolanaEvent>;\n\n constructor(options: Options) {\n this.options = options;\n this.events = new SessionEvents(options.connections, async (before, after) =>\n Promise.all(\n diffSessions(before, after).map(async ({ origin, session }): Promise<SolanaEvent> => ({\n name: \"solanaAccountsChanged\",\n origin,\n accounts: await this.sessionAccountsChanged(session),\n })),\n ),\n );\n }\n\n /** `standard:events` `change` per origin — derived from changes to the sessions. */\n subscribe(listener: (event: SolanaEvent) => void): () => void {\n return this.events.subscribe(listener);\n }\n\n async handle(origin: string | WalletConnectOrigin, request: SolanaRequest): Promise<unknown> {\n const caller = this.options.connections.checkOrigin(origin);\n if (request.method === \"standard:connect\") {\n return this.connect(caller, request);\n }\n if (request.method === \"standard:disconnect\") {\n await this.options.connections.revoke(caller.origin);\n return {};\n }\n if (request.method === \"solana:signTransaction\") {\n return this.signTransactions(caller, request, false);\n }\n if (request.method === \"solana:signAndSendTransaction\") {\n return this.signTransactions(caller, request, true);\n }\n if (request.method === \"solana:signMessage\") {\n return this.signMessage(caller, request);\n }\n if (request.method === \"solana:signIn\") {\n return this.signIn(caller, request);\n }\n throw invalidParams(`unsupported solana method ${request.method}`);\n }\n\n private async connect(\n caller: ConnectionOrigin,\n request: SolanaRequest,\n ): Promise<{ accounts: ReadonlyArray<SolanaWalletAccount> }> {\n const params =\n typeof request.params === \"object\" && request.params !== null ? request.params : {};\n const silent = (params as { silent?: boolean }).silent === true;\n const network = request.network ?? this.options.solanaNetwork();\n let binding = this.options.connections.sessionAccounts(caller.origin, network);\n if (binding === undefined) {\n if (silent) {\n throw new ProviderError(4100, \"the wallet is not connected\");\n }\n await this.options.connections.request(caller.origin, {\n kind: \"connect\",\n namespace: \"solana\",\n });\n binding = this.options.connections.sessionAccounts(caller.origin, network);\n if (binding === undefined) {\n throw new ProviderError(4100, \"the wallet is not connected\");\n }\n } else {\n await this.options.connections.touch(caller.origin);\n }\n const account = await this.options.solanaAccount(binding.group, network);\n if (account.address !== binding.addresses[0]) {\n throw new ProviderError(-32603, \"the session's account does not derive for its group\");\n }\n return { accounts: [this.walletAccount(account, network)] };\n }\n\n private walletAccount(\n account: { readonly address: string; readonly publicKey: Uint8Array },\n network: string,\n ): SolanaWalletAccount {\n const chain = walletStandardChain(network);\n if (chain === undefined) {\n throw new ProviderError(-32603, `network ${network} has no Wallet Standard chain id`);\n }\n return {\n address: account.address,\n publicKey: account.publicKey,\n chains: [chain],\n features: SOLANA_METHODS.filter((m) => m.startsWith(\"solana:\")),\n };\n }\n\n private async signTransactions(\n caller: ConnectionOrigin,\n request: SolanaRequest,\n send: boolean,\n ): Promise<unknown> {\n const network = this.networkOf(request.params, send, request.network);\n this.options.connections.authorize(caller.origin, network, request.method);\n const binding = this.options.connections.sessionAccounts(caller.origin, network);\n const address = binding?.addresses[0];\n if (binding === undefined || address === undefined) {\n throw new ProviderError(4100, \"no solana account for this origin\");\n }\n checkAccounts(request.params, address);\n const txs = transactionsOf(request.params);\n for (const tx of txs) {\n try {\n const { unsigned } = decodeSolanaTransaction(tx, address);\n // A sign-and-send whose other signers have not signed can never land (Solana Pay's\n // transaction-request spec requires wallets to reject these).\n if (send && unsigned.length > 0) {\n throw invalidParams(`the transaction still needs signatures from ${unsigned.join(\", \")}`);\n }\n } catch (error) {\n throw error instanceof ChainError ? invalidParams(error.message) : error;\n }\n }\n const outcome = await this.signRequest(caller, network, binding.group, address, {\n kind: \"transactions\",\n transactions: txs,\n send,\n });\n if (!(\"kind\" in outcome) || outcome.kind !== \"solana.transactions\") {\n throw new ProviderError(-32603, \"the solana-sign request settled unexpectedly\");\n }\n if (send && outcome.stopped !== undefined) {\n throw batchStopped(outcome.stopped, outcome.signatures ?? []);\n }\n return send\n ? { signatures: (outcome.signatures ?? []).map((signature) => base58.decode(signature)) }\n : { signedTransactions: outcome.signedTransactions };\n }\n\n /**\n * The network a transaction call targets: `network` (a WalletConnect request names its CAIP-2\n * chain) or the wallet's default when no input names a chain, otherwise the one chain every input\n * agrees on (`chain` is required for sign-and-send).\n */\n private networkOf(params: unknown, requireChain: boolean, network?: string): string {\n const chains = paramList(params, \"chains\");\n if (requireChain && (chains.length === 0 || chains.some((chain) => chain === undefined))) {\n throw invalidParams(\"chain is required for solana:signAndSendTransaction\");\n }\n const named = new Set(chains.filter((chain) => chain !== undefined));\n if (named.size === 0) {\n return network ?? this.options.solanaNetwork();\n }\n if (named.size > 1 || chains.some((chain) => chain === undefined)) {\n throw invalidParams(\"every input must use the same chain\");\n }\n const [chain] = [...named];\n const resolved = typeof chain === \"string\" ? SOLANA_CHAIN_IDS[chain] : undefined;\n if (resolved === undefined) {\n throw invalidParams(\"unknown chain\");\n }\n return resolved;\n }\n\n private async signMessage(caller: ConnectionOrigin, request: SolanaRequest): Promise<unknown> {\n const network = request.network ?? this.options.solanaNetwork();\n this.options.connections.authorize(caller.origin, network, \"solana:signMessage\");\n const binding = this.options.connections.sessionAccounts(caller.origin, network);\n if (binding !== undefined && binding.addresses[0] !== undefined) {\n checkAccounts(request.params, binding.addresses[0]);\n }\n const message = messageOf(request.params);\n const signature = await this.signMessageRequest(caller, network, message);\n return { signature, signedMessage: message };\n }\n\n /**\n * Sign In With Solana: connects first when needed, binds the message to the page's host and the\n * session's account, and signs the exact text the user is shown.\n */\n private async signIn(caller: ConnectionOrigin, request: SolanaRequest): Promise<unknown> {\n const params =\n typeof request.params === \"object\" && request.params !== null ? request.params : {};\n const { input: raw } = params as { input?: unknown };\n const input = checkSignInInput(raw === undefined ? {} : raw);\n const { host } = new URL(dappUrl(caller));\n if (input.domain !== undefined && input.domain !== host) {\n throw invalidParams(\"domain does not match the page\");\n }\n const { accounts } = await this.connect(caller, request);\n const [walletAccount] = accounts;\n const network = request.network ?? this.options.solanaNetwork();\n this.options.connections.authorize(caller.origin, network, \"solana:signIn\");\n if (walletAccount === undefined) {\n throw new ProviderError(4100, \"no solana account for this origin\");\n }\n if (input.address !== undefined && input.address !== walletAccount.address) {\n throw new ProviderError(4100, \"address is not the connected account\");\n }\n const fields: SignInFields = { ...input, domain: host, address: walletAccount.address };\n const message = new TextEncoder().encode(signInMessageText(fields));\n const signature = await this.signMessageRequest(caller, network, message, fields);\n return [\n { account: walletAccount, signedMessage: message, signature, signatureType: \"ed25519\" },\n ];\n }\n\n private async signMessageRequest(\n caller: ConnectionOrigin,\n network: string,\n message: Uint8Array,\n signIn?: SignInFields,\n ): Promise<Uint8Array> {\n const binding = this.options.connections.sessionAccounts(caller.origin, network);\n const address = binding?.addresses[0];\n if (binding === undefined || address === undefined) {\n throw new ProviderError(4100, \"no solana account for this origin\");\n }\n const outcome = await this.signRequest(caller, network, binding.group, address, {\n kind: \"message\",\n message,\n ...(signIn === undefined ? {} : { signIn }),\n });\n if (!(\"kind\" in outcome) || outcome.kind !== \"solana.message\") {\n throw new ProviderError(-32603, \"the solana-sign request settled unexpectedly\");\n }\n return outcome.signature;\n }\n\n /** One `solana-sign` request for the session's bound group, resolved to its outcome. */\n private async signRequest(\n caller: ConnectionOrigin,\n network: string,\n group: { readonly walletId: string; readonly groupIndex: number },\n address: string,\n request: Parameters<SolanaRequests[\"prepare\"]>[0] extends infer I\n ? I extends { method: \"solana-sign\"; request: infer R }\n ? R\n : never\n : never,\n ): Promise<Awaited<ReturnType<SolanaRequests[\"outcome\"]>>> {\n try {\n const pending = await this.options.requests.prepare({\n method: \"solana-sign\",\n origin: caller,\n account: { walletId: group.walletId, groupIndex: group.groupIndex, address },\n network,\n request,\n });\n return await this.options.requests.outcome(pending.id);\n } catch (error) {\n throw toProviderError(error);\n }\n }\n\n /**\n * A `change` event's accounts, derived only from the session after the write: the binding's\n * account — empty when the session is gone or no Solana account is bound.\n */\n private async sessionAccountsChanged(\n session: ConnectionSession | undefined,\n ): Promise<SolanaWalletAccount[]> {\n const network = this.options.solanaNetwork();\n const binding = sessionAccounts(session, network);\n const address = binding?.addresses[0];\n if (binding === undefined || address === undefined) {\n return [];\n }\n try {\n const account = await this.options.solanaAccount(binding.group, network);\n return account.address === address ? [this.walletAccount(account, network)] : [];\n } catch {\n /* A session whose account cannot be derived or advertised changes to an empty list. */\n return [];\n }\n }\n}\n\nconst paramList = (params: unknown, name: string): ReadonlyArray<unknown> => {\n const value: unknown =\n typeof params === \"object\" && params !== null\n ? new Map<string, unknown>(Object.entries(params)).get(name)\n : undefined;\n if (value === undefined) {\n return [];\n }\n if (!Array.isArray(value)) {\n throw invalidParams(`${name} must be an array`);\n }\n return value as unknown[];\n};\n\n/** Every account the page names must be the session's Solana account. */\nconst checkAccounts = (params: unknown, address: string): void => {\n if (paramList(params, \"accounts\").some((account) => account !== address)) {\n throw new ProviderError(4100, \"account is not the connected account\");\n }\n};\n\nconst isBytesEnvelope = (v: unknown): v is { __bytes: string } =>\n typeof v === \"object\" && v !== null && typeof (v as { __bytes?: unknown }).__bytes === \"string\";\n\nconst transactionsOf = (params: unknown): Uint8Array[] => {\n const raw =\n typeof params === \"object\" && params !== null\n ? (params as { transactions?: unknown }).transactions\n : undefined;\n if (!Array.isArray(raw)) {\n throw invalidParams(\"solana:signTransaction needs a transactions array\");\n }\n return raw.map((tx) => {\n if (tx instanceof Uint8Array) {\n return tx;\n }\n if (typeof tx === \"string\" && /^[0-9a-fA-F]+$/.test(tx)) {\n return hexToBytes(tx);\n }\n if (isBytesEnvelope(tx)) {\n return hexToBytes(tx.__bytes);\n }\n throw invalidParams(\"each transaction must be Uint8Array bytes or hex\");\n });\n};\n\nconst messageOf = (params: unknown): Uint8Array => {\n const message =\n typeof params === \"object\" && params !== null\n ? (params as { message?: unknown }).message\n : undefined;\n if (message instanceof Uint8Array) {\n return message;\n }\n if (typeof message === \"string\" && /^[0-9a-fA-F]+$/.test(message)) {\n return hexToBytes(message);\n }\n if (isBytesEnvelope(message)) {\n return hexToBytes(message.__bytes);\n }\n throw invalidParams(\"solana:signMessage needs Uint8Array bytes or hex\");\n};\n\nconst byOrigin = (\n sessions: Readonly<Record<string, ConnectionSession>>,\n): Map<string, ConnectionSession> =>\n new Map(Object.values(sessions).map((s) => [s.origin.origin, s]));\n\nconst solanaAccounts = (session: ConnectionSession): ReadonlyArray<string> =>\n Object.entries(session.scopes)\n .filter(([network]) => network.startsWith(\"solana:\"))\n .flatMap(([, scope]) => scope.accounts.map((a) => a.slice(a.lastIndexOf(\":\") + 1)));\n\n/**\n * The origins whose Solana scope's accounts changed between the two snapshots, each with the\n * session after the write (`undefined` when the session is gone).\n */\nfunction diffSessions(\n before: Readonly<Record<string, ConnectionSession>>,\n after: Readonly<Record<string, ConnectionSession>>,\n): ReadonlyArray<{ origin: string; session: ConnectionSession | undefined }> {\n const events: Array<{ origin: string; session: ConnectionSession | undefined }> = [];\n const prev = byOrigin(before);\n const next = byOrigin(after);\n for (const [origin, session] of prev) {\n const now = next.get(origin);\n const was = solanaAccounts(session).join(\",\");\n const is = now === undefined ? \"\" : solanaAccounts(now).join(\",\");\n if (was !== is) {\n events.push({ origin, session: now });\n }\n }\n for (const [origin, session] of next) {\n if (!prev.has(origin) && solanaAccounts(session).length > 0) {\n events.push({ origin, session });\n }\n }\n return events;\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, hexToBytes } from \"@noble/hashes/utils.js\";\n\nimport { ChainError } from \"@qntx/wallet-chains\";\nimport {\n isTronAddress,\n tronAddressToHex,\n tronRawDataFromJson,\n tronTypedDataFromArgs,\n} from \"@qntx/wallet-chains/tron\";\n\nimport { networkById } from \"../networks/registry.ts\";\nimport {\n InvalidTokenError,\n OriginBusyError,\n RequestEndedError,\n SignInOriginError,\n} from \"../requests/controller.ts\";\nimport type { RequestController } from \"../requests/controller.ts\";\nimport type { DappOrigin } from \"../requests/types.ts\";\nimport { BroadcastRefusedError } from \"../transactions/broadcast.ts\";\nimport type { TransactionController } from \"../transactions/controller.ts\";\nimport type { ConnectionController, ConnectionSession } from \"./controller.ts\";\nimport { sessionAccounts } from \"./controller.ts\";\nimport {\n ProviderError,\n internalError,\n invalidParams,\n unauthorized,\n unrecognizedChain,\n unsupportedMethod,\n userRejectedRequest,\n} from \"./errors.ts\";\nimport { SessionEvents } from \"./subscription.ts\";\n\n/**\n * The TronLink-style (`window.tron` / `window.tronLink`) handler — the bridge routes `provider:\n * \"tron\"` messages here.\n */\nexport type TronRequest = {\n readonly method: string;\n readonly params?: unknown;\n};\n\nexport type TronHandler = {\n readonly handle: (origin: string, request: TronRequest) => Promise<unknown>;\n readonly subscribe: (listener: (event: TronEvent) => void) => () => void;\n};\n\n/** The address pair `tron_getProviderState` and `tronWeb.defaultAddress` report. */\nexport type TronProviderAddress = { readonly base58: string; readonly hex: string };\n\n/** The injected provider's state: the page mirrors it on `defaultAddress`/`ready`/events. */\nexport type TronProviderState = {\n readonly address: TronProviderAddress | false;\n readonly chainId: string;\n /** The network's genesis block id — `trx.getBlockByNumber(0)` reports it as `blockID`. */\n readonly genesis: string;\n};\n\nexport type TronEvent = {\n readonly name: \"tronStateChanged\";\n readonly origin: string;\n readonly state: TronProviderState;\n};\n\ntype TronConnections = Pick<\n ConnectionController,\n | \"checkOrigin\"\n | \"session\"\n | \"authorize\"\n | \"sessionAccounts\"\n | \"setTronNetwork\"\n | \"request\"\n | \"touch\"\n | \"revoke\"\n | \"getState\"\n | \"store\"\n>;\n\ntype TronRequests = Pick<RequestController, \"prepare\" | \"outcome\">;\n\ntype Options = {\n readonly connections: TronConnections;\n readonly requests: TronRequests;\n readonly transactions: Pick<TransactionController, \"submitDappTron\">;\n /** The enabled TRON networks (`tron:` CAIP-2 ids) — every one is in a `tron` grant's scopes. */\n readonly tronNetworks: () => ReadonlyArray<string>;\n /** The default TRON network — the current one until a session picks another. */\n readonly tronNetwork: () => string;\n /** Whether the TRC-20 contract at `address` on `network` is already tracked. */\n readonly isTracked: (network: string, address: string) => boolean;\n};\n\n/** `raw_data_hex` must fit a broadcastable TRON transaction; 500 KiB is far above the node limit. */\nconst TRON_RAW_DATA_HEX_MAX = 500 * 1024 * 2;\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\nconst isBytesEnvelope = (v: unknown): v is { __bytes: string } =>\n isObject(v) && typeof v[\"__bytes\"] === \"string\";\n\n/** `tron:728126428` → `0x2b6653dc` — the CAIP-2 decimal reference in lowercase hex. */\nconst tronChainId = (network: string): string | undefined => {\n const ref = /^tron:(\\d+)$/.exec(network)?.[1];\n return ref === undefined ? undefined : `0x${BigInt(ref).toString(16)}`;\n};\n\nconst bytesOf = (value: unknown, name: string): Uint8Array => {\n if (value instanceof Uint8Array) {\n return value;\n }\n if (typeof value === \"string\" && /^[0-9a-fA-F]+$/.test(value)) {\n return hexToBytes(value);\n }\n if (isBytesEnvelope(value) && /^[0-9a-fA-F]+$/.test(value.__bytes)) {\n return hexToBytes(value.__bytes);\n }\n throw invalidParams(`${name} must be Uint8Array bytes or hex`);\n};\n\nconst toProviderError = (error: unknown): ProviderError => {\n if (error instanceof ProviderError) {\n return error;\n }\n if (error instanceof InvalidTokenError || error instanceof SignInOriginError) {\n return invalidParams(error.message);\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\n/**\n * The Wallet-Standard-like TronLink handler: `tron_requestAccounts`/`eth_requestAccounts` authorize\n * the `tron` scope, signing goes through `tron-sign`, `tronStateChanged` carries the provider state\n * the injected script turns into `accountsChanged`/`chainChanged`/`connect`.\n */\nexport class TronWalletHandler implements TronHandler {\n readonly options: Options;\n private readonly events: SessionEvents<TronEvent>;\n\n constructor(options: Options) {\n this.options = options;\n this.events = new SessionEvents(options.connections, (before, after) =>\n diffSessions(before, after).map(({ origin, session }): TronEvent => ({\n name: \"tronStateChanged\",\n origin,\n state: this.providerState(session),\n })),\n );\n }\n\n /** `tronStateChanged` per origin — derived from changes to the sessions. */\n subscribe(listener: (event: TronEvent) => void): () => void {\n return this.events.subscribe(listener);\n }\n\n async handle(origin: string, request: TronRequest): Promise<unknown> {\n const checked = this.options.connections.checkOrigin(origin);\n switch (request.method) {\n case \"tron_getProviderState\":\n return this.providerState(this.options.connections.session(checked.origin));\n case \"eth_requestAccounts\":\n return this.requestAccounts(checked, false);\n case \"tron_requestAccounts\":\n return this.requestAccounts(checked, true);\n case \"wallet_switchEthereumChain\":\n return this.switchChain(checked, request.params);\n case \"wallet_watchAsset\":\n return this.watchAsset(checked, request.params);\n case \"tron_signTransaction\":\n return this.signTransaction(checked, request.params);\n case \"tron_sendRawTransaction\":\n return this.sendRawTransaction(checked, request.params);\n case \"tron_signMessageV2\":\n return this.signMessage(checked, request.params);\n case \"tron_signTypedData\":\n return this.signTypedData(checked, request.params);\n default:\n throw unsupportedMethod(request.method);\n }\n }\n\n /** The injected provider's state for the session's TRON network (or the default when absent). */\n private providerState(session: ConnectionSession | undefined): TronProviderState {\n const network = session?.tronNetwork ?? this.options.tronNetwork();\n const binding = sessionAccounts(session, network);\n const base58 = binding?.addresses[0];\n return {\n address:\n base58 === undefined ? false : { base58, hex: tronAddressToHex(base58).toLowerCase() },\n chainId: tronChainId(network) ?? \"0x0\",\n genesis: networkById(network)?.genesisHash ?? \"\",\n };\n }\n\n /**\n * `eth_requestAccounts` resolves `[base58]`; the legacy `tron_requestAccounts` resolves a `{code,\n * message}` result instead of rejecting — 200 on success, 4001 when the user refused, 4000 for\n * anything else (TronLink's own convention).\n */\n private async requestAccounts(checked: DappOrigin, legacy: boolean): Promise<unknown> {\n try {\n const session = this.options.connections.session(checked.origin);\n const network = session?.tronNetwork;\n const binding =\n network === undefined\n ? undefined\n : this.options.connections.sessionAccounts(checked.origin, network);\n const address = binding?.addresses[0];\n if (address !== undefined) {\n await this.options.connections.touch(checked.origin);\n return legacy ? { code: 200, message: \"wallet authorized\" } : [address];\n }\n await this.options.connections.request(checked.origin, {\n kind: \"connect\",\n namespace: \"tron\",\n });\n const granted = this.options.connections.session(checked.origin);\n const grantedNetwork = granted?.tronNetwork;\n const grantedBinding =\n grantedNetwork === undefined\n ? undefined\n : this.options.connections.sessionAccounts(checked.origin, grantedNetwork);\n const grantedAddress = grantedBinding?.addresses[0];\n if (grantedAddress === undefined) {\n throw unauthorized(\"the wallet is not connected\");\n }\n return legacy ? { code: 200, message: \"wallet authorized\" } : [grantedAddress];\n } catch (error) {\n if (!legacy) {\n throw toProviderError(error);\n }\n const code = error instanceof ProviderError && error.code === 4001 ? 4001 : 4000;\n return { code, message: error instanceof Error ? error.message : String(error) };\n }\n }\n\n /** The session's current TRON network and its binding — every signing method requires both. */\n private signingSession(\n checked: DappOrigin,\n method: string,\n ): {\n readonly network: string;\n readonly binding: NonNullable<ReturnType<TronConnections[\"sessionAccounts\"]>>;\n } {\n const session = this.options.connections.session(checked.origin);\n const network = session?.tronNetwork;\n if (network === undefined) {\n throw unauthorized(\"the wallet is not connected\");\n }\n this.options.connections.authorize(checked.origin, network, method);\n const binding = this.options.connections.sessionAccounts(checked.origin, network);\n if (binding === undefined || binding.addresses[0] === undefined) {\n throw unauthorized(\"no TRON account is bound to the session\");\n }\n return { network, binding };\n }\n\n /**\n * A `wallet_switchEthereumChain` on `window.tron` switches the session's TRON network: a chain id\n * that names no enabled TRON network is 4902, no session is 4100.\n */\n private async switchChain(checked: DappOrigin, params: unknown): Promise<unknown> {\n const param: unknown = Array.isArray(params) ? params[0] : undefined;\n const chainId = isObject(param) ? param[\"chainId\"] : undefined;\n if (typeof chainId !== \"string\" || !/^0x[0-9a-fA-F]+$/.test(chainId)) {\n throw invalidParams(\"params must be [{ chainId: '0x…' }]\");\n }\n const network = this.options\n .tronNetworks()\n .find((n) => tronChainId(n)?.toLowerCase() === chainId.toLowerCase());\n if (network === undefined) {\n throw unrecognizedChain(`${chainId} is not an enabled TRON chain`);\n }\n if (this.options.connections.session(checked.origin) === undefined) {\n throw unauthorized(\"the wallet is not connected\");\n }\n await this.options.connections.setTronNetwork(checked.origin, network);\n return null;\n }\n\n /** The TRC-20 `wallet_watchAsset`: other token kinds are 4200, malformed params invalid. */\n private async watchAsset(checked: DappOrigin, params: unknown): Promise<void> {\n if (!isObject(params) || params[\"type\"] !== \"trc20\" || !isObject(params[\"options\"])) {\n if (isObject(params) && (params[\"type\"] === \"trc10\" || params[\"type\"] === \"trc721\")) {\n throw unsupportedMethod(`${params[\"type\"]} watch-asset`);\n }\n throw invalidParams(\"params must be { type: 'trc20', options: { address } }\");\n }\n const { address } = params[\"options\"];\n if (typeof address !== \"string\" || !isTronAddress(address)) {\n throw invalidParams(\"options.address must be a TRON address\");\n }\n const { network, binding } = this.signingSession(checked, \"wallet_watchAsset\");\n if (this.options.isTracked(network, address)) {\n return;\n }\n try {\n const pending = await this.options.requests.prepare({\n method: \"watch-asset\",\n origin: checked,\n account: { kind: \"hd\", ...binding.group, template: \"tron.bip44\" },\n network,\n address,\n });\n await this.options.requests.outcome(pending.id);\n await this.options.connections.touch(checked.origin);\n } catch (error) {\n throw toProviderError(error);\n }\n }\n\n /**\n * The dApp transaction shape checks every `tron_sign*`/`tron_send*` call shares: the declared\n * `txID` must be the sha256 of `raw_data_hex`, and a `raw_data` JSON must encode to exactly those\n * bytes — the wallet never signs bytes the page could misrepresent.\n */\n private transactionOf(\n params: unknown,\n signaturePolicy: \"absent\" | \"one\",\n ): {\n readonly transaction: Record<string, unknown>;\n readonly rawData: Uint8Array;\n readonly signature: string | undefined;\n } {\n if (!isObject(params) || !isObject(params[\"transaction\"])) {\n throw invalidParams(\"params must be { transaction }\");\n }\n const { transaction } = params;\n if (signaturePolicy === \"absent\" && transaction[\"signature\"] !== undefined) {\n throw invalidParams(\"the transaction is already signed\");\n }\n const signatures = transaction[\"signature\"];\n if (\n signaturePolicy === \"one\" &&\n (!Array.isArray(signatures) ||\n signatures.length !== 1 ||\n signatures.some((s) => typeof s !== \"string\" || !/^[0-9a-fA-F]{130}$/.test(s)))\n ) {\n throw invalidParams(\"transaction.signature must be exactly one 65-byte hex signature\");\n }\n const rawDataHex = transaction[\"raw_data_hex\"];\n if (\n typeof rawDataHex !== \"string\" ||\n rawDataHex.length % 2 !== 0 ||\n rawDataHex.length > TRON_RAW_DATA_HEX_MAX ||\n !/^[0-9a-fA-F]*$/.test(rawDataHex)\n ) {\n throw invalidParams(\"transaction.raw_data_hex must be even-length hex within 500 KiB\");\n }\n const { txID } = transaction;\n if (typeof txID !== \"string\" || !/^[0-9a-fA-F]{64}$/.test(txID)) {\n throw invalidParams(\"transaction.txID must be 64 hex characters\");\n }\n if (transaction[\"visible\"] !== undefined && typeof transaction[\"visible\"] !== \"boolean\") {\n throw invalidParams(\"transaction.visible must be a boolean\");\n }\n const rawData = hexToBytes(rawDataHex);\n if (bytesToHex(sha256(rawData)) !== txID.toLowerCase()) {\n throw invalidParams(\"transaction.txID does not match raw_data_hex\");\n }\n if (transaction[\"raw_data\"] !== undefined) {\n if (!isObject(transaction[\"raw_data\"])) {\n throw invalidParams(\"transaction.raw_data must be an object\");\n }\n let encoded: Uint8Array;\n try {\n encoded = tronRawDataFromJson(transaction[\"raw_data\"], transaction[\"visible\"] === true);\n } catch (error) {\n throw error instanceof ChainError ? invalidParams(error.message) : error;\n }\n if (bytesToHex(encoded) !== rawDataHex.toLowerCase()) {\n throw invalidParams(\"raw_data does not match raw_data_hex\");\n }\n }\n const signature =\n Array.isArray(signatures) && typeof signatures[0] === \"string\" ? signatures[0] : undefined;\n return { transaction, rawData, signature };\n }\n\n private async tronSign(\n checked: DappOrigin,\n network: string,\n binding: NonNullable<ReturnType<TronConnections[\"sessionAccounts\"]>>,\n request: Parameters<TronRequests[\"prepare\"]>[0] extends infer I\n ? I extends { method: \"tron-sign\"; request: infer R }\n ? R\n : never\n : never,\n ): Promise<Awaited<ReturnType<TronRequests[\"outcome\"]>>> {\n try {\n const pending = await this.options.requests.prepare({\n method: \"tron-sign\",\n origin: checked,\n account: { kind: \"hd\", ...binding.group, template: \"tron.bip44\" },\n network,\n request,\n });\n return await this.options.requests.outcome(pending.id);\n } catch (error) {\n throw toProviderError(error);\n }\n }\n\n /** `trx.sign(tx)` — signs the exact `raw_data` bytes; the page broadcasts them itself. */\n private async signTransaction(\n checked: DappOrigin,\n params: unknown,\n ): Promise<Record<string, unknown>> {\n const { transaction, rawData } = this.transactionOf(params, \"absent\");\n const { network, binding } = this.signingSession(checked, \"tron_signTransaction\");\n const outcome = await this.tronSign(checked, network, binding, {\n kind: \"tron.transaction\",\n network,\n account: { kind: \"hd\", ...binding.group, template: \"tron.bip44\" },\n rawData,\n });\n const signature =\n \"tron\" in outcome && outcome.tron !== undefined ? outcome.tron.dappSignature : undefined;\n if (typeof signature !== \"string\") {\n throw internalError(\"the tron-sign request settled unexpectedly\");\n }\n return { ...transaction, signature: [signature] };\n }\n\n /** `trx.sendRawTransaction(tx)` — broadcasts a transaction this wallet already signed. */\n private async sendRawTransaction(\n checked: DappOrigin,\n params: unknown,\n ): Promise<Record<string, unknown>> {\n const { transaction, rawData, signature } = this.transactionOf(params, \"one\");\n const { network } = this.signingSession(checked, \"tron_sendRawTransaction\");\n const txid = typeof transaction[\"txID\"] === \"string\" ? transaction[\"txID\"] : \"\";\n try {\n await this.options.transactions.submitDappTron(network, rawData, hexToBytes(signature ?? \"\"));\n return { result: true, txid, transaction };\n } catch (error) {\n if (error instanceof BroadcastRefusedError) {\n const { cause } = error;\n const code =\n isObject(cause) && typeof cause[\"code\"] === \"string\" ? cause[\"code\"] : \"REFUSED\";\n return { result: false, code, message: error.message, txid, transaction };\n }\n throw toProviderError(error);\n }\n }\n\n /** `trx.signMessageV2(m)` — a TIP-191 personal-sign of arbitrary bytes. */\n private async signMessage(checked: DappOrigin, params: unknown): Promise<string> {\n const message = isObject(params) ? params[\"message\"] : undefined;\n if (message === undefined) {\n throw invalidParams(\"params must be { message }\");\n }\n const bytes = bytesOf(message, \"message\");\n const { network, binding } = this.signingSession(checked, \"tron_signMessageV2\");\n const outcome = await this.tronSign(checked, network, binding, {\n kind: \"tron.message\",\n network,\n account: { kind: \"hd\", ...binding.group, template: \"tron.bip44\" },\n message: bytes,\n });\n if (!(\"signature\" in outcome) || !(outcome.signature instanceof Uint8Array)) {\n throw internalError(\"the tron-sign request settled unexpectedly\");\n }\n return `0x${bytesToHex(outcome.signature)}`;\n }\n\n /** `trx.signTypedData`/`_signTypedData` — a TIP-712 typed-data signature. */\n private async signTypedData(checked: DappOrigin, params: unknown): Promise<string> {\n if (\n !isObject(params) ||\n !isObject(params[\"domain\"]) ||\n !isObject(params[\"types\"]) ||\n params[\"message\"] === undefined\n ) {\n throw invalidParams(\"params must be { domain, types, message }\");\n }\n let typedData: string;\n try {\n typedData = tronTypedDataFromArgs(params[\"domain\"], params[\"types\"], params[\"message\"]);\n } catch (error) {\n throw error instanceof ChainError ? invalidParams(error.message) : error;\n }\n const { network, binding } = this.signingSession(checked, \"tron_signTypedData\");\n const outcome = await this.tronSign(checked, network, binding, {\n kind: \"tron.typed-data\",\n network,\n account: { kind: \"hd\", ...binding.group, template: \"tron.bip44\" },\n typedData,\n });\n if (!(\"signature\" in outcome) || !(outcome.signature instanceof Uint8Array)) {\n throw internalError(\"the tron-sign request settled unexpectedly\");\n }\n return `0x${bytesToHex(outcome.signature)}`;\n }\n}\n\nconst byOrigin = (\n sessions: Readonly<Record<string, ConnectionSession>>,\n): Map<string, ConnectionSession> =>\n new Map(Object.values(sessions).map((s) => [s.origin.origin, s]));\n\nconst tronAccounts = (session: ConnectionSession): ReadonlyArray<string> =>\n Object.entries(session.scopes)\n .filter(([network]) => network.startsWith(\"tron:\"))\n .flatMap(([, scope]) => scope.accounts.map((a) => a.slice(a.lastIndexOf(\":\") + 1)));\n\nconst tronFingerprint = (session: ConnectionSession): string =>\n `${tronAccounts(session).join(\",\")}@${session.tronNetwork ?? \"\"}`;\n\n/**\n * The origins whose TRON scope accounts or current TRON network changed between the two snapshots,\n * each with the session after the write (`undefined` when the session is gone).\n */\nfunction diffSessions(\n before: Readonly<Record<string, ConnectionSession>>,\n after: Readonly<Record<string, ConnectionSession>>,\n): ReadonlyArray<{ origin: string; session: ConnectionSession | undefined }> {\n const events: Array<{ origin: string; session: ConnectionSession | undefined }> = [];\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 || tronFingerprint(session) !== tronFingerprint(now)) {\n events.push({ origin, session: now });\n }\n }\n for (const [origin, session] of next) {\n if (!prev.has(origin) && tronAccounts(session).length > 0) {\n events.push({ origin, session });\n }\n }\n return events;\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 | {\n /** A WalletConnect pairing URI; the host passes it to the walletconnect entry's `pair`. */\n readonly kind: \"walletconnect\";\n readonly uri: string;\n }\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 (/^wc:[0-9a-f]{64}@2\\?/i.test(text)) {\n return { kind: \"walletconnect\", uri: text };\n }\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","/**\n * The WebLN (`window.webln`) handler — the bridge routes `provider: \"webln\"` messages here.\n * `enable` asks for a `lightning` connection approval when the origin is not yet authorized;\n * `sendPayment` and `lnurl` pay through the request pipeline's `pay` (a funds request with a\n * factor) and then poll `paymentStatus` for the settled preimage; `makeInvoice` goes through the\n * factor-free `webln-invoice`; `getBalance` additionally needs the session's\n * `lightningPolicy.balance`; `getInfo` exposes only the configured alias and methods.\n */\nimport { bytesToHex } from \"@noble/hashes/utils.js\";\n\nimport type { LightningPayment } from \"@qntx/spark\";\nimport type { SparkAccountRef, SparkNetwork } from \"@qntx/wallet/protocol\";\n\nimport type { PaymentOption } from \"../payments/parse.ts\";\nimport { parsePayment } from \"../payments/parse.ts\";\nimport type { RequestController } from \"../requests/controller.ts\";\nimport type { SparkController } from \"../spark/controller.ts\";\nimport type { ConnectionController } from \"./controller.ts\";\nimport { LIGHTNING_METHODS } from \"./controller.ts\";\nimport {\n invalidParams,\n paymentPending,\n ProviderError,\n unauthorized,\n unsupportedMethod,\n} from \"./errors.ts\";\n\n/** A WebLN method call from the page. */\nexport type WeblnRequest = {\n readonly method: string;\n readonly params?: unknown;\n};\n\nexport type WeblnHandlerOptions = {\n readonly connections: Pick<\n ConnectionController,\n | \"checkOrigin\"\n | \"authorize\"\n | \"session\"\n | \"sessionAccounts\"\n | \"lightningPolicy\"\n | \"request\"\n | \"touch\"\n >;\n readonly requests: Pick<RequestController, \"prepare\" | \"outcome\">;\n readonly spark: Pick<SparkController, \"accountBalance\" | \"paymentStatus\">;\n /** The Spark network the account's signer runs on. */\n readonly sparkNetwork: SparkNetwork;\n readonly now: () => number;\n /** The node's display alias — host-configured, never a pubkey. */\n readonly alias: string;\n /** The host's lightning fee cap — `pay`'s `maxFeeSats` comes from here. */\n readonly lightningMaxFee: (amountSats: number) => number;\n /** The injected wait for the preimage poll. */\n readonly sleep: (ms: number) => Promise<void>;\n};\n\nconst MAX_MEMO_LENGTH = 640;\nconst PREIMAGE_POLL_START_MS = 1000;\nconst PREIMAGE_POLL_MAX_MS = 8000;\nconst PREIMAGE_POLL_BUDGET_MS = 60000;\n\nconst NOT_SETTLED = \"the payment has not settled yet and may still settle; do not retry it\";\n\n/** A committed payment whose answer was lost: it may still settle under its transfer id. */\nconst unknownOutcome = (transferId: string): ProviderError =>\n paymentPending(\n `the payment outcome is unknown: it may still settle under transfer ${transferId}; do not retry it`,\n );\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null;\n\nconst checkString = (value: unknown, name: string): string => {\n if (typeof value !== \"string\" || value === \"\") {\n throw invalidParams(`${name} must be a non-empty string`);\n }\n return value;\n};\n\nconst checkAmount = (value: unknown, name: string): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n const n = typeof value === \"string\" ? Number(value) : value;\n if (typeof n !== \"number\" || !Number.isSafeInteger(n) || n < 0) {\n throw invalidParams(`${name} must be a non-negative safe integer`);\n }\n return n;\n};\n\nconst checkInvoiceArgs = (\n params: unknown,\n): { readonly amountSats: number; readonly memo?: string } => {\n const args = isObject(params) ? params : {};\n const amount =\n checkAmount(args[\"amount\"], \"makeInvoice amount\") ??\n checkAmount(args[\"defaultAmount\"], \"makeInvoice defaultAmount\");\n checkAmount(args[\"minimumAmount\"], \"makeInvoice minimumAmount\");\n checkAmount(args[\"maximumAmount\"], \"makeInvoice maximumAmount\");\n if (amount === undefined) {\n throw invalidParams(\"makeInvoice needs an amount or a defaultAmount\");\n }\n const memo = args[\"defaultMemo\"];\n if (memo !== undefined && (typeof memo !== \"string\" || memo.length > MAX_MEMO_LENGTH)) {\n throw invalidParams(\"makeInvoice defaultMemo must be a string at most 640 characters\");\n }\n return { amountSats: amount, ...(typeof memo === \"string\" ? { memo } : {}) };\n};\n\nconst checkMaxFee = (fn: (n: number) => number, amountSats: number): number => {\n const maxFee = fn(amountSats);\n if (!Number.isSafeInteger(maxFee) || maxFee < 0) {\n throw new ProviderError(-32603, \"invalid lightning fee cap\");\n }\n return maxFee;\n};\n\nexport class WeblnHandler {\n private readonly options: WeblnHandlerOptions;\n\n constructor(options: WeblnHandlerOptions) {\n this.options = options;\n }\n\n /** The session's `lightning` binding as a Spark ref — the group the session authorized. */\n private ref(origin: string): SparkAccountRef {\n const group = this.options.connections.sessionAccounts(origin, \"lightning\")?.group;\n if (group === undefined) {\n throw unauthorized(\"no lightning account is bound to the session\");\n }\n return { ...group, network: this.options.sparkNetwork };\n }\n\n async handle(origin: string, request: WeblnRequest): Promise<unknown> {\n if (request.method === \"enable\") {\n if (this.options.connections.lightningPolicy(origin) === undefined) {\n await this.options.connections.request(origin, { kind: \"connect\", namespace: \"lightning\" });\n }\n await this.options.connections.touch(origin);\n return true;\n }\n this.options.connections.authorize(origin, \"lightning\", request.method);\n await this.options.connections.touch(origin);\n const ref = this.ref(origin);\n switch (request.method) {\n case \"getInfo\":\n return { node: { alias: this.options.alias }, methods: [...LIGHTNING_METHODS] };\n case \"sendPayment\":\n return this.sendPayment(origin, ref, request.params);\n case \"makeInvoice\":\n return this.makeInvoice(origin, ref, request.params);\n case \"lnurl\":\n return this.lnurl(origin, ref, request.params);\n case \"getBalance\":\n return this.getBalance(origin);\n default:\n throw unsupportedMethod(request.method);\n }\n }\n\n private async sendPayment(\n origin: string,\n ref: SparkAccountRef,\n params: unknown,\n ): Promise<unknown> {\n const invoice = checkString(params, \"sendPayment invoice\");\n const option = this.lightningOption(ref, invoice);\n if (option.amountSats === undefined) {\n throw invalidParams(\"sendPayment needs a fixed-amount invoice\");\n }\n const maxFeeSats = checkMaxFee(this.options.lightningMaxFee, option.amountSats);\n const pending = await this.options.requests.prepare({\n method: \"pay\",\n origin: { kind: \"browser\", origin },\n account: ref,\n option,\n maxFeeSats,\n });\n const outcome = await this.options.requests.outcome(pending.id);\n if (!(\"kind\" in outcome) || outcome.kind !== \"lightning\") {\n if (\"kind\" in outcome && outcome.kind === \"pending\") {\n throw unknownOutcome(outcome.payment.id);\n }\n throw new ProviderError(-32603, \"the lightning payment settled unexpectedly\");\n }\n return this.preimage(ref, outcome.payment);\n }\n\n private async makeInvoice(\n origin: string,\n ref: SparkAccountRef,\n params: unknown,\n ): Promise<unknown> {\n const { amountSats, memo } = checkInvoiceArgs(params);\n const pending = await this.options.requests.prepare({\n method: \"webln-invoice\",\n origin: { kind: \"browser\", origin },\n ref,\n amountSats,\n ...(memo === undefined ? {} : { memo }),\n });\n const outcome = await this.options.requests.outcome(pending.id);\n if (!(\"kind\" in outcome) || outcome.kind !== \"lightning.invoice\") {\n throw new ProviderError(-32603, \"the invoice request settled unexpectedly\");\n }\n return { paymentRequest: outcome.paymentRequest };\n }\n\n private async lnurl(origin: string, ref: SparkAccountRef, params: unknown): Promise<unknown> {\n const text = checkString(params, \"lnurl\");\n const parsed = parsePayment(text, { network: ref.network, now: this.options.now() });\n if (parsed.kind !== \"request\") {\n throw invalidParams(\"lnurl is not an LNURL-pay request\");\n }\n if (parsed.request.options.some((o) => o.kind === \"lnurl-withdraw\")) {\n throw unsupportedMethod(\"lnurl-withdraw\");\n }\n const option = parsed.request.options.find((o) => o.kind === \"lnurl-pay\");\n if (option === undefined || option.kind !== \"lnurl-pay\") {\n throw invalidParams(\"lnurl is not an LNURL-pay request\");\n }\n const amountSats = Math.ceil(option.request.minSendableMsat / 1000);\n const maxFeeSats = checkMaxFee(this.options.lightningMaxFee, amountSats);\n const pending = await this.options.requests.prepare({\n method: \"pay\",\n origin: { kind: \"browser\", origin },\n account: ref,\n option,\n amountSats,\n maxFeeSats,\n amountFromServiceMinimum: true,\n });\n const outcome = await this.options.requests.outcome(pending.id);\n if (!(\"kind\" in outcome) || outcome.kind !== \"lightning\") {\n if (\"kind\" in outcome && outcome.kind === \"pending\") {\n throw unknownOutcome(outcome.payment.id);\n }\n throw new ProviderError(-32603, \"the lnurl payment settled unexpectedly\");\n }\n return this.preimage(ref, outcome.payment);\n }\n\n private async preimage(ref: SparkAccountRef, payment: LightningPayment): Promise<unknown> {\n let delay = PREIMAGE_POLL_START_MS;\n let waited = 0;\n // The payment is already committed: a status read failure, an exhausted budget or a settled\n // payment without a preimage must never read as failed, or the page pays again.\n while (true) {\n let status: Awaited<ReturnType<SparkController[\"paymentStatus\"]>>;\n try {\n // oxlint-disable-next-line eslint/no-await-in-loop -- the preimage poll serially polls\n status = await this.options.spark.paymentStatus(ref, {\n requestId: payment.requestId,\n paymentHash: payment.paymentHash,\n });\n } catch {\n throw paymentPending(NOT_SETTLED);\n }\n if (status.outcome === \"failed\" || status.outcome === \"returned\") {\n throw new ProviderError(-32603, \"payment failed\");\n }\n if (status.outcome === \"succeeded\") {\n if (status.preimage === undefined) {\n throw paymentPending(\n \"the payment settled but its preimage is unavailable; do not retry it\",\n );\n }\n return { preimage: bytesToHex(status.preimage) };\n }\n if (waited >= PREIMAGE_POLL_BUDGET_MS) {\n throw paymentPending(NOT_SETTLED);\n }\n const step = Math.min(delay, PREIMAGE_POLL_MAX_MS);\n // oxlint-disable-next-line eslint/no-await-in-loop -- the preimage poll serially waits\n await this.options.sleep(step);\n waited += step;\n delay *= 2;\n }\n }\n\n private lightningOption(\n ref: SparkAccountRef,\n invoice: string,\n ): Extract<PaymentOption, { readonly kind: \"lightning\" }> {\n const parsed = parsePayment(invoice, { network: ref.network, now: this.options.now() });\n if (parsed.kind !== \"request\") {\n throw invalidParams(\"sendPayment invoice is not a BOLT11 invoice\");\n }\n const option = parsed.request.options.find((o) => o.kind === \"lightning\");\n if (option === undefined || option.kind !== \"lightning\") {\n throw invalidParams(\"sendPayment invoice is not a BOLT11 invoice\");\n }\n return option;\n }\n\n private getBalance(origin: string): unknown {\n const policy = this.options.connections.lightningPolicy(origin);\n if (policy?.balance !== true) {\n throw unauthorized(\"balance access is not granted\");\n }\n const balance = this.options.spark.accountBalance(this.ref(origin));\n if (balance === undefined) {\n throw new ProviderError(-32603, \"no cached balance for the active spark account\");\n }\n return { balance, currency: \"sats\" };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAMA,MAAa,2BAA2B;;;ACIxC,IAAa,gBAAb,cAAmC,MAAM;CACvC;CAEA,YAAY,MAAc,SAAiB;EACzC,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;AAEA,MAAa,uBAAuB,UAAU,gCAC5C,IAAI,cAAc,MAAM,OAAO;AAEjC,MAAa,gBAAgB,UAAU,qBACrC,IAAI,cAAc,MAAM,OAAO;AAEjC,MAAa,qBAAqB,WAChC,IAAI,cAAc,MAAM,GAAG,OAAO,kBAAkB;AAEtD,MAAa,qBAAqB,UAAU,yBAC1C,IAAI,cAAc,MAAM,OAAO;AAEjC,MAAa,iBAAiB,YAAmC,IAAI,cAAc,QAAQ,OAAO;AAElG,MAAa,kBAAkB,YAC7B,IAAI,cAAc,QAAQ,OAAO;;AAGnC,MAAa,iBAAiB,YAAmC,IAAI,cAAc,QAAQ,OAAO;AAElG,MAAa,iBAAiB,YAAmC,IAAI,cAAc,QAAQ,OAAO;AAElG,SAAgBA,kBAAgB,OAA+B;CAC7D,IAAI,iBAAiB,eACnB,OAAO;CAET,IAAI,iBAAiB,qBAAqB,iBAAiB,mBACzD,OAAO,cAAc,MAAM,OAAO;CAEpC,IAAI,iBAAiB,iBACnB,OAAO,oBAAoB,MAAM,OAAO;CAE1C,IAAI,iBAAiB,mBACnB,OAAO,MAAM,UAAU,WACnB,cAAc,MAAM,OAAO,IAC3B,oBAAoB,MAAM,OAAO;CAEvC,IAAI,iBAAiB,YACnB,OAAO,cAAc,MAAM,OAAO;CAEpC,OAAO,cAAc,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAC7E;;AAGA,MAAa,uBAAuB;;;;;;AAOpC,MAAa,kBAAkB,YAC7B,IAAI,cAAc,sBAAs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