@qntx/wallet-chains 0.11.0 → 0.12.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.
@@ -1,4 +1,4 @@
1
- import { _ as SignRequest, c as DisplayIntent, y as Verifiability } from "./index-QxoxkD5m.mjs";
1
+ import { a as BitcoinTemplate, b as Verifiability, l as DisplayIntent, v as SignRequest } from "./index-DYwm4-Ec.mjs";
2
2
  import { NETWORK } from "@scure/btc-signer/utils.js";
3
3
  type BitcoinNetwork = {
4
4
  readonly caip2: string;
@@ -13,7 +13,7 @@ type BitcoinNetwork = {
13
13
  };
14
14
  export declare const BITCOIN_NETWORKS: Readonly<Record<string, BitcoinNetwork>>;
15
15
  export declare const bitcoinNetwork: (caip2: string) => BitcoinNetwork;
16
- type BitcoinAccountTemplate = "btc.bip44" | "btc.bip49" | "btc.bip84" | "btc.bip86";
16
+ type BitcoinAccountTemplate = BitcoinTemplate;
17
17
  /**
18
18
  * Derive the address at `change`/`index` under an account-level xpub (`m/84'/c'/i'` or
19
19
  * `m/86'/c'/i'`) — P2WPKH for `btc.bip84`, P2TR key-path for `btc.bip86`.
package/dist/bitcoin.mjs CHANGED
@@ -46,11 +46,18 @@ const checkDerivations = (tx, coinType) => {
46
46
  };
47
47
  const DEFAULT_SIGHASH = 0;
48
48
  const SIGHASH_ALL = 1;
49
+ const TEMPLATES = /* @__PURE__ */ new Set([
50
+ "btc.bip44",
51
+ "btc.bip49",
52
+ "btc.bip84",
53
+ "btc.bip86"
54
+ ]);
55
+ const isSignEntry = (value) => isRecord$1(value) && typeof value["index"] === "number" && Number.isSafeInteger(value["index"]) && value["index"] >= 0 && typeof value["template"] === "string" && TEMPLATES.has(value["template"]);
49
56
  const isTaprootInput = (input) => input.tapInternalKey !== void 0 || getInputType(input).type === "taproot";
50
57
  /**
51
58
  * Validates and canonicalizes a bitcoin.psbt request (network already checked by the caller).
52
59
  * `strictPrevoutValidation` makes btc-signer verify every `nonWitnessUtxo`'s txid against its
53
- * outpoint.
60
+ * outpoint. The returned `sign` is sorted ascending by index — a normalized request is canonical.
54
61
  */
55
62
  const normalizeBitcoinPsbt = (psbt, sign, network) => {
56
63
  const net = bitcoinNetwork(network);
@@ -60,15 +67,16 @@ const normalizeBitcoinPsbt = (psbt, sign, network) => {
60
67
  } catch {
61
68
  throw new ChainError("invalid-request", "PSBT failed to decode");
62
69
  }
63
- if (!Array.isArray(sign) || sign.length === 0 || !sign.every((i) => Number.isSafeInteger(i) && i >= 0)) throw new ChainError("invalid-request", "sign must be a non-empty array of input indices");
64
- const unique = [...new Set(sign.map(Number))].sort((a, b) => a - b);
65
- const last = unique.at(-1);
66
- if (unique.length !== sign.length || last === void 0 || last >= tx.inputsLength) throw new ChainError("invalid-request", "sign must be unique, ascending, and in range");
70
+ if (!Array.isArray(sign) || sign.length === 0 || !sign.every(isSignEntry)) throw new ChainError("invalid-request", "sign must be a non-empty array of {index, template} entries");
71
+ const sorted = [...sign].sort((a, b) => a.index - b.index);
72
+ const indices = new Set(sorted.map((s) => s.index));
73
+ const last = sorted.at(-1)?.index;
74
+ if (indices.size !== sorted.length || last === void 0 || last >= tx.inputsLength) throw new ChainError("invalid-request", "sign must be unique, ascending, and in range");
67
75
  checkDerivations(tx, net.coinType);
68
- for (const idx of unique) {
76
+ for (const { index: idx, template } of sorted) {
69
77
  const input = tx.getInput(idx);
70
78
  if (input.witnessUtxo === void 0 && input.nonWitnessUtxo === void 0) throw new ChainError("invalid-request", `input ${idx} carries neither witnessUtxo nor nonWitnessUtxo`);
71
- if (input.bip32Derivation === void 0 && input.tapBip32Derivation === void 0) throw new ChainError("invalid-request", `input ${idx} is missing a bip32 derivation`);
79
+ if (template === "btc.bip86" ? input.tapBip32Derivation === void 0 : input.bip32Derivation === void 0) throw new ChainError("invalid-request", `input ${idx} is missing a bip32 derivation`);
72
80
  const { type } = getInputType(input);
73
81
  if ((type === "legacy" || type === "nonwitness-script") && input.nonWitnessUtxo === void 0) throw new ChainError("invalid-request", `input ${idx} is missing nonWitnessUtxo`);
74
82
  const sighash = input.sighashType;
@@ -77,7 +85,7 @@ const normalizeBitcoinPsbt = (psbt, sign, network) => {
77
85
  }
78
86
  return {
79
87
  psbt: tx.toPSBT(0),
80
- sign: unique
88
+ sign: sorted
81
89
  };
82
90
  };
83
91
  // src/bitcoin/account.ts
@@ -154,7 +162,7 @@ const decodeOutput = (script, amount) => {
154
162
  const decodeBitcoinPsbt = (request, ownScripts = /* @__PURE__ */ new Set()) => {
155
163
  const tx = parsePsbt(request.psbt);
156
164
  const coder = Address(bitcoinNetwork(request.network).params);
157
- const signed = new Set(request.sign);
165
+ const signed = new Set(request.sign.map((s) => s.index));
158
166
  const outflows = [];
159
167
  let canFee = true;
160
168
  let outSum = 0n;
@@ -190,7 +198,7 @@ const decodeBitcoinPsbt = (request, ownScripts = /* @__PURE__ */ new Set()) => {
190
198
  }
191
199
  const external = tx.inputsLength - signed.size > 0;
192
200
  const undecodable = outflows.some((o) => !o.verified);
193
- const listing = request.sign.some((i) => tx.getInput(i).sighashType === SIGHASH_SINGLE_ANYONECANPAY);
201
+ const listing = request.sign.some((s) => tx.getInput(s.index).sighashType === SIGHASH_SINGLE_ANYONECANPAY);
194
202
  const verifiability = external ? "opaque" : listing || undecodable ? "partial" : "full";
195
203
  return {
196
204
  family: "bitcoin",
@@ -421,19 +429,28 @@ const messageTarget = (address, network, format) => {
421
429
  */
422
430
  const normalizeBitcoin = (request) => {
423
431
  if (!isRecord$2(request) || typeof request["kind"] !== "string") throw new ChainError("invalid-request", "request must be an object with a kind");
424
- const { network, account } = common(request);
425
432
  if (request["kind"] === "bitcoin.psbt") {
426
- const { psbt } = request;
433
+ const { network, account, psbt } = request;
434
+ if (typeof network !== "string") throw new ChainError("invalid-request", "request.network must be a string");
435
+ bitcoinNetwork(network);
436
+ if (!isRecord$2(account) || account["kind"] !== "hd") throw new ChainError("invalid-request", "request.account must be a wallet group");
437
+ const { walletId, groupIndex } = account;
438
+ if (typeof walletId !== "string" || typeof groupIndex !== "number" || !Number.isSafeInteger(groupIndex) || groupIndex < 0) throw new ChainError("invalid-request", "request.account must be a wallet group");
427
439
  if (!(psbt instanceof Uint8Array)) throw new ChainError("invalid-request", "psbt must be bytes");
428
440
  const normalized = normalizeBitcoinPsbt(psbt, request["sign"], network);
429
441
  return {
430
442
  kind: "bitcoin.psbt",
431
443
  network,
432
- account,
444
+ account: {
445
+ kind: "hd",
446
+ walletId,
447
+ groupIndex
448
+ },
433
449
  psbt: normalized.psbt,
434
450
  sign: normalized.sign
435
451
  };
436
452
  }
453
+ const { network, account } = common(request);
437
454
  if (request["kind"] === "bitcoin.message") {
438
455
  const { format } = request;
439
456
  const target = messageTarget(request["address"], network, format);
@@ -1 +1 @@
1
- {"version":3,"file":"bitcoin.mjs","names":["isRecord","SIGHASH_SINGLE_ANYONECANPAY","isRecord"],"sources":["../src/bitcoin/psbt.ts","../src/bitcoin/account.ts","../src/bitcoin/decode.ts","../src/bitcoin/verify.ts","../src/bitcoin/index.ts"],"sourcesContent":["import { Transaction, getInputType } from \"@scure/btc-signer/transaction.js\";\n\nimport { ChainError } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\n/**\n * BIP-32 derivation paths carry a coin type: 0 for mainnet, 1 for every test network. This is what\n * binds PSBT metadata to the requested network — the raw output scripts themselves carry no network\n * marker.\n */\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Bip32Derivation values are [pubkey, { fingerprint, path }] tuples; tapBip32Derivation values are\n * { hashes, der: { fingerprint, path } }.\n */\nconst derivationPaths = (map: unknown): ReadonlyArray<ReadonlyArray<number>> => {\n const entries =\n map instanceof Map\n ? [...map.values()]\n : Array.isArray(map)\n ? map\n : isRecord(map)\n ? Object.values(map)\n : [];\n const paths: number[][] = [];\n for (const entry of entries) {\n const value: unknown = Array.isArray(entry) ? entry[1] : entry;\n if (!isRecord(value)) {\n continue;\n }\n const der = isRecord(value[\"der\"]) ? value[\"der\"] : value;\n const { path } = der;\n if (Array.isArray(path) && path.every((p) => typeof p === \"number\")) {\n paths.push(path);\n }\n }\n return paths;\n};\n\nconst checkPaths = (\n paths: ReadonlyArray<ReadonlyArray<number>>,\n where: string,\n coinType: number,\n): void => {\n for (const path of paths) {\n if (path.length >= 2 && (path[1] ?? -1) - 0x80000000 !== coinType) {\n throw new ChainError(\n \"chain-id-mismatch\",\n `${where} derivation coin type is not this network's`,\n );\n }\n }\n};\n\nconst checkDerivations = (tx: Transaction, coinType: number): void => {\n for (let i = 0; i < tx.inputsLength; i++) {\n const input = tx.getInput(i);\n checkPaths(derivationPaths(input.bip32Derivation), `input ${i}`, coinType);\n checkPaths(derivationPaths(input.tapBip32Derivation), `input ${i}`, coinType);\n }\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n checkPaths(derivationPaths(output.bip32Derivation), `output ${i}`, coinType);\n checkPaths(derivationPaths(output.tapBip32Derivation), `output ${i}`, coinType);\n }\n};\n\nconst DEFAULT_SIGHASH = 0;\nconst SIGHASH_ALL = 1;\n/** SIGHASH_SINGLE | ANYONECANPAY — the marketplace listing sighash, the only other one accepted. */\nexport const SIGHASH_SINGLE_ANYONECANPAY = 0x83;\n\nconst isTaprootInput = (input: ReturnType<Transaction[\"getInput\"]>): boolean =>\n input.tapInternalKey !== undefined || getInputType(input).type === \"taproot\";\n\n/**\n * Validates and canonicalizes a bitcoin.psbt request (network already checked by the caller).\n * `strictPrevoutValidation` makes btc-signer verify every `nonWitnessUtxo`'s txid against its\n * outpoint.\n */\nexport const normalizeBitcoinPsbt = (\n psbt: Uint8Array,\n sign: unknown,\n network: string,\n): { psbt: Uint8Array; sign: ReadonlyArray<number> } => {\n const net = bitcoinNetwork(network);\n let tx: Transaction;\n try {\n tx = Transaction.fromPSBT(psbt, { strictPrevoutValidation: true });\n } catch {\n throw new ChainError(\"invalid-request\", \"PSBT failed to decode\");\n }\n if (\n !Array.isArray(sign) ||\n sign.length === 0 ||\n !sign.every((i) => Number.isSafeInteger(i) && i >= 0)\n ) {\n throw new ChainError(\"invalid-request\", \"sign must be a non-empty array of input indices\");\n }\n const unique = [...new Set(sign.map(Number))].sort((a, b) => a - b);\n const last = unique.at(-1);\n if (unique.length !== sign.length || last === undefined || last >= tx.inputsLength) {\n throw new ChainError(\"invalid-request\", \"sign must be unique, ascending, and in range\");\n }\n checkDerivations(tx, net.coinType);\n for (const idx of unique) {\n const input = tx.getInput(idx);\n if (input.witnessUtxo === undefined && input.nonWitnessUtxo === undefined) {\n throw new ChainError(\n \"invalid-request\",\n `input ${idx} carries neither witnessUtxo nor nonWitnessUtxo`,\n );\n }\n if (input.bip32Derivation === undefined && input.tapBip32Derivation === undefined) {\n throw new ChainError(\"invalid-request\", `input ${idx} is missing a bip32 derivation`);\n }\n const { type } = getInputType(input);\n if ((type === \"legacy\" || type === \"nonwitness-script\") && input.nonWitnessUtxo === undefined) {\n throw new ChainError(\"invalid-request\", `input ${idx} is missing nonWitnessUtxo`);\n }\n const sighash = input.sighashType;\n const allowed =\n sighash === undefined ||\n sighash === SIGHASH_ALL ||\n (isTaprootInput(input) && sighash === DEFAULT_SIGHASH) ||\n sighash === SIGHASH_SINGLE_ANYONECANPAY;\n if (!allowed) {\n throw new ChainError(\"unsupported\", `input ${idx} uses a non-default sighash`);\n }\n // SIGHASH_SINGLE signs a constant when the same-index output is missing (the legacy bug).\n if (sighash === SIGHASH_SINGLE_ANYONECANPAY && idx >= tx.outputsLength) {\n throw new ChainError(\n \"unsupported\",\n `input ${idx} uses SIGHASH_SINGLE without a same-index output`,\n );\n }\n }\n return { psbt: tx.toPSBT(0), sign: unique };\n};\n","/** Public-derivation helpers for account-level extended keys — no secrets involved. */\nimport { HDKey } from \"@scure/bip32\";\nimport { p2pkh, p2sh, p2tr, p2wpkh } from \"@scure/btc-signer/payment.js\";\n\nimport { ChainError } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\nconst xpubChild = (xpub: string, network: string, change: 0 | 1, index: number): Uint8Array => {\n if (!Number.isInteger(index) || index < 0) {\n throw new ChainError(\"invalid-request\", \"index must be a non-negative integer\");\n }\n const net = bitcoinNetwork(network);\n let node: HDKey;\n try {\n node = HDKey.fromExtendedKey(xpub, net.bip32);\n } catch (error) {\n throw new ChainError(\n \"invalid-request\",\n `xpub: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n const child = node.derive(`m/${change}/${index}`);\n const pub = child.publicKey;\n if (pub === null) {\n throw new ChainError(\"invalid-request\", \"xpub carries no public key\");\n }\n return pub;\n};\n\nexport type BitcoinAccountTemplate = \"btc.bip44\" | \"btc.bip49\" | \"btc.bip84\" | \"btc.bip86\";\n\n/**\n * Derive the address at `change`/`index` under an account-level xpub (`m/84'/c'/i'` or\n * `m/86'/c'/i'`) — P2WPKH for `btc.bip84`, P2TR key-path for `btc.bip86`.\n */\nexport function bitcoinAddressFromXpub(\n xpub: string,\n template: BitcoinAccountTemplate,\n network: string,\n change: 0 | 1,\n index: number,\n): string {\n const net = bitcoinNetwork(network);\n const pub = xpubChild(xpub, network, change, index);\n const address =\n template === \"btc.bip84\"\n ? p2wpkh(pub, net.params).address\n : template === \"btc.bip49\"\n ? p2sh(p2wpkh(pub, net.params), net.params).address\n : template === \"btc.bip44\"\n ? p2pkh(pub, net.params).address\n : p2tr(pub.subarray(1), undefined, net.params).address;\n if (address === undefined) {\n throw new ChainError(\"invalid-request\", \"could not encode the derived address\");\n }\n return address;\n}\n\n/**\n * The compressed (P2WPKH) or x-only (P2TR) public key at `change`/`index` under an account-level\n * xpub — the key placed in a PSBT's bip32Derivation/tapBip32Derivation entry so the signing kernel\n * can re-derive it.\n */\nexport function bitcoinPubkeyFromXpub(\n xpub: string,\n template: BitcoinAccountTemplate,\n network: string,\n change: 0 | 1,\n index: number,\n): Uint8Array {\n const pub = xpubChild(xpub, network, change, index);\n // bip44/bip49 keep the compressed key — the signing kernel needs it for\n // redeemScript/scriptSig; only bip86 derives to the x-only key.\n return template === \"btc.bip86\" ? pub.subarray(1) : pub;\n}\n","import { Address, OutScript } from \"@scure/btc-signer/payment.js\";\nimport { Transaction } from \"@scure/btc-signer/transaction.js\";\n\nimport { ChainError } from \"../index.ts\";\nimport type { AssetFlow, DisplayIntent, SignRequest, Verifiability } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\nconst SATS = \"sats\";\nconst SIGHASH_SINGLE_ANYONECANPAY = 0x83;\nconst OP_RETURN = 0x6a;\n\n/** Btc-signer's parse failures are foreign exceptions — the request is a malformed PSBT. */\nconst parsePsbt = (psbt: Uint8Array): Transaction => {\n try {\n return Transaction.fromPSBT(psbt);\n } catch (error) {\n throw error instanceof ChainError ? error : new ChainError(\"invalid-request\", \"malformed PSBT\");\n }\n};\n\nconst bytesToHex = (bytes: Uint8Array): string => {\n let out = \"\";\n for (const b of bytes) {\n out += b.toString(16).padStart(2, \"0\");\n }\n return out;\n};\n\ntype DecodedOutput = {\n readonly amount: bigint;\n readonly script: string;\n readonly opReturn: boolean;\n};\n\n/** Decodes an output scriptPubKey; OP_RETURN gets an amount-0 display row. */\nconst decodeOutput = (script: Uint8Array, amount: bigint): DecodedOutput => {\n const hex = bytesToHex(script);\n if (script[0] === OP_RETURN) {\n return { amount, script: hex, opReturn: true };\n }\n return { amount, script: hex, opReturn: false };\n};\n\nexport type BitcoinDisplay = {\n readonly intent: DisplayIntent;\n};\n\n/**\n * Decodes a normalized bitcoin.psbt request for display. `ownScripts` is the set of output script\n * hexes the caller has independently verified as this account's (e.g. the kernel re-deriving\n * change) — not a display hint.\n */\nexport const decodeBitcoinPsbt = (\n request: Extract<SignRequest, { kind: \"bitcoin.psbt\" }>,\n ownScripts: ReadonlySet<string> = new Set(),\n): DisplayIntent => {\n const tx = parsePsbt(request.psbt);\n const coder = Address(bitcoinNetwork(request.network).params);\n const signed = new Set(request.sign);\n const outflows: AssetFlow[] = [];\n let canFee = true;\n let outSum = 0n;\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n const { script } = output;\n const { amount } = output;\n if (script === undefined || amount === undefined) {\n continue;\n }\n const decoded = decodeOutput(script, amount);\n outSum += amount;\n if (decoded.opReturn || ownScripts.has(decoded.script)) {\n continue;\n }\n let addr: string | undefined;\n try {\n const out = OutScript.decode(script);\n addr = out === undefined ? undefined : coder.encode(out);\n } catch {\n addr = undefined;\n }\n outflows.push({\n to: addr ?? decoded.script,\n amount: { asset: SATS, amount: amount.toString(10) },\n verified: addr !== undefined,\n });\n }\n let inSum = 0n;\n for (let i = 0; i < tx.inputsLength; i++) {\n const input = tx.getInput(i);\n if (input.witnessUtxo === undefined) {\n canFee = false;\n } else {\n inSum += input.witnessUtxo.amount;\n }\n }\n const external = tx.inputsLength - signed.size > 0;\n const undecodable = outflows.some((o) => !o.verified);\n const listing = request.sign.some(\n (i) => tx.getInput(i).sighashType === SIGHASH_SINGLE_ANYONECANPAY,\n );\n const verifiability: Verifiability = external\n ? \"opaque\"\n : listing || undecodable\n ? \"partial\"\n : \"full\";\n return {\n family: \"bitcoin\",\n network: request.network,\n summary: outflows.length > 0 ? \"transfer\" : \"contract-call\",\n outflows,\n approvals: [],\n fee:\n canFee && !listing\n ? { max: { asset: SATS, amount: (inSum - outSum).toString(10) } }\n : undefined,\n warnings: listing\n ? [\n {\n kind: \"sighash-single-anyonecanpay\",\n message:\n \"signed inputs bind only their same-index outputs; the rest of the transaction can change\",\n },\n ]\n : [],\n verifiability,\n };\n};\n\nexport const verifiabilityBitcoin = (\n request: Extract<SignRequest, { kind: \"bitcoin.psbt\" }>,\n ownScripts: ReadonlySet<string> = new Set(),\n): Verifiability => decodeBitcoinPsbt(request, ownScripts).verifiability;\n","/**\n * Result verification for `chain.sign`: the host re-checks the kernel's Bitcoin work against the\n * account's xpub — a kernel returning someone else's signature fails closed with `integrity`.\n * `/bitcoin` entry only — no private key material.\n */\nimport { secp256k1, schnorr } from \"@noble/curves/secp256k1.js\";\nimport { base64 } from \"@scure/base\";\nimport { HDKey } from \"@scure/bip32\";\nimport { Address, OutScript, p2tr } from \"@scure/btc-signer/payment.js\";\nimport { SigHash, Transaction } from \"@scure/btc-signer/transaction.js\";\nimport { taprootTweakPubkey } from \"@scure/btc-signer/utils.js\";\n\nimport type { BitcoinAccountTemplate } from \"./account.ts\";\nimport { bip322ToSpendTxid } from \"./message.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\nconst isRecord = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v) && !(v instanceof Uint8Array);\n\n/** Derive the child's public key from the account xpub at `change/index` (non-hardened). */\nconst childPub = (xpub: string, network: string, change: number, index: number): Uint8Array => {\n const child = HDKey.fromExtendedKey(xpub, bitcoinNetwork(network).bip32)\n .deriveChild(change)\n .deriveChild(index);\n if (child.publicKey === null || child.publicKey === undefined) {\n throw new Error(\"xpub cannot derive this child\");\n }\n return child.publicKey;\n};\n\n/** Extract `[pubkey, {fingerprint, path}]`-shaped entries from either PSBT derivation map. */\nconst derivationOf = (\n map: unknown,\n): ReadonlyArray<{ pubkey: Uint8Array; path: ReadonlyArray<number> }> => {\n const out: Array<{ pubkey: Uint8Array; path: ReadonlyArray<number> }> = [];\n const readEntry = (key: unknown, value: unknown): void => {\n const der = isRecord(value) && isRecord(value[\"der\"]) ? value[\"der\"] : value;\n const { path } = isRecord(der) ? der : {};\n if (\n key instanceof Uint8Array &&\n Array.isArray(path) &&\n path.every((p) => typeof p === \"number\")\n ) {\n out.push({ pubkey: key, path });\n }\n };\n if (map instanceof Map) {\n for (const [key, value] of map) {\n readEntry(key, value);\n }\n } else if (Array.isArray(map)) {\n for (const entry of map) {\n if (Array.isArray(entry) && entry.length === 2) {\n readEntry(entry[0], entry[1]);\n }\n }\n }\n return out;\n};\n\n/** The non-hardened `{change, index}` tail of a derivation path, if present and valid. */\nconst tailOf = (path: ReadonlyArray<number>): { change: 0 | 1; index: number } | undefined => {\n const change = path.at(-2);\n const index = path.at(-1);\n if ((change !== 0 && change !== 1) || index === undefined || index < 0 || index >= 0x80000000) {\n return undefined;\n }\n return { change, index };\n};\n\nconst eq = (a: Uint8Array, b: Uint8Array): boolean =>\n a.length === b.length && a.every((v, i) => v === b[i]);\n\n/**\n * Verify every signature on the inputs listed in `sign` against the account's xpub: the input's\n * derivation entry must claim the child pubkey re-derived from the xpub, and the signature must\n * verify over the input's sighash (BIP-143 partialSig for P2WPKH, tapKeySig for P2TR key path).\n */\nconst preimageLegacy = (\n tx: Transaction,\n idx: number,\n scriptCode: Uint8Array,\n sighashType: number,\n): Uint8Array => {\n const f: unknown = Reflect.get(tx, \"preimageLegacy\");\n if (typeof f !== \"function\") {\n return new Uint8Array(0);\n }\n const out: unknown = Reflect.apply(f, tx, [idx, scriptCode, sighashType]);\n return out instanceof Uint8Array ? out : new Uint8Array(0);\n};\n\nexport const verifyBitcoinPsbtSignatures = (\n signedPsbt: Uint8Array,\n sign: ReadonlyArray<number>,\n xpub: string,\n template: BitcoinAccountTemplate,\n network: string,\n): boolean => {\n try {\n const tx = Transaction.fromPSBT(signedPsbt);\n const taproot = template === \"btc.bip86\";\n for (const idx of sign) {\n const input = tx.getInput(idx);\n const claimed = derivationOf(taproot ? input.tapBip32Derivation : input.bip32Derivation).find(\n ({ path }) => tailOf(path) !== undefined,\n );\n const tail = claimed === undefined ? undefined : tailOf(claimed.path);\n if (claimed === undefined || tail === undefined) {\n return false;\n }\n const vout = input.index;\n const nw:\n | {\n readonly outputs: ReadonlyArray<{\n readonly script: Uint8Array;\n readonly amount: bigint;\n }>;\n }\n | undefined = input.nonWitnessUtxo;\n const legacyOut = nw === undefined || vout === undefined ? undefined : nw.outputs[vout];\n const prevout = input.witnessUtxo ?? legacyOut;\n if (prevout === undefined) {\n return false;\n }\n const prevScript: Uint8Array = prevout.script;\n const prevAmount: bigint = prevout.amount;\n const pub = childPub(xpub, network, tail.change, tail.index);\n if (taproot) {\n const xonly = pub.slice(1);\n const rawSig = input.tapKeySig;\n if (\n !eq(claimed.pubkey, xonly) ||\n !(rawSig instanceof Uint8Array) ||\n (rawSig.length !== 64 && rawSig.length !== 65) ||\n (input.tapInternalKey !== undefined && !eq(input.tapInternalKey, xonly)) ||\n !eq(prevScript, p2tr(xonly).script)\n ) {\n return false;\n }\n const sighashType =\n rawSig.length === 65 ? (rawSig[64] ?? SigHash.DEFAULT) : SigHash.DEFAULT;\n const sig = rawSig.slice(0, 64);\n const scripts: Uint8Array[] = [];\n const amounts: bigint[] = [];\n let complete = true;\n for (let i = 0; i < tx.inputsLength; i++) {\n const w = tx.getInput(i).witnessUtxo;\n if (w === undefined) {\n complete = false;\n break;\n }\n scripts.push(w.script);\n amounts.push(w.amount);\n }\n // BIP-341 key-path signatures commit to the tweaked output key, not the internal key.\n const [outputKey] = taprootTweakPubkey(xonly, new Uint8Array());\n if (\n !complete ||\n !schnorr.verify(sig, tx.preimageWitnessV1(idx, scripts, sighashType, amounts), outputKey)\n ) {\n return false;\n }\n } else {\n const partial = input.partialSig;\n const found = Array.isArray(partial)\n ? partial.find(([p]) => p instanceof Uint8Array && eq(p, pub))\n : undefined;\n const rawSig =\n Array.isArray(found) && found[1] instanceof Uint8Array ? found[1] : undefined;\n if (!eq(claimed.pubkey, pub) || rawSig === undefined || rawSig.length === 0) {\n return false;\n }\n const sighashType = input.sighashType ?? rawSig.at(-1) ?? SigHash.ALL;\n // bip49 prevouts are P2SH — the BIP143 scriptCode is the inner P2WPKH\n // redeem script, canonicalized to the equivalent P2PKH script.\n const effective: Uint8Array = input.redeemScript ?? prevScript;\n const decoded = OutScript.decode(effective);\n const scriptCode: Uint8Array =\n decoded !== undefined && decoded.type === \"wpkh\"\n ? OutScript.encode({ type: \"pkh\", hash: decoded.hash })\n : effective;\n // P2PKH inputs sign the legacy (non-segwit) preimage — btc-signer exposes it as a\n // private method; the public witness preimages do not apply to non-witness inputs.\n const hash =\n input.nonWitnessUtxo === undefined\n ? tx.preimageWitnessV0(idx, scriptCode, sighashType, prevAmount)\n : preimageLegacy(tx, idx, scriptCode, sighashType);\n if (\n !secp256k1.verify(\n secp256k1.Signature.fromBytes(rawSig.slice(0, -1), \"der\").toBytes(),\n hash,\n pub,\n { prehash: false },\n )\n ) {\n return false;\n }\n }\n }\n return true;\n } catch {\n return false;\n }\n};\n\n/** Deserialize the `smp`-prefixed base64 witness: count + pushData items. */\nconst witnessOf = (sig: string): ReadonlyArray<Uint8Array> | undefined => {\n if (!sig.startsWith(\"smp\")) {\n return undefined;\n }\n const raw = base64.decode(sig.slice(3));\n if (raw === undefined || raw.length === 0) {\n return undefined;\n }\n const items: Uint8Array[] = [];\n let off = 1;\n for (let i = 0; i < (raw[0] ?? 0); i++) {\n const len = raw[off];\n if (len === undefined || off + 1 + len > raw.length) {\n return undefined;\n }\n items.push(raw.slice(off + 1, off + 1 + len));\n off += 1 + len;\n }\n return off === raw.length ? items : undefined;\n};\n\n/**\n * BIP-322 simple verification against an address: rebuild to_spend/to_sign exactly as the signer\n * does, then verify the witness signature (P2WPKH ECDSA / P2TR schnorr) over the input preimage.\n */\nexport const verifyBitcoinMessage = (\n address: string,\n message: string,\n signatureBase64: string,\n network: string,\n): boolean => {\n try {\n const net = bitcoinNetwork(network);\n const scriptPubKey = OutScript.encode(Address(net.params).decode(address));\n const witness = witnessOf(signatureBase64);\n if (witness === undefined || witness.length === 0) {\n return false;\n }\n const tx = new Transaction({ version: 0, lockTime: 0, allowUnknownOutputs: true });\n tx.addInput({\n txid: Uint8Array.from([...bip322ToSpendTxid(scriptPubKey, message)].reverse()),\n index: 0,\n sequence: 0,\n witnessUtxo: { script: scriptPubKey, amount: 0n },\n });\n tx.addOutput({ script: Uint8Array.of(0x6a), amount: 0n });\n if (scriptPubKey.at(0) === 0x51) {\n const [rawSig] = witness;\n const xonly = scriptPubKey.slice(2);\n if (\n rawSig === undefined ||\n xonly.length !== 32 ||\n (rawSig.length !== 64 && rawSig.length !== 65)\n ) {\n return false;\n }\n const sighashType =\n rawSig.length === 65 ? (rawSig.at(64) ?? SigHash.DEFAULT) : SigHash.DEFAULT;\n return schnorr.verify(\n rawSig.slice(0, 64),\n tx.preimageWitnessV1(0, [scriptPubKey], sighashType, [0n]),\n xonly,\n );\n }\n const [rawSig, pub] = witness;\n if (rawSig === undefined || pub === undefined || pub.length !== 33 || rawSig.length === 0) {\n return false;\n }\n const sighashType = rawSig.at(-1) ?? SigHash.ALL;\n const decoded = OutScript.decode(scriptPubKey);\n const scriptCode =\n decoded !== undefined && decoded.type === \"wpkh\"\n ? OutScript.encode({ type: \"pkh\", hash: decoded.hash })\n : scriptPubKey;\n return secp256k1.verify(\n secp256k1.Signature.fromBytes(rawSig.slice(0, -1), \"der\").toBytes(),\n tx.preimageWitnessV0(0, scriptCode, sighashType, 0n),\n pub,\n { prehash: false },\n );\n } catch {\n return false;\n }\n};\n","import { Address, OutScript } from \"@scure/btc-signer/payment.js\";\n\nimport { isRecord, requestBase } from \"../account-ref.ts\";\nimport { ChainError } from \"../index.ts\";\nimport type { AccountRef, SignRequest } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\nimport { normalizeBitcoinPsbt } from \"./psbt.ts\";\n\nexport { BITCOIN_NETWORKS, bitcoinNetwork } from \"./networks.ts\";\nexport type { BitcoinAccountTemplate } from \"./account.ts\";\nexport { bitcoinAddressFromXpub, bitcoinPubkeyFromXpub } from \"./account.ts\";\nexport { decodeBitcoinPsbt, verifiabilityBitcoin } from \"./decode.ts\";\nexport { verifyBitcoinMessage, verifyBitcoinPsbtSignatures } from \"./verify.ts\";\n\nconst common = (request: Record<string, unknown>): { network: string; account: AccountRef } => {\n const base = requestBase(request);\n bitcoinNetwork(base.network);\n return base;\n};\n\n/** The decoded `address` fields needed by message signers. */\nexport type MessageTarget = {\n readonly type: string;\n readonly address: string;\n readonly format: \"bip322-simple\" | \"legacy\";\n readonly scriptPubKey: Uint8Array;\n};\n\nconst messageTarget = (address: unknown, network: string, format: unknown): MessageTarget => {\n if (typeof address !== \"string\") {\n throw new ChainError(\"invalid-request\", \"address must be a string\");\n }\n const net = bitcoinNetwork(network);\n let decoded: ReturnType<ReturnType<typeof Address>[\"decode\"]>;\n try {\n decoded = Address(net.params).decode(address);\n } catch {\n throw new ChainError(\"invalid-address\", \"address does not belong to this network\");\n }\n if (format === \"bip322-simple\") {\n if (decoded.type !== \"wpkh\" && decoded.type !== \"tr\") {\n throw new ChainError(\"unsupported\", \"bip322-simple is only for P2WPKH/P2TR addresses\");\n }\n } else if (format === \"legacy\") {\n if (decoded.type !== \"pkh\") {\n throw new ChainError(\"unsupported\", \"legacy signing is only for P2PKH addresses\");\n }\n } else {\n throw new ChainError(\"unsupported\", `unsupported message format: ${String(format)}`);\n }\n const scriptPubKey = OutScript.encode(decoded);\n return { type: decoded.type, address, format, scriptPubKey };\n};\n\n/**\n * Normalizes a bitcoin sign request. Idempotent: the returned PSBT is the canonical\n * re-serialization.\n */\nexport const normalizeBitcoin = (request: unknown): SignRequest => {\n if (!isRecord(request) || typeof request[\"kind\"] !== \"string\") {\n throw new ChainError(\"invalid-request\", \"request must be an object with a kind\");\n }\n const { network, account } = common(request);\n if (request[\"kind\"] === \"bitcoin.psbt\") {\n const { psbt } = request;\n if (!(psbt instanceof Uint8Array)) {\n throw new ChainError(\"invalid-request\", \"psbt must be bytes\");\n }\n const normalized = normalizeBitcoinPsbt(psbt, request[\"sign\"], network);\n return { kind: \"bitcoin.psbt\", network, account, psbt: normalized.psbt, sign: normalized.sign };\n }\n if (request[\"kind\"] === \"bitcoin.message\") {\n const { format } = request;\n const target = messageTarget(request[\"address\"], network, format);\n void target;\n const { message, change, index } = request;\n if (typeof message !== \"string\") {\n throw new ChainError(\"invalid-request\", \"message must be a string\");\n }\n if (change !== 0 && change !== 1) {\n throw new ChainError(\"invalid-request\", \"change must be 0 or 1\");\n }\n if (\n typeof index !== \"number\" ||\n !Number.isSafeInteger(index) ||\n index < 0 ||\n index >= 0x80000000\n ) {\n throw new ChainError(\"invalid-request\", \"index must be a non-hardened path index\");\n }\n return {\n kind: \"bitcoin.message\",\n network,\n account,\n address: target.address,\n message,\n format: target.format,\n change,\n index,\n };\n }\n throw new ChainError(\"unsupported\", `unsupported sign request kind: ${request[\"kind\"]}`);\n};\n\n/** Decodes the message `address` into the scriptPubKey the signer needs. */\nexport const decodeMessageTarget = (\n request: Extract<SignRequest, { kind: \"bitcoin.message\" }>,\n): MessageTarget => messageTarget(request.address, request.network, request.format);\n"],"mappings":";;;;;;;;;;;;;;;AAUA,MAAMA,cAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;;;;AAMrE,MAAM,mBAAmB,QAAuD;CAC9E,MAAM,UACJ,eAAe,MACX,CAAC,GAAG,IAAI,OAAO,CAAC,IAChB,MAAM,QAAQ,GAAG,IACf,MACAA,WAAS,GAAG,IACV,OAAO,OAAO,GAAG,IACjB,CAAC;CACX,MAAM,QAAoB,CAAC;CAC3B,KAAK,MAAM,SAAS,SAAS;EAC3B,MAAM,QAAiB,MAAM,QAAQ,KAAK,IAAI,MAAM,KAAK;EACzD,IAAI,CAACA,WAAS,KAAK,GACjB;EAGF,MAAM,EAAE,SADIA,WAAS,MAAM,MAAM,IAAI,MAAM,SAAS;EAEpD,IAAI,MAAM,QAAQ,IAAI,KAAK,KAAK,OAAO,MAAM,OAAO,MAAM,QAAQ,GAChE,MAAM,KAAK,IAAI;CAEnB;CACA,OAAO;AACT;AAEA,MAAM,cACJ,OACA,OACA,aACS;CACT,KAAK,MAAM,QAAQ,OACjB,IAAI,KAAK,UAAU,MAAM,KAAK,MAAM,MAAM,eAAe,UACvD,MAAM,IAAI,WACR,qBACA,GAAG,MAAM,4CACX;AAGN;AAEA,MAAM,oBAAoB,IAAiB,aAA2B;CACpE,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,cAAc,KAAK;EACxC,MAAM,QAAQ,GAAG,SAAS,CAAC;EAC3B,WAAW,gBAAgB,MAAM,eAAe,GAAG,SAAS,KAAK,QAAQ;EACzE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AAM,QAAQ,SAAS,OAAO;EACtE,OAAO;GAAE,MAAM;GAAgB;GAAS;GAAS,MAAM,WAAW;GAAM,MAAM,WAAW;EAAK;CAChG;CACA,IAAI,QAAQ,YAAY,mBAAmB;EACzC,MAAM,EAAE,WAAW;EACnB,MAAM,SAAS,cAAc,QAAQ,YAAY,SAAS,MAAM;EAEhE,MAAM,EAAE,SAAS,QAAQ,UAAU;EACnC,IAAI,OAAO,YAAY,UACrB,MAAM,IAAI,WAAW,mBAAmB,0BAA0B;EAEpE,IAAI,WAAW,KAAK,WAAW,GAC7B,MAAM,IAAI,WAAW,mBAAmB,uBAAuB;EAEjE,IACE,OAAO,UAAU,YACjB,CAAC,OAAO,cAAc,KAAK,KAC3B,QAAQ,KACR,SAAS,YAET,MAAM,IAAI,WAAW,mBAAmB,yCAAyC;EAEnF,OAAO;GACL,MAAM;GACN;GACA;GACA,SAAS,OAAO;GAChB;GACA,QAAQ,OAAO;GACf;GACA;EACF;CACF;CACA,MAAM,IAAI,WAAW,eAAe,kCAAkC,QAAQ,SAAS;AACzF;;AAGA,MAAa,uBACX,YACkB,cAAc,QAAQ,SAAS,QAAQ,SAAS,QAAQ,MAAM"}
1
+ {"version":3,"file":"bitcoin.mjs","names":["isRecord","SIGHASH_SINGLE_ANYONECANPAY","isRecord"],"sources":["../src/bitcoin/psbt.ts","../src/bitcoin/account.ts","../src/bitcoin/decode.ts","../src/bitcoin/verify.ts","../src/bitcoin/index.ts"],"sourcesContent":["import { Transaction, getInputType } from \"@scure/btc-signer/transaction.js\";\n\nimport { ChainError } from \"../index.ts\";\nimport type { BitcoinTemplate } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\n/**\n * BIP-32 derivation paths carry a coin type: 0 for mainnet, 1 for every test network. This is what\n * binds PSBT metadata to the requested network — the raw output scripts themselves carry no network\n * marker.\n */\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Bip32Derivation values are [pubkey, { fingerprint, path }] tuples; tapBip32Derivation values are\n * { hashes, der: { fingerprint, path } }.\n */\nconst derivationPaths = (map: unknown): ReadonlyArray<ReadonlyArray<number>> => {\n const entries =\n map instanceof Map\n ? [...map.values()]\n : Array.isArray(map)\n ? map\n : isRecord(map)\n ? Object.values(map)\n : [];\n const paths: number[][] = [];\n for (const entry of entries) {\n const value: unknown = Array.isArray(entry) ? entry[1] : entry;\n if (!isRecord(value)) {\n continue;\n }\n const der = isRecord(value[\"der\"]) ? value[\"der\"] : value;\n const { path } = der;\n if (Array.isArray(path) && path.every((p) => typeof p === \"number\")) {\n paths.push(path);\n }\n }\n return paths;\n};\n\nconst checkPaths = (\n paths: ReadonlyArray<ReadonlyArray<number>>,\n where: string,\n coinType: number,\n): void => {\n for (const path of paths) {\n if (path.length >= 2 && (path[1] ?? -1) - 0x80000000 !== coinType) {\n throw new ChainError(\n \"chain-id-mismatch\",\n `${where} derivation coin type is not this network's`,\n );\n }\n }\n};\n\nconst checkDerivations = (tx: Transaction, coinType: number): void => {\n for (let i = 0; i < tx.inputsLength; i++) {\n const input = tx.getInput(i);\n checkPaths(derivationPaths(input.bip32Derivation), `input ${i}`, coinType);\n checkPaths(derivationPaths(input.tapBip32Derivation), `input ${i}`, coinType);\n }\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n checkPaths(derivationPaths(output.bip32Derivation), `output ${i}`, coinType);\n checkPaths(derivationPaths(output.tapBip32Derivation), `output ${i}`, coinType);\n }\n};\n\nconst DEFAULT_SIGHASH = 0;\nconst SIGHASH_ALL = 1;\n/** SIGHASH_SINGLE | ANYONECANPAY — the marketplace listing sighash, the only other one accepted. */\nexport const SIGHASH_SINGLE_ANYONECANPAY = 0x83;\n\nconst TEMPLATES: ReadonlySet<string> = new Set([\n \"btc.bip44\",\n \"btc.bip49\",\n \"btc.bip84\",\n \"btc.bip86\",\n]);\n\nexport type PsbtSignEntry = { readonly index: number; readonly template: BitcoinTemplate };\n\nconst isSignEntry = (value: unknown): value is PsbtSignEntry =>\n isRecord(value) &&\n typeof value[\"index\"] === \"number\" &&\n Number.isSafeInteger(value[\"index\"]) &&\n value[\"index\"] >= 0 &&\n typeof value[\"template\"] === \"string\" &&\n TEMPLATES.has(value[\"template\"]);\n\nconst isTaprootInput = (input: ReturnType<Transaction[\"getInput\"]>): boolean =>\n input.tapInternalKey !== undefined || getInputType(input).type === \"taproot\";\n\n/**\n * Validates and canonicalizes a bitcoin.psbt request (network already checked by the caller).\n * `strictPrevoutValidation` makes btc-signer verify every `nonWitnessUtxo`'s txid against its\n * outpoint. The returned `sign` is sorted ascending by index — a normalized request is canonical.\n */\nexport const normalizeBitcoinPsbt = (\n psbt: Uint8Array,\n sign: unknown,\n network: string,\n): { psbt: Uint8Array; sign: ReadonlyArray<PsbtSignEntry> } => {\n const net = bitcoinNetwork(network);\n let tx: Transaction;\n try {\n tx = Transaction.fromPSBT(psbt, { strictPrevoutValidation: true });\n } catch {\n throw new ChainError(\"invalid-request\", \"PSBT failed to decode\");\n }\n if (!Array.isArray(sign) || sign.length === 0 || !sign.every(isSignEntry)) {\n throw new ChainError(\n \"invalid-request\",\n \"sign must be a non-empty array of {index, template} entries\",\n );\n }\n const sorted = [...sign].sort((a, b) => a.index - b.index);\n const indices = new Set(sorted.map((s) => s.index));\n const last = sorted.at(-1)?.index;\n if (indices.size !== sorted.length || last === undefined || last >= tx.inputsLength) {\n throw new ChainError(\"invalid-request\", \"sign must be unique, ascending, and in range\");\n }\n checkDerivations(tx, net.coinType);\n for (const { index: idx, template } of sorted) {\n const input = tx.getInput(idx);\n if (input.witnessUtxo === undefined && input.nonWitnessUtxo === undefined) {\n throw new ChainError(\n \"invalid-request\",\n `input ${idx} carries neither witnessUtxo nor nonWitnessUtxo`,\n );\n }\n // bip86 inputs are taproot: they derive via tapBip32Derivation, the rest via bip32Derivation.\n if (\n template === \"btc.bip86\"\n ? input.tapBip32Derivation === undefined\n : input.bip32Derivation === undefined\n ) {\n throw new ChainError(\"invalid-request\", `input ${idx} is missing a bip32 derivation`);\n }\n const { type } = getInputType(input);\n if ((type === \"legacy\" || type === \"nonwitness-script\") && input.nonWitnessUtxo === undefined) {\n throw new ChainError(\"invalid-request\", `input ${idx} is missing nonWitnessUtxo`);\n }\n const sighash = input.sighashType;\n const allowed =\n sighash === undefined ||\n sighash === SIGHASH_ALL ||\n (isTaprootInput(input) && sighash === DEFAULT_SIGHASH) ||\n sighash === SIGHASH_SINGLE_ANYONECANPAY;\n if (!allowed) {\n throw new ChainError(\"unsupported\", `input ${idx} uses a non-default sighash`);\n }\n // SIGHASH_SINGLE signs a constant when the same-index output is missing (the legacy bug).\n if (sighash === SIGHASH_SINGLE_ANYONECANPAY && idx >= tx.outputsLength) {\n throw new ChainError(\n \"unsupported\",\n `input ${idx} uses SIGHASH_SINGLE without a same-index output`,\n );\n }\n }\n return { psbt: tx.toPSBT(0), sign: sorted };\n};\n","/** Public-derivation helpers for account-level extended keys — no secrets involved. */\nimport { HDKey } from \"@scure/bip32\";\nimport { p2pkh, p2sh, p2tr, p2wpkh } from \"@scure/btc-signer/payment.js\";\n\nimport { ChainError } from \"../index.ts\";\nimport type { BitcoinTemplate } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\nconst xpubChild = (xpub: string, network: string, change: 0 | 1, index: number): Uint8Array => {\n if (!Number.isInteger(index) || index < 0) {\n throw new ChainError(\"invalid-request\", \"index must be a non-negative integer\");\n }\n const net = bitcoinNetwork(network);\n let node: HDKey;\n try {\n node = HDKey.fromExtendedKey(xpub, net.bip32);\n } catch (error) {\n throw new ChainError(\n \"invalid-request\",\n `xpub: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n const child = node.derive(`m/${change}/${index}`);\n const pub = child.publicKey;\n if (pub === null) {\n throw new ChainError(\"invalid-request\", \"xpub carries no public key\");\n }\n return pub;\n};\n\nexport type BitcoinAccountTemplate = BitcoinTemplate;\n\n/**\n * Derive the address at `change`/`index` under an account-level xpub (`m/84'/c'/i'` or\n * `m/86'/c'/i'`) — P2WPKH for `btc.bip84`, P2TR key-path for `btc.bip86`.\n */\nexport function bitcoinAddressFromXpub(\n xpub: string,\n template: BitcoinAccountTemplate,\n network: string,\n change: 0 | 1,\n index: number,\n): string {\n const net = bitcoinNetwork(network);\n const pub = xpubChild(xpub, network, change, index);\n const address =\n template === \"btc.bip84\"\n ? p2wpkh(pub, net.params).address\n : template === \"btc.bip49\"\n ? p2sh(p2wpkh(pub, net.params), net.params).address\n : template === \"btc.bip44\"\n ? p2pkh(pub, net.params).address\n : p2tr(pub.subarray(1), undefined, net.params).address;\n if (address === undefined) {\n throw new ChainError(\"invalid-request\", \"could not encode the derived address\");\n }\n return address;\n}\n\n/**\n * The compressed (P2WPKH) or x-only (P2TR) public key at `change`/`index` under an account-level\n * xpub — the key placed in a PSBT's bip32Derivation/tapBip32Derivation entry so the signing kernel\n * can re-derive it.\n */\nexport function bitcoinPubkeyFromXpub(\n xpub: string,\n template: BitcoinAccountTemplate,\n network: string,\n change: 0 | 1,\n index: number,\n): Uint8Array {\n const pub = xpubChild(xpub, network, change, index);\n // bip44/bip49 keep the compressed key — the signing kernel needs it for\n // redeemScript/scriptSig; only bip86 derives to the x-only key.\n return template === \"btc.bip86\" ? pub.subarray(1) : pub;\n}\n","import { Address, OutScript } from \"@scure/btc-signer/payment.js\";\nimport { Transaction } from \"@scure/btc-signer/transaction.js\";\n\nimport { ChainError } from \"../index.ts\";\nimport type { AssetFlow, DisplayIntent, SignRequest, Verifiability } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\nconst SATS = \"sats\";\nconst SIGHASH_SINGLE_ANYONECANPAY = 0x83;\nconst OP_RETURN = 0x6a;\n\n/** Btc-signer's parse failures are foreign exceptions — the request is a malformed PSBT. */\nconst parsePsbt = (psbt: Uint8Array): Transaction => {\n try {\n return Transaction.fromPSBT(psbt);\n } catch (error) {\n throw error instanceof ChainError ? error : new ChainError(\"invalid-request\", \"malformed PSBT\");\n }\n};\n\nconst bytesToHex = (bytes: Uint8Array): string => {\n let out = \"\";\n for (const b of bytes) {\n out += b.toString(16).padStart(2, \"0\");\n }\n return out;\n};\n\ntype DecodedOutput = {\n readonly amount: bigint;\n readonly script: string;\n readonly opReturn: boolean;\n};\n\n/** Decodes an output scriptPubKey; OP_RETURN gets an amount-0 display row. */\nconst decodeOutput = (script: Uint8Array, amount: bigint): DecodedOutput => {\n const hex = bytesToHex(script);\n if (script[0] === OP_RETURN) {\n return { amount, script: hex, opReturn: true };\n }\n return { amount, script: hex, opReturn: false };\n};\n\nexport type BitcoinDisplay = {\n readonly intent: DisplayIntent;\n};\n\n/**\n * Decodes a normalized bitcoin.psbt request for display. `ownScripts` is the set of output script\n * hexes the caller has independently verified as this account's (e.g. the kernel re-deriving\n * change) — not a display hint.\n */\nexport const decodeBitcoinPsbt = (\n request: Extract<SignRequest, { kind: \"bitcoin.psbt\" }>,\n ownScripts: ReadonlySet<string> = new Set(),\n): DisplayIntent => {\n const tx = parsePsbt(request.psbt);\n const coder = Address(bitcoinNetwork(request.network).params);\n const signed = new Set(request.sign.map((s) => s.index));\n const outflows: AssetFlow[] = [];\n let canFee = true;\n let outSum = 0n;\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n const { script } = output;\n const { amount } = output;\n if (script === undefined || amount === undefined) {\n continue;\n }\n const decoded = decodeOutput(script, amount);\n outSum += amount;\n if (decoded.opReturn || ownScripts.has(decoded.script)) {\n continue;\n }\n let addr: string | undefined;\n try {\n const out = OutScript.decode(script);\n addr = out === undefined ? undefined : coder.encode(out);\n } catch {\n addr = undefined;\n }\n outflows.push({\n to: addr ?? decoded.script,\n amount: { asset: SATS, amount: amount.toString(10) },\n verified: addr !== undefined,\n });\n }\n let inSum = 0n;\n for (let i = 0; i < tx.inputsLength; i++) {\n const input = tx.getInput(i);\n if (input.witnessUtxo === undefined) {\n canFee = false;\n } else {\n inSum += input.witnessUtxo.amount;\n }\n }\n const external = tx.inputsLength - signed.size > 0;\n const undecodable = outflows.some((o) => !o.verified);\n const listing = request.sign.some(\n (s) => tx.getInput(s.index).sighashType === SIGHASH_SINGLE_ANYONECANPAY,\n );\n const verifiability: Verifiability = external\n ? \"opaque\"\n : listing || undecodable\n ? \"partial\"\n : \"full\";\n return {\n family: \"bitcoin\",\n network: request.network,\n summary: outflows.length > 0 ? \"transfer\" : \"contract-call\",\n outflows,\n approvals: [],\n fee:\n canFee && !listing\n ? { max: { asset: SATS, amount: (inSum - outSum).toString(10) } }\n : undefined,\n warnings: listing\n ? [\n {\n kind: \"sighash-single-anyonecanpay\",\n message:\n \"signed inputs bind only their same-index outputs; the rest of the transaction can change\",\n },\n ]\n : [],\n verifiability,\n };\n};\n\nexport const verifiabilityBitcoin = (\n request: Extract<SignRequest, { kind: \"bitcoin.psbt\" }>,\n ownScripts: ReadonlySet<string> = new Set(),\n): Verifiability => decodeBitcoinPsbt(request, ownScripts).verifiability;\n","/**\n * Result verification for `chain.sign`: the host re-checks the kernel's Bitcoin work against the\n * account's xpub — a kernel returning someone else's signature fails closed with `integrity`.\n * `/bitcoin` entry only — no private key material.\n */\nimport { secp256k1, schnorr } from \"@noble/curves/secp256k1.js\";\nimport { base64 } from \"@scure/base\";\nimport { HDKey } from \"@scure/bip32\";\nimport { Address, OutScript, p2tr } from \"@scure/btc-signer/payment.js\";\nimport { SigHash, Transaction } from \"@scure/btc-signer/transaction.js\";\nimport { taprootTweakPubkey } from \"@scure/btc-signer/utils.js\";\n\nimport type { BitcoinAccountTemplate } from \"./account.ts\";\nimport { bip322ToSpendTxid } from \"./message.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\nconst isRecord = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v) && !(v instanceof Uint8Array);\n\n/** Derive the child's public key from the account xpub at `change/index` (non-hardened). */\nconst childPub = (xpub: string, network: string, change: number, index: number): Uint8Array => {\n const child = HDKey.fromExtendedKey(xpub, bitcoinNetwork(network).bip32)\n .deriveChild(change)\n .deriveChild(index);\n if (child.publicKey === null || child.publicKey === undefined) {\n throw new Error(\"xpub cannot derive this child\");\n }\n return child.publicKey;\n};\n\n/** Extract `[pubkey, {fingerprint, path}]`-shaped entries from either PSBT derivation map. */\nconst derivationOf = (\n map: unknown,\n): ReadonlyArray<{ pubkey: Uint8Array; path: ReadonlyArray<number> }> => {\n const out: Array<{ pubkey: Uint8Array; path: ReadonlyArray<number> }> = [];\n const readEntry = (key: unknown, value: unknown): void => {\n const der = isRecord(value) && isRecord(value[\"der\"]) ? value[\"der\"] : value;\n const { path } = isRecord(der) ? der : {};\n if (\n key instanceof Uint8Array &&\n Array.isArray(path) &&\n path.every((p) => typeof p === \"number\")\n ) {\n out.push({ pubkey: key, path });\n }\n };\n if (map instanceof Map) {\n for (const [key, value] of map) {\n readEntry(key, value);\n }\n } else if (Array.isArray(map)) {\n for (const entry of map) {\n if (Array.isArray(entry) && entry.length === 2) {\n readEntry(entry[0], entry[1]);\n }\n }\n }\n return out;\n};\n\n/** The non-hardened `{change, index}` tail of a derivation path, if present and valid. */\nconst tailOf = (path: ReadonlyArray<number>): { change: 0 | 1; index: number } | undefined => {\n const change = path.at(-2);\n const index = path.at(-1);\n if ((change !== 0 && change !== 1) || index === undefined || index < 0 || index >= 0x80000000) {\n return undefined;\n }\n return { change, index };\n};\n\nconst eq = (a: Uint8Array, b: Uint8Array): boolean =>\n a.length === b.length && a.every((v, i) => v === b[i]);\n\n/**\n * Verify every signature on the inputs listed in `sign` against the account's xpub: the input's\n * derivation entry must claim the child pubkey re-derived from the xpub, and the signature must\n * verify over the input's sighash (BIP-143 partialSig for P2WPKH, tapKeySig for P2TR key path).\n */\nconst preimageLegacy = (\n tx: Transaction,\n idx: number,\n scriptCode: Uint8Array,\n sighashType: number,\n): Uint8Array => {\n const f: unknown = Reflect.get(tx, \"preimageLegacy\");\n if (typeof f !== \"function\") {\n return new Uint8Array(0);\n }\n const out: unknown = Reflect.apply(f, tx, [idx, scriptCode, sighashType]);\n return out instanceof Uint8Array ? out : new Uint8Array(0);\n};\n\nexport const verifyBitcoinPsbtSignatures = (\n signedPsbt: Uint8Array,\n sign: ReadonlyArray<number>,\n xpub: string,\n template: BitcoinAccountTemplate,\n network: string,\n): boolean => {\n try {\n const tx = Transaction.fromPSBT(signedPsbt);\n const taproot = template === \"btc.bip86\";\n for (const idx of sign) {\n const input = tx.getInput(idx);\n const claimed = derivationOf(taproot ? input.tapBip32Derivation : input.bip32Derivation).find(\n ({ path }) => tailOf(path) !== undefined,\n );\n const tail = claimed === undefined ? undefined : tailOf(claimed.path);\n if (claimed === undefined || tail === undefined) {\n return false;\n }\n const vout = input.index;\n const nw:\n | {\n readonly outputs: ReadonlyArray<{\n readonly script: Uint8Array;\n readonly amount: bigint;\n }>;\n }\n | undefined = input.nonWitnessUtxo;\n const legacyOut = nw === undefined || vout === undefined ? undefined : nw.outputs[vout];\n const prevout = input.witnessUtxo ?? legacyOut;\n if (prevout === undefined) {\n return false;\n }\n const prevScript: Uint8Array = prevout.script;\n const prevAmount: bigint = prevout.amount;\n const pub = childPub(xpub, network, tail.change, tail.index);\n if (taproot) {\n const xonly = pub.slice(1);\n const rawSig = input.tapKeySig;\n if (\n !eq(claimed.pubkey, xonly) ||\n !(rawSig instanceof Uint8Array) ||\n (rawSig.length !== 64 && rawSig.length !== 65) ||\n (input.tapInternalKey !== undefined && !eq(input.tapInternalKey, xonly)) ||\n !eq(prevScript, p2tr(xonly).script)\n ) {\n return false;\n }\n const sighashType =\n rawSig.length === 65 ? (rawSig[64] ?? SigHash.DEFAULT) : SigHash.DEFAULT;\n const sig = rawSig.slice(0, 64);\n const scripts: Uint8Array[] = [];\n const amounts: bigint[] = [];\n let complete = true;\n for (let i = 0; i < tx.inputsLength; i++) {\n const w = tx.getInput(i).witnessUtxo;\n if (w === undefined) {\n complete = false;\n break;\n }\n scripts.push(w.script);\n amounts.push(w.amount);\n }\n // BIP-341 key-path signatures commit to the tweaked output key, not the internal key.\n const [outputKey] = taprootTweakPubkey(xonly, new Uint8Array());\n if (\n !complete ||\n !schnorr.verify(sig, tx.preimageWitnessV1(idx, scripts, sighashType, amounts), outputKey)\n ) {\n return false;\n }\n } else {\n const partial = input.partialSig;\n const found = Array.isArray(partial)\n ? partial.find(([p]) => p instanceof Uint8Array && eq(p, pub))\n : undefined;\n const rawSig =\n Array.isArray(found) && found[1] instanceof Uint8Array ? found[1] : undefined;\n if (!eq(claimed.pubkey, pub) || rawSig === undefined || rawSig.length === 0) {\n return false;\n }\n const sighashType = input.sighashType ?? rawSig.at(-1) ?? SigHash.ALL;\n // bip49 prevouts are P2SH — the BIP143 scriptCode is the inner P2WPKH\n // redeem script, canonicalized to the equivalent P2PKH script.\n const effective: Uint8Array = input.redeemScript ?? prevScript;\n const decoded = OutScript.decode(effective);\n const scriptCode: Uint8Array =\n decoded !== undefined && decoded.type === \"wpkh\"\n ? OutScript.encode({ type: \"pkh\", hash: decoded.hash })\n : effective;\n // P2PKH inputs sign the legacy (non-segwit) preimage — btc-signer exposes it as a\n // private method; the public witness preimages do not apply to non-witness inputs.\n const hash =\n input.nonWitnessUtxo === undefined\n ? tx.preimageWitnessV0(idx, scriptCode, sighashType, prevAmount)\n : preimageLegacy(tx, idx, scriptCode, sighashType);\n if (\n !secp256k1.verify(\n secp256k1.Signature.fromBytes(rawSig.slice(0, -1), \"der\").toBytes(),\n hash,\n pub,\n { prehash: false },\n )\n ) {\n return false;\n }\n }\n }\n return true;\n } catch {\n return false;\n }\n};\n\n/** Deserialize the `smp`-prefixed base64 witness: count + pushData items. */\nconst witnessOf = (sig: string): ReadonlyArray<Uint8Array> | undefined => {\n if (!sig.startsWith(\"smp\")) {\n return undefined;\n }\n const raw = base64.decode(sig.slice(3));\n if (raw === undefined || raw.length === 0) {\n return undefined;\n }\n const items: Uint8Array[] = [];\n let off = 1;\n for (let i = 0; i < (raw[0] ?? 0); i++) {\n const len = raw[off];\n if (len === undefined || off + 1 + len > raw.length) {\n return undefined;\n }\n items.push(raw.slice(off + 1, off + 1 + len));\n off += 1 + len;\n }\n return off === raw.length ? items : undefined;\n};\n\n/**\n * BIP-322 simple verification against an address: rebuild to_spend/to_sign exactly as the signer\n * does, then verify the witness signature (P2WPKH ECDSA / P2TR schnorr) over the input preimage.\n */\nexport const verifyBitcoinMessage = (\n address: string,\n message: string,\n signatureBase64: string,\n network: string,\n): boolean => {\n try {\n const net = bitcoinNetwork(network);\n const scriptPubKey = OutScript.encode(Address(net.params).decode(address));\n const witness = witnessOf(signatureBase64);\n if (witness === undefined || witness.length === 0) {\n return false;\n }\n const tx = new Transaction({ version: 0, lockTime: 0, allowUnknownOutputs: true });\n tx.addInput({\n txid: Uint8Array.from([...bip322ToSpendTxid(scriptPubKey, message)].reverse()),\n index: 0,\n sequence: 0,\n witnessUtxo: { script: scriptPubKey, amount: 0n },\n });\n tx.addOutput({ script: Uint8Array.of(0x6a), amount: 0n });\n if (scriptPubKey.at(0) === 0x51) {\n const [rawSig] = witness;\n const xonly = scriptPubKey.slice(2);\n if (\n rawSig === undefined ||\n xonly.length !== 32 ||\n (rawSig.length !== 64 && rawSig.length !== 65)\n ) {\n return false;\n }\n const sighashType =\n rawSig.length === 65 ? (rawSig.at(64) ?? SigHash.DEFAULT) : SigHash.DEFAULT;\n return schnorr.verify(\n rawSig.slice(0, 64),\n tx.preimageWitnessV1(0, [scriptPubKey], sighashType, [0n]),\n xonly,\n );\n }\n const [rawSig, pub] = witness;\n if (rawSig === undefined || pub === undefined || pub.length !== 33 || rawSig.length === 0) {\n return false;\n }\n const sighashType = rawSig.at(-1) ?? SigHash.ALL;\n const decoded = OutScript.decode(scriptPubKey);\n const scriptCode =\n decoded !== undefined && decoded.type === \"wpkh\"\n ? OutScript.encode({ type: \"pkh\", hash: decoded.hash })\n : scriptPubKey;\n return secp256k1.verify(\n secp256k1.Signature.fromBytes(rawSig.slice(0, -1), \"der\").toBytes(),\n tx.preimageWitnessV0(0, scriptCode, sighashType, 0n),\n pub,\n { prehash: false },\n );\n } catch {\n return false;\n }\n};\n","import { Address, OutScript } from \"@scure/btc-signer/payment.js\";\n\nimport { isRecord, requestBase } from \"../account-ref.ts\";\nimport { ChainError } from \"../index.ts\";\nimport type { AccountRef, SignRequest } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\nimport { normalizeBitcoinPsbt } from \"./psbt.ts\";\n\nexport { BITCOIN_NETWORKS, bitcoinNetwork } from \"./networks.ts\";\nexport type { BitcoinAccountTemplate } from \"./account.ts\";\nexport { bitcoinAddressFromXpub, bitcoinPubkeyFromXpub } from \"./account.ts\";\nexport { decodeBitcoinPsbt, verifiabilityBitcoin } from \"./decode.ts\";\nexport { verifyBitcoinMessage, verifyBitcoinPsbtSignatures } from \"./verify.ts\";\n\nconst common = (request: Record<string, unknown>): { network: string; account: AccountRef } => {\n const base = requestBase(request);\n bitcoinNetwork(base.network);\n return base;\n};\n\n/** The decoded `address` fields needed by message signers. */\nexport type MessageTarget = {\n readonly type: string;\n readonly address: string;\n readonly format: \"bip322-simple\" | \"legacy\";\n readonly scriptPubKey: Uint8Array;\n};\n\nconst messageTarget = (address: unknown, network: string, format: unknown): MessageTarget => {\n if (typeof address !== \"string\") {\n throw new ChainError(\"invalid-request\", \"address must be a string\");\n }\n const net = bitcoinNetwork(network);\n let decoded: ReturnType<ReturnType<typeof Address>[\"decode\"]>;\n try {\n decoded = Address(net.params).decode(address);\n } catch {\n throw new ChainError(\"invalid-address\", \"address does not belong to this network\");\n }\n if (format === \"bip322-simple\") {\n if (decoded.type !== \"wpkh\" && decoded.type !== \"tr\") {\n throw new ChainError(\"unsupported\", \"bip322-simple is only for P2WPKH/P2TR addresses\");\n }\n } else if (format === \"legacy\") {\n if (decoded.type !== \"pkh\") {\n throw new ChainError(\"unsupported\", \"legacy signing is only for P2PKH addresses\");\n }\n } else {\n throw new ChainError(\"unsupported\", `unsupported message format: ${String(format)}`);\n }\n const scriptPubKey = OutScript.encode(decoded);\n return { type: decoded.type, address, format, scriptPubKey };\n};\n\n/**\n * Normalizes a bitcoin sign request. Idempotent: the returned PSBT is the canonical\n * re-serialization.\n */\nexport const normalizeBitcoin = (request: unknown): SignRequest => {\n if (!isRecord(request) || typeof request[\"kind\"] !== \"string\") {\n throw new ChainError(\"invalid-request\", \"request must be an object with a kind\");\n }\n if (request[\"kind\"] === \"bitcoin.psbt\") {\n const { network, account, psbt } = request;\n if (typeof network !== \"string\") {\n throw new ChainError(\"invalid-request\", \"request.network must be a string\");\n }\n bitcoinNetwork(network);\n if (!isRecord(account) || account[\"kind\"] !== \"hd\") {\n throw new ChainError(\"invalid-request\", \"request.account must be a wallet group\");\n }\n const { walletId, groupIndex } = account;\n if (\n typeof walletId !== \"string\" ||\n typeof groupIndex !== \"number\" ||\n !Number.isSafeInteger(groupIndex) ||\n groupIndex < 0\n ) {\n throw new ChainError(\"invalid-request\", \"request.account must be a wallet group\");\n }\n if (!(psbt instanceof Uint8Array)) {\n throw new ChainError(\"invalid-request\", \"psbt must be bytes\");\n }\n const normalized = normalizeBitcoinPsbt(psbt, request[\"sign\"], network);\n return {\n kind: \"bitcoin.psbt\",\n network,\n account: { kind: \"hd\", walletId, groupIndex },\n psbt: normalized.psbt,\n sign: normalized.sign,\n };\n }\n const { network, account } = common(request);\n if (request[\"kind\"] === \"bitcoin.message\") {\n const { format } = request;\n const target = messageTarget(request[\"address\"], network, format);\n void target;\n const { message, change, index } = request;\n if (typeof message !== \"string\") {\n throw new ChainError(\"invalid-request\", \"message must be a string\");\n }\n if (change !== 0 && change !== 1) {\n throw new ChainError(\"invalid-request\", \"change must be 0 or 1\");\n }\n if (\n typeof index !== \"number\" ||\n !Number.isSafeInteger(index) ||\n index < 0 ||\n index >= 0x80000000\n ) {\n throw new ChainError(\"invalid-request\", \"index must be a non-hardened path index\");\n }\n return {\n kind: \"bitcoin.message\",\n network,\n account,\n address: target.address,\n message,\n format: target.format,\n change,\n index,\n };\n }\n throw new ChainError(\"unsupported\", `unsupported sign request kind: ${request[\"kind\"]}`);\n};\n\n/** Decodes the message `address` into the scriptPubKey the signer needs. */\nexport const decodeMessageTarget = (\n request: Extract<SignRequest, { kind: \"bitcoin.message\" }>,\n): MessageTarget => messageTarget(request.address, request.network, request.format);\n"],"mappings":";;;;;;;;;;;;;;;AAWA,MAAMA,cAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;;;;AAMrE,MAAM,mBAAmB,QAAuD;CAC9E,MAAM,UACJ,eAAe,MACX,CAAC,GAAG,IAAI,OAAO,CAAC,IAChB,MAAM,QAAQ,GAAG,IACf,MACAA,WAAS,GAAG,IACV,OAAO,OAAO,GAAG,IACjB,CAAC;CACX,MAAM,QAAoB,CAAC;CAC3B,KAAK,MAAM,SAAS,SAAS;EAC3B,MAAM,QAAiB,MAAM,QAAQ,KAAK,IAAI,MAAM,KAAK;EACzD,IAAI,CAACA,WAAS,KAAK,GACjB;EAGF,MAAM,EAAE,SADIA,WAAS,MAAM,MAAM,IAAI,MAAM,SAAS;EAEpD,IAAI,MAAM,QAAQ,IAAI,KAAK,KAAK,OAAO,MAAM,OAAO,MAAM,QAAQ,GAChE,MAAM,KAAK,IAAI;CAEnB;CACA,OAAO;AACT;AAEA,MAAM,cACJ,OACA,OACA,aACS;CACT,KAAK,MAAM,QAAQ,OACjB,IAAI,KAAK,UAAU,MAAM,KAAK,MAAM,MAAM,eAAe,UACvD,MAAM,IAAI,WACR,qBACA,GAAG,MAAM,4CACX;AAGN;AAEA,MAAM,oBAAoB,IAAiB,aAA2B;CACpE,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,cAAc,KAAK;EACxC,MAAM,QAAQ,GAAG,SAAS,CAAC;EAC3B,WAAW,gBAAgB,MAAM,eAAe,GAAG,SAAS,KAAK,QAAQ;EACzE,WAAW,gBAAgB,MAAM,kBAAkB,GAAG,SAAS,KAAK,QAAQ;CAC9E;CACA,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,e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AQ,SAAS;AACzF;;AAGA,MAAa,uBACX,YACkB,cAAc,QAAQ,SAAS,QAAQ,SAAS,QAAQ,MAAM"}
@@ -1,4 +1,4 @@
1
- import { u as EvmTransaction } from "./index-QxoxkD5m.mjs";
1
+ import { d as EvmTransaction } from "./index-DYwm4-Ec.mjs";
2
2
  /** Signs a normalized transaction; returns the serialized signed envelope. */
3
3
  export declare const signEvmTransaction: (tx: EvmTransaction, privateKey: Uint8Array) => Uint8Array;
4
4
  /** EIP-191 personal_sign; returns the 65-byte signature r‖s‖v with v∈{27,28}. */
package/dist/evm.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as SignRequest, c as DisplayIntent, u as EvmTransaction, y as Verifiability } from "./index-QxoxkD5m.mjs";
1
+ import { b as Verifiability, d as EvmTransaction, l as DisplayIntent, v as SignRequest } from "./index-DYwm4-Ec.mjs";
2
2
  /** The native asset id in `AssetFlow` and simulated asset changes. */
3
3
  export declare const EVM_NATIVE_ASSET = "native";
4
4
  /** EIP-55 checksummed address, e.g. `0x52908400098527886E0F7030069857D2E4169EE7`. */
@@ -25,13 +25,23 @@ type AccountRef = {
25
25
  readonly keyId: string;
26
26
  readonly family: ChainFamily;
27
27
  };
28
+ /** The BIP-44/49/84/86 account-level templates a bitcoin.psbt input may sign under. */
29
+ type BitcoinTemplate = "btc.bip44" | "btc.bip49" | "btc.bip84" | "btc.bip86";
28
30
  type SignRequest = {
29
31
  readonly kind: "bitcoin.psbt";
30
32
  readonly network: string;
31
- readonly account: AccountRef;
33
+ /** The wallet group whose keys sign; each signed input names its template. */
34
+ readonly account: {
35
+ readonly kind: "hd";
36
+ readonly walletId: string;
37
+ readonly groupIndex: number;
38
+ };
32
39
  readonly psbt: Uint8Array;
33
- /** Input indices to sign — non-empty, unique, ascending, in range. */
34
- readonly sign: ReadonlyArray<number>;
40
+ /** Inputs to sign — non-empty, unique, ascending by index, in range; each with its template. */
41
+ readonly sign: ReadonlyArray<{
42
+ readonly index: number;
43
+ readonly template: BitcoinTemplate;
44
+ }>;
35
45
  } | {
36
46
  readonly kind: "bitcoin.message";
37
47
  readonly network: string;
@@ -242,5 +252,5 @@ declare class ChainError extends Error {
242
252
  readonly code: ChainErrorCode;
243
253
  constructor(code: ChainErrorCode, message: string);
244
254
  }
245
- export { SignRequest as _, ChainError as a, SignInParse as b, DisplayIntent as c, IntentSummary as d, IntentWarning as f, SeaportOrder as g, SeaportItem as h, AssetFlow as i, EvmAccessListEntry as l, SafeTransaction as m, ApprovalChange as n, ChainErrorCode as o, MessageContent as p, AssetAmount as r, ChainFamily as s, AccountRef as t, EvmTransaction as u, TypedDataDomain as v, parseSignIn as x, Verifiability as y };
246
- //# sourceMappingURL=index-QxoxkD5m.d.mts.map
255
+ export { parseSignIn as S, SeaportOrder as _, BitcoinTemplate as a, Verifiability as b, ChainFamily as c, EvmTransaction as d, IntentSummary as f, SeaportItem as g, SafeTransaction as h, AssetFlow as i, DisplayIntent as l, MessageContent as m, ApprovalChange as n, ChainError as o, IntentWarning as p, AssetAmount as r, ChainErrorCode as s, AccountRef as t, EvmAccessListEntry as u, SignRequest as v, SignInParse as x, TypedDataDomain as y };
256
+ //# sourceMappingURL=index-DYwm4-Ec.d.mts.map
package/dist/index.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { _ as SignRequest, a as ChainError, b as SignInParse, c as DisplayIntent, d as IntentSummary, f as IntentWarning, g as SeaportOrder, h as SeaportItem, i as AssetFlow, l as EvmAccessListEntry, m as SafeTransaction, n as ApprovalChange, o as ChainErrorCode, p as MessageContent, r as AssetAmount, s as ChainFamily, t as AccountRef, u as EvmTransaction, v as TypedDataDomain, x as parseSignIn, y as Verifiability } from "./index-QxoxkD5m.mjs";
2
- export { AccountRef, ApprovalChange, AssetAmount, AssetFlow, ChainError, ChainErrorCode, ChainFamily, DisplayIntent, EvmAccessListEntry, EvmTransaction, IntentSummary, IntentWarning, MessageContent, SafeTransaction, SeaportItem, SeaportOrder, type SignInParse, SignRequest, TypedDataDomain, Verifiability, parseSignIn };
1
+ import { S as parseSignIn, _ as SeaportOrder, a as BitcoinTemplate, b as Verifiability, c as ChainFamily, d as EvmTransaction, f as IntentSummary, g as SeaportItem, h as SafeTransaction, i as AssetFlow, l as DisplayIntent, m as MessageContent, n as ApprovalChange, o as ChainError, p as IntentWarning, r as AssetAmount, s as ChainErrorCode, t as AccountRef, u as EvmAccessListEntry, v as SignRequest, x as SignInParse, y as TypedDataDomain } from "./index-DYwm4-Ec.mjs";
2
+ export { AccountRef, ApprovalChange, AssetAmount, AssetFlow, BitcoinTemplate, ChainError, ChainErrorCode, ChainFamily, DisplayIntent, EvmAccessListEntry, EvmTransaction, IntentSummary, IntentWarning, MessageContent, SafeTransaction, SeaportItem, SeaportOrder, type SignInParse, SignRequest, TypedDataDomain, Verifiability, parseSignIn };
package/dist/solana.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as SignRequest, c as DisplayIntent, y as Verifiability } from "./index-QxoxkD5m.mjs";
1
+ import { b as Verifiability, l as DisplayIntent, v as SignRequest } from "./index-DYwm4-Ec.mjs";
2
2
  /** Well-known Solana program ids (base58, 32 bytes) — frozen constants. */
3
3
  export declare const PROGRAM_IDS: Readonly<{
4
4
  system: string;
@@ -1 +1 @@
1
- {"version":3,"file":"src-8NZeEnrW.mjs","names":[],"sources":["../src/sign-in.ts","../src/index.ts"],"sourcesContent":["/** Recognition of Sign-In with Ethereum (ERC-4361) and Sign-In with Solana text in signed messages. */\nimport type { Message, MessageFields } from \"@qntx/siwx\";\nimport { evm } from \"@qntx/siwx/evm\";\nimport { siws, validateAddress as validateSolanaAddress } from \"@qntx/siwx/svm\";\n\n/** A Sign-In with X message found in signed text (ERC-4361 / SIWS). */\nexport type SignInParse =\n | { readonly status: \"valid\"; readonly fields: MessageFields }\n /** The text contains the sign-in preamble but is not a conforming message for this chain family. */\n | { readonly status: \"malformed\" };\n\nconst PREAMBLE = \" wants you to sign in with your \";\n\nconst OPTIONAL_KEYS = [\"scheme\", \"statement\", \"expirationTime\", \"notBefore\", \"requestId\"] as const;\n\nconst plainFields = (message: Message): MessageFields => {\n const { domain, address, uri, version, chainId, nonce, issuedAt, resources } = message;\n const fields: { -readonly [K in keyof MessageFields]: MessageFields[K] } = {\n domain,\n address,\n uri,\n version,\n chainId,\n nonce,\n issuedAt,\n };\n for (const key of OPTIONAL_KEYS) {\n const value = message[key];\n if (value !== undefined) {\n fields[key] = value;\n }\n }\n if (resources !== undefined) {\n fields.resources = [...resources];\n }\n return fields;\n};\n\nconst parseValid = (text: string, family: \"evm\" | \"solana\"): MessageFields => {\n if (family === \"evm\") {\n const ns = evm();\n const message = ns.parse(new TextEncoder().encode(text));\n ns.account(message);\n return plainFields(message);\n }\n const message = siws.parse(text);\n validateSolanaAddress(message.address);\n return plainFields(message);\n};\n\n/**\n * Finds a Sign-In with X message in `text` for the chain `family`. `undefined` when the text has no\n * sign-in preamble; `malformed` when it has one but is not a conforming message for the family\n * (ERC-4361: wallets should warn about that shape).\n */\nexport function parseSignIn(text: string, family: \"evm\" | \"solana\"): SignInParse | undefined {\n try {\n return { status: \"valid\", fields: parseValid(text, family) };\n } catch {\n return text.includes(PREAMBLE) ? { status: \"malformed\" } : undefined;\n }\n}\n","/**\n * @qntx/wallet-chains — shared chain semantics for the wallet.\n * Types here are wire-safe: values crossing the main↔kernel protocol are\n * Uint8Array, safe integers, strings, booleans, arrays and plain objects.\n * Quantities are canonical `0x` hex (lowercase, no leading zeros, `0x0` for\n * zero), token amounts are decimal strings of the smallest unit.\n */\n\nimport type { SignInParse } from \"./sign-in.ts\";\n\nexport { parseSignIn } from \"./sign-in.ts\";\nexport type { SignInParse } from \"./sign-in.ts\";\n\nexport type ChainFamily = \"evm\" | \"solana\" | \"bitcoin\";\n\nexport type AccountRef =\n | {\n readonly kind: \"hd\";\n readonly walletId: string;\n readonly groupIndex: number;\n readonly template: string;\n }\n | { readonly kind: \"imported\"; readonly keyId: string; readonly family: ChainFamily };\n\nexport type SignRequest =\n | {\n readonly kind: \"bitcoin.psbt\";\n readonly network: string;\n readonly account: AccountRef;\n readonly psbt: Uint8Array;\n /** Input indices to sign — non-empty, unique, ascending, in range. */\n readonly sign: ReadonlyArray<number>;\n }\n | {\n readonly kind: \"bitcoin.message\";\n readonly network: string;\n readonly account: AccountRef;\n readonly address: string;\n readonly message: string;\n readonly format: \"bip322-simple\" | \"legacy\";\n /** Account change chain and index the address is derived at (0 = receive, 1 = change). */\n readonly change: 0 | 1;\n readonly index: number;\n }\n | {\n readonly kind: \"solana.transaction\";\n readonly network: string;\n readonly account: AccountRef;\n /** Compiled wire message (legacy or v0). */\n readonly message: Uint8Array;\n readonly lookupTables?: ReadonlyArray<{\n readonly address: string;\n readonly addresses: ReadonlyArray<string>;\n }>;\n }\n | {\n readonly kind: \"solana.message\";\n readonly network: string;\n readonly account: AccountRef;\n readonly message: Uint8Array;\n /** Only \"raw\" exists in this layer; offchain formats land with C7. */\n readonly format: \"raw\";\n }\n | {\n readonly kind: \"evm.transaction\";\n readonly network: string;\n readonly account: AccountRef;\n readonly tx: EvmTransaction;\n }\n | {\n readonly kind: \"evm.personal-message\";\n readonly network: string;\n readonly account: AccountRef;\n readonly message: Uint8Array;\n }\n | {\n readonly kind: \"evm.typed-data\";\n readonly network: string;\n readonly account: AccountRef;\n readonly typedData: string;\n };\n\nexport type EvmAccessListEntry = {\n readonly address: string;\n readonly storageKeys: ReadonlyArray<string>;\n};\n\ntype EvmTransactionBase = {\n readonly chainId: number;\n readonly nonce: number;\n readonly gas: string;\n readonly value: string;\n readonly data: string;\n readonly to?: string;\n};\n\n/**\n * A complete transaction — every field the signer needs is present; `to` absent means contract\n * creation.\n */\nexport type EvmTransaction =\n | (EvmTransactionBase & { readonly type: \"legacy\"; readonly gasPrice: string })\n | (EvmTransactionBase & {\n readonly type: \"eip2930\";\n readonly gasPrice: string;\n readonly accessList: ReadonlyArray<EvmAccessListEntry>;\n })\n | (EvmTransactionBase & {\n readonly type: \"eip1559\";\n readonly accessList: ReadonlyArray<EvmAccessListEntry>;\n readonly maxFeePerGas: string;\n readonly maxPriorityFeePerGas: string;\n });\n\nexport type Verifiability = \"full\" | \"partial\" | \"opaque\";\n\nexport type IntentSummary =\n | \"transfer\"\n | \"approve\"\n | \"contract-call\"\n | \"swap\"\n | \"message\"\n | \"authorization\"\n | \"batch\";\n\nexport type AssetAmount = {\n readonly asset: string;\n readonly amount: string;\n readonly decimals?: number;\n readonly symbol?: string;\n};\n\nexport type AssetFlow = {\n readonly to: string;\n readonly amount: AssetAmount;\n readonly verified: boolean;\n /** The ENS name the recipient was resolved from; attached by the engine, never decoded. */\n readonly name?: string;\n};\n\nexport type ApprovalChange =\n | {\n /** A fungible-token allowance: on the token itself, or on Permit2 when `via` is \"permit2\". */\n readonly kind: \"allowance\";\n readonly spender: string;\n /** The token and amount (base units); symbol/decimals when the token is in the built-in table. */\n readonly amount: AssetAmount;\n /**\n * `set`: the allowance becomes `amount`; `increase`/`decrease`: it changes by `amount`;\n * `transfer`: a one-time right to take up to `amount` before `expiration` (Permit2\n * SignatureTransfer).\n */\n readonly change: \"set\" | \"increase\" | \"decrease\" | \"transfer\";\n /** `amount` is the type's maximum (uint256; uint160 for Permit2). */\n readonly unlimited: boolean;\n /** Unix seconds after which the allowance lapses (Permit2), when it has one. */\n readonly expiration?: number;\n readonly via?: \"permit2\";\n /** The token is in the built-in table. */\n readonly verified: boolean;\n }\n | {\n /** ERC-721/1155 `setApprovalForAll`: `spender` may move every token of `asset`. */\n readonly kind: \"operator\";\n readonly asset: string;\n readonly spender: string;\n /** `false` revokes. */\n readonly approved: boolean;\n readonly verified: false;\n };\n\nexport type IntentWarning = {\n readonly kind: string;\n readonly message: string;\n};\n\n/** One item a Seaport order offers or requests; recognized from EIP-712 `itemType` 0–5. */\nexport type SeaportItem = {\n readonly kind: \"native\" | \"erc20\" | \"erc721\" | \"erc1155\" | \"erc721-criteria\" | \"erc1155-criteria\";\n /** The item's contract (EIP-55 checksummed; the zero address for `native`). */\n readonly token: string;\n /** `identifierOrCriteria` as a decimal string; a criteria root for the criteria kinds. */\n readonly identifier: string;\n readonly startAmount: AssetAmount;\n readonly endAmount: AssetAmount;\n};\n\n/** A recognized Seaport `OrderComponents` message. */\nexport type SeaportOrder = {\n readonly offerer: string;\n readonly zone: string;\n readonly startTime: number | undefined;\n readonly endTime: number | undefined;\n readonly offer: ReadonlyArray<SeaportItem>;\n readonly consideration: ReadonlyArray<SeaportItem & { readonly recipient: string }>;\n};\n\n/** A recognized Safe `SafeTx` message. */\nexport type SafeTransaction = {\n readonly safe: string;\n /** The Safe nonce as a decimal string. */\n readonly nonce: string;\n readonly operation: \"call\" | \"delegatecall\";\n readonly to: string;\n /** Wei, decimal. */\n readonly value: string;\n readonly data: string;\n /** The inner call(s) decoded with the transaction rules (no fee); one per MultiSend entry. */\n readonly calls: ReadonlyArray<DisplayIntent>;\n /** The gas-refund terms, present when `gasPrice` is not zero. */\n readonly refund?: {\n readonly gasPrice: string;\n readonly gasToken: string;\n readonly refundReceiver: string;\n };\n};\n\n/** The EIP-712 domain fields a wallet shows. */\nexport type TypedDataDomain = {\n readonly name?: string;\n readonly version?: string;\n readonly chainId?: number;\n /** EIP-55 checksummed. */\n readonly verifyingContract?: string;\n readonly salt?: string;\n};\n\n/** What a message request signs. */\nexport type MessageContent =\n | { readonly kind: \"text\"; readonly text: string; readonly signIn?: SignInParse }\n | { readonly kind: \"bytes\"; readonly hex: string }\n | {\n readonly kind: \"typed-data\";\n readonly primaryType: string;\n readonly domain: TypedDataDomain;\n readonly data: Readonly<Record<string, unknown>>;\n /** A recognized Seaport order; only the exact `OrderComponents` shape populates it. */\n readonly seaport?: SeaportOrder;\n /** A recognized Safe transaction; only the exact `SafeTx` shape populates it. */\n readonly safe?: SafeTransaction;\n };\n\nexport type DisplayIntent = {\n readonly family: ChainFamily;\n readonly network: string;\n readonly summary: IntentSummary;\n readonly outflows: ReadonlyArray<AssetFlow>;\n readonly approvals: ReadonlyArray<ApprovalChange>;\n /**\n * `l1Data`: OP Stack L1 data fee plus operator fee, estimated by the engine and charged on top of\n * `max`; not decodable from the transaction, so the kernel's own decode never sets it.\n */\n readonly fee: { readonly max: AssetAmount; readonly l1Data?: AssetAmount } | undefined;\n readonly warnings: ReadonlyArray<IntentWarning>;\n /** What a message request signs; absent for transactions. */\n readonly message?: MessageContent;\n readonly verifiability: Verifiability;\n};\n\nexport type ChainErrorCode =\n | \"unknown-field\"\n | \"chain-id-mismatch\"\n | \"fee-payer-mismatch\"\n | \"invalid-quantity\"\n | \"invalid-address\"\n | \"invalid-typed-data\"\n | \"invalid-request\"\n | \"unsupported\";\n\nexport class ChainError extends Error {\n readonly code: ChainErrorCode;\n constructor(code: ChainErrorCode, message: string) {\n super(message);\n this.name = \"ChainError\";\n this.code = code;\n }\n}\n"],"mappings":";;;AAWA,MAAM,WAAW;AAEjB,MAAM,gBAAgB;CAAC;CAAU;CAAa;CAAkB;CAAa;AAAW;AAExF,MAAM,eAAe,YAAoC;CACvD,MAAM,EAAE,QAAQ,SAAS,KAAK,SAAS,SAAS,OAAO,UAAU,cAAc;CAC/E,MAAM,SAAqE;EACzE;EACA;EACA;EACA;EACA;EACA;EACA;CACF;CACA,KAAK,MAAM,OAAO,eAAe;EAC/B,MAAM,QAAQ,QAAQ;EACtB,IAAI,UAAU,KAAA,GACZ,OAAO,OAAO;CAElB;CACA,IAAI,cAAc,KAAA,GAChB,OAAO,YAAY,CAAC,GAAG,SAAS;CAElC,OAAO;AACT;AAEA,MAAM,cAAc,MAAc,WAA4C;CAC5E,IAAI,WAAW,OAAO;EACpB,MAAM,KAAK,IAAI;EACf,MAAM,UAAU,GAAG,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI,CAAC;EACvD,GAAG,QAAQ,OAAO;EAClB,OAAO,YAAY,OAAO;CAC5B;CACA,MAAM,UAAU,KAAK,MAAM,IAAI;CAC/B,gBAAsB,QAAQ,OAAO;CACrC,OAAO,YAAY,OAAO;AAC5B;;;;;;AAOA,SAAgB,YAAY,MAAc,QAAmD;CAC3F,IAAI;EACF,OAAO;GAAE,QAAQ;GAAS,QAAQ,WAAW,MAAM,MAAM;EAAE;CAC7D,QAAQ;EACN,OAAO,KAAK,SAAS,QAAQ,IAAI,EAAE,QAAQ,YAAY,IAAI,KAAA;CAC7D;AACF;;ACgNA,IAAa,aAAb,cAAgC,MAAM;CACpC;CACA,YAAY,MAAsB,SAAiB;EACjD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF"}
1
+ {"version":3,"file":"src-8NZeEnrW.mjs","names":[],"sources":["../src/sign-in.ts","../src/index.ts"],"sourcesContent":["/** Recognition of Sign-In with Ethereum (ERC-4361) and Sign-In with Solana text in signed messages. */\nimport type { Message, MessageFields } from \"@qntx/siwx\";\nimport { evm } from \"@qntx/siwx/evm\";\nimport { siws, validateAddress as validateSolanaAddress } from \"@qntx/siwx/svm\";\n\n/** A Sign-In with X message found in signed text (ERC-4361 / SIWS). */\nexport type SignInParse =\n | { readonly status: \"valid\"; readonly fields: MessageFields }\n /** The text contains the sign-in preamble but is not a conforming message for this chain family. */\n | { readonly status: \"malformed\" };\n\nconst PREAMBLE = \" wants you to sign in with your \";\n\nconst OPTIONAL_KEYS = [\"scheme\", \"statement\", \"expirationTime\", \"notBefore\", \"requestId\"] as const;\n\nconst plainFields = (message: Message): MessageFields => {\n const { domain, address, uri, version, chainId, nonce, issuedAt, resources } = message;\n const fields: { -readonly [K in keyof MessageFields]: MessageFields[K] } = {\n domain,\n address,\n uri,\n version,\n chainId,\n nonce,\n issuedAt,\n };\n for (const key of OPTIONAL_KEYS) {\n const value = message[key];\n if (value !== undefined) {\n fields[key] = value;\n }\n }\n if (resources !== undefined) {\n fields.resources = [...resources];\n }\n return fields;\n};\n\nconst parseValid = (text: string, family: \"evm\" | \"solana\"): MessageFields => {\n if (family === \"evm\") {\n const ns = evm();\n const message = ns.parse(new TextEncoder().encode(text));\n ns.account(message);\n return plainFields(message);\n }\n const message = siws.parse(text);\n validateSolanaAddress(message.address);\n return plainFields(message);\n};\n\n/**\n * Finds a Sign-In with X message in `text` for the chain `family`. `undefined` when the text has no\n * sign-in preamble; `malformed` when it has one but is not a conforming message for the family\n * (ERC-4361: wallets should warn about that shape).\n */\nexport function parseSignIn(text: string, family: \"evm\" | \"solana\"): SignInParse | undefined {\n try {\n return { status: \"valid\", fields: parseValid(text, family) };\n } catch {\n return text.includes(PREAMBLE) ? { status: \"malformed\" } : undefined;\n }\n}\n","/**\n * @qntx/wallet-chains — shared chain semantics for the wallet.\n * Types here are wire-safe: values crossing the main↔kernel protocol are\n * Uint8Array, safe integers, strings, booleans, arrays and plain objects.\n * Quantities are canonical `0x` hex (lowercase, no leading zeros, `0x0` for\n * zero), token amounts are decimal strings of the smallest unit.\n */\n\nimport type { SignInParse } from \"./sign-in.ts\";\n\nexport { parseSignIn } from \"./sign-in.ts\";\nexport type { SignInParse } from \"./sign-in.ts\";\n\nexport type ChainFamily = \"evm\" | \"solana\" | \"bitcoin\";\n\nexport type AccountRef =\n | {\n readonly kind: \"hd\";\n readonly walletId: string;\n readonly groupIndex: number;\n readonly template: string;\n }\n | { readonly kind: \"imported\"; readonly keyId: string; readonly family: ChainFamily };\n\n/** The BIP-44/49/84/86 account-level templates a bitcoin.psbt input may sign under. */\nexport type BitcoinTemplate = \"btc.bip44\" | \"btc.bip49\" | \"btc.bip84\" | \"btc.bip86\";\n\nexport type SignRequest =\n | {\n readonly kind: \"bitcoin.psbt\";\n readonly network: string;\n /** The wallet group whose keys sign; each signed input names its template. */\n readonly account: {\n readonly kind: \"hd\";\n readonly walletId: string;\n readonly groupIndex: number;\n };\n readonly psbt: Uint8Array;\n /** Inputs to sign — non-empty, unique, ascending by index, in range; each with its template. */\n readonly sign: ReadonlyArray<{ readonly index: number; readonly template: BitcoinTemplate }>;\n }\n | {\n readonly kind: \"bitcoin.message\";\n readonly network: string;\n readonly account: AccountRef;\n readonly address: string;\n readonly message: string;\n readonly format: \"bip322-simple\" | \"legacy\";\n /** Account change chain and index the address is derived at (0 = receive, 1 = change). */\n readonly change: 0 | 1;\n readonly index: number;\n }\n | {\n readonly kind: \"solana.transaction\";\n readonly network: string;\n readonly account: AccountRef;\n /** Compiled wire message (legacy or v0). */\n readonly message: Uint8Array;\n readonly lookupTables?: ReadonlyArray<{\n readonly address: string;\n readonly addresses: ReadonlyArray<string>;\n }>;\n }\n | {\n readonly kind: \"solana.message\";\n readonly network: string;\n readonly account: AccountRef;\n readonly message: Uint8Array;\n /** Only \"raw\" exists in this layer; offchain formats land with C7. */\n readonly format: \"raw\";\n }\n | {\n readonly kind: \"evm.transaction\";\n readonly network: string;\n readonly account: AccountRef;\n readonly tx: EvmTransaction;\n }\n | {\n readonly kind: \"evm.personal-message\";\n readonly network: string;\n readonly account: AccountRef;\n readonly message: Uint8Array;\n }\n | {\n readonly kind: \"evm.typed-data\";\n readonly network: string;\n readonly account: AccountRef;\n readonly typedData: string;\n };\n\nexport type EvmAccessListEntry = {\n readonly address: string;\n readonly storageKeys: ReadonlyArray<string>;\n};\n\ntype EvmTransactionBase = {\n readonly chainId: number;\n readonly nonce: number;\n readonly gas: string;\n readonly value: string;\n readonly data: string;\n readonly to?: string;\n};\n\n/**\n * A complete transaction — every field the signer needs is present; `to` absent means contract\n * creation.\n */\nexport type EvmTransaction =\n | (EvmTransactionBase & { readonly type: \"legacy\"; readonly gasPrice: string })\n | (EvmTransactionBase & {\n readonly type: \"eip2930\";\n readonly gasPrice: string;\n readonly accessList: ReadonlyArray<EvmAccessListEntry>;\n })\n | (EvmTransactionBase & {\n readonly type: \"eip1559\";\n readonly accessList: ReadonlyArray<EvmAccessListEntry>;\n readonly maxFeePerGas: string;\n readonly maxPriorityFeePerGas: string;\n });\n\nexport type Verifiability = \"full\" | \"partial\" | \"opaque\";\n\nexport type IntentSummary =\n | \"transfer\"\n | \"approve\"\n | \"contract-call\"\n | \"swap\"\n | \"message\"\n | \"authorization\"\n | \"batch\";\n\nexport type AssetAmount = {\n readonly asset: string;\n readonly amount: string;\n readonly decimals?: number;\n readonly symbol?: string;\n};\n\nexport type AssetFlow = {\n readonly to: string;\n readonly amount: AssetAmount;\n readonly verified: boolean;\n /** The ENS name the recipient was resolved from; attached by the engine, never decoded. */\n readonly name?: string;\n};\n\nexport type ApprovalChange =\n | {\n /** A fungible-token allowance: on the token itself, or on Permit2 when `via` is \"permit2\". */\n readonly kind: \"allowance\";\n readonly spender: string;\n /** The token and amount (base units); symbol/decimals when the token is in the built-in table. */\n readonly amount: AssetAmount;\n /**\n * `set`: the allowance becomes `amount`; `increase`/`decrease`: it changes by `amount`;\n * `transfer`: a one-time right to take up to `amount` before `expiration` (Permit2\n * SignatureTransfer).\n */\n readonly change: \"set\" | \"increase\" | \"decrease\" | \"transfer\";\n /** `amount` is the type's maximum (uint256; uint160 for Permit2). */\n readonly unlimited: boolean;\n /** Unix seconds after which the allowance lapses (Permit2), when it has one. */\n readonly expiration?: number;\n readonly via?: \"permit2\";\n /** The token is in the built-in table. */\n readonly verified: boolean;\n }\n | {\n /** ERC-721/1155 `setApprovalForAll`: `spender` may move every token of `asset`. */\n readonly kind: \"operator\";\n readonly asset: string;\n readonly spender: string;\n /** `false` revokes. */\n readonly approved: boolean;\n readonly verified: false;\n };\n\nexport type IntentWarning = {\n readonly kind: string;\n readonly message: string;\n};\n\n/** One item a Seaport order offers or requests; recognized from EIP-712 `itemType` 0–5. */\nexport type SeaportItem = {\n readonly kind: \"native\" | \"erc20\" | \"erc721\" | \"erc1155\" | \"erc721-criteria\" | \"erc1155-criteria\";\n /** The item's contract (EIP-55 checksummed; the zero address for `native`). */\n readonly token: string;\n /** `identifierOrCriteria` as a decimal string; a criteria root for the criteria kinds. */\n readonly identifier: string;\n readonly startAmount: AssetAmount;\n readonly endAmount: AssetAmount;\n};\n\n/** A recognized Seaport `OrderComponents` message. */\nexport type SeaportOrder = {\n readonly offerer: string;\n readonly zone: string;\n readonly startTime: number | undefined;\n readonly endTime: number | undefined;\n readonly offer: ReadonlyArray<SeaportItem>;\n readonly consideration: ReadonlyArray<SeaportItem & { readonly recipient: string }>;\n};\n\n/** A recognized Safe `SafeTx` message. */\nexport type SafeTransaction = {\n readonly safe: string;\n /** The Safe nonce as a decimal string. */\n readonly nonce: string;\n readonly operation: \"call\" | \"delegatecall\";\n readonly to: string;\n /** Wei, decimal. */\n readonly value: string;\n readonly data: string;\n /** The inner call(s) decoded with the transaction rules (no fee); one per MultiSend entry. */\n readonly calls: ReadonlyArray<DisplayIntent>;\n /** The gas-refund terms, present when `gasPrice` is not zero. */\n readonly refund?: {\n readonly gasPrice: string;\n readonly gasToken: string;\n readonly refundReceiver: string;\n };\n};\n\n/** The EIP-712 domain fields a wallet shows. */\nexport type TypedDataDomain = {\n readonly name?: string;\n readonly version?: string;\n readonly chainId?: number;\n /** EIP-55 checksummed. */\n readonly verifyingContract?: string;\n readonly salt?: string;\n};\n\n/** What a message request signs. */\nexport type MessageContent =\n | { readonly kind: \"text\"; readonly text: string; readonly signIn?: SignInParse }\n | { readonly kind: \"bytes\"; readonly hex: string }\n | {\n readonly kind: \"typed-data\";\n readonly primaryType: string;\n readonly domain: TypedDataDomain;\n readonly data: Readonly<Record<string, unknown>>;\n /** A recognized Seaport order; only the exact `OrderComponents` shape populates it. */\n readonly seaport?: SeaportOrder;\n /** A recognized Safe transaction; only the exact `SafeTx` shape populates it. */\n readonly safe?: SafeTransaction;\n };\n\nexport type DisplayIntent = {\n readonly family: ChainFamily;\n readonly network: string;\n readonly summary: IntentSummary;\n readonly outflows: ReadonlyArray<AssetFlow>;\n readonly approvals: ReadonlyArray<ApprovalChange>;\n /**\n * `l1Data`: OP Stack L1 data fee plus operator fee, estimated by the engine and charged on top of\n * `max`; not decodable from the transaction, so the kernel's own decode never sets it.\n */\n readonly fee: { readonly max: AssetAmount; readonly l1Data?: AssetAmount } | undefined;\n readonly warnings: ReadonlyArray<IntentWarning>;\n /** What a message request signs; absent for transactions. */\n readonly message?: MessageContent;\n readonly verifiability: Verifiability;\n};\n\nexport type ChainErrorCode =\n | \"unknown-field\"\n | \"chain-id-mismatch\"\n | \"fee-payer-mismatch\"\n | \"invalid-quantity\"\n | \"invalid-address\"\n | \"invalid-typed-data\"\n | \"invalid-request\"\n | \"unsupported\";\n\nexport class ChainError extends Error {\n readonly code: ChainErrorCode;\n constructor(code: ChainErrorCode, message: string) {\n super(message);\n this.name = \"ChainError\";\n this.code = code;\n }\n}\n"],"mappings":";;;AAWA,MAAM,WAAW;AAEjB,MAAM,gBAAgB;CAAC;CAAU;CAAa;CAAkB;CAAa;AAAW;AAExF,MAAM,eAAe,YAAoC;CACvD,MAAM,EAAE,QAAQ,SAAS,KAAK,SAAS,SAAS,OAAO,UAAU,cAAc;CAC/E,MAAM,SAAqE;EACzE;EACA;EACA;EACA;EACA;EACA;EACA;CACF;CACA,KAAK,MAAM,OAAO,eAAe;EAC/B,MAAM,QAAQ,QAAQ;EACtB,IAAI,UAAU,KAAA,GACZ,OAAO,OAAO;CAElB;CACA,IAAI,cAAc,KAAA,GAChB,OAAO,YAAY,CAAC,GAAG,SAAS;CAElC,OAAO;AACT;AAEA,MAAM,cAAc,MAAc,WAA4C;CAC5E,IAAI,WAAW,OAAO;EACpB,MAAM,KAAK,IAAI;EACf,MAAM,UAAU,GAAG,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI,CAAC;EACvD,GAAG,QAAQ,OAAO;EAClB,OAAO,YAAY,OAAO;CAC5B;CACA,MAAM,UAAU,KAAK,MAAM,IAAI;CAC/B,gBAAsB,QAAQ,OAAO;CACrC,OAAO,YAAY,OAAO;AAC5B;;;;;;AAOA,SAAgB,YAAY,MAAc,QAAmD;CAC3F,IAAI;EACF,OAAO;GAAE,QAAQ;GAAS,QAAQ,WAAW,MAAM,MAAM;EAAE;CAC7D,QAAQ;EACN,OAAO,KAAK,SAAS,QAAQ,IAAI,EAAE,QAAQ,YAAY,IAAI,KAAA;CAC7D;AACF;;ACwNA,IAAa,aAAb,cAAgC,MAAM;CACpC;CACA,YAAY,MAAsB,SAAiB;EACjD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qntx/wallet-chains",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "qntx/wallet chain semantics: SignRequest codecs, display decoding, verifiability and signing for EVM, Solana and Bitcoin",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": "QuantX <x@qntx.org>",