@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.
Files changed (80) hide show
  1. package/README.md +1057 -20
  2. package/dist/apps-fiat24.d.mts +202 -0
  3. package/dist/apps-fiat24.mjs +1378 -0
  4. package/dist/apps-fiat24.mjs.map +1 -0
  5. package/dist/apps-hyperliquid.d.mts +549 -0
  6. package/dist/apps-hyperliquid.mjs +2742 -0
  7. package/dist/apps-hyperliquid.mjs.map +1 -0
  8. package/dist/apps-polymarket.d.mts +729 -0
  9. package/dist/apps-polymarket.mjs +3786 -0
  10. package/dist/apps-polymarket.mjs.map +1 -0
  11. package/dist/apps.d.mts +136 -0
  12. package/dist/apps.mjs +535 -0
  13. package/dist/apps.mjs.map +1 -0
  14. package/dist/connect-BY1C5ZRI.mjs +210 -0
  15. package/dist/connect-BY1C5ZRI.mjs.map +1 -0
  16. package/dist/connect.d.mts +17 -9
  17. package/dist/connect.mjs +3 -185
  18. package/dist/{errors-CQnlTc1i.d.mts → controller-DpNVHVsj.d.mts} +1093 -758
  19. package/dist/controller-rMnaxKAH.mjs +46 -0
  20. package/dist/controller-rMnaxKAH.mjs.map +1 -0
  21. package/dist/decimal-COJ4g8qy.mjs +38 -0
  22. package/dist/decimal-COJ4g8qy.mjs.map +1 -0
  23. package/dist/eligibility-BfM9ybYZ.mjs +48 -0
  24. package/dist/eligibility-BfM9ybYZ.mjs.map +1 -0
  25. package/dist/engine-Dic_kkEr.d.mts +1829 -0
  26. package/dist/errors-B8W-hoYW.d.mts +7 -0
  27. package/dist/errors-horUy5k1.mjs +24 -0
  28. package/dist/errors-horUy5k1.mjs.map +1 -0
  29. package/dist/gateway-contract.d.mts +3 -608
  30. package/dist/gateway-contract.mjs +1467 -161
  31. package/dist/gateway-contract.mjs.map +1 -1
  32. package/dist/idb.d.mts +5 -0
  33. package/dist/idb.mjs +122 -46
  34. package/dist/idb.mjs.map +1 -1
  35. package/dist/index-vBgfOFIh.d.mts +2227 -0
  36. package/dist/index.d.mts +58 -618
  37. package/dist/index.mjs +21963 -6836
  38. package/dist/index.mjs.map +1 -1
  39. package/dist/json-BDwV38cj.mjs +15 -0
  40. package/dist/json-BDwV38cj.mjs.map +1 -0
  41. package/dist/link-Ceq8Dggp.mjs +139 -0
  42. package/dist/link-Ceq8Dggp.mjs.map +1 -0
  43. package/dist/primitives-DbSHLZKq.mjs +31 -0
  44. package/dist/primitives-DbSHLZKq.mjs.map +1 -0
  45. package/dist/push-message-AQuzoNFY.d.mts +84 -0
  46. package/dist/push-message-kbnH1A5w.mjs +142 -0
  47. package/dist/push-message-kbnH1A5w.mjs.map +1 -0
  48. package/dist/push.d.mts +13 -0
  49. package/dist/push.mjs +70 -0
  50. package/dist/push.mjs.map +1 -0
  51. package/dist/qr.d.mts +292 -0
  52. package/dist/qr.mjs +1725 -0
  53. package/dist/qr.mjs.map +1 -0
  54. package/dist/registry-CbtwcxkX.mjs +374 -0
  55. package/dist/registry-CbtwcxkX.mjs.map +1 -0
  56. package/dist/risk-DyABgg4W.mjs +757 -0
  57. package/dist/risk-DyABgg4W.mjs.map +1 -0
  58. package/dist/session-CNJFLarP.mjs +18 -0
  59. package/dist/session-CNJFLarP.mjs.map +1 -0
  60. package/dist/socket-ChG9JRT_.mjs +110 -0
  61. package/dist/socket-ChG9JRT_.mjs.map +1 -0
  62. package/dist/spi-BrTw5s98.d.mts +3 -0
  63. package/dist/timer-Cdk5rGM2.mjs +43 -0
  64. package/dist/timer-Cdk5rGM2.mjs.map +1 -0
  65. package/dist/types-BpvioFGo.d.mts +258 -0
  66. package/dist/types-DbftVZ3I.mjs +90 -0
  67. package/dist/types-DbftVZ3I.mjs.map +1 -0
  68. package/dist/walletconnect.d.mts +86 -0
  69. package/dist/walletconnect.mjs +1507 -0
  70. package/dist/walletconnect.mjs.map +1 -0
  71. package/dist/webln-BgrtPXpG.mjs +2593 -0
  72. package/dist/webln-BgrtPXpG.mjs.map +1 -0
  73. package/dist/webln-Bllk_xJ2.d.mts +666 -0
  74. package/package.json +92 -19
  75. package/dist/connect.mjs.map +0 -1
  76. package/dist/registry-DwguKWvt.d.mts +0 -27
  77. package/dist/registry-oorLoGtz.mjs +0 -120
  78. package/dist/registry-oorLoGtz.mjs.map +0 -1
  79. package/dist/webln-DKqCnqx1.mjs +0 -3677
  80. package/dist/webln-DKqCnqx1.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"qr.mjs","names":["HARDENED","decode","bytesToHex","encode","evmProbe","bytesToHex","Transaction","HARDENED","hex","bytesToHex","HARDENED","solanaSignature","Transaction","bytesToHex","evmProbe"],"sources":["../src/qr/scan.ts","../src/qr/request.ts","../src/qr/response.ts","../src/qr/export.ts","../src/qr/bind.ts","../src/qr/inspect.ts","../src/qr/signer.ts","../src/qr/counterpart.ts"],"sourcesContent":["/**\n * The bounded incremental QR scanner: `@qntx/ur`'s fountain decoder under the engine's own caps — a\n * UR payload is public, untrusted bytes, so every frame counts toward a frame budget and the\n * deadline runs from the first frame. Rejected and duplicate frames still consume the budget.\n */\nimport { UrDecoder, isUrType } from \"@qntx/ur\";\nimport type { DecoderLimits, UrType } from \"@qntx/ur\";\nimport type { QrPayload } from \"@qntx/wallet/hardware\";\n\nimport { QrError } from \"./errors.ts\";\n\nexport type QrScanLimits = {\n readonly maxMessageBytes: number;\n readonly maxFragments: number;\n readonly maxFragmentBytes: number;\n readonly maxUriBytes: number;\n readonly maxFrames: number;\n readonly timeoutMs: number;\n};\n\nexport const QR_SCAN_LIMITS: QrScanLimits = {\n maxMessageBytes: 65_536,\n maxFragments: 512,\n maxFragmentBytes: 2048,\n maxUriBytes: 4096,\n maxFrames: 4096,\n timeoutMs: 120_000,\n};\n\nconst ACCEPT: Readonly<Record<\"request\" | \"export\" | \"response\", ReadonlyArray<string>>> = {\n request: [\"eth-sign-request\", \"sol-sign-request\", \"tron-sign-request\", \"crypto-psbt\", \"psbt\"],\n export: [\"crypto-hdkey\", \"crypto-account\", \"crypto-multi-accounts\"],\n response: [\"eth-signature\", \"sol-signature\", \"tron-signature\", \"crypto-psbt\", \"psbt\"],\n};\n\nexport type QrScanOutcome =\n | { readonly status: \"progress\"; readonly ratio: number }\n | { readonly status: \"complete\"; readonly payload: QrPayload };\n\nexport type QrScanner = {\n readonly receive: (text: string) => QrScanOutcome;\n};\n\nexport const createQrScanner = (options: {\n readonly kind: \"request\" | \"export\" | \"response\";\n readonly now: () => number;\n readonly limits?: Partial<QrScanLimits>;\n}): QrScanner => {\n const merged = { ...QR_SCAN_LIMITS, ...options.limits };\n const keys = [\n \"maxMessageBytes\",\n \"maxFragments\",\n \"maxFragmentBytes\",\n \"maxUriBytes\",\n \"maxFrames\",\n \"timeoutMs\",\n ] as const;\n for (const key of keys) {\n if (merged[key] > QR_SCAN_LIMITS[key]) {\n throw new QrError(\"unsupported\", `${key} above the default bound`);\n }\n }\n const limits: Partial<DecoderLimits> = {\n maxMessageLength: merged.maxMessageBytes,\n maxFragmentCount: merged.maxFragments,\n maxFragmentLength: merged.maxFragmentBytes,\n maxUriLength: merged.maxUriBytes,\n };\n const accept: UrType[] = ACCEPT[options.kind].map((type) => {\n if (!isUrType(type)) {\n throw new QrError(\"unsupported\", `bad UR type ${type}`);\n }\n return type;\n });\n const decoder = new UrDecoder({ accept, limits });\n let frames = 0;\n let deadline: number | undefined;\n let done: QrScanOutcome | undefined;\n return {\n receive: (text) => {\n if (done !== undefined) {\n return done;\n }\n frames += 1;\n if (frames > merged.maxFrames) {\n throw new QrError(\"scan-exhausted\", \"frame budget exceeded\");\n }\n if (deadline === undefined) {\n deadline = options.now() + merged.timeoutMs;\n } else if (options.now() > deadline) {\n throw new QrError(\"scan-timeout\", \"scan deadline exceeded\");\n }\n const outcome = decoder.receive(text);\n if (outcome.status === \"fatal\") {\n throw new QrError(\"scan-failed\", outcome.error.message);\n }\n const { state } = decoder;\n /* A foreign-type frame is tolerated while nothing has been collected (the camera still\n hunts) but fails the scan once a real payload is in flight — a mid-scan type mix can only\n come from showing the wrong QR. */\n if (\n outcome.status === \"rejected\" &&\n outcome.error.code === \"UnexpectedType\" &&\n state.phase === \"collecting\"\n ) {\n throw new QrError(\"scan-failed\", \"UR type changed mid-scan\");\n }\n if (state.phase === \"complete\") {\n done = {\n status: \"complete\",\n payload: { type: state.value.type, cbor: state.value.message },\n };\n return done;\n }\n return { status: \"progress\", ratio: decoder.progress.ratio };\n },\n };\n};\n","import { bytesToHex } from \"@noble/hashes/utils.js\";\n/**\n * `readQrRequest` — a scanned sign-request UR payload to the engine's `QrRequest`: strictly decoded\n * through `@qntx/ur`'s interop codecs (Keystone layout only for TRON), with every foreign failure\n * folded into `QrError`. The result is still untrusted: the kernel re-normalizes whatever sign\n * request the pipeline builds from it.\n */\nimport { base58 } from \"@scure/base\";\nimport { parseTransaction } from \"viem\";\n\nimport {\n ethSignRequestCodec,\n solSignRequestCodec,\n tronSignRequestCodec,\n oneKeyTronSignRequestCodec,\n} from \"@qntx/ur/interop\";\nimport type { Keypath, TronSignRequest } from \"@qntx/ur/interop\";\nimport { cryptoPsbtCodec, psbtCodec } from \"@qntx/ur/registry\";\nimport { Ur, fromUr } from \"@qntx/ur/typed\";\nimport type { UrCodec } from \"@qntx/ur/typed\";\nimport type { EvmTransaction, KeyPath } from \"@qntx/wallet-chains\";\nimport { evmSigningPreimage } from \"@qntx/wallet-chains/evm\";\nimport { isTronAddress, tronAddressFromBytes } from \"@qntx/wallet-chains/tron\";\nimport type { QrPayload } from \"@qntx/wallet/hardware\";\n\nimport { safeDisplayText } from \"../display.ts\";\nimport { QrError, malformed, qrGuard, unsupported } from \"./errors.ts\";\n\nconst HARDENED = 0x80000000;\n\ntype QrBase = {\n readonly requestId?: Uint8Array;\n readonly path: KeyPath;\n readonly xfp: number;\n readonly declared?: string;\n};\n\nexport type QrRequest =\n | (QrBase & {\n readonly family: \"evm\";\n readonly kind: \"transaction\";\n readonly chainId?: number;\n readonly address?: string;\n readonly tx: EvmTransaction;\n readonly data: Uint8Array;\n })\n | (QrBase & {\n readonly family: \"evm\";\n readonly kind: \"typed-data\";\n readonly chainId?: number;\n readonly address?: string;\n readonly typedData: string;\n })\n | (QrBase & {\n readonly family: \"evm\";\n readonly kind: \"personal-message\";\n readonly chainId?: number;\n readonly address?: string;\n readonly message: Uint8Array;\n })\n | (QrBase & {\n readonly family: \"solana\";\n readonly kind: \"transaction\" | \"message\";\n readonly address?: string;\n readonly data: Uint8Array;\n })\n | (QrBase & {\n readonly family: \"tron\";\n readonly kind: \"transaction\" | \"message\";\n readonly address?: string;\n readonly data: Uint8Array;\n })\n | {\n readonly family: \"bitcoin\";\n readonly kind: \"psbt\";\n readonly urType: \"crypto-psbt\" | \"psbt\";\n readonly psbt: Uint8Array;\n };\n\n/** `ur`'s body decoded by `codec`; the codec's own tag must name the payload type. */\nconst decode = <T>(payload: QrPayload, codec: UrCodec<T>): T =>\n qrGuard(\"malformed\", () => fromUr(Ur.fromCborData(payload.type, payload.cbor), codec));\n\n/** A BIP-32 keypath as the kernel's KeyPath numbers; wildcards and ranges are refused. */\nconst base = (path: Keypath, origin?: string): Omit<QrBase, \"requestId\"> => {\n if (path.components.length === 0) {\n malformed(\"empty derivation path\");\n }\n const steps: number[] = [];\n for (const component of path.components) {\n if (component.kind !== \"index\") {\n malformed(\"non-concrete derivation path\");\n }\n steps.push(component.index + (component.hardened ? HARDENED : 0));\n }\n if (path.sourceFingerprint === undefined) {\n throw new QrError(\"fingerprint-missing\", \"request carries no source fingerprint\");\n }\n const declared = origin === undefined ? undefined : safeDisplayText(origin, 64);\n return {\n path: steps,\n xfp: path.sourceFingerprint,\n ...(declared === undefined ? {} : { declared }),\n };\n};\n\nconst requestId = (bytes: Uint8Array | undefined): Uint8Array | undefined => {\n if (bytes === undefined) {\n return undefined;\n }\n if (bytes.length !== 16) {\n malformed(\"requestId must be a 16-byte UUID\");\n }\n return bytes;\n};\n\nconst ethChainId = (value: number | undefined): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n if (!Number.isSafeInteger(value) || value < 1) {\n malformed(\"chainId must be a safe integer in [1, 2^53)\");\n }\n return value;\n};\n\nconst evmAddress = (bytes: Uint8Array | undefined): string | undefined => {\n if (bytes === undefined) {\n return undefined;\n }\n if (bytes.length !== 20) {\n malformed(\"address must be 20 bytes\");\n }\n return `0x${bytesToHex(bytes)}`;\n};\n\nconst accessList = (\n list: ReadonlyArray<{ address: string; storageKeys: ReadonlyArray<`0x${string}`> }> | undefined,\n): ReadonlyArray<{ address: string; storageKeys: ReadonlyArray<string> }> =>\n (list ?? []).map((entry) => ({ address: entry.address, storageKeys: [...entry.storageKeys] }));\n\nconst bigintField = (value: bigint | undefined, name: string): string => {\n if (value === undefined) {\n malformed(`transaction is missing ${name}`);\n }\n // `EvmTransaction` quantities are canonical-hex strings, not decimals.\n return `0x${value.toString(16)}`;\n};\n\nconst evmTx = (signData: Uint8Array): { tx: EvmTransaction; typeByte: \"legacy\" | number } => {\n const [first] = signData;\n if (first === 0x04) {\n unsupported(\"eip7702 envelopes are not accepted over QR\");\n }\n const parsed = qrGuard(\"malformed\", () => parseTransaction(`0x${bytesToHex(signData)}`));\n const type = parsed.type ?? \"legacy\";\n if (type !== \"legacy\" && type !== \"eip2930\" && type !== \"eip1559\") {\n unsupported(`envelope type ${type}`);\n }\n if (type === \"legacy\" && parsed.chainId === undefined) {\n unsupported(\"a legacy transaction without an EIP-155 chain id is replayable\");\n }\n const shared = {\n chainId: parsed.chainId ?? malformed(\"typed transaction is missing chainId\"),\n nonce: parsed.nonce ?? malformed(\"transaction is missing nonce\"),\n gas: bigintField(parsed.gas, \"gas\"),\n value: `0x${(parsed.value ?? 0n).toString(16)}`,\n data: parsed.data ?? \"0x\",\n ...(parsed.to === undefined || parsed.to === null ? {} : { to: parsed.to }),\n };\n const tx: EvmTransaction =\n type === \"legacy\"\n ? { ...shared, type, gasPrice: bigintField(parsed.gasPrice, \"gasPrice\") }\n : type === \"eip2930\"\n ? {\n ...shared,\n type,\n gasPrice: bigintField(parsed.gasPrice, \"gasPrice\"),\n accessList: accessList(parsed.accessList),\n }\n : {\n ...shared,\n type,\n accessList: accessList(parsed.accessList),\n maxFeePerGas: bigintField(parsed.maxFeePerGas, \"maxFeePerGas\"),\n maxPriorityFeePerGas: bigintField(parsed.maxPriorityFeePerGas, \"maxPriorityFeePerGas\"),\n };\n return { tx, typeByte: type === \"legacy\" ? \"legacy\" : (first ?? 0) };\n};\n\nconst utf8 = (bytes: Uint8Array): string =>\n qrGuard(\"malformed\", () => new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n\nconst nonEmpty = (bytes: Uint8Array, what: string): Uint8Array => {\n if (bytes.length === 0) {\n malformed(`${what} must not be empty`);\n }\n return bytes;\n};\n\nconst readEth = (payload: QrPayload): QrRequest => {\n const req = decode(payload, ethSignRequestCodec);\n nonEmpty(req.signData, \"signData\");\n const head = base(req.derivationPath, req.origin);\n const id = requestId(req.requestId);\n const address = evmAddress(req.address);\n const chainId = ethChainId(req.chainId);\n const tail = {\n ...(id === undefined ? {} : { requestId: id }),\n ...(chainId === undefined ? {} : { chainId }),\n ...(address === undefined ? {} : { address }),\n };\n if (req.dataType === \"transaction\" || req.dataType === \"typedTransaction\") {\n const { tx } = evmTx(req.signData);\n if (bytesToHex(evmSigningPreimage(tx)) !== bytesToHex(req.signData)) {\n malformed(\"transaction does not re-serialize to the signed bytes\");\n }\n return { ...head, ...tail, family: \"evm\", kind: \"transaction\", tx, data: req.signData };\n }\n if (req.dataType === \"typedData\") {\n return { ...head, ...tail, family: \"evm\", kind: \"typed-data\", typedData: utf8(req.signData) };\n }\n return {\n ...head,\n ...tail,\n family: \"evm\",\n kind: \"personal-message\",\n message: req.signData,\n };\n};\n\nconst solanaAddress = (bytes: Uint8Array | undefined): string | undefined => {\n if (bytes === undefined) {\n return undefined;\n }\n if (bytes.length === 32) {\n return base58.encode(bytes);\n }\n const text = qrGuard(\"malformed\", () => new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n if (!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(text)) {\n malformed(\"solana address is neither 32 bytes nor base58 text\");\n }\n return text;\n};\n\nconst readSol = (payload: QrPayload): QrRequest => {\n const req = decode(payload, solSignRequestCodec);\n if (req.signType !== \"transaction\" && req.signType !== \"message\") {\n unsupported(`solana signType ${req.signType}`);\n }\n nonEmpty(req.signData, \"signData\");\n const id = requestId(req.requestId);\n const address = solanaAddress(req.address);\n return {\n ...base(req.derivationPath, req.origin),\n ...(id === undefined ? {} : { requestId: id }),\n ...(address === undefined ? {} : { address }),\n family: \"solana\",\n kind: req.signType === \"transaction\" ? \"transaction\" : \"message\",\n data: req.signData,\n };\n};\n\nconst tronAddress = (bytes: Uint8Array | undefined): string | undefined => {\n if (bytes === undefined) {\n return undefined;\n }\n if (bytes.length === 21 && bytes[0] === 0x41) {\n return tronAddressFromBytes(bytes);\n }\n const text = qrGuard(\"malformed\", () => new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n if (!isTronAddress(text)) {\n malformed(\"tron address is neither 21 raw bytes nor base58check text\");\n }\n return text;\n};\n\nconst readTron = (payload: QrPayload): QrRequest => {\n let req: TronSignRequest;\n try {\n req = decode(payload, tronSignRequestCodec);\n } catch (error) {\n // A payload only OneKey's layout reads is refused as unsupported, not malformed.\n if (error instanceof QrError && error.code === \"malformed\") {\n try {\n decode(payload, oneKeyTronSignRequestCodec);\n } catch {\n throw error;\n }\n return unsupported(\"OneKey tron-sign-request layout\");\n }\n throw error;\n }\n if (req.dataType === \"messageV1\") {\n unsupported(\"tron messageV1\");\n }\n nonEmpty(req.signData, \"signData\");\n const id = requestId(req.requestId);\n const address = tronAddress(req.address);\n return {\n ...base(req.derivationPath, req.origin),\n ...(id === undefined ? {} : { requestId: id }),\n ...(address === undefined ? {} : { address }),\n family: \"tron\",\n kind: req.dataType === \"transaction\" ? \"transaction\" : \"message\",\n data: req.signData,\n };\n};\n\nconst readPsbt = (payload: QrPayload): QrRequest => {\n const codec = payload.type === \"crypto-psbt\" ? cryptoPsbtCodec : psbtCodec;\n const { bytes } = decode(payload, codec as UrCodec<{ readonly bytes: Uint8Array }>);\n return {\n family: \"bitcoin\",\n kind: \"psbt\",\n urType: payload.type === \"crypto-psbt\" ? \"crypto-psbt\" : \"psbt\",\n psbt: bytes,\n };\n};\n\nexport const readQrRequest = (payload: QrPayload): QrRequest => {\n switch (payload.type) {\n case \"eth-sign-request\":\n return readEth(payload);\n case \"sol-sign-request\":\n return readSol(payload);\n case \"tron-sign-request\":\n return readTron(payload);\n case \"crypto-psbt\":\n case \"psbt\":\n return readPsbt(payload);\n default:\n return unsupported(`UR type ${payload.type} is not a sign request`);\n }\n};\n","/**\n * `qrResponse` — a verified `chain.sign` result as the UR signature the watching wallet expects.\n * Before anything is encoded the result is re-verified against the request's own bytes (recovered\n * signer for EVM/TRON, ed25519 verify for Solana, unchanged-PSBT-plus-new-signature for Bitcoin),\n * so a wrong result ends in `result-mismatch` and produces no payload.\n */\nimport { bytesToHex, concatBytes, hexToBytes } from \"@noble/hashes/utils.js\";\nimport { Transaction } from \"@scure/btc-signer/transaction.js\";\nimport { parseTransaction } from \"viem\";\n\nimport { ethSignatureCodec, solSignatureCodec, tronSignatureCodec } from \"@qntx/ur/interop\";\nimport { cryptoPsbtCodec, psbtCodec } from \"@qntx/ur/registry\";\nimport { toUr } from \"@qntx/ur/typed\";\nimport type { UrCodec } from \"@qntx/ur/typed\";\nimport type { EvmTransaction, SignRequest } from \"@qntx/wallet-chains\";\nimport { samePsbtContent } from \"@qntx/wallet-chains/bitcoin\";\nimport { recoverEvmSigner } from \"@qntx/wallet-chains/evm\";\nimport { verifySolanaSignature } from \"@qntx/wallet-chains/solana\";\nimport { recoverTronMessageSigner, recoverTronTransactionSigner } from \"@qntx/wallet-chains/tron\";\nimport type { QrPayload } from \"@qntx/wallet/hardware\";\nimport type { ChainSignResult } from \"@qntx/wallet/protocol\";\n\nimport { qrGuard, resultMismatch as mismatch } from \"./errors.ts\";\nimport type { QrRequest } from \"./request.ts\";\n\n/** The account the response claims — the request's address is untrusted, the caller's is not. */\nexport type QrSigner = { readonly address: string };\n\nconst encode = <T>(type: string, value: T, codec: UrCodec<T>): QrPayload =>\n qrGuard(\"result-mismatch\", () => ({\n type,\n cbor: toUr(value, codec).toCborData(),\n }));\n\nconst fixed32 = (value: `0x${string}` | undefined): Uint8Array => {\n const bytes = hexToBytes((value ?? \"0x\").slice(2).padStart(64, \"0\"));\n if (bytes.length !== 32) {\n mismatch(\"signature component is not 32 bytes\");\n }\n return bytes;\n};\n\n/** Big-endian, leading-zero-free — the minimal `v` Keystone firmware writes for legacy txs. */\nconst minimalInt = (value: number): Uint8Array => {\n const hex = value.toString(16);\n return hexToBytes(hex.length % 2 === 0 ? hex : `0${hex}`);\n};\n\n/** The evm fields a probe reads — both `QrRequest` and the counterpart's `QrSignInput` fit. */\nexport type EvmProbeInput =\n | { readonly kind: \"transaction\"; readonly tx: EvmTransaction; readonly chainId?: number }\n | { readonly kind: \"typed-data\"; readonly typedData: string; readonly chainId?: number }\n | { readonly kind: \"personal-message\"; readonly message: Uint8Array; readonly chainId?: number };\n\n/** A `chain.sign`-shaped request for `recoverEvmSigner`; account/network fields are unused there. */\nexport const evmProbe = (request: EvmProbeInput): SignRequest => {\n const chainId = request.kind === \"transaction\" ? request.tx.chainId : request.chainId;\n const network = `eip155:${chainId ?? 1}`;\n const account = { kind: \"hd\" as const, walletId: \"\", groupIndex: 0, template: \"evm.bip44\" };\n if (request.kind === \"transaction\") {\n return { kind: \"evm.transaction\", network, account, tx: request.tx };\n }\n if (request.kind === \"typed-data\") {\n return { kind: \"evm.typed-data\", network, account, typedData: request.typedData };\n }\n return { kind: \"evm.personal-message\", network, account, message: request.message };\n};\n\nconst evmResponse = (request: QrRequest, result: ChainSignResult, signer: QrSigner): QrPayload => {\n if (request.family !== \"evm\") {\n mismatch(\"not an evm request\");\n }\n let signature: Uint8Array;\n if (request.kind === \"transaction\") {\n if (result.kind !== \"evm.transaction\") {\n mismatch(\"expected an evm.transaction result\");\n }\n const parsed = qrGuard(\"result-mismatch\", () =>\n parseTransaction(`0x${bytesToHex(result.signedTransaction)}`),\n );\n if (parsed.r === undefined || parsed.s === undefined || parsed.yParity === undefined) {\n mismatch(\"the signed envelope carries no signature\");\n }\n const recovered = qrGuard(\"result-mismatch\", () =>\n recoverEvmSigner(evmProbe(request), { signedTransaction: result.signedTransaction }),\n );\n if (recovered.toLowerCase() !== signer.address.toLowerCase()) {\n mismatch(\"signature does not recover to the signer\");\n }\n const v =\n request.tx.type === \"legacy\"\n ? minimalInt(parsed.yParity + 27 + request.tx.chainId * 2 + 8)\n : new Uint8Array([parsed.yParity]);\n signature = concatBytes(fixed32(parsed.r), fixed32(parsed.s), v);\n } else {\n if (result.kind !== \"evm.typed-data\" && result.kind !== \"evm.personal-message\") {\n mismatch(\"expected an evm signature result\");\n }\n if (result.signature.length !== 65) {\n mismatch(\"expected a 65-byte signature\");\n }\n const recovered = qrGuard(\"result-mismatch\", () =>\n recoverEvmSigner(evmProbe(request), { signature: result.signature }),\n );\n if (recovered.toLowerCase() !== signer.address.toLowerCase()) {\n mismatch(\"signature does not recover to the signer\");\n }\n const [last] = result.signature.subarray(64);\n if (last === undefined) {\n mismatch(\"unexpected recovery id\");\n }\n const recid = last - 27;\n if (recid !== 0 && recid !== 1) {\n mismatch(\"unexpected recovery id\");\n }\n signature = concatBytes(result.signature.subarray(0, 64), new Uint8Array([recid + 27]));\n }\n return encode(\n \"eth-signature\",\n {\n ...(request.requestId === undefined ? {} : { requestId: request.requestId }),\n signature,\n },\n ethSignatureCodec,\n );\n};\n\nconst solanaResponse = (\n request: QrRequest,\n result: ChainSignResult,\n signer: QrSigner,\n): QrPayload => {\n if (request.family !== \"solana\") {\n mismatch(\"not a solana request\");\n }\n const want = request.kind === \"transaction\" ? \"solana.transaction\" : \"solana.message\";\n if (result.kind !== want) {\n mismatch(`expected a ${want} result`);\n }\n if (result.signature.length !== 64) {\n mismatch(\"expected a 64-byte signature\");\n }\n if (!verifySolanaSignature(request.data, result.signature, signer.address)) {\n mismatch(\"signature does not verify under the signer\");\n }\n return encode(\n \"sol-signature\",\n {\n ...(request.requestId === undefined ? {} : { requestId: request.requestId }),\n signature: result.signature,\n },\n solSignatureCodec,\n );\n};\n\nconst tronResponse = (request: QrRequest, result: ChainSignResult, signer: QrSigner): QrPayload => {\n if (request.family !== \"tron\") {\n mismatch(\"not a tron request\");\n }\n const want = request.kind === \"transaction\" ? \"tron.transaction\" : \"tron.message\";\n if (result.kind !== want) {\n mismatch(`expected a ${want} result`);\n }\n if (result.signature.length !== 65) {\n mismatch(\"expected a 65-byte signature\");\n }\n const recovered =\n request.kind === \"transaction\"\n ? qrGuard(\"result-mismatch\", () =>\n recoverTronTransactionSigner(request.data, result.signature),\n )\n : qrGuard(\"result-mismatch\", () => recoverTronMessageSigner(request.data, result.signature));\n if (recovered !== signer.address) {\n mismatch(\"signature does not recover to the signer\");\n }\n const [last] = result.signature.subarray(64);\n if (last === undefined) {\n mismatch(\"unexpected recovery id\");\n }\n const recid = last - 27;\n if (recid !== 0 && recid !== 1) {\n mismatch(\"unexpected recovery id\");\n }\n // Keystone firmware writes v = recid on transactions and v = recid + 27 on messages.\n const v = request.kind === \"transaction\" ? recid : recid + 27;\n return encode(\n \"tron-signature\",\n {\n ...(request.requestId === undefined ? {} : { requestId: request.requestId }),\n signature: concatBytes(result.signature.subarray(0, 64), new Uint8Array([v])),\n },\n tronSignatureCodec,\n );\n};\n\nconst inputSignatures = (input: {\n tapKeySig?: Uint8Array;\n partialSig?: ReadonlyArray<unknown>;\n tapScriptSig?: ReadonlyArray<unknown>;\n}): number =>\n (input.tapKeySig === undefined ? 0 : 1) +\n (input.partialSig?.length ?? 0) +\n (input.tapScriptSig?.length ?? 0);\n\nconst bitcoinResponse = (request: QrRequest, result: ChainSignResult): QrPayload => {\n if (request.family !== \"bitcoin\") {\n mismatch(\"not a bitcoin request\");\n }\n if (result.kind !== \"bitcoin.psbt\") {\n mismatch(\"expected a bitcoin.psbt result\");\n }\n if (!samePsbtContent(request.psbt, result.signedPsbt)) {\n mismatch(\"the signed PSBT does not match the request\");\n }\n const [requested, signed] = qrGuard(\"result-mismatch\", () => [\n Transaction.fromPSBT(request.psbt),\n Transaction.fromPSBT(result.signedPsbt),\n ]);\n let fresh = 0;\n for (let index = 0; index < signed.inputsLength; index += 1) {\n fresh += inputSignatures(signed.getInput(index)) - inputSignatures(requested.getInput(index));\n }\n if (fresh < 1) {\n mismatch(\"the signed PSBT carries no new signature\");\n }\n return encode(\n request.urType,\n { bytes: result.signedPsbt },\n (request.urType === \"crypto-psbt\" ? cryptoPsbtCodec : psbtCodec) as UrCodec<{\n readonly bytes: Uint8Array;\n }>,\n );\n};\n\n// oxlint-disable-next-line typescript/consistent-return -- exhaustive switch, no fall-off\nexport const qrResponse = (\n request: QrRequest,\n result: ChainSignResult,\n signer: QrSigner | undefined,\n): QrPayload => {\n const signerOrThrow = (): QrSigner => {\n if (signer === undefined) {\n mismatch(\"the request bound no signer to verify against\");\n }\n return signer;\n };\n switch (request.family) {\n case \"evm\":\n return evmResponse(request, result, signerOrThrow());\n case \"solana\":\n return solanaResponse(request, result, signerOrThrow());\n case \"tron\":\n return tronResponse(request, result, signerOrThrow());\n case \"bitcoin\":\n return bitcoinResponse(request, result);\n }\n};\n","/**\n * `qrExport` — the public material `chain.exportAccount` produced, encoded as the account UR a\n * watch-only wallet reads: `crypto-hdkey` for an EVM account node (MetaMask/Rabby),\n * `crypto-account` for a Bitcoin account descriptor (BlueWallet/Sparrow) and\n * `crypto-multi-accounts` for the Web wallet's per-leaf form. Only public fields are written;\n * `device`/`name`, where a reader expects one, is the constant `\"qntx\"`.\n */\nimport { cryptoMultiAccountsCodec } from \"@qntx/ur/interop\";\nimport type { DerivedHdKey, MultiAccounts, MultiAccountsKey } from \"@qntx/ur/interop\";\nimport { CoinType, Network, cryptoAccountCodec, cryptoHdKeyCodec } from \"@qntx/ur/registry\";\nimport type { AccountDescriptor } from \"@qntx/ur/registry\";\nimport { toUr } from \"@qntx/ur/typed\";\nimport { bitcoinNetwork } from \"@qntx/wallet-chains/bitcoin\";\nimport type { QrPayload } from \"@qntx/wallet/hardware\";\nimport type { ChainExportedKey, ChainExportResult } from \"@qntx/wallet/protocol\";\n\nimport { qrGuard, resultMismatch as mismatch, unsupported } from \"./errors.ts\";\nimport { keypath } from \"./link.ts\";\n\nexport type QrExportForm = \"crypto-hdkey\" | \"crypto-account\" | \"crypto-multi-accounts\";\n\nexport type QrExport = {\n readonly payload: QrPayload;\n readonly discloses: \"evm-all-addresses\" | \"account-addresses\" | \"single-addresses\";\n};\n\nconst fingerprint = (hex: string): number => {\n if (!/^[0-9a-f]{8}$/.test(hex)) {\n mismatch(\"fingerprint must be 8 lowercase hex digits\");\n }\n return Number.parseInt(hex, 16);\n};\n\nconst accountFields = (key: ChainExportedKey): { chainCode: Uint8Array; parent: number } => {\n const { chainCode, parentFingerprint } = key;\n if (chainCode === undefined || parentFingerprint === undefined) {\n mismatch(\"an account node carries a chain code and parent fingerprint\");\n }\n if (key.publicKey.length !== 33 || chainCode.length !== 32) {\n mismatch(\"bad account node key lengths\");\n }\n return { chainCode, parent: fingerprint(parentFingerprint) };\n};\n\nconst single = (\n result: ChainExportResult,\n kind: ChainExportedKey[\"node\"][\"kind\"],\n form: string,\n): ChainExportedKey => {\n const [key] = result.keys;\n if (result.keys.length !== 1 || key === undefined || key.node.kind !== kind) {\n unsupported(`${form} exports exactly one ${kind} key`);\n }\n return key;\n};\n\nconst hdkeyExport = (result: ChainExportResult): QrExport => {\n const key = single(result, \"evm.account\", \"crypto-hdkey\");\n const { chainCode, parent } = accountFields(key);\n const mfp = fingerprint(result.fingerprint);\n const hd: DerivedHdKey = {\n kind: \"derived\",\n isPrivate: false,\n keyData: key.publicKey,\n chainCode,\n origin: keypath(key.path, mfp),\n children: {\n components: [\n { kind: \"index\" as const, index: 0, hardened: false },\n { kind: \"wildcard\" as const, hardened: false },\n ],\n },\n parentFingerprint: parent,\n name: \"qntx\",\n note: \"account.standard\",\n };\n return {\n payload: qrGuard(\"result-mismatch\", () => ({\n type: \"crypto-hdkey\",\n cbor: toUr(hd, cryptoHdKeyCodec).toCborData(),\n })),\n discloses: \"evm-all-addresses\",\n };\n};\n\nconst DESCRIPTOR: Readonly<Record<string, string>> = {\n \"btc.bip44\": \"pkh(@0)\",\n \"btc.bip49\": \"sh(wpkh(@0))\",\n \"btc.bip84\": \"wpkh(@0)\",\n \"btc.bip86\": \"tr(@0)\",\n};\n\nconst accountExport = (result: ChainExportResult): QrExport => {\n const key = single(result, \"btc.account\", \"crypto-account\");\n if (key.node.kind !== \"btc.account\") {\n unsupported(\"crypto-account exports a btc.account key\");\n }\n const source = DESCRIPTOR[key.node.template];\n if (source === undefined) {\n unsupported(`account template ${key.node.template}`);\n }\n const { chainCode, parent } = accountFields(key);\n const mfp = fingerprint(result.fingerprint);\n const { network } = key.node;\n const net = qrGuard(\"result-mismatch\", () => bitcoinNetwork(network));\n const account: AccountDescriptor = {\n masterFingerprint: mfp,\n outputDescriptors: [\n {\n source,\n keys: [\n {\n kind: \"hdkey\",\n key: {\n kind: \"derived\",\n isPrivate: false,\n keyData: key.publicKey,\n chainCode,\n useInfo: {\n type: CoinType.btc,\n network: net.coinType === 0 ? Network.mainnet : Network.btcTestnet,\n },\n origin: keypath(key.path, mfp),\n parentFingerprint: parent,\n },\n },\n ],\n },\n ],\n };\n return {\n payload: qrGuard(\"result-mismatch\", () => ({\n type: \"crypto-account\",\n cbor: toUr(account, cryptoAccountCodec).toCborData(),\n })),\n discloses: \"account-addresses\",\n };\n};\n\nconst multiKey = (key: ChainExportedKey, mfp: number): MultiAccountsKey => {\n if (key.node.kind === \"evm.account\") {\n unsupported(\"evm.account belongs in crypto-hdkey, not crypto-multi-accounts\");\n }\n if (key.node.kind === \"leaf\") {\n if (key.node.template === \"solana.bip44-change\") {\n if (key.curve !== \"ed25519\" || key.publicKey.length !== 32) {\n mismatch(\"solana leaf must be a 32-byte ed25519 key\");\n }\n return {\n curve: \"ed25519\",\n key: { keyData: key.publicKey, origin: keypath(key.path, mfp) },\n };\n }\n if (key.curve !== \"secp256k1\" || key.publicKey.length !== 33) {\n mismatch(\"a leaf must be a 33-byte secp256k1 key\");\n }\n return {\n curve: \"secp256k1\",\n key: {\n kind: \"derived\",\n isPrivate: false,\n keyData: key.publicKey,\n origin: keypath(key.path, mfp),\n },\n };\n }\n if (key.node.kind === \"btc.account\") {\n const { chainCode, parent } = accountFields(key);\n return {\n curve: \"secp256k1\",\n key: {\n kind: \"derived\",\n isPrivate: false,\n keyData: key.publicKey,\n chainCode,\n origin: keypath(key.path, mfp),\n parentFingerprint: parent,\n },\n };\n }\n return unsupported(\"export node is not encodable as crypto-multi-accounts\");\n};\n\nconst multiExport = (result: ChainExportResult): QrExport => {\n if (result.keys.length === 0) {\n unsupported(\"crypto-multi-accounts exports at least one key\");\n }\n const mfp = fingerprint(result.fingerprint);\n const accounts: MultiAccounts = {\n masterFingerprint: mfp,\n keys: result.keys.map((key) => multiKey(key, mfp)),\n device: \"qntx\",\n };\n return {\n payload: qrGuard(\"result-mismatch\", () => ({\n type: \"crypto-multi-accounts\",\n cbor: toUr(accounts, cryptoMultiAccountsCodec).toCborData(),\n })),\n discloses: result.keys.some((key) => key.node.kind === \"btc.account\")\n ? \"account-addresses\"\n : \"single-addresses\",\n };\n};\n\n// oxlint-disable-next-line typescript/consistent-return -- exhaustive switch, no fall-off\nexport const qrExport = (result: ChainExportResult, form: QrExportForm): QrExport => {\n switch (form) {\n case \"crypto-hdkey\":\n return hdkeyExport(result);\n case \"crypto-account\":\n return accountExport(result);\n case \"crypto-multi-accounts\":\n return multiExport(result);\n }\n};\n","/**\n * Pure QR request binding: a decoded `QrRequest` is matched against the selected account's\n * authenticated facts — fingerprint, derivation path, declared address, enabled networks — and\n * turned into candidate `RequestInput`s for the existing request pipeline. Solana and TRON\n * transactions produce one candidate per enabled network (mainnet first): a lifetime/cluster\n * binding failure there means trying the next candidate.\n *\n * No wallet I/O happens here — `QrAccountFacts` carries everything the wallet already proved.\n */\nimport { OutScript, Transaction } from \"@scure/btc-signer\";\n\nimport type { BitcoinTemplate, KeyPath } from \"@qntx/wallet-chains\";\nimport { parseTypedData } from \"@qntx/wallet-chains/evm\";\nimport { parseCompiledMessage } from \"@qntx/wallet-chains/solana\";\n\nimport type {\n BitcoinSignInput,\n EvmSignInput,\n SolanaSignInput,\n TronSignInput,\n} from \"../requests/controller.ts\";\nimport type { BitcoinPsbtInput, BitcoinSigHash, QrOrigin } from \"../requests/types.ts\";\nimport type { AccountRef } from \"../transactions/route.ts\";\nimport { QrError, qrGuard } from \"./errors.ts\";\nimport { BITCOIN_MAINNET, PURPOSE_TEMPLATE } from \"./link.ts\";\nimport type { QrRequest } from \"./request.ts\";\n\n/**\n * Everything binding checks against: the selected account's facts — the resolved leaf addresses per\n * family and the enabled networks per family. The master fingerprint is a public value the\n * transport reports: nothing authenticates it, and a hostile reader can claim any value — matching\n * it here is a consistency check for the user's benefit, not what makes the binding safe. Safety\n * rests on the kernel verifying every input of the transaction the request carries.\n */\nexport type QrAccountFacts = {\n readonly walletId: string;\n readonly groupIndex: number;\n /** The master key fingerprint as a number — what a UR request's `sourceFingerprint` carries. */\n readonly fingerprint: number;\n /** The resolved leaf address per family — only the request's own family is guaranteed present. */\n readonly addresses: {\n readonly evm?: string;\n readonly tron?: string;\n readonly solana?: string;\n };\n /** Enabled CAIP-2 ids per family; `solana`/`tron` are ordered mainnet first. */\n readonly networks: {\n readonly evm: ReadonlyArray<string>;\n readonly solana: ReadonlyArray<string>;\n readonly tron: ReadonlyArray<string>;\n readonly bitcoin: ReadonlyArray<string>;\n };\n};\n\nconst HARDENED = 0x80_00_00_00;\n\n/** The leaf path each family's account template derives at for `groupIndex`. */\nconst leafPath = (family: \"evm\" | \"tron\" | \"solana\", groupIndex: number): KeyPath =>\n family === \"evm\"\n ? [44 + HARDENED, 60 + HARDENED, HARDENED, 0, groupIndex]\n : family === \"tron\"\n ? [44 + HARDENED, 195 + HARDENED, HARDENED, 0, groupIndex]\n : [44 + HARDENED, 501 + HARDENED, groupIndex + HARDENED, HARDENED];\n\nconst samePath = (a: KeyPath, b: KeyPath): boolean =>\n a.length === b.length && a.every((step, index) => step === b[index]);\n\nconst mismatch = (what: string): QrError =>\n new QrError(\"account-mismatch\", `the request's ${what} is not this account's`);\n\n/**\n * The fingerprint, the leaf path and — when the request declares one — the address must all be the\n * selected account's, or the request was meant for another key entirely.\n */\nconst requireAccount = (\n request: { readonly path: KeyPath; readonly xfp: number; readonly address?: string },\n facts: QrAccountFacts,\n family: \"evm\" | \"tron\" | \"solana\",\n): void => {\n if (request.xfp !== facts.fingerprint) {\n throw mismatch(\"fingerprint\");\n }\n if (!samePath(request.path, leafPath(family, facts.groupIndex))) {\n throw mismatch(\"derivation path\");\n }\n const { address } = request;\n if (address === undefined) {\n return;\n }\n const own = facts.addresses[family];\n if (family === \"evm\" ? address.toLowerCase() !== own?.toLowerCase() : address !== own) {\n throw mismatch(\"address\");\n }\n};\n\nconst qrOrigin = (declared: string | undefined): QrOrigin => ({\n kind: \"qr\",\n ...(declared === undefined ? {} : { declared }),\n});\n\n/** `domain.chainId` as a number, when present — the same reading wallet-chains' normalize uses. */\nconst typedDataChainId = (typedData: string): number | undefined => {\n const { json } = qrGuard(\"malformed\", () => parseTypedData(typedData));\n const { chainId } = json.domain;\n if (chainId === undefined) {\n return undefined;\n }\n const numeric =\n typeof chainId === \"number\"\n ? chainId\n : typeof chainId === \"string\" && /^(?:[0-9]+|0x[0-9a-fA-F]+)$/.test(chainId)\n ? Number(chainId)\n : Number.NaN;\n if (!Number.isSafeInteger(numeric) || numeric < 0) {\n throw new QrError(\"malformed\", \"typed-data domain.chainId is malformed\");\n }\n return numeric;\n};\n\nconst evmCandidates = (\n request: QrRequest & { family: \"evm\" },\n facts: QrAccountFacts,\n): EvmSignInput => {\n requireAccount(request, facts, \"evm\");\n const account: AccountRef = {\n kind: \"hd\",\n walletId: facts.walletId,\n groupIndex: facts.groupIndex,\n template: \"evm.bip44\",\n };\n const origin = qrOrigin(request.declared);\n if (request.kind === \"transaction\") {\n const { tx } = request;\n if (tx.type === \"eip7702\") {\n throw new QrError(\"unsupported\", \"an EIP-7702 authorization cannot be a QR request\");\n }\n if (tx.to === undefined) {\n throw new QrError(\"contract-creation\", \"a QR request cannot create a contract\");\n }\n if (request.chainId !== undefined && request.chainId !== tx.chainId) {\n throw new QrError(\"chain-mismatch\", \"the request's chain id is not its transaction's\");\n }\n const network = `eip155:${tx.chainId}`;\n if (!facts.networks.evm.includes(network)) {\n throw new QrError(\"network-unknown\", `network ${network} is not enabled`);\n }\n if (tx.data !== \"0x\" && tx.to.toLowerCase() === facts.addresses.evm?.toLowerCase()) {\n throw new QrError(\"self-call\", \"a QR request cannot call the signing account\");\n }\n return {\n method: \"evm-sign\",\n origin,\n account,\n network,\n request: { kind: \"evm.transaction\", network, account, tx },\n };\n }\n if (request.kind === \"typed-data\") {\n const domainChain = typedDataChainId(request.typedData);\n if (\n domainChain !== undefined &&\n request.chainId !== undefined &&\n domainChain !== request.chainId\n ) {\n throw new QrError(\"chain-mismatch\", \"the request's chain id is not its domain's\");\n }\n const bound = domainChain ?? request.chainId;\n /* A carried chain id binds the signature, so the network must be one the wallet serves;\n with no chain at all the network is a display label only. */\n const network = `eip155:${bound ?? 1}`;\n if (bound !== undefined && !facts.networks.evm.includes(network)) {\n throw new QrError(\"network-unknown\", `network ${network} is not enabled`);\n }\n return {\n method: \"evm-sign\",\n origin,\n account,\n network,\n request: { kind: \"evm.typed-data\", network, account, typedData: request.typedData },\n };\n }\n const network = `eip155:${request.chainId ?? 1}`;\n return {\n method: \"evm-sign\",\n origin,\n account,\n network,\n request: { kind: \"evm.personal-message\", network, account, message: request.message },\n };\n};\n\n/** Bitcoin-style shortvec: 7-bit groups, low to high, continuation bit on all but the last. */\nconst shortvec = (n: number): Uint8Array => {\n const out: number[] = [];\n let rest = n;\n do {\n let byte = rest % 128;\n rest = Math.floor(rest / 128);\n if (rest > 0) {\n byte += 128;\n }\n out.push(byte);\n } while (rest > 0);\n return new Uint8Array(out);\n};\n\nconst solanaCandidates = (\n request: QrRequest & { family: \"solana\" },\n facts: QrAccountFacts,\n): ReadonlyArray<SolanaSignInput> => {\n requireAccount(request, facts, \"solana\");\n const address = facts.addresses.solana;\n if (address === undefined) {\n /* `accountFacts` resolves the request's own family or already refused — never bind a\n signature slot against an empty address. */\n throw new QrError(\"wallet-unsupported\", \"the account has no solana address\");\n }\n const account = { walletId: facts.walletId, groupIndex: facts.groupIndex, address };\n const origin = qrOrigin(request.declared);\n if (request.kind === \"message\") {\n const [network] = facts.networks.solana;\n if (network === undefined) {\n throw new QrError(\"network-unknown\", \"no solana network is enabled\");\n }\n return [\n {\n method: \"solana-sign\",\n origin,\n account,\n network,\n request: { kind: \"message\", message: request.data },\n },\n ];\n }\n const parsed = qrGuard(\"malformed\", () => parseCompiledMessage(request.data));\n /* The account must be a required signer of the message — else this request is not for it. */\n if (!parsed.staticAccounts.slice(0, parsed.numRequiredSignatures).includes(account.address)) {\n throw mismatch(\"signer\");\n }\n /* `transactions` carries whole wires: the account's signature slot rides along zeroed. */\n const count = shortvec(parsed.numRequiredSignatures);\n const wire = new Uint8Array(\n count.length + 64 * parsed.numRequiredSignatures + request.data.length,\n );\n wire.set(count, 0);\n wire.set(request.data, count.length + 64 * parsed.numRequiredSignatures);\n return facts.networks.solana.map((network): SolanaSignInput => ({\n method: \"solana-sign\",\n origin,\n account,\n network,\n request: { kind: \"transactions\", transactions: [wire], send: false },\n }));\n};\n\nconst tronCandidates = (\n request: QrRequest & { family: \"tron\" },\n facts: QrAccountFacts,\n): ReadonlyArray<TronSignInput> => {\n requireAccount(request, facts, \"tron\");\n const account: AccountRef = {\n kind: \"hd\",\n walletId: facts.walletId,\n groupIndex: facts.groupIndex,\n template: \"tron.bip44\",\n };\n const origin = qrOrigin(request.declared);\n if (request.kind === \"message\") {\n const [network] = facts.networks.tron;\n if (network === undefined) {\n throw new QrError(\"network-unknown\", \"no tron network is enabled\");\n }\n return [\n {\n method: \"tron-sign\",\n origin,\n account,\n network,\n request: { kind: \"tron.message\", network, account, message: request.data },\n },\n ];\n }\n return facts.networks.tron.map((network): TronSignInput => ({\n method: \"tron-sign\",\n origin,\n account,\n network,\n request: { kind: \"tron.transaction\", network, account, rawData: request.data },\n }));\n};\n\nconst SIGHASH_ALL = 1;\nconst SIGHASH_DEFAULT = 0;\nconst SIGHASH_SINGLE_ANYONECANPAY = 0x83;\n\n/** The script type that template's prevout must carry — `OutScript.decode` names are lowercase. */\nconst PURPOSE_SCRIPT: Record<number, \"pkh\" | \"sh\" | \"wpkh\" | \"tr\"> = {\n 44: \"pkh\",\n 49: \"sh\",\n 84: \"wpkh\",\n 86: \"tr\",\n};\n\nexport type PsbtEntry = {\n readonly fingerprint: number;\n readonly path: ReadonlyArray<number>;\n readonly tap: boolean;\n readonly leafHashes: number;\n};\n\nexport const inputEntries = (input: {\n readonly bip32Derivation?: ReadonlyArray<\n readonly [Uint8Array, { readonly fingerprint: number; readonly path: ReadonlyArray<number> }]\n >;\n readonly tapBip32Derivation?: ReadonlyArray<\n readonly [\n Uint8Array,\n {\n readonly hashes: ReadonlyArray<Uint8Array>;\n readonly der: { readonly fingerprint: number; readonly path: ReadonlyArray<number> };\n },\n ]\n >;\n}): ReadonlyArray<PsbtEntry> => [\n ...(input.bip32Derivation ?? []).map(([, der]) => ({\n fingerprint: der.fingerprint,\n path: der.path,\n tap: false,\n leafHashes: 0,\n })),\n ...(input.tapBip32Derivation ?? []).map(([, entry]) => ({\n fingerprint: entry.der.fingerprint,\n path: entry.der.path,\n tap: true,\n leafHashes: entry.hashes.length,\n })),\n];\n\ntype PsbtInput = ReturnType<Transaction[\"getInput\"]>;\n\n/**\n * The prevout script a signable input spends: `witnessUtxo` when present, else the output its\n * `nonWitnessUtxo` (the decoded previous transaction) points at — needed to check the path's\n * purpose against the script type.\n */\nconst prevoutScript = (input: PsbtInput): Uint8Array | undefined => {\n const witness = input.witnessUtxo?.script;\n if (witness !== undefined) {\n return witness;\n }\n const prev = input.nonWitnessUtxo;\n const vout = input.index;\n if (prev === undefined || vout === undefined || vout >= prev.outputs.length) {\n return undefined;\n }\n const out = prev.outputs[vout];\n const script: unknown = out?.script;\n return script instanceof Uint8Array ? script : undefined;\n};\n\nconst multisig = (why: string): QrError =>\n new QrError(\"multisig-unsupported\", `the kernel signs single-sig only — ${why}`);\n\nconst bitcoinCandidates = (\n request: QrRequest & { family: \"bitcoin\" },\n facts: QrAccountFacts,\n): ReadonlyArray<BitcoinSignInput> => {\n const tx = qrGuard(\"malformed\", () => Transaction.fromPSBT(request.psbt));\n const sign: Array<{ index: number; sigHash: BitcoinSigHash; template: BitcoinTemplate }> = [];\n const coins = new Set<number>();\n for (let index = 0; index < tx.inputsLength; index += 1) {\n const input = tx.getInput(index);\n const ours = inputEntries(input).filter((entry) => entry.fingerprint === facts.fingerprint);\n if (ours.length === 0) {\n continue;\n }\n if (input.witnessScript !== undefined && input.witnessScript.length > 0) {\n throw multisig(\"a witness script on this input cannot be signed\");\n }\n for (const entry of ours) {\n const [purpose, coin, group, change, i] = entry.path;\n /* This wallet's fingerprint under a path that is not the selected group's account leaf is\n not this account's material — refuse rather than skip. */\n if (\n entry.path.length !== 5 ||\n purpose === undefined ||\n coin === undefined ||\n group === undefined ||\n change === undefined ||\n i === undefined ||\n purpose < HARDENED ||\n coin < HARDENED ||\n coin - HARDENED > 1 ||\n group < HARDENED ||\n group - HARDENED !== facts.groupIndex ||\n change >= HARDENED ||\n change > 1 ||\n i >= HARDENED\n ) {\n throw mismatch(\"derivation path\");\n }\n const p = purpose - HARDENED;\n const c = coin - HARDENED;\n const template = PURPOSE_TEMPLATE[p];\n if (template === undefined) {\n throw mismatch(\"derivation path\");\n }\n if (entry.leafHashes > 0) {\n throw multisig(\"a taproot script-path entry cannot be signed\");\n }\n const script = prevoutScript(input);\n const decoded =\n script === undefined ? undefined : qrGuard(\"malformed\", () => OutScript.decode(script));\n if (decoded === undefined) {\n throw mismatch(\"script\");\n }\n if (\n decoded.type === \"ms\" ||\n decoded.type === \"wsh\" ||\n decoded.type === \"tr_ms\" ||\n decoded.type === \"tr_ns\"\n ) {\n throw multisig(\"the input's script is not a single-key output\");\n }\n if (decoded.type !== PURPOSE_SCRIPT[p]) {\n throw mismatch(\"script\");\n }\n if (decoded.type === \"sh\") {\n /* Only the plain p2sh-wrapped p2wpkh is a single-sig template output — the PSBT parser\n already refused a redeem script anywhere else. */\n const redeem = input.redeemScript;\n const inner =\n redeem === undefined ? undefined : qrGuard(\"malformed\", () => OutScript.decode(redeem));\n if (inner === undefined || inner.type !== \"wpkh\") {\n throw multisig(\"the redeem script is not a p2wpkh wrapper\");\n }\n }\n const { sighashType } = input;\n const sigHash: BitcoinSigHash =\n sighashType === undefined ||\n sighashType === SIGHASH_ALL ||\n (sighashType === SIGHASH_DEFAULT && entry.tap)\n ? \"ALL\"\n : sighashType === SIGHASH_SINGLE_ANYONECANPAY\n ? \"SINGLE|ANYONECANPAY\"\n : (() => {\n throw new QrError(\n \"sighash-unsupported\",\n `input ${index} requests an unsupported sighash`,\n );\n })();\n coins.add(c);\n sign.push({ index, sigHash, template });\n }\n }\n if (sign.length === 0) {\n throw new QrError(\"nothing-to-sign\", \"no input carries this wallet's fingerprint\");\n }\n const coinSet = [...coins];\n if (coinSet.length !== 1) {\n throw new QrError(\"network-ambiguous\", \"the inputs span several bitcoin networks\");\n }\n const [coin] = coinSet;\n let network: string;\n if (coin === 0) {\n network = BITCOIN_MAINNET;\n if (!facts.networks.bitcoin.includes(network)) {\n throw new QrError(\"network-unknown\", `network ${network} is not enabled`);\n }\n } else {\n const testnets = facts.networks.bitcoin.filter((n) => n !== BITCOIN_MAINNET);\n const [testnet] = testnets;\n if (testnets.length !== 1 || testnet === undefined) {\n throw new QrError(\n \"network-ambiguous\",\n \"the inputs need a test network but none or several are enabled\",\n );\n }\n network = testnet;\n }\n const input: BitcoinPsbtInput = { psbt: request.psbt, sign };\n return [\n {\n method: \"bitcoin-sign\",\n origin: qrOrigin(undefined),\n account: { walletId: facts.walletId, groupIndex: facts.groupIndex },\n network,\n request: { kind: \"psbt\", psbts: [input], send: false },\n },\n ];\n};\n\n/**\n * The candidate request inputs for a decoded QR request, in try order — one, except Solana and TRON\n * transactions which produce one per enabled network for the facade to try in order. All\n * account/chain/network checks happen here; the pipeline repeats the semantic ones.\n */\nexport const bindQrRequest = (\n request: QrRequest,\n facts: QrAccountFacts,\n): ReadonlyArray<EvmSignInput | SolanaSignInput | TronSignInput | BitcoinSignInput> =>\n request.family === \"evm\"\n ? [evmCandidates(request, facts)]\n : request.family === \"solana\"\n ? solanaCandidates(request, facts)\n : request.family === \"tron\"\n ? tronCandidates(request, facts)\n : bitcoinCandidates(request, facts);\n","/**\n * `inspectQrRequest` — wallet-free inspection of a decoded QR sign request: the display the host\n * can render plus the digests a signing device would show. The digests prove the meaning of the\n * scanned bytes, not that the desktop sent the same bytes to the device — compare the digest shown\n * on the device.\n */\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, hexToBytes } from \"@noble/hashes/utils.js\";\nimport { base58 } from \"@scure/base\";\nimport { Transaction } from \"@scure/btc-signer\";\nimport * as TypedData from \"ox/TypedData\";\n\nimport type { AccountRef, DisplayIntent, SignRequest, TaskKey } from \"@qntx/wallet-chains\";\nimport { BITCOIN_NETWORKS, decodeBitcoinPsbt } from \"@qntx/wallet-chains/bitcoin\";\nimport { decodeEvm, parseTypedData, planEvm } from \"@qntx/wallet-chains/evm\";\nimport { decodeSolana } from \"@qntx/wallet-chains/solana\";\nimport { decodeTron, tronMessageDigest } from \"@qntx/wallet-chains/tron\";\n\nimport { inputEntries } from \"./bind.ts\";\nimport { QrError, qrGuard } from \"./errors.ts\";\nimport { BITCOIN_MAINNET } from \"./link.ts\";\nimport type { QrRequest } from \"./request.ts\";\n\nexport type QrDigestKind =\n | \"evm-transaction-hash\"\n | \"eip712-domain-hash\"\n | \"eip712-message-hash\"\n | \"eip712-digest\"\n | \"eip191-digest\"\n | \"solana-message-hash\"\n | \"tron-txid\"\n | \"tron-message-digest\";\n\nexport type QrDigest = {\n readonly kind: QrDigestKind;\n readonly value: string;\n readonly shownBy: ReadonlyArray<\"ledger-ethereum\" | \"ledger-solana\">;\n};\n\n/**\n * One decoded view of the request: `networks` names every network the address encoding serves —\n * several when one bech32 prefix covers them (a coin-type-1' PSBT shows its `tb1…` outputs for\n * testnet and signet alike, so one intent is labelled by both; regtest's `bcrt1…` is a separate\n * entry). `intent.network` is the id the decode ran under — always a member of `networks`.\n */\nexport type QrDisplay = {\n readonly networks: ReadonlyArray<string>;\n readonly intent: DisplayIntent;\n};\n\nexport type QrInspection = {\n readonly request: QrRequest;\n /**\n * One decoded intent per output encoding the request permits — a single entry for every request\n * but a coin-type-1' PSBT, which carries both the `tb1…` and `bcrt1…` decodings. Absent when the\n * request lacks what a decoder needs (a missing counterpart address) or every decode failed.\n */\n readonly displays?: ReadonlyArray<QrDisplay>;\n readonly digests: ReadonlyArray<QrDigest>;\n};\n\nconst hex = (bytes: Uint8Array): string => `0x${bytesToHex(bytes)}`;\n\n/**\n * `planEvm` only copies the task key into the plan — the digest depends on the request bytes alone\n * — so inspection runs with the request path and a fixed placeholder point.\n */\nconst probeKey = (request: { readonly path: ReadonlyArray<number> }): TaskKey => ({\n path: request.path,\n publicKey: hexToBytes(`02${\"00\".repeat(32)}`),\n});\n\nconst account: AccountRef = {\n kind: \"hd\",\n walletId: \"\",\n groupIndex: 0,\n template: \"\",\n};\n\nconst evmNetwork = (request: Extract<QrRequest, { family: \"evm\" }>): string => {\n const chainId = request.kind === \"transaction\" ? request.tx.chainId : request.chainId;\n return `eip155:${chainId ?? 1}`;\n};\n\nconst solanaProbe = (\n request: Extract<QrRequest, { family: \"solana\" }>,\n): Extract<SignRequest, { kind: \"solana.transaction\" | \"solana.message\" }> =>\n request.kind === \"transaction\"\n ? {\n kind: \"solana.transaction\",\n network: \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\",\n account,\n message: request.data,\n }\n : {\n kind: \"solana.message\",\n network: \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\",\n account,\n message: request.data,\n format: \"raw\",\n };\n\nconst tronProbe = (\n request: Extract<QrRequest, { family: \"tron\" }>,\n): Extract<SignRequest, { kind: \"tron.transaction\" | \"tron.message\" }> =>\n request.kind === \"transaction\"\n ? {\n kind: \"tron.transaction\",\n network: \"tron:728126428\",\n account,\n rawData: request.data,\n }\n : {\n kind: \"tron.message\",\n network: \"tron:728126428\",\n account,\n message: request.data,\n };\n\n/* The coin-type-1' encodings from @qntx/wallet-chains' bitcoin network table, one CAIP-2 id\n group per bech32 prefix: testnet and signet share `tb1…` (one display serves both); regtest's\n `bcrt1…` is its own display. */\nconst COIN1_ENCODINGS: ReadonlyArray<ReadonlyArray<string>> = (() => {\n const groups = new Map<string, string[]>();\n for (const network of Object.values(BITCOIN_NETWORKS)) {\n if (network.coinType !== 1) {\n continue;\n }\n const list = groups.get(network.params.bech32) ?? [];\n list.push(network.caip2);\n groups.set(network.params.bech32, list);\n }\n return [...groups.values()];\n})();\n\nconst HARDENED = 0x80000000;\n\n/**\n * The network labels a PSBT's derivations permit, one entry per address encoding: coin type 0' is\n * mainnet alone; coin type 1' is ambiguous between the `tb1…` test networks and regtest's `bcrt1…`,\n * so both encodings are returned. A derivation with no hardened coin type, a coin type this wallet\n * never serves, derivations across several coin types, or no derivations at all leave the network\n * unreadable — refuse rather than show outputs on a guessed one (the same `network-ambiguous`\n * `bindQrRequest` raises).\n */\nconst psbtEncodings = (psbt: Uint8Array): ReadonlyArray<ReadonlyArray<string>> => {\n const tx = qrGuard(\"malformed\", () => Transaction.fromPSBT(psbt));\n const coins = new Set<number>();\n const collect = (\n io: Parameters<typeof inputEntries>[0],\n side: \"input\" | \"output\",\n index: number,\n ): void => {\n for (const entry of inputEntries(io)) {\n const [, coin] = entry.path;\n if (entry.path.length < 2 || coin === undefined || coin < HARDENED) {\n throw new QrError(\n \"network-ambiguous\",\n `a ${side} ${index} derivation carries no coin type`,\n );\n }\n coins.add(coin - HARDENED);\n }\n };\n for (let index = 0; index < tx.inputsLength; index += 1) {\n collect(\n qrGuard(\"malformed\", () => tx.getInput(index)),\n \"input\",\n index,\n );\n }\n for (let index = 0; index < tx.outputsLength; index += 1) {\n collect(\n qrGuard(\"malformed\", () => tx.getOutput(index)),\n \"output\",\n index,\n );\n }\n if (coins.size !== 1) {\n throw new QrError(\n \"network-ambiguous\",\n coins.size === 0\n ? \"the PSBT carries no derivation to read a network from\"\n : \"the derivations span several bitcoin coin types\",\n );\n }\n const [coin] = coins;\n if (coin === 0) {\n return [[BITCOIN_MAINNET]];\n }\n if (coin === 1) {\n return COIN1_ENCODINGS;\n }\n throw new QrError(\n \"network-ambiguous\",\n `coin type ${coin ?? \"unknown\"}' is not a bitcoin network we serve`,\n );\n};\n\nconst bitcoinProbe = (\n request: Extract<QrRequest, { family: \"bitcoin\" }>,\n network: string,\n): Extract<SignRequest, { kind: \"bitcoin.psbt\" }> => ({\n kind: \"bitcoin.psbt\",\n network,\n account: { kind: \"hd\", walletId: \"\", groupIndex: 0 },\n origin: \"external\",\n psbt: request.psbt,\n sign: [],\n});\n\n/** A normalized `chain.sign` request for the decoders; account fields are never read. */\n// oxlint-disable-next-line typescript/consistent-return -- exhaustive switch, no fall-off\nconst probe = (request: Extract<QrRequest, { family: \"evm\" | \"solana\" | \"tron\" }>): SignRequest => {\n switch (request.family) {\n case \"evm\": {\n const network = evmNetwork(request);\n return request.kind === \"transaction\"\n ? { kind: \"evm.transaction\", network, account, tx: request.tx }\n : request.kind === \"typed-data\"\n ? { kind: \"evm.typed-data\", network, account, typedData: request.typedData }\n : { kind: \"evm.personal-message\", network, account, message: request.message };\n }\n case \"solana\":\n return solanaProbe(request);\n case \"tron\":\n return tronProbe(request);\n }\n};\n\ntype EvmProbe = Parameters<typeof planEvm>[0];\n\nconst evmProbe = (request: Extract<QrRequest, { family: \"evm\" }>): EvmProbe => {\n const network = evmNetwork(request);\n return request.kind === \"transaction\"\n ? { kind: \"evm.transaction\", network, account, tx: request.tx }\n : request.kind === \"typed-data\"\n ? { kind: \"evm.typed-data\", network, account, typedData: request.typedData }\n : { kind: \"evm.personal-message\", network, account, message: request.message };\n};\n\nconst evmDigests = (request: Extract<QrRequest, { family: \"evm\" }>): ReadonlyArray<QrDigest> => {\n if (request.kind === \"transaction\") {\n return [\n {\n kind: \"evm-transaction-hash\",\n value: hex(planEvm(evmProbe(request), probeKey(request)).tasks[0].digest),\n /* Ledger app-ethereum ≥ 1.14.0 shows the transaction hash in the blind-signing flow —\n https://github.com/LedgerHQ/app-ethereum/blob/master/CHANGELOG.md §1.14.0 \"Changed\". */\n shownBy: [\"ledger-ethereum\"],\n },\n ];\n }\n if (request.kind === \"typed-data\") {\n const { json } = parseTypedData(request.typedData);\n return [\n {\n kind: \"eip712-domain-hash\",\n value: TypedData.hashDomain({\n domain: json.domain,\n types: json.types,\n }),\n /* Ledger app-ethereum ≥ 1.18.0 shows the EIP-712 domain and message hashes —\n https://github.com/LedgerHQ/app-ethereum/blob/master/CHANGELOG.md §1.18.0. */\n shownBy: [\"ledger-ethereum\"],\n },\n {\n kind: \"eip712-message-hash\",\n value: TypedData.hashStruct({\n data: json.message,\n primaryType: json.primaryType,\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- parseTypedData validated the shape\n types: json.types as TypedData.TypedData,\n }),\n // Same app-ethereum ≥ 1.18.0 source as the domain hash above.\n shownBy: [\"ledger-ethereum\"],\n },\n {\n kind: \"eip712-digest\",\n value: hex(planEvm(evmProbe(request), probeKey(request)).tasks[0].digest),\n /* No source says the device shows the final digest — compare only the domain and message\n hashes above. */\n shownBy: [],\n },\n ];\n }\n return [\n {\n kind: \"eip191-digest\",\n value: hex(planEvm(evmProbe(request), probeKey(request)).tasks[0].digest),\n // No primary source shows which hash app-ethereum displays for a personal message.\n shownBy: [],\n },\n ];\n};\n\n/** One decode per network the PSBT's derivations permit; a failed decode drops that entry. */\nconst bitcoinDisplays = (\n request: Extract<QrRequest, { family: \"bitcoin\" }>,\n): ReadonlyArray<QrDisplay> | undefined => {\n const encodings = psbtEncodings(request.psbt);\n const out: QrDisplay[] = [];\n for (const networks of encodings) {\n const [network] = networks;\n if (network === undefined) {\n continue;\n }\n try {\n out.push({ networks, intent: decodeBitcoinPsbt(bitcoinProbe(request, network)) });\n } catch {\n /* An undecodable frame loses that encoding's display, not the inspection. */\n }\n }\n return out.length === 0 ? undefined : out;\n};\n\n/** The display decodes, or `undefined` when the request lacks what a decoder needs. */\n// oxlint-disable-next-line typescript/consistent-return -- exhaustive switch, no fall-off\nconst displays = (request: QrRequest): ReadonlyArray<QrDisplay> | undefined => {\n if (request.family === \"bitcoin\") {\n return bitcoinDisplays(request);\n }\n if (request.address === undefined) {\n return undefined;\n }\n try {\n switch (request.family) {\n case \"evm\": {\n const intent = decodeEvm(probe(request), request.address);\n return [{ networks: [intent.network], intent }];\n }\n case \"solana\": {\n if (request.kind !== \"transaction\") {\n return undefined;\n }\n const probed = solanaProbe(request);\n if (probed.kind !== \"solana.transaction\") {\n return undefined;\n }\n const intent = decodeSolana(probed, request.address);\n return [{ networks: [intent.network], intent }];\n }\n case \"tron\": {\n const intent = decodeTron(probe(request), request.address);\n return [{ networks: [intent.network], intent }];\n }\n }\n } catch {\n return undefined;\n }\n};\n\nconst displayed = (request: QrRequest): { readonly displays?: ReadonlyArray<QrDisplay> } => {\n const decoded = displays(request);\n return decoded === undefined ? {} : { displays: decoded };\n};\n\n// oxlint-disable-next-line typescript/consistent-return -- exhaustive switch, no fall-off\nexport const inspectQrRequest = (request: QrRequest): QrInspection => {\n try {\n switch (request.family) {\n case \"evm\":\n return { request, ...displayed(request), digests: evmDigests(request) };\n case \"solana\":\n return {\n request,\n ...displayed(request),\n digests: [\n {\n kind: \"solana-message-hash\",\n value: base58.encode(sha256(request.data)),\n /* Ledger app-solana blind signing shows base58(sha256(message)) as \"Message Hash\" —\n https://github.com/LedgerHQ/app-solana/blob/a19da6c/src/handle_sign_message.c\n (cx_hash_sha256 over the message). */\n shownBy: [\"ledger-solana\"],\n },\n ],\n };\n case \"tron\":\n return {\n request,\n ...displayed(request),\n digests: [\n request.kind === \"transaction\"\n ? { kind: \"tron-txid\" as const, value: hex(sha256(request.data)), shownBy: [] }\n : {\n kind: \"tron-message-digest\" as const,\n value: hex(tronMessageDigest(request.data)),\n shownBy: [],\n },\n ],\n };\n case \"bitcoin\":\n return { request, ...displayed(request), digests: [] };\n }\n } catch (error) {\n if (error instanceof QrError) {\n throw error;\n }\n throw new QrError(\"malformed\", error instanceof Error ? error.message : \"inspect failed\");\n }\n};\n","/**\n * `qrSigner` — the QR signing facade. `prepare` binds a decoded `QrRequest` to the selected\n * account's authenticated facts and hands it to the request pipeline as one more request origin;\n * `respond` awaits the pipeline's outcome and encodes the counterpart's answer UR; `exportAccount`\n * encodes the wallet's public account material for a watch-only wallet to show. Nothing here holds\n * secrets — the kernel remains the final authority over every signature.\n */\nimport type { VerifyFactor, Wallet } from \"@qntx/wallet\";\nimport { parseCompiledMessage } from \"@qntx/wallet-chains/solana\";\nimport type { ChainsApi } from \"@qntx/wallet/chains\";\nimport type { QrPayload } from \"@qntx/wallet/hardware\";\nimport type { ChainAccount, ChainExportNode, ChainSignResult } from \"@qntx/wallet/protocol\";\n\nimport type { NetworkController } from \"../networks/controller.ts\";\nimport type { PendingRequest, RequestController, RequestResult } from \"../requests/controller.ts\";\nimport { SolanaClusterBindingError, TronBindingError } from \"../transactions/binding.ts\";\nimport { bindQrRequest } from \"./bind.ts\";\nimport type { QrAccountFacts } from \"./bind.ts\";\nimport { QrError, qrGuard } from \"./errors.ts\";\nimport { qrExport } from \"./export.ts\";\nimport type { QrExport } from \"./export.ts\";\nimport { BITCOIN_MAINNET } from \"./link.ts\";\nimport type { QrRequest } from \"./request.ts\";\nimport { qrResponse } from \"./response.ts\";\nimport type { QrSigner } from \"./response.ts\";\n\n/** The account a QR request is bound to: a wallet group the request must have been built for. */\nexport type QrAccount = { readonly walletId: string; readonly groupIndex: number };\n\nconst isBindingRefusal = (error: unknown): boolean =>\n error instanceof SolanaClusterBindingError || error instanceof TronBindingError;\n\n/**\n * The slice of the engine a QR signer drives: the request pipeline every origin feeds and the\n * enabled networks a request may be bound to. A `WalletEngine` satisfies it structurally.\n */\nexport type QrEngineSurface = {\n readonly requests: Pick<RequestController, \"prepare\" | \"outcome\">;\n readonly networks: Pick<NetworkController, \"enabled\">;\n /**\n * The one account seam — the engine's `signers.apis`: vault material derives in the kernel, card\n * and hardware wallets read their pinned material.\n */\n readonly signers: { readonly apis: Pick<ChainsApi, \"account\" | \"exportAccount\"> };\n};\n\n/** The networks a QR counterpart can address: mainnet first for the binding-fallback order. */\nconst SOLANA_MAINNET = \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\";\nconst TRON_MAINNET = \"tron:728126428\";\nconst EVM_ACCOUNT_NETWORK = \"eip155:1\";\n\nconst mainnetFirst = (ids: ReadonlyArray<string>, mainnet: string): ReadonlyArray<string> => [\n ...ids.filter((id) => id === mainnet),\n ...ids.filter((id) => id !== mainnet),\n];\n\n/** The account template and account-network the request family's leaf address comes from. */\nconst LEAF_ACCOUNT = {\n evm: { template: \"evm.bip44\", network: EVM_ACCOUNT_NETWORK },\n tron: { template: \"tron.bip44\", network: TRON_MAINNET },\n solana: { template: \"solana.bip44-change\", network: SOLANA_MAINNET },\n} as const;\n\ntype Bound = { readonly request: QrRequest; readonly signer: QrSigner | undefined };\n\n/** A chain account's address — a reply without one is never bound against an empty string. */\nconst accountAddress = (chain: ChainAccount, family: \"evm\" | \"tron\" | \"solana\"): string => {\n if (!(\"address\" in chain)) {\n throw new QrError(\n \"wallet-unsupported\",\n `the account has no ${family} address — never bind a request against an empty one`,\n );\n }\n return chain.address;\n};\n\n/**\n * The account's authenticated facts for binding: a hardware fingerprint comes from the device's\n * attested wallet info, a vault's or card's from its Bitcoin account material; the address comes\n * from `chain.account` — never from the request. Only the request's own family resolves: a card or\n * hardware wallet missing another family's pinned material must not blind this request. A missing\n * node surfaces the kernel's typed `device-required` unwrapped so the host can fetch accounts and\n * retry; nothing here wraps it in a QrError.\n */\nconst accountFacts = async (\n deps: { readonly engine: QrEngineSurface; readonly wallet: Wallet },\n account: QrAccount,\n family: QrRequest[\"family\"],\n): Promise<QrAccountFacts> => {\n const info = deps.wallet.getSnapshot().wallets.find((w) => w.walletId === account.walletId);\n if (info === undefined) {\n throw new QrError(\n \"wallet-unsupported\",\n \"a QR signer must be a vault, card or hardware wallet — imported keys cannot sign\",\n );\n }\n const { apis } = deps.engine.signers;\n const { walletId, groupIndex } = account;\n const [chain, bitcoin] = await Promise.all([\n family === \"bitcoin\"\n ? Promise.resolve(undefined)\n : apis.account({ walletId, groupIndex, ...LEAF_ACCOUNT[family] }),\n info.custody === \"hardware\"\n ? Promise.resolve(undefined)\n : apis.account({ walletId, groupIndex, template: \"btc.bip84\", network: BITCOIN_MAINNET }),\n ]);\n const fingerprint =\n info.custody === \"hardware\"\n ? Number.parseInt(info.fingerprint, 16)\n : bitcoin === undefined || !(\"fingerprint\" in bitcoin) || bitcoin.fingerprint === undefined\n ? Number.NaN\n : Number.parseInt(bitcoin.fingerprint, 16);\n if (!Number.isSafeInteger(fingerprint)) {\n throw new QrError(\"wallet-unsupported\", \"the wallet's master fingerprint is unavailable\");\n }\n return {\n walletId,\n groupIndex,\n fingerprint,\n addresses:\n chain === undefined || family === \"bitcoin\"\n ? {}\n : { [family]: accountAddress(chain, family) },\n networks: {\n evm: deps.engine.networks.enabled(\"evm\"),\n solana: mainnetFirst(deps.engine.networks.enabled(\"solana\"), SOLANA_MAINNET),\n tron: mainnetFirst(deps.engine.networks.enabled(\"tron\"), TRON_MAINNET),\n bitcoin: deps.engine.networks.enabled(\"bitcoin\"),\n },\n };\n};\n\n/* The address `qrResponse` verifies the signature against — the request's family decides which.\n Bitcoin responses carry no signer (the PSBT itself is the answer), so they bind nothing. */\nconst signerOf = (request: QrRequest, facts: QrAccountFacts): QrSigner | undefined => {\n if (request.family === \"bitcoin\") {\n return undefined;\n }\n const address = facts.addresses[request.family];\n if (address === undefined) {\n /* `accountFacts` resolves the request's own family or already refused — this is the\n integrity floor, not a reachable wallet state. */\n throw new QrError(\"wallet-unsupported\", `the account has no ${request.family} address`);\n }\n return { address };\n};\n\n/** The 64-byte ed25519 signature this account contributed to a signed transaction wire. */\nconst solanaSignature = (wire: Uint8Array, address: string): Uint8Array => {\n const [count] = wire;\n if (count === undefined || wire.length < 1 + 64 * count) {\n throw new QrError(\"result-mismatch\", \"the signed wire is truncated\");\n }\n const message = qrGuard(\"result-mismatch\", () =>\n parseCompiledMessage(wire.subarray(1 + 64 * count)),\n );\n const index = message.staticAccounts.slice(0, count).indexOf(address);\n if (index === -1) {\n throw new QrError(\"result-mismatch\", \"the signed wire carries no signature of this account\");\n }\n const signature = wire.subarray(1 + 64 * index, 1 + 64 * (index + 1));\n if (signature.length !== 64 || signature.every((byte) => byte === 0)) {\n throw new QrError(\"result-mismatch\", \"this account's signature slot is empty\");\n }\n return signature;\n};\n\n/** A pipeline outcome as the `chain.sign` result `qrResponse` verifies against the request. */\nconst toChainResult = (result: RequestResult, signer: QrSigner | undefined): ChainSignResult => {\n if (!(\"kind\" in result)) {\n throw new QrError(\"result-mismatch\", \"a QR request never produces a tracked transaction\");\n }\n switch (result.kind) {\n case \"evm.signed-transaction\":\n return { kind: \"evm.transaction\", signedTransaction: result.signedTransaction };\n case \"evm.personal-message\":\n case \"evm.typed-data\":\n return { kind: result.kind, signature: result.signature };\n case \"tron.signed-transaction\":\n return { kind: \"tron.transaction\", signature: result.signature };\n case \"tron.message\":\n return { kind: \"tron.message\", signature: result.signature };\n case \"solana.message\":\n return { kind: \"solana.message\", signature: result.signature };\n case \"solana.transactions\": {\n const wires = result.signedTransactions;\n if (\n result.send ||\n result.stopped !== undefined ||\n wires === undefined ||\n wires.length !== 1 ||\n signer === undefined\n ) {\n throw new QrError(\"result-mismatch\", \"a QR request signs exactly one transaction\");\n }\n const [wire] = wires;\n if (wire === undefined) {\n throw new QrError(\"result-mismatch\", \"a QR request signs exactly one transaction\");\n }\n return { kind: \"solana.transaction\", signature: solanaSignature(wire, signer.address) };\n }\n case \"bitcoin.psbts\": {\n const [signed] = result.signedPsbts;\n if (result.stopped !== undefined || result.signedPsbts.length !== 1 || signed === undefined) {\n throw new QrError(\"result-mismatch\", \"a QR request signs exactly one PSBT\");\n }\n return { kind: \"bitcoin.psbt\", signedPsbt: signed };\n }\n default:\n throw new QrError(\"result-mismatch\", \"the request produced an unexpected result\");\n }\n};\n\n/**\n * The QR signing surface: `prepare` feeds the pipeline, `respond` encodes the result back into the\n * counterpart's UR, `exportAccount` encodes public account material for a watch-only wallet.\n */\nexport const qrSigner = (deps: {\n readonly engine: QrEngineSurface;\n readonly wallet: Wallet;\n}): {\n readonly prepare: (request: QrRequest, account: QrAccount) => Promise<PendingRequest>;\n readonly respond: (id: string) => Promise<QrPayload>;\n readonly exportAccount: (params: QrExportParams) => Promise<QrExport>;\n} => {\n const bound = new Map<string, Bound>();\n return {\n prepare: async (request, account) => {\n const facts = await accountFacts(deps, account, request.family);\n const candidates = bindQrRequest(request, facts);\n for (const candidate of candidates) {\n try {\n /* Candidates are tried in order — a later one binds only after the earlier refused. */\n // oxlint-disable-next-line eslint/no-await-in-loop -- the try order is the binding rule\n const pending = await deps.engine.requests.prepare(candidate);\n bound.set(pending.id, { request, signer: signerOf(request, facts) });\n /* A request that ended without a result frees its entry — one `respond` can never\n consume it. An approved one keeps the entry until `respond` answers the UR. */\n const { id } = pending;\n const releaseOnEnd = async (): Promise<void> => {\n try {\n await deps.engine.requests.outcome(id);\n } catch {\n bound.delete(id);\n }\n };\n void releaseOnEnd();\n return pending;\n } catch (error) {\n if (isBindingRefusal(error)) {\n continue;\n }\n throw error;\n }\n }\n throw new QrError(\"unbound\", \"the request could not be bound to any enabled network\");\n },\n respond: async (id) => {\n /* `outcome` rejects with the pipeline's own RequestEndedError for a request that ended —\n it reaches the caller unchanged. */\n const result = await deps.engine.requests.outcome(id);\n const entry = bound.get(id);\n if (entry === undefined) {\n throw new QrError(\"result-mismatch\", \"the request was not prepared by this signer\");\n }\n bound.delete(id);\n return qrResponse(entry.request, toChainResult(result, entry.signer), entry.signer);\n },\n exportAccount: async (params) => {\n const { apis } = deps.engine.signers;\n const nodes: ChainExportNode[] = exportNodes(params);\n const result = await apis.exportAccount({\n walletId: params.account.walletId,\n groupIndex: params.account.groupIndex,\n nodes,\n verify: params.verify,\n ...(params.acknowledgeUnconfirmed === undefined\n ? {}\n : { acknowledgeUnconfirmed: params.acknowledgeUnconfirmed }),\n });\n return qrExport(result, params.form);\n },\n };\n};\n\n/** The export forms the facade maps onto `chain.exportAccount` nodes. */\nexport type QrExportParams =\n | {\n readonly account: QrAccount;\n readonly form: \"crypto-hdkey\";\n readonly verify: VerifyFactor;\n /** Export nodes a device never confirmed — the prompt shows a danger row per node. */\n readonly acknowledgeUnconfirmed?: true;\n }\n | {\n readonly account: QrAccount;\n readonly form: \"crypto-account\";\n readonly bitcoin: {\n readonly template: \"btc.bip44\" | \"btc.bip49\" | \"btc.bip84\" | \"btc.bip86\";\n readonly network: string;\n };\n readonly verify: VerifyFactor;\n readonly acknowledgeUnconfirmed?: true;\n }\n | {\n readonly account: QrAccount;\n readonly form: \"crypto-multi-accounts\";\n readonly families: ReadonlyArray<\"evm\" | \"tron\" | \"solana\">;\n readonly bitcoin?: {\n readonly template: \"btc.bip44\" | \"btc.bip49\" | \"btc.bip84\" | \"btc.bip86\";\n readonly network: string;\n };\n readonly verify: VerifyFactor;\n readonly acknowledgeUnconfirmed?: true;\n };\n\nconst LEAF_TEMPLATES = {\n evm: \"evm.bip44\",\n tron: \"tron.bip44\",\n solana: \"solana.bip44-change\",\n} as const;\n\nconst exportNodes = (params: QrExportParams): ChainExportNode[] =>\n params.form === \"crypto-hdkey\"\n ? [{ kind: \"evm.account\" }]\n : params.form === \"crypto-account\"\n ? [\n {\n kind: \"btc.account\",\n template: params.bitcoin.template,\n network: params.bitcoin.network,\n },\n ]\n : [\n ...params.families.map((family): ChainExportNode => ({\n kind: \"leaf\",\n template: LEAF_TEMPLATES[family],\n })),\n ...(params.bitcoin === undefined\n ? []\n : [\n {\n kind: \"btc.account\",\n template: params.bitcoin.template,\n network: params.bitcoin.network,\n } satisfies ChainExportNode,\n ]),\n ];\n","/**\n * The watch-only side of the QR channel: a Web wallet holds no keys — `readQrExport` turns the\n * phone's `crypto-multi-accounts` export into per-family `QrLink`s, `qrSignRequest` writes the UR\n * request our own `readQrRequest` accepts and binds, and `readQrSignature` verifies the phone's UR\n * answer against what was sent. Every hop is frames; nothing here touches a wallet.\n */\nimport { bytesToHex, hexToBytes } from \"@noble/hashes/utils.js\";\nimport { base58 } from \"@scure/base\";\nimport { HDKey } from \"@scure/bip32\";\nimport { Transaction } from \"@scure/btc-signer/transaction.js\";\nimport * as Hex from \"ox/Hex\";\nimport * as PublicKey from \"ox/PublicKey\";\nimport * as Secp256k1 from \"ox/Secp256k1\";\nimport * as Signature from \"ox/Signature\";\n\nimport {\n cryptoMultiAccountsCodec,\n ethSignRequestCodec,\n ethSignatureCodec,\n solSignRequestCodec,\n solSignatureCodec,\n tronSignRequestCodec,\n tronSignatureCodec,\n} from \"@qntx/ur/interop\";\nimport type {\n EthSignRequest,\n Keypath,\n MultiAccountsKey,\n SolSignRequest,\n TronSignRequest,\n} from \"@qntx/ur/interop\";\nimport { cryptoPsbtCodec } from \"@qntx/ur/registry\";\nimport { Ur, fromUr, toUr } from \"@qntx/ur/typed\";\nimport type { UrCodec } from \"@qntx/ur/typed\";\nimport type { EvmTransaction, SignRequest } from \"@qntx/wallet-chains\";\nimport {\n bitcoinAddressFromXpub,\n bitcoinNetwork,\n samePsbtContent,\n} from \"@qntx/wallet-chains/bitcoin\";\nimport {\n assembleEvm,\n evmAddressFromPublicKey,\n evmSigningPreimage,\n planEvm,\n recoverEvmSigner,\n} from \"@qntx/wallet-chains/evm\";\nimport type { EvmSignPlan } from \"@qntx/wallet-chains/evm\";\nimport {\n parseCompiledMessage,\n solanaAddressFromPublicKey,\n verifySolanaSignature,\n} from \"@qntx/wallet-chains/solana\";\nimport {\n recoverTronMessageSigner,\n recoverTronTransactionSigner,\n tronAddressFromPublicKey,\n tronAddressToBytes,\n} from \"@qntx/wallet-chains/tron\";\nimport type { QrPayload } from \"@qntx/wallet/hardware\";\n\nimport { inputEntries } from \"./bind.ts\";\nimport { QrError, malformed, qrGuard, resultMismatch as mismatch, unsupported } from \"./errors.ts\";\nimport {\n BITCOIN_MAINNET,\n BITCOIN_TESTNET,\n PURPOSE_TEMPLATE,\n QR_FINGERPRINT,\n keypath,\n pathComponents,\n qrLinkPath,\n} from \"./link.ts\";\nimport { evmProbe } from \"./response.ts\";\n\n/** One phone account a watch-only wallet signs through, read from the phone's export. */\nexport type QrLink = {\n readonly family: \"evm\" | \"solana\" | \"tron\" | \"bitcoin\";\n /** Master fingerprint, 8 lowercase hex. */\n readonly fingerprint: string;\n /** The signing key's path: the leaf for evm/tron/solana, the account for bitcoin. */\n readonly path: string;\n /** Evm/tron/solana: the leaf's address; bitcoin: the account's first receive address (0/0). */\n readonly address: string;\n /** Bitcoin only: the account xpub (version bytes for its network/purpose). */\n readonly xpub?: string;\n};\n\nexport type QrSignInput =\n | { readonly family: \"evm\"; readonly kind: \"transaction\"; readonly tx: EvmTransaction }\n | {\n readonly family: \"evm\";\n readonly kind: \"typed-data\";\n readonly typedData: string;\n readonly chainId?: number;\n }\n | {\n readonly family: \"evm\";\n readonly kind: \"personal-message\";\n readonly message: Uint8Array;\n readonly chainId?: number;\n }\n | {\n readonly family: \"solana\";\n readonly kind: \"transaction\" | \"message\";\n readonly data: Uint8Array;\n }\n | {\n readonly family: \"tron\";\n readonly kind: \"transaction\" | \"message\";\n readonly data: Uint8Array;\n }\n | { readonly family: \"bitcoin\"; readonly kind: \"psbt\"; readonly psbt: Uint8Array };\n\nexport type QrSentRequest = {\n readonly link: QrLink;\n readonly input: QrSignInput;\n readonly requestId?: Uint8Array;\n readonly payload: QrPayload;\n};\n\nexport type QrSignature =\n | { readonly kind: \"evm.transaction\"; readonly signedTransaction: Uint8Array }\n | { readonly kind: \"evm.signature\"; readonly signature: Uint8Array }\n | { readonly kind: \"solana.signature\"; readonly signature: Uint8Array }\n | { readonly kind: \"tron.signature\"; readonly signature: Uint8Array }\n | { readonly kind: \"bitcoin.psbt\"; readonly psbt: Uint8Array };\n\nconst HARDENED = 0x80000000;\n\nconst pathString = (components: Keypath[\"components\"]): string =>\n `m/${components.map((c) => (c.kind === \"index\" ? `${c.index}${c.hardened ? \"'\" : \"\"}` : \"*\")).join(\"/\")}`;\n\nconst fingerprintHex = (n: number): string => n.toString(16).padStart(8, \"0\");\n\n/* --- readQrExport -------------------------------------------------------- */\n\n/** An exported key as the link its family shape makes it, or `unsupported`. */\nconst keyLink = (key: MultiAccountsKey, mfp: number): QrLink => {\n const { origin } = key.key;\n if (origin === undefined || origin.components.length === 0) {\n malformed(\"an exported key carries no derivation path\");\n }\n if (origin.sourceFingerprint !== mfp) {\n malformed(\"an exported key's fingerprint is not the export's\");\n }\n const path = pathString(origin.components);\n const fingerprint = fingerprintHex(mfp);\n const secp = key.curve === \"secp256k1\" ? key.key.keyData : undefined;\n const ed = key.curve === \"ed25519\" ? key.key.keyData : undefined;\n const secp33 = (what: string): Uint8Array => {\n if (secp === undefined) {\n malformed(`${what} must be a secp256k1 key`);\n }\n return secp;\n };\n const leaf = (family: \"evm\" | \"tron\" | \"solana\", address: string): QrLink => ({\n family,\n fingerprint,\n path,\n address: qrGuard(\"malformed\", () => address),\n });\n // m/44'/60'/0'/0/i\n if (qrLinkPath(\"evm\", path)) {\n return leaf(\"evm\", evmAddressFromPublicKey(secp33(\"an evm leaf\")));\n }\n // m/44'/195'/0'/0/i\n if (qrLinkPath(\"tron\", path)) {\n return leaf(\"tron\", tronAddressFromPublicKey(secp33(\"a tron leaf\")));\n }\n // m/44'/501'/i'/0'\n if (qrLinkPath(\"solana\", path)) {\n if (ed === undefined) {\n malformed(\"a solana leaf must be an ed25519 key\");\n }\n return leaf(\"solana\", solanaAddressFromPublicKey(ed));\n }\n // m/{44,49,84,86}'/{0,1}'/i'\n if (!qrLinkPath(\"bitcoin\", path)) {\n return unsupported(`path ${path} is not a signing key the phone exports`);\n }\n const steps = pathComponents(path) ?? malformed(\"unreadable derivation path\");\n const purpose = steps[0]?.index ?? 0;\n const coin = steps[1]?.index ?? -1;\n const template = PURPOSE_TEMPLATE[purpose];\n if (template === undefined) {\n return unsupported(`path ${path} is not a signing key the phone exports`);\n }\n const pubkey = secp33(\"a bitcoin account\");\n const { chainCode } = key.key;\n const { parentFingerprint } = key.key;\n if (chainCode === undefined) {\n malformed(\"a bitcoin account carries no chain code\");\n }\n if (parentFingerprint === undefined) {\n malformed(\"a bitcoin account carries no parent fingerprint\");\n }\n const network = coin === 0 ? BITCOIN_MAINNET : BITCOIN_TESTNET;\n const version = bitcoinNetwork(network).bip32.public;\n const xpub = qrGuard(\n \"malformed\",\n () =>\n new HDKey({\n versions: { private: version, public: version },\n depth: steps.length,\n parentFingerprint,\n index: (steps[2]?.index ?? 0) + HARDENED,\n chainCode,\n publicKey: pubkey,\n }).publicExtendedKey,\n );\n return {\n family: \"bitcoin\",\n fingerprint,\n path,\n address: qrGuard(\"malformed\", () => bitcoinAddressFromXpub(xpub, template, network, 0, 0)),\n xpub,\n };\n};\n\n/**\n * The phone's `crypto-multi-accounts` export as one link per family. Strict: the fingerprint is\n * required, every key's path must be one of the shapes a `QrLink` declares, all keys share the\n * master fingerprint, and at most one key per family is accepted.\n */\nexport const readQrExport = (payload: QrPayload): ReadonlyArray<QrLink> => {\n if (payload.type !== \"crypto-multi-accounts\") {\n return unsupported(`UR type ${payload.type} is not an export the Web wallet reads`);\n }\n const accounts = qrGuard(\"malformed\", () =>\n fromUr(Ur.fromCborData(payload.type, payload.cbor), cryptoMultiAccountsCodec),\n );\n /* The codec proves `masterFingerprint` a uint32 before any key is read. */\n const mfp = accounts.masterFingerprint;\n const links: QrLink[] = [];\n for (const key of accounts.keys) {\n const link = keyLink(key, mfp);\n if (links.some((l) => l.family === link.family)) {\n malformed(`the export carries two ${link.family} keys`);\n }\n links.push(link);\n }\n return links;\n};\n\n/* --- qrSignRequest ------------------------------------------------------- */\n\nconst requestKeypath = (link: QrLink): Keypath =>\n keypath(link.path, Number.parseInt(link.fingerprint, 16));\n\nconst encode = <T>(value: T, codec: UrCodec<T>): QrPayload =>\n qrGuard(\"malformed\", () => {\n const ur = toUr(value, codec);\n return { type: ur.type, cbor: ur.toCborData() };\n });\n\nconst evmAddressBytes = (address: string): Uint8Array => {\n const bytes = hexToBytes(address.startsWith(\"0x\") ? address.slice(2) : address);\n if (bytes.length !== 20) {\n malformed(`evm link address ${address} is not 20 bytes`);\n }\n return bytes;\n};\n\n/** A PSBT derivation `link` owns: its fingerprint, under its account path. */\nconst underLink = (\n entry: { readonly fingerprint: number; readonly path: ReadonlyArray<number> },\n linkPath: ReadonlyArray<number>,\n fp: number,\n): boolean =>\n entry.fingerprint === fp &&\n entry.path.length >= linkPath.length &&\n linkPath.every((step, i) => entry.path[i] === step);\n\n/** `link`'s numeric account path and fingerprint — the PSBT derivation match keys. */\nconst linkDerivation = (link: QrLink): { path: ReadonlyArray<number>; fp: number } => ({\n path: (pathComponents(link.path) ?? malformed(`bad link path ${link.path}`)).map(\n (s) => s.index + (s.hardened ? HARDENED : 0),\n ),\n fp: Number.parseInt(link.fingerprint, 16),\n});\n\nconst psbtHasLinkInput = (psbt: Uint8Array, link: QrLink): boolean => {\n const tx = qrGuard(\"malformed\", () => Transaction.fromPSBT(psbt));\n const { path, fp } = linkDerivation(link);\n for (let index = 0; index < tx.inputsLength; index += 1) {\n if (inputEntries(tx.getInput(index)).some((e) => underLink(e, path, fp))) {\n return true;\n }\n }\n return false;\n};\n\nconst evmRequest = (\n link: QrLink,\n input: QrSignInput & { readonly family: \"evm\" },\n requestId: Uint8Array,\n origin: string | undefined,\n): QrPayload => {\n const head = {\n requestId,\n derivationPath: requestKeypath(link),\n address: evmAddressBytes(link.address),\n ...(origin === undefined ? {} : { origin }),\n };\n if (input.kind === \"transaction\") {\n const { tx } = input;\n if (tx.type === \"eip7702\") {\n throw new QrError(\"unsupported\", \"an EIP-7702 authorization cannot be a QR request\");\n }\n if (tx.to === undefined) {\n throw new QrError(\"contract-creation\", \"a QR request cannot create a contract\");\n }\n const request: EthSignRequest = {\n ...head,\n signData: qrGuard(\"malformed\", () => evmSigningPreimage(tx)),\n dataType: tx.type === \"legacy\" ? \"transaction\" : \"typedTransaction\",\n chainId: tx.chainId,\n };\n return encode(request, ethSignRequestCodec);\n }\n const request: EthSignRequest = {\n ...head,\n signData:\n input.kind === \"typed-data\" ? new TextEncoder().encode(input.typedData) : input.message,\n dataType: input.kind === \"typed-data\" ? \"typedData\" : \"personalMessage\",\n ...(input.chainId === undefined ? {} : { chainId: input.chainId }),\n };\n return encode(request, ethSignRequestCodec);\n};\n\n/**\n * The watch-only wallet's sign request, encoded as the exact UR the phone accepts: Keystone layouts\n * (`eth`/`sol`/`tron` sign request, `crypto-psbt` for Bitcoin), the link's fingerprint and path, a\n * random 16-byte request id and — only when given — an origin. Inputs the phone would refuse anyway\n * are refused here with the same codes `bindQrRequest` raises.\n */\nexport const qrSignRequest = (\n link: QrLink,\n input: QrSignInput,\n options: { readonly random: (n: number) => Uint8Array; readonly origin?: string },\n): QrSentRequest => {\n if (input.family !== link.family) {\n return malformed(`a ${input.family} input cannot sign through a ${link.family} link`);\n }\n if (!QR_FINGERPRINT.test(link.fingerprint)) {\n return malformed(`bad fingerprint ${link.fingerprint}`);\n }\n if (!qrLinkPath(link.family, link.path)) {\n return malformed(`path ${link.path} is not a ${link.family} signing path`);\n }\n const requestId = options.random(16);\n if (requestId.length !== 16) {\n return malformed(\"the random source must give 16 bytes\");\n }\n const head = {\n requestId,\n derivationPath: requestKeypath(link),\n ...(options.origin === undefined ? {} : { origin: options.origin }),\n };\n let payload: QrPayload;\n if (input.family === \"evm\") {\n payload = evmRequest(link, input, requestId, options.origin);\n } else if (input.family === \"solana\") {\n if (input.kind === \"transaction\") {\n const parsed = qrGuard(\"malformed\", () => parseCompiledMessage(input.data));\n if (!parsed.staticAccounts.slice(0, parsed.numRequiredSignatures).includes(link.address)) {\n throw new QrError(\"account-mismatch\", \"the request's signer is not this account's\");\n }\n }\n const request: SolSignRequest = {\n ...head,\n signData: input.data,\n address: base58.decode(link.address),\n signType: input.kind,\n };\n payload = encode(request, solSignRequestCodec);\n } else if (input.family === \"tron\") {\n const request: TronSignRequest = {\n ...head,\n signData: input.data,\n dataType: input.kind === \"transaction\" ? \"transaction\" : \"messageV2\",\n address: tronAddressToBytes(link.address),\n };\n payload = encode(request, tronSignRequestCodec);\n } else {\n if (!psbtHasLinkInput(input.psbt, link)) {\n throw new QrError(\"nothing-to-sign\", \"no input carries this wallet's fingerprint\");\n }\n payload = encode({ bytes: input.psbt }, cryptoPsbtCodec);\n }\n return { link, input, requestId, payload };\n};\n\n/* --- readQrSignature ----------------------------------------------------- */\n\nconst decode = <T>(payload: QrPayload, codec: UrCodec<T>): T =>\n qrGuard(\"result-mismatch\", () => fromUr(Ur.fromCborData(payload.type, payload.cbor), codec));\n\nconst echoRequestId = (sent: QrSentRequest, got: Uint8Array | undefined): void => {\n const want = sent.requestId;\n if (\n want === undefined\n ? got === undefined\n : got !== undefined && bytesToHex(want) === bytesToHex(got)\n ) {\n return;\n }\n mismatch(\"the response's request id is not the request's\");\n};\n\n/* The transaction half of a sign request as the plan's request shape — planEvm reads only\n `tx`; the head fields exist for the type, they name no account. */\nconst evmTxRequest = (tx: EvmTransaction): Extract<SignRequest, { kind: \"evm.transaction\" }> => ({\n kind: \"evm.transaction\",\n network: `eip155:${tx.chainId}`,\n account: { kind: \"hd\", walletId: \"\", groupIndex: 0, template: \"\" },\n tx,\n});\n\n/* R‖s‖v as the phone writes it → the signed envelope assembled by the signing plan. The wire's v\n is inverted to the parity acceptEcdsa's signature form carries (legacy: EIP-155\n 27 + 2·chainId + 8 + parity; typed: the parity itself); any other v is result-mismatch. The\n link names an address, not a key — the key is recovered over the plan's digest with that\n declared parity, verified inside assembleEvm, and the recovered sender is re-checked against\n the link below. */\nconst evmSignedTransaction = (tx: EvmTransaction, signature: Uint8Array): Uint8Array => {\n /* The eth-signature codec bounds the wire signature to exactly its min/max on decode, so a\n signature reaching this point is the right length — only the v remains to check. */\n const v = signature.subarray(64).reduce((acc, byte) => acc * 256 + byte, 0);\n const yParity = tx.type === \"legacy\" ? v - 27 - tx.chainId * 2 - 8 : v;\n if (yParity !== 0 && yParity !== 1) {\n mismatch(\"unexpected recovery id\");\n }\n const plan = (publicKey: Uint8Array): EvmSignPlan =>\n planEvm(evmTxRequest(tx), { path: [], publicKey });\n const wire = qrGuard(\"result-mismatch\", () =>\n Signature.from({\n r: Hex.fromBytes(signature.subarray(0, 32)),\n s: Hex.fromBytes(signature.subarray(32, 64)),\n yParity,\n }),\n );\n const publicKey = qrGuard(\"result-mismatch\", () =>\n PublicKey.toBytes(\n PublicKey.compress(\n Secp256k1.recoverPublicKey({\n payload: Hex.fromBytes(plan(new Uint8Array(33)).tasks[0].digest),\n signature: wire,\n }),\n ),\n ),\n );\n const assembled = qrGuard(\"result-mismatch\", () =>\n assembleEvm(plan(publicKey), [signature.subarray(0, 64)]),\n );\n if (assembled.kind !== \"signed\") {\n mismatch(\"the transaction plan did not sign\");\n }\n return assembled.artefact;\n};\n\nconst evmSignature = (sent: QrSentRequest, payload: QrPayload): QrSignature => {\n const { requestId, signature } = decode(payload, ethSignatureCodec);\n echoRequestId(sent, requestId);\n const { input } = sent;\n if (input.family !== \"evm\") {\n mismatch(\"not an evm request\");\n }\n const signedTransaction =\n input.kind === \"transaction\" ? evmSignedTransaction(input.tx, signature) : undefined;\n const recovered = qrGuard(\"result-mismatch\", () =>\n recoverEvmSigner(\n evmProbe(input),\n signedTransaction === undefined ? { signature } : { signedTransaction },\n ),\n );\n if (recovered.toLowerCase() !== sent.link.address.toLowerCase()) {\n mismatch(\"signature does not recover to the signer\");\n }\n return signedTransaction === undefined\n ? { kind: \"evm.signature\", signature }\n : { kind: \"evm.transaction\", signedTransaction };\n};\n\nconst solanaSignature = (sent: QrSentRequest, payload: QrPayload): QrSignature => {\n const { requestId, signature } = decode(payload, solSignatureCodec);\n echoRequestId(sent, requestId);\n const { input } = sent;\n if (input.family !== \"solana\") {\n mismatch(\"not a solana request\");\n }\n if (signature.length !== 64 || !verifySolanaSignature(input.data, signature, sent.link.address)) {\n mismatch(\"signature does not verify under the signer\");\n }\n return { kind: \"solana.signature\", signature };\n};\n\nconst tronSignature = (sent: QrSentRequest, payload: QrPayload): QrSignature => {\n const { requestId, signature } = decode(payload, tronSignatureCodec);\n echoRequestId(sent, requestId);\n const { input } = sent;\n if (input.family !== \"tron\") {\n mismatch(\"not a tron request\");\n }\n // The phone writes v = recid on transactions and recid + 27 on messages.\n const last = signature.at(-1);\n const normalized =\n input.kind === \"transaction\" && (last === 0 || last === 1)\n ? new Uint8Array([...signature.subarray(0, 64), last + 27])\n : signature;\n const recovered = qrGuard(\"result-mismatch\", () =>\n input.kind === \"transaction\"\n ? recoverTronTransactionSigner(input.data, normalized)\n : recoverTronMessageSigner(input.data, normalized),\n );\n if (recovered !== sent.link.address) {\n mismatch(\"signature does not recover to the signer\");\n }\n return { kind: \"tron.signature\", signature };\n};\n\n/** New signatures by a key whose derivation sits under `link`'s account path. */\nconst linkSignatures = (\n requested: ReturnType<Transaction[\"getInput\"]>,\n signed: ReturnType<Transaction[\"getInput\"]>,\n linkPath: ReadonlyArray<number>,\n fp: number,\n): number => {\n const linkKeys = new Set<string>();\n for (const [pubkey, der] of signed.bip32Derivation ?? []) {\n if (underLink(der, linkPath, fp)) {\n linkKeys.add(bytesToHex(pubkey));\n }\n }\n let linkTap = false;\n for (const [pubkey, entry] of signed.tapBip32Derivation ?? []) {\n if (underLink(entry.der, linkPath, fp)) {\n linkKeys.add(bytesToHex(pubkey));\n linkTap = true;\n }\n }\n /* Only signatures by a link key count — a foreign signer's new signature is not progress. */\n const requestedKeys = new Set((requested.partialSig ?? []).map(([pubkey]) => bytesToHex(pubkey)));\n let fresh = 0;\n for (const [pubkey] of signed.partialSig ?? []) {\n if (linkKeys.has(bytesToHex(pubkey)) && !requestedKeys.has(bytesToHex(pubkey))) {\n fresh += 1;\n }\n }\n if (signed.tapKeySig !== undefined && requested.tapKeySig === undefined && linkTap) {\n fresh += 1;\n }\n return fresh;\n};\n\nconst bitcoinSignature = (sent: QrSentRequest, payload: QrPayload): QrSignature => {\n const { input } = sent;\n if (input.family !== \"bitcoin\") {\n mismatch(\"not a bitcoin request\");\n }\n const { bytes } = decode(payload, cryptoPsbtCodec);\n if (!samePsbtContent(input.psbt, bytes)) {\n mismatch(\"the signed PSBT does not match the request\");\n }\n const { path: linkPath, fp } = linkDerivation(sent.link);\n const [requested, signed] = qrGuard(\"result-mismatch\", () => [\n Transaction.fromPSBT(input.psbt),\n Transaction.fromPSBT(bytes),\n ]);\n let fresh = 0;\n for (let index = 0; index < signed.inputsLength; index += 1) {\n fresh += linkSignatures(requested.getInput(index), signed.getInput(index), linkPath, fp);\n }\n if (fresh < 1) {\n mismatch(\"the signed PSBT carries no new signature by this account\");\n }\n return { kind: \"bitcoin.psbt\", psbt: bytes };\n};\n\n/**\n * The phone's UR answer verified against what this session sent: the payload type must be the\n * response type for the request, the request id must echo, and the signature must recover or verify\n * to `link.address` (a PSBT must carry unchanged content plus at least one new signature by a key\n * under the link). Anything else is `result-mismatch`.\n */\nconst RESPONSE_TYPES: Readonly<Record<QrLink[\"family\"], string>> = {\n evm: \"eth-signature\",\n solana: \"sol-signature\",\n tron: \"tron-signature\",\n bitcoin: \"crypto-psbt\",\n};\n\nconst VERIFY: Readonly<\n Record<QrLink[\"family\"], (sent: QrSentRequest, payload: QrPayload) => QrSignature>\n> = {\n evm: evmSignature,\n solana: solanaSignature,\n tron: tronSignature,\n bitcoin: bitcoinSignature,\n};\n\nexport const readQrSignature = (sent: QrSentRequest, payload: QrPayload): QrSignature => {\n const expected = RESPONSE_TYPES[sent.input.family];\n if (payload.type !== expected) {\n mismatch(`the response type ${payload.type} is not the request's ${expected}`);\n }\n return VERIFY[sent.input.family](sent, payload);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,MAAa,iBAA+B;CAC1C,iBAAiB;CACjB,cAAc;CACd,kBAAkB;CAClB,aAAa;CACb,WAAW;CACX,WAAW;AACb;AAEA,MAAM,SAAqF;CACzF,SAAS;EAAC;EAAoB;EAAoB;EAAqB;EAAe;CAAM;CAC5F,QAAQ;EAAC;EAAgB;EAAkB;CAAuB;CAClE,UAAU;EAAC;EAAiB;EAAiB;EAAkB;EAAe;CAAM;AACtF;AAUA,MAAa,mBAAmB,YAIf;CACf,MAAM,SAAS;EAAE,GAAG;EAAgB,GAAG,QAAQ;CAAO;CAStD,KAAK,MAAM,OAAO;EAPhB;EACA;EACA;EACA;EACA;EACA;CAEmB,GACnB,IAAI,OAAO,OAAO,eAAe,MAC/B,MAAM,IAAI,QAAQ,eAAe,GAAG,IAAI,yBAAyB;CAGrE,MAAM,SAAiC;EACrC,kBAAkB,OAAO;EACzB,kBAAkB,OAAO;EACzB,mBAAmB,OAAO;EAC1B,cAAc,OAAO;CACvB;CACA,MAAM,SAAmB,OAAO,QAAQ,KAAK,CAAC,KAAK,SAAS;EAC1D,IAAI,CAAC,SAAS,IAAI,GAChB,MAAM,IAAI,QAAQ,eAAe,eAAe,MAAM;EAExD,OAAO;CACT,CAAC;CACD,MAAM,UAAU,IAAI,UAAU;EAAE;EAAQ;CAAO,CAAC;CAChD,IAAI,SAAS;CACb,IAAI;CACJ,IAAI;CACJ,OAAO,EACL,UAAU,SAAS;EACjB,IAAI,SAAS,KAAA,GACX,OAAO;EAET,UAAU;EACV,IAAI,SAAS,OAAO,WAClB,MAAM,IAAI,QAAQ,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