@qntx/wallet-engine 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 { D as NostrPolicy, S as ConnectionController, T as ConnectionSession, _ as BitcoinHandler, a as SolanaEvent, b as BitcoinWalletHandler, c as SolanaWalletAccount, d as Nip07Request, f as Eip1193Event, g as BitcoinEvent, h as BITCOIN_CHAIN_IDS, i as SOLANA_CHAIN_IDS, l as SolanaWalletHandler, m as Eip1193Request, n as WeblnHandler, o as SolanaHandler, p as Eip1193Handler, r as WeblnRequest, s as SolanaRequest, t as ProviderError, u as Nip07Handler, v as BitcoinRequest, y as BitcoinWalletAccount } from "./errors-Bglz0VYn.mjs";
1
+ import { D as NostrPolicy, S as ConnectionController, T as ConnectionSession, _ as BitcoinHandler, a as SolanaEvent, b as BitcoinWalletHandler, c as SolanaWalletAccount, d as Nip07Request, f as Eip1193Event, g as BitcoinEvent, h as BITCOIN_CHAIN_IDS, i as SOLANA_CHAIN_IDS, l as SolanaWalletHandler, m as Eip1193Request, n as WeblnHandler, o as SolanaHandler, p as Eip1193Handler, r as WeblnRequest, s as SolanaRequest, t as ProviderError, u as Nip07Handler, v as BitcoinRequest, y as BitcoinWalletAccount } from "./errors-DpkJneDe.mjs";
2
2
  /** The EIP-6963 provider identity the host stamps into the injected script. */
3
3
  export type ProviderInfo = {
4
4
  /** UUIDv4 — the host generates or fixes one per install. */
package/dist/connect.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { U as ProviderError, a as Nip07Handler, i as SolanaWalletHandler, o as BITCOIN_CHAIN_IDS, r as SOLANA_CHAIN_IDS, s as BitcoinWalletHandler, t as WeblnHandler } from "./webln-BGKm12wd.mjs";
1
+ import { U as ProviderError, a as Nip07Handler, i as SolanaWalletHandler, o as BITCOIN_CHAIN_IDS, r as SOLANA_CHAIN_IDS, s as BitcoinWalletHandler, t as WeblnHandler } from "./webln-DzsI7jVb.mjs";
2
2
  import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils.js";
3
3
  import { sha256 } from "@noble/hashes/sha2.js";
4
4
  // src/connect/inject.generated.ts
@@ -628,7 +628,9 @@ declare class PhishingController extends Controller<PhishingState> {
628
628
  }
629
629
  type ChainApis = ReturnType<typeof chains>;
630
630
  type SignParams = Parameters<ChainApis["sign"]>[0];
631
- type AccountRef = SignParams["request"]["account"];
631
+ type AccountRef = Exclude<SignParams["request"], {
632
+ kind: "bitcoin.psbt";
633
+ }>["account"];
632
634
  type DisplayIntent = ReturnType<typeof decodeEvm>;
633
635
  type TxState = "draft" | "signed" | "submitted" | "pending" | "confirmed" | "failed" | "rejected" | "dropped" | "replaced";
634
636
  /** A bitcoin transaction that funds the wallet's own Spark account; it is claimed once confirmed. */
@@ -827,6 +829,14 @@ type BitcoinAccount = {
827
829
  /** `btc.bip84` for the `payment` purpose, `btc.bip86` for `ordinals`. */
828
830
  readonly template: "btc.bip84" | "btc.bip86";
829
831
  };
832
+ /**
833
+ * The wallet group a `bitcoin-sign` PSBT request signs for: inputs of several dApp-facing templates
834
+ * of the same group may mix in one PSBT — each sign entry names its own template.
835
+ */
836
+ type BitcoinGroup = {
837
+ readonly walletId: string;
838
+ readonly groupIndex: number;
839
+ };
830
840
  /** The sighash a dApp asks for per input; anything else is refused before it reaches a request. */
831
841
  type BitcoinSigHash = "ALL" | "SINGLE|ANYONECANPAY";
832
842
  /** One dApp PSBT and the inputs it asks the wallet to sign. */
@@ -835,6 +845,7 @@ type BitcoinPsbtInput = {
835
845
  readonly sign: ReadonlyArray<{
836
846
  readonly index: number;
837
847
  readonly sigHash: BitcoinSigHash;
848
+ readonly template: BitcoinAccount["template"];
838
849
  }>;
839
850
  };
840
851
  /**
@@ -851,6 +862,7 @@ type PreparedBitcoinPsbt = {
851
862
  readonly index: number;
852
863
  readonly value: number;
853
864
  readonly sigHash: BitcoinSigHash;
865
+ readonly template: BitcoinAccount["template"];
854
866
  }>;
855
867
  };
856
868
  type SignLogOutcome = "submitted" | "rejected" | "failed" | "expired" | "invalidated";
@@ -859,7 +871,7 @@ type SignLogEntry = {
859
871
  readonly at: number;
860
872
  readonly origin: RequestOrigin;
861
873
  readonly method: RequestMethod;
862
- readonly account: AccountRef | SparkAccountRef | NostrKeyRef | SolanaAccount | BitcoinAccount;
874
+ readonly account: AccountRef | SparkAccountRef | NostrKeyRef | SolanaAccount | BitcoinAccount | BitcoinGroup;
863
875
  readonly network: string;
864
876
  readonly summary: string;
865
877
  readonly verification: "verified" | "unverifiable";
@@ -977,7 +989,13 @@ type BitcoinSignInput = {
977
989
  readonly request: {
978
990
  readonly kind: "message";
979
991
  readonly message: string;
980
- } | {
992
+ };
993
+ } | {
994
+ readonly method: "bitcoin-sign";
995
+ readonly origin: BrowserOrigin;
996
+ readonly account: BitcoinGroup;
997
+ readonly network: string;
998
+ readonly request: {
981
999
  readonly kind: "psbt";
982
1000
  readonly psbts: ReadonlyArray<BitcoinPsbtInput>;
983
1001
  readonly send: boolean;
@@ -1064,7 +1082,7 @@ type PendingRequest = {
1064
1082
  readonly id: string;
1065
1083
  readonly origin: RequestOrigin;
1066
1084
  readonly method: RequestMethod;
1067
- readonly account: AccountRef | SparkAccountRef | NostrKeyRef | SolanaAccount | BitcoinAccount;
1085
+ readonly account: AccountRef | SparkAccountRef | NostrKeyRef | SolanaAccount | BitcoinAccount | BitcoinGroup;
1068
1086
  readonly network: string;
1069
1087
  readonly stage: RequestStage;
1070
1088
  /** Decoded locally from the exact content that will be signed; `family` tells the shapes apart. */
@@ -1129,10 +1147,10 @@ type RequestControllerOptions = {
1129
1147
  readonly kind: "message";
1130
1148
  readonly message: string;
1131
1149
  }, verify: SendParams["verify"]) => Promise<BitcoinSignResult>;
1132
- /** Adds the account's derivation data to a dApp's PSBTs; refuses inputs that are not its own. */
1133
- readonly bitcoinPrepare: (account: BitcoinAccount, network: string, psbts: ReadonlyArray<BitcoinPsbtInput>) => Promise<ReadonlyArray<PreparedBitcoinPsbt>>;
1150
+ /** Adds the group's derivation data to a dApp's PSBTs; refuses inputs that are not its own. */
1151
+ readonly bitcoinPrepare: (account: BitcoinGroup, network: string, psbts: ReadonlyArray<BitcoinPsbtInput>) => Promise<ReadonlyArray<PreparedBitcoinPsbt>>;
1134
1152
  /** Signs (and with `send` broadcasts) the prepared PSBTs. */
1135
- readonly bitcoinSignPsbts: (account: BitcoinAccount, network: string, prepared: ReadonlyArray<PreparedBitcoinPsbt>, send: boolean, verify: SendParams["verify"]) => Promise<BitcoinSignResult>;
1153
+ readonly bitcoinSignPsbts: (account: BitcoinGroup, network: string, prepared: ReadonlyArray<PreparedBitcoinPsbt>, send: boolean, verify: SendParams["verify"]) => Promise<BitcoinSignResult>;
1136
1154
  };
1137
1155
  /** Requests expire this long after creation. */
1138
1156
  declare const REQUEST_TTL_MS: number;
@@ -1476,8 +1494,8 @@ declare class BitcoinWalletHandler implements BitcoinHandler {
1476
1494
  private signMessage;
1477
1495
  /**
1478
1496
  * Signs (and with `send` broadcasts) a batch of dApp PSBTs under one approval. Every account
1479
- * named must be a session account of one purpose — a PSBT spending both payment and ordinals
1480
- * inputs is not supported yet — and `chain`, when given, must be the session's network.
1497
+ * named must be a session account — inputs of both purposes may mix in one PSBT, each sign entry
1498
+ * carries its account's template — and `chain`, when given, must be the session's network.
1481
1499
  */
1482
1500
  private signTransactions;
1483
1501
  /** The `setActiveGroup` re-point: the bitcoin session's new accounts, `payment` then `ordinals`. */
@@ -1675,4 +1693,4 @@ declare class ProviderError extends Error {
1675
1693
  constructor(code: number, message: string);
1676
1694
  }
1677
1695
  export { PrepareZapContext as $, PayInput as A, EngineCollection as At, SignLogEntry as B, ConnectionOrigin as C, NetworkController as Ct, NostrPolicy as D, AddressBookEntry as Dt, ConnectionState as E, AddressBookState as Et, RequestControllerState as F, createEventBus as Ft, RiskFinding as G, BrowserOrigin as H, RequestInput as I, Controller as It, PHISHING_REFRESH_MS as J, TransactionController as K, RequestStage as L, ControllerOptions as Lt, REQUEST_TTL_MS as M, PublicStore as Mt, RESIMULATE_AFTER_MS as N, EngineLogger as Nt, PendingConnection as O, AddressBookRecord as Ot, RequestController as P, EventBus as Pt, PhishingStatus as Q, SparkDepositInput as R, ConnectionController as S, RequestCheckCode as St, ConnectionSession as T, AddressBookController as Tt, RequestMethod as U, SignLogOutcome as V, RequestOrigin as W, PhishingControllerOptions as X, PhishingController as Y, PhishingState as Z, BitcoinHandler as _, SparkControllerOptions as _t, SolanaEvent as a, WithdrawLnurlParams as at, BitcoinWalletHandler as b, PaymentNote as bt, SolanaWalletAccount as c, PaymentParse as ct, Nip07Request as d, PreparedSparkAction as dt, PrepareZapParams as et, Eip1193Event as f, SparkDisplay as ft, BitcoinEvent as g, SparkController as gt, BITCOIN_CHAIN_IDS as h, SparkClientFactory as ht, SOLANA_CHAIN_IDS as i, PayParams as it, PendingRequest as j, EngineStore as jt, EvmSignInput as k, AddressFamily as kt, SolanaWalletHandler as l, PaymentRequest as lt, Eip1193Request as m, SparkAccountState as mt, WeblnHandler as n, ZapRecipient as nt, SolanaHandler as o, ParseOptions as ot, Eip1193Handler as p, SparkResult as pt, SignatureResult as q, WeblnRequest as r, prepareZap as rt, SolanaRequest as s, PaymentOption as st, ProviderError as t, PreparedZap as tt, Nip07Handler as u, parsePayment as ut, BitcoinRequest as v, SparkControllerState as vt, ConnectionScope as w, Esplora as wt, AccountGroup as x, SparkActivity as xt, BitcoinWalletAccount as y, sparkStore as yt, SparkExitInput as z };
1678
- //# sourceMappingURL=errors-Bglz0VYn.d.mts.map
1696
+ //# sourceMappingURL=errors-DpkJneDe.d.mts.map
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as PrepareZapContext, A as PayInput, At as EngineCollection, B as SignLogEntry, C as ConnectionOrigin, Ct as NetworkController, Dt as AddressBookEntry, E as ConnectionState, Et as AddressBookState, F as RequestControllerState, Ft as createEventBus, G as RiskFinding, H as BrowserOrigin, I as RequestInput, It as Controller, J as PHISHING_REFRESH_MS, K as TransactionController, L as RequestStage, Lt as ControllerOptions, M as REQUEST_TTL_MS, Mt as PublicStore, N as RESIMULATE_AFTER_MS, Nt as EngineLogger, O as PendingConnection, Ot as AddressBookRecord, P as RequestController, Pt as EventBus, Q as PhishingStatus, R as SparkDepositInput, S as ConnectionController, St as RequestCheckCode, T as ConnectionSession, Tt as AddressBookController, U as RequestMethod, V as SignLogOutcome, W as RequestOrigin, X as PhishingControllerOptions, Y as PhishingController, Z as PhishingState, _t as SparkControllerOptions, at as WithdrawLnurlParams, b as BitcoinWalletHandler, bt as PaymentNote, ct as PaymentParse, dt as PreparedSparkAction, et as PrepareZapParams, f as Eip1193Event, ft as SparkDisplay, gt as SparkController, ht as SparkClientFactory, it as PayParams, j as PendingRequest, jt as EngineStore, k as EvmSignInput, kt as AddressFamily, l as SolanaWalletHandler, lt as PaymentRequest, m as Eip1193Request, mt as SparkAccountState, n as WeblnHandler, nt as ZapRecipient, ot as ParseOptions, p as Eip1193Handler, pt as SparkResult, q as SignatureResult, rt as prepareZap, st as PaymentOption, t as ProviderError, tt as PreparedZap, u as Nip07Handler, ut as parsePayment, vt as SparkControllerState, w as ConnectionScope, wt as Esplora, x as AccountGroup$1, xt as SparkActivity, yt as sparkStore, z as SparkExitInput } from "./errors-Bglz0VYn.mjs";
1
+ import { $ as PrepareZapContext, A as PayInput, At as EngineCollection, B as SignLogEntry, C as ConnectionOrigin, Ct as NetworkController, Dt as AddressBookEntry, E as ConnectionState, Et as AddressBookState, F as RequestControllerState, Ft as createEventBus, G as RiskFinding, H as BrowserOrigin, I as RequestInput, It as Controller, J as PHISHING_REFRESH_MS, K as TransactionController, L as RequestStage, Lt as ControllerOptions, M as REQUEST_TTL_MS, Mt as PublicStore, N as RESIMULATE_AFTER_MS, Nt as EngineLogger, O as PendingConnection, Ot as AddressBookRecord, P as RequestController, Pt as EventBus, Q as PhishingStatus, R as SparkDepositInput, S as ConnectionController, St as RequestCheckCode, T as ConnectionSession, Tt as AddressBookController, U as RequestMethod, V as SignLogOutcome, W as RequestOrigin, X as PhishingControllerOptions, Y as PhishingController, Z as PhishingState, _t as SparkControllerOptions, at as WithdrawLnurlParams, b as BitcoinWalletHandler, bt as PaymentNote, ct as PaymentParse, dt as PreparedSparkAction, et as PrepareZapParams, f as Eip1193Event, ft as SparkDisplay, gt as SparkController, ht as SparkClientFactory, it as PayParams, j as PendingRequest, jt as EngineStore, k as EvmSignInput, kt as AddressFamily, l as SolanaWalletHandler, lt as PaymentRequest, m as Eip1193Request, mt as SparkAccountState, n as WeblnHandler, nt as ZapRecipient, ot as ParseOptions, p as Eip1193Handler, pt as SparkResult, q as SignatureResult, rt as prepareZap, st as PaymentOption, t as ProviderError, tt as PreparedZap, u as Nip07Handler, ut as parsePayment, vt as SparkControllerState, w as ConnectionScope, wt as Esplora, x as AccountGroup$1, xt as SparkActivity, yt as sparkStore, z as SparkExitInput } from "./errors-DpkJneDe.mjs";
2
2
  import { BackupHeader, BackupInfo, InitialFactor, UnlockFactor, Wallet, WalletInfo } from "@qntx/wallet";
3
3
  import { LightningInvoice, SparkExitChain, SparkNetwork } from "@qntx/spark";
4
4
  import { Event, Filter } from "@qntx/nostr";
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { A as newId, B as normalizeAddress, C as exceedsNetworkCap, D as mergeSatPerByte, E as mergeEvmQuote, F as PaymentError, G as invalidParams, H as evmChainId, I as SparkControllerError, J as unsupportedMethod, K as unauthorized, L as categorize, M as submitTx, N as prepareZap, O as mergeSolanaQuote, P as withdrawLnurl, Q as Controller, R as safeDecimals, S as collectChecks, T as feesDiffer, U as ProviderError, V as ConnectionController, W as internalError, X as EngineStoreError, Y as userRejectedRequest, Z as errorMessage, _ as boundedSimulation, a as Nip07Handler, b as feeTiers, c as SessionEvents, d as OriginBusyError, f as REQUEST_TTL_MS, g as SignInOriginError, h as RequestEndedError, i as SolanaWalletHandler, j as replacementStaleReason, k as failTx, l as BlindSigningDisabledError, m as RequestController, n as parsePayment, o as BITCOIN_CHAIN_IDS, p as RESIMULATE_AFTER_MS, q as unrecognizedChain, r as SOLANA_CHAIN_IDS, s as BitcoinWalletHandler, t as WeblnHandler, u as InvalidTokenError, v as BitcoinChainAdapter, w as feeReachesAmount, x as timeoutSignal, y as esplora, z as safeDisplayText } from "./webln-BGKm12wd.mjs";
1
+ import { A as newId, B as normalizeAddress, C as exceedsNetworkCap, D as mergeSatPerByte, E as mergeEvmQuote, F as PaymentError, G as invalidParams, H as evmChainId, I as SparkControllerError, J as unsupportedMethod, K as unauthorized, L as categorize, M as submitTx, N as prepareZap, O as mergeSolanaQuote, P as withdrawLnurl, Q as Controller, R as safeDecimals, S as collectChecks, T as feesDiffer, U as ProviderError, V as ConnectionController, W as internalError, X as EngineStoreError, Y as userRejectedRequest, Z as errorMessage, _ as boundedSimulation, a as Nip07Handler, b as feeTiers, c as SessionEvents, d as OriginBusyError, f as REQUEST_TTL_MS, g as SignInOriginError, h as RequestEndedError, i as SolanaWalletHandler, j as replacementStaleReason, k as failTx, l as BlindSigningDisabledError, m as RequestController, n as parsePayment, o as BITCOIN_CHAIN_IDS, p as RESIMULATE_AFTER_MS, q as unrecognizedChain, r as SOLANA_CHAIN_IDS, s as BitcoinWalletHandler, t as WeblnHandler, u as InvalidTokenError, v as BitcoinChainAdapter, w as feeReachesAmount, x as timeoutSignal, y as esplora, z as safeDisplayText } from "./webln-DzsI7jVb.mjs";
2
2
  import { i as networkById } from "./registry-wYrcuFNc.mjs";
3
3
  import { EVM_RPC_METHODS, INSTALL_ID_HEADER, applyDiff, contains, decodeHashList, encodeHashList, esploraBasePath, networksPath, parseWith, phishingCandidates, phishingHash, phishingListPath, phishingListResponse, rpcPath, servedNetworksResponse } from "./gateway-contract.mjs";
4
4
  import { bytesToHex, hexToBytes, utf8ToBytes } from "@noble/hashes/utils.js";
@@ -3231,9 +3231,16 @@ const createBitcoinRoute = () => {
3231
3231
  const request = {
3232
3232
  kind: "bitcoin.psbt",
3233
3233
  network,
3234
- account,
3234
+ account: {
3235
+ kind: "hd",
3236
+ walletId: account.walletId,
3237
+ groupIndex: account.groupIndex
3238
+ },
3235
3239
  psbt,
3236
- sign: Array.from({ length: txP.inputsLength }, (_, i) => i)
3240
+ sign: Array.from({ length: txP.inputsLength }, (_, i) => ({
3241
+ index: i,
3242
+ template
3243
+ }))
3237
3244
  };
3238
3245
  const intent = decodeBitcoinPsbt(request, ownScripts);
3239
3246
  const vsize = Math.ceil(10.5 + txP.inputsLength * (tap ? 57.5 : 68) + txP.outputsLength * (tap ? 43 : 31));
@@ -3341,12 +3348,20 @@ const createBitcoinRoute = () => {
3341
3348
  const prepareFinish = (ctx, stash, es, account, old, psbt, record, link, requestId, held, flags) => {
3342
3349
  const apis = ctx.options.chains ?? chains(ctx.options.wallet);
3343
3350
  const txP = Transaction.fromPSBT(psbt);
3351
+ if (account.kind !== "hd") throw new Error("imported accounts are not yet supported");
3344
3352
  const request = {
3345
3353
  kind: "bitcoin.psbt",
3346
3354
  network: old.network,
3347
- account,
3355
+ account: {
3356
+ kind: "hd",
3357
+ walletId: account.walletId,
3358
+ groupIndex: account.groupIndex
3359
+ },
3348
3360
  psbt,
3349
- sign: Array.from({ length: txP.inputsLength }, (_, i) => i)
3361
+ sign: Array.from({ length: txP.inputsLength }, (_, i) => ({
3362
+ index: i,
3363
+ template: stash.template
3364
+ }))
3350
3365
  };
3351
3366
  const ownScripts = new Set(stash.changeAddresses.map((a) => hex.encode(scriptPubKey(a, bitcoinNetwork(stash.network).params))));
3352
3367
  const intent = decodeBitcoinPsbt(request, ownScripts);
@@ -3611,8 +3626,9 @@ const createBitcoinRoute = () => {
3611
3626
  /**
3612
3627
  * DApp PSBTs (Bitcoin Wallet Standard `signTransaction`): a dApp-built PSBT carries no derivation
3613
3628
  * data, so the engine adds it for the inputs it was asked to sign — and only for inputs whose
3614
- * prevout script is one of this account's scanned addresses. The kernel re-derives and checks every
3615
- * entry; nothing added here is trusted.
3629
+ * prevout script is one of the account's scanned addresses, under the template the sign entry
3630
+ * names. Outputs to the group's own scripts get the same binding so the kernel marks them as
3631
+ * change-like. The kernel re-derives and checks every entry; nothing added here is trusted.
3616
3632
  */
3617
3633
  const SIGHASH_ALL = 1;
3618
3634
  const SIGHASH_DEFAULT = 0;
@@ -3643,34 +3659,60 @@ const sighashFor = (existing, requested, taproot, index) => {
3643
3659
  if (existing !== void 0 && existing !== SIGHASH_ALL && !(taproot && existing === SIGHASH_DEFAULT)) throw invalid(`input ${index} already has a different sighash than requested`);
3644
3660
  return existing;
3645
3661
  };
3662
+ const DAPP_TEMPLATES = ["btc.bip84", "btc.bip86"];
3646
3663
  /**
3647
- * Enriches and normalizes each dApp PSBT for `account`: the requested inputs must spend scanned
3648
- * addresses of the account's template, get that address's derivation, and agree on the sighash.
3664
+ * Enriches and normalizes each dApp PSBT for `group`: a sign entry's prevout script must be a
3665
+ * scanned address of the template the entry names (a template with no inputs to sign contributes
3666
+ * only its fixed 0/0 address), gets that address's derivation, and agrees on the sighash. Outputs
3667
+ * to any own script get the same derivation binding.
3649
3668
  */
3650
- const prepareDappPsbts = async (apis, es, account, network, psbts) => {
3651
- const { template } = account;
3652
- const derived = await apis.account({
3653
- walletId: account.walletId,
3654
- groupIndex: account.groupIndex,
3655
- template,
3656
- network
3657
- });
3658
- if (!("xpub" in derived) || derived.xpub === void 0) throw new Error("bitcoin account carries no xpub");
3659
- const { xpub, fingerprint, path } = derived;
3660
- const fp = Number.parseInt(fingerprint, 16);
3669
+ const prepareDappPsbts = async (apis, es, group, network, psbts) => {
3661
3670
  const net = bitcoinNetwork(network);
3662
- const base = accountPath(path);
3663
- const taproot = template === "btc.bip86";
3664
- const scanned = [...await scanChain(es, xpub, template, network, net.params, 0), ...await scanChain(es, xpub, template, network, net.params, 1)];
3665
- const own = new Map([...scanned.map((a) => [hex.encode(scriptPubKey(a.address, net.params)), {
3666
- chain: a.chain,
3667
- index: a.index
3668
- }]), [hex.encode(scriptPubKey(account.address, net.params)), {
3669
- chain: 0,
3670
- index: 0
3671
- }]]);
3672
- if (bitcoinAddressFromXpub(xpub, template, network, 0, 0) !== account.address) throw invalid("the account address is not the wallet's address for this purpose");
3671
+ const signing = new Set(psbts.flatMap((p) => p.sign.map((s) => s.template)));
3672
+ const derives = /* @__PURE__ */ new Map();
3673
+ const own = /* @__PURE__ */ new Map();
3674
+ await Promise.all(DAPP_TEMPLATES.map(async (template) => {
3675
+ const derived = await apis.account({
3676
+ walletId: group.walletId,
3677
+ groupIndex: group.groupIndex,
3678
+ template,
3679
+ network
3680
+ });
3681
+ if (!("xpub" in derived) || derived.xpub === void 0) throw new Error("bitcoin account carries no xpub");
3682
+ const { xpub, fingerprint, path } = derived;
3683
+ derives.set(template, {
3684
+ xpub,
3685
+ fp: Number.parseInt(fingerprint, 16),
3686
+ base: accountPath(path)
3687
+ });
3688
+ const scanned = signing.has(template) ? [...await scanChain(es, xpub, template, network, net.params, 0), ...await scanChain(es, xpub, template, network, net.params, 1)] : [{
3689
+ chain: 0,
3690
+ index: 0,
3691
+ address: bitcoinAddressFromXpub(xpub, template, network, 0, 0),
3692
+ used: false
3693
+ }];
3694
+ for (const a of scanned) own.set(hex.encode(scriptPubKey(a.address, net.params)), {
3695
+ template,
3696
+ chain: a.chain,
3697
+ index: a.index
3698
+ });
3699
+ }));
3673
3700
  const ownScripts = new Set(own.keys());
3701
+ const derivation = (template, chain, index) => {
3702
+ const d = derives.get(template);
3703
+ if (d === void 0) throw new Error(`no account derived for ${template}`);
3704
+ return {
3705
+ pubkey: bitcoinPubkeyFromXpub(d.xpub, template, network, chain, index),
3706
+ der: {
3707
+ fingerprint: d.fp,
3708
+ path: [
3709
+ ...d.base,
3710
+ chain,
3711
+ index
3712
+ ]
3713
+ }
3714
+ };
3715
+ };
3674
3716
  return psbts.map((entry) => {
3675
3717
  let tx;
3676
3718
  try {
@@ -3679,25 +3721,17 @@ const prepareDappPsbts = async (apis, es, account, network, psbts) => {
3679
3721
  throw invalid("PSBT failed to decode");
3680
3722
  }
3681
3723
  const inputs = [];
3682
- for (const { index, sigHash } of entry.sign) {
3724
+ for (const { index, sigHash, template } of entry.sign) {
3683
3725
  if (!Number.isSafeInteger(index) || index < 0 || index >= tx.inputsLength) throw invalid(`input ${String(index)} is out of range`);
3684
3726
  const input = tx.getInput(index);
3685
3727
  const prevout = prevoutOf(input);
3686
3728
  const spend = prevout === void 0 ? void 0 : own.get(hex.encode(prevout.script));
3687
- if (prevout === void 0 || spend === void 0) throw invalid(`input ${String(index)} is not this wallet's`);
3688
- const sighashType = sighashFor(input.sighashType, sigHash, taproot, index);
3689
- const pubkey = bitcoinPubkeyFromXpub(xpub, template, network, spend.chain, spend.index);
3690
- const der = {
3691
- fingerprint: fp,
3692
- path: [
3693
- ...base,
3694
- spend.chain,
3695
- spend.index
3696
- ]
3697
- };
3729
+ if (prevout === void 0 || spend === void 0 || spend.template !== template) throw invalid(`input ${String(index)} is not this account's`);
3730
+ const sighashType = sighashFor(input.sighashType, sigHash, template === "btc.bip86", index);
3731
+ const { pubkey, der } = derivation(template, spend.chain, spend.index);
3698
3732
  tx.updateInput(index, {
3699
3733
  ...sighashType === void 0 ? {} : { sighashType },
3700
- ...taproot ? {
3734
+ ...template === "btc.bip86" ? {
3701
3735
  tapInternalKey: pubkey,
3702
3736
  tapBip32Derivation: [[pubkey, {
3703
3737
  hashes: [],
@@ -3708,20 +3742,36 @@ const prepareDappPsbts = async (apis, es, account, network, psbts) => {
3708
3742
  inputs.push({
3709
3743
  index,
3710
3744
  value: Number(prevout.amount),
3711
- sigHash
3745
+ sigHash,
3746
+ template
3712
3747
  });
3713
3748
  }
3749
+ for (let i = 0; i < tx.outputsLength; i++) {
3750
+ const output = tx.getOutput(i);
3751
+ const bound = output.script === void 0 ? void 0 : own.get(hex.encode(output.script));
3752
+ if (bound === void 0) continue;
3753
+ const { pubkey, der } = derivation(bound.template, bound.chain, bound.index);
3754
+ tx.updateOutput(i, bound.template === "btc.bip86" ? {
3755
+ tapInternalKey: pubkey,
3756
+ tapBip32Derivation: [[pubkey, {
3757
+ hashes: [],
3758
+ der
3759
+ }]]
3760
+ } : { bip32Derivation: [[pubkey, der]] }, true);
3761
+ }
3714
3762
  const request = normalizeBitcoin({
3715
3763
  kind: "bitcoin.psbt",
3716
3764
  network,
3717
3765
  account: {
3718
3766
  kind: "hd",
3719
- walletId: account.walletId,
3720
- groupIndex: account.groupIndex,
3721
- template
3767
+ walletId: group.walletId,
3768
+ groupIndex: group.groupIndex
3722
3769
  },
3723
3770
  psbt: tx.toPSBT(0),
3724
- sign: inputs.map((i) => i.index).sort((a, b) => a - b)
3771
+ sign: inputs.map(({ index, template }) => ({
3772
+ index,
3773
+ template
3774
+ }))
3725
3775
  });
3726
3776
  if (request.kind !== "bitcoin.psbt") throw invalid("unexpected request kind");
3727
3777
  return {
@@ -3736,19 +3786,11 @@ const prepareDappPsbts = async (apis, es, account, network, psbts) => {
3736
3786
  * finalize — a PSBT with inputs this wallet did not sign cannot be broadcast — before any is
3737
3787
  * broadcast.
3738
3788
  */
3739
- const signDappPsbts = async (apis, account, es, prepared, send, verify) => {
3789
+ const signDappPsbts = async (apis, es, prepared, send, verify) => {
3740
3790
  const results = [];
3741
3791
  for (const { request } of prepared) {
3742
3792
  const result = await apis.sign({
3743
- request: {
3744
- ...request,
3745
- account: {
3746
- kind: "hd",
3747
- walletId: account.walletId,
3748
- groupIndex: account.groupIndex,
3749
- template: account.template
3750
- }
3751
- },
3793
+ request,
3752
3794
  verify
3753
3795
  });
3754
3796
  if (result.kind !== "bitcoin.psbt" || !(result.signedPsbt instanceof Uint8Array)) throw new Error("unexpected bitcoin sign result");
@@ -6516,8 +6558,8 @@ function createWalletEngine(options) {
6516
6558
  };
6517
6559
  },
6518
6560
  bitcoinPrepare: async (account, network, psbts) => prepareDappPsbts(chains(options.wallet), networks.esplora(network), account, network, psbts),
6519
- bitcoinSignPsbts: async (account, network, prepared, send, verify) => {
6520
- const { signedPsbts, txids } = await signDappPsbts(chains(options.wallet), account, networks.esplora(network), prepared, send, verify);
6561
+ bitcoinSignPsbts: async (_account, network, prepared, send, verify) => {
6562
+ const { signedPsbts, txids } = await signDappPsbts(chains(options.wallet), networks.esplora(network), prepared, send, verify);
6521
6563
  return {
6522
6564
  kind: "bitcoin.psbts",
6523
6565
  signedPsbts,