@arkade-os/sdk 0.4.70 → 0.4.72

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +29 -0
  2. package/dist/adapters/expo.cjs +5 -5
  3. package/dist/adapters/expo.d.cts +2 -2
  4. package/dist/adapters/expo.d.ts +2 -2
  5. package/dist/adapters/expo.js +3 -3
  6. package/dist/adapters/indexedDB.cjs +5 -5
  7. package/dist/adapters/indexedDB.js +4 -4
  8. package/dist/{asyncStorageTaskQueue-BgUJN-3X.d.ts → asyncStorageTaskQueue-DhhNZc4v.d.ts} +1 -1
  9. package/dist/{asyncStorageTaskQueue-Cstx6hS7.d.cts → asyncStorageTaskQueue-s5lUGWxu.d.cts} +1 -1
  10. package/dist/{chunk-JJ7AXR4O.cjs → chunk-4BWZ437E.cjs} +21 -17
  11. package/dist/chunk-4BWZ437E.cjs.map +1 -0
  12. package/dist/{chunk-3KW4TWP2.cjs → chunk-4C5PMGBB.cjs} +51 -25
  13. package/dist/chunk-4C5PMGBB.cjs.map +1 -0
  14. package/dist/{chunk-TXSF2DKX.js → chunk-5GQFYVWP.js} +30 -5
  15. package/dist/chunk-5GQFYVWP.js.map +1 -0
  16. package/dist/{chunk-57636V35.cjs → chunk-6FTHFJAN.cjs} +30 -4
  17. package/dist/chunk-6FTHFJAN.cjs.map +1 -0
  18. package/dist/{chunk-JVHO6XHG.js → chunk-BHLYB44A.js} +476 -78
  19. package/dist/chunk-BHLYB44A.js.map +1 -0
  20. package/dist/{chunk-6UM55KPZ.js → chunk-CB6QPAO5.js} +3 -3
  21. package/dist/{chunk-6UM55KPZ.js.map → chunk-CB6QPAO5.js.map} +1 -1
  22. package/dist/{chunk-IUFTICRY.js → chunk-CZPBPMO2.js} +4 -4
  23. package/dist/{chunk-IUFTICRY.js.map → chunk-CZPBPMO2.js.map} +1 -1
  24. package/dist/{chunk-F5E7LI6G.js → chunk-IGER5FPC.js} +37 -11
  25. package/dist/chunk-IGER5FPC.js.map +1 -0
  26. package/dist/{chunk-B73Q75IL.cjs → chunk-KDMHEWTD.cjs} +10 -10
  27. package/dist/{chunk-B73Q75IL.cjs.map → chunk-KDMHEWTD.cjs.map} +1 -1
  28. package/dist/{chunk-3OKEUDHU.cjs → chunk-NPM5YZBC.cjs} +49 -49
  29. package/dist/{chunk-3OKEUDHU.cjs.map → chunk-NPM5YZBC.cjs.map} +1 -1
  30. package/dist/{chunk-UG3EZDLF.js → chunk-S5PUFSXC.js} +8 -4
  31. package/dist/chunk-S5PUFSXC.js.map +1 -0
  32. package/dist/{chunk-XTCOSZ34.cjs → chunk-U5I3ITV7.cjs} +907 -507
  33. package/dist/chunk-U5I3ITV7.cjs.map +1 -0
  34. package/dist/contracts/handlers/index.cjs +9 -9
  35. package/dist/contracts/handlers/index.d.cts +3 -3
  36. package/dist/contracts/handlers/index.d.ts +3 -3
  37. package/dist/contracts/handlers/index.js +2 -2
  38. package/dist/{delegate-DrwIar11.d.cts → delegate-BJp8f6LT.d.cts} +1 -1
  39. package/dist/{delegate-BPdzTbwN.d.ts → delegate-Ckz_TWzM.d.ts} +1 -1
  40. package/dist/{hdWalletCapable-D4WH35z0.d.cts → hdWalletCapable-DA9bJ5eB.d.cts} +2 -2
  41. package/dist/{hdWalletCapable-DyxCiNVE.d.ts → hdWalletCapable-DABgAD-T.d.ts} +2 -2
  42. package/dist/{index-TZJvbIaA.d.ts → index-B8xrELXY.d.ts} +2 -2
  43. package/dist/{index-BqhpAqqj.d.cts → index-DSbDm0Io.d.cts} +2 -2
  44. package/dist/{index-dWRqYSdS.d.ts → index-Dg0-TvBQ.d.cts} +149 -5
  45. package/dist/{index-dWRqYSdS.d.cts → index-Dg0-TvBQ.d.ts} +149 -5
  46. package/dist/index.cjs +309 -297
  47. package/dist/index.d.cts +91 -12
  48. package/dist/index.d.ts +91 -12
  49. package/dist/index.js +4 -4
  50. package/dist/repositories/realm/index.cjs +19 -19
  51. package/dist/repositories/realm/index.d.cts +2 -2
  52. package/dist/repositories/realm/index.d.ts +2 -2
  53. package/dist/repositories/realm/index.js +5 -5
  54. package/dist/repositories/sqlite/index.cjs +18 -18
  55. package/dist/repositories/sqlite/index.d.cts +2 -2
  56. package/dist/repositories/sqlite/index.d.ts +2 -2
  57. package/dist/repositories/sqlite/index.js +5 -5
  58. package/dist/{taskRunner-CzYKyJ9c.d.cts → taskRunner-BH_FxaNI.d.cts} +1 -1
  59. package/dist/{taskRunner-D2fnbqYw.d.ts → taskRunner-DrVz2QZs.d.ts} +1 -1
  60. package/dist/wallet/expo/background.cjs +14 -14
  61. package/dist/wallet/expo/background.d.cts +3 -3
  62. package/dist/wallet/expo/background.d.ts +3 -3
  63. package/dist/wallet/expo/background.js +6 -6
  64. package/dist/wallet/expo/index.cjs +14 -14
  65. package/dist/wallet/expo/index.d.cts +4 -4
  66. package/dist/wallet/expo/index.d.ts +4 -4
  67. package/dist/wallet/expo/index.js +5 -5
  68. package/dist/worker/expo/index.cjs +9 -9
  69. package/dist/worker/expo/index.d.cts +4 -4
  70. package/dist/worker/expo/index.d.ts +4 -4
  71. package/dist/worker/expo/index.js +5 -5
  72. package/package.json +1 -1
  73. package/dist/chunk-3KW4TWP2.cjs.map +0 -1
  74. package/dist/chunk-57636V35.cjs.map +0 -1
  75. package/dist/chunk-F5E7LI6G.js.map +0 -1
  76. package/dist/chunk-JJ7AXR4O.cjs.map +0 -1
  77. package/dist/chunk-JVHO6XHG.js.map +0 -1
  78. package/dist/chunk-TXSF2DKX.js.map +0 -1
  79. package/dist/chunk-UG3EZDLF.js.map +0 -1
  80. package/dist/chunk-XTCOSZ34.cjs.map +0 -1
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
- var chunk3KW4TWP2_cjs = require('./chunk-3KW4TWP2.cjs');
4
- var chunk3OKEUDHU_cjs = require('./chunk-3OKEUDHU.cjs');
5
- var chunk57636V35_cjs = require('./chunk-57636V35.cjs');
3
+ var chunk4C5PMGBB_cjs = require('./chunk-4C5PMGBB.cjs');
4
+ var chunkNPM5YZBC_cjs = require('./chunk-NPM5YZBC.cjs');
5
+ var chunk6FTHFJAN_cjs = require('./chunk-6FTHFJAN.cjs');
6
6
  var chunk5BLDMQED_cjs = require('./chunk-5BLDMQED.cjs');
7
7
  var utils_js = require('@scure/btc-signer/utils.js');
8
8
  var btcSigner = require('@scure/btc-signer');
@@ -188,7 +188,7 @@ var TreeSignerSession = class _TreeSignerSession {
188
188
  noncesByPubkey.set(base.hex.encode(myPublicKey.subarray(1)), myNonce);
189
189
  const tx = this.graph.find(txid);
190
190
  if (!tx) throw new Error(`missing tx for txid ${txid}`);
191
- const cosigners = chunk57636V35_cjs.getArkPsbtFields(tx.root, 0, chunk57636V35_cjs.CosignerPublicKey).map(
191
+ const cosigners = chunk6FTHFJAN_cjs.getArkPsbtFields(tx.root, 0, chunk6FTHFJAN_cjs.CosignerPublicKey).map(
192
192
  (c) => base.hex.encode(c.key.subarray(1))
193
193
  // xonly pubkey
194
194
  );
@@ -240,7 +240,7 @@ var TreeSignerSession = class _TreeSignerSession {
240
240
  if (!aggNonce) throw new Error("missing aggregate nonce");
241
241
  const prevoutAmounts = [];
242
242
  const prevoutScripts = [];
243
- const cosigners = chunk57636V35_cjs.getArkPsbtFields(g.root, 0, chunk57636V35_cjs.CosignerPublicKey).map((c) => c.key);
243
+ const cosigners = chunk6FTHFJAN_cjs.getArkPsbtFields(g.root, 0, chunk6FTHFJAN_cjs.CosignerPublicKey).map((c) => c.key);
244
244
  const { finalKey } = aggregateKeys(cosigners, true, {
245
245
  taprootTweak: this.scriptRoot
246
246
  });
@@ -323,7 +323,7 @@ var SingleKey = class _SingleKey {
323
323
  async sign(tx, inputIndexes) {
324
324
  const txCpy = tx.clone();
325
325
  if (!inputIndexes) {
326
- chunk57636V35_cjs.assertAllowedSighashTypes(txCpy, ALLOWED_SIGHASH);
326
+ chunk6FTHFJAN_cjs.assertAllowedSighashTypes(txCpy, ALLOWED_SIGHASH);
327
327
  try {
328
328
  if (!txCpy.sign(this.key, ALLOWED_SIGHASH)) {
329
329
  throw new Error("Failed to sign transaction");
@@ -432,7 +432,7 @@ var SeedIdentity = class _SeedIdentity {
432
432
  let network;
433
433
  if ("descriptor" in opts && typeof opts.descriptor === "string") {
434
434
  descriptor = opts.descriptor;
435
- network = chunk3OKEUDHU_cjs.isMainnetDescriptor(descriptor) ? descriptorsScure.networks.bitcoin : descriptorsScure.networks.testnet;
435
+ network = chunkNPM5YZBC_cjs.isMainnetDescriptor(descriptor) ? descriptorsScure.networks.bitcoin : descriptorsScure.networks.testnet;
436
436
  } else {
437
437
  network = opts.isMainnet ?? true ? descriptorsScure.networks.bitcoin : descriptorsScure.networks.testnet;
438
438
  descriptor = descriptorsScure.scriptExpressions.trBIP32({
@@ -530,7 +530,7 @@ var SeedIdentity = class _SeedIdentity {
530
530
  * `StaticDescriptorProvider` for legacy single-key wallets.
531
531
  */
532
532
  isOurs(descriptor) {
533
- return chunk3OKEUDHU_cjs.descriptorIsOurs(descriptor, this.descriptor, utils_js.pubSchnorr(this.derivedKey));
533
+ return chunkNPM5YZBC_cjs.descriptorIsOurs(descriptor, this.descriptor, utils_js.pubSchnorr(this.derivedKey));
534
534
  }
535
535
  /**
536
536
  * Signs each request with the key derived from its descriptor.
@@ -579,7 +579,7 @@ var SeedIdentity = class _SeedIdentity {
579
579
  }
580
580
  // ── internal helpers ─────────────────────────────────────────────
581
581
  derivePrivateKeyForDescriptor(descriptor) {
582
- const network = chunk3OKEUDHU_cjs.isMainnetDescriptor(descriptor) ? descriptorsScure.networks.bitcoin : descriptorsScure.networks.testnet;
582
+ const network = chunkNPM5YZBC_cjs.isMainnetDescriptor(descriptor) ? descriptorsScure.networks.bitcoin : descriptorsScure.networks.testnet;
583
583
  const expansion = descriptorsScure.expand({ descriptor, network });
584
584
  if (expansion.isRanged) {
585
585
  throw new Error(
@@ -604,7 +604,7 @@ var SeedIdentity = class _SeedIdentity {
604
604
  signTxWithKey(tx, key, inputIndexes) {
605
605
  const txCpy = tx.clone();
606
606
  if (!inputIndexes) {
607
- chunk57636V35_cjs.assertAllowedSighashTypes(txCpy, ALLOWED_SIGHASH2);
607
+ chunk6FTHFJAN_cjs.assertAllowedSighashTypes(txCpy, ALLOWED_SIGHASH2);
608
608
  try {
609
609
  if (!txCpy.sign(key, ALLOWED_SIGHASH2)) {
610
610
  throw new Error("Failed to sign transaction");
@@ -666,7 +666,7 @@ var ReadonlyDescriptorIdentity = class _ReadonlyDescriptorIdentity {
666
666
  */
667
667
  descriptor;
668
668
  constructor(descriptor) {
669
- const network = chunk3OKEUDHU_cjs.isMainnetDescriptor(descriptor) ? descriptorsScure.networks.bitcoin : descriptorsScure.networks.testnet;
669
+ const network = chunkNPM5YZBC_cjs.isMainnetDescriptor(descriptor) ? descriptorsScure.networks.bitcoin : descriptorsScure.networks.testnet;
670
670
  let expansion;
671
671
  try {
672
672
  expansion = descriptorsScure.expand({ descriptor, network, index: 0 });
@@ -716,7 +716,7 @@ var ReadonlyDescriptorIdentity = class _ReadonlyDescriptorIdentity {
716
716
  * `StaticDescriptorProvider` for legacy single-key wallets.
717
717
  */
718
718
  isOurs(descriptor) {
719
- return chunk3OKEUDHU_cjs.descriptorIsOurs(descriptor, this.descriptor, this.indexZero.pubkey);
719
+ return chunkNPM5YZBC_cjs.descriptorIsOurs(descriptor, this.descriptor, this.indexZero.pubkey);
720
720
  }
721
721
  };
722
722
  function serializeSeedOwnedSigningIdentity(identity) {
@@ -878,10 +878,10 @@ var DescriptorIdentity = class {
878
878
  this.base = base;
879
879
  }
880
880
  async xOnlyPublicKey() {
881
- return chunk3OKEUDHU_cjs.deriveDescriptorLeafPubKey(this.descriptor);
881
+ return chunkNPM5YZBC_cjs.deriveDescriptorLeafPubKey(this.descriptor);
882
882
  }
883
883
  async compressedPublicKey() {
884
- return chunk3OKEUDHU_cjs.deriveDescriptorLeafCompressedPubKey(this.descriptor);
884
+ return chunkNPM5YZBC_cjs.deriveDescriptorLeafCompressedPubKey(this.descriptor);
885
885
  }
886
886
  async sign(tx, inputIndexes) {
887
887
  const [signed] = await this.signer.signWithDescriptor([
@@ -949,12 +949,12 @@ var WalletCannotAllocateAddressError = class extends Error {
949
949
  };
950
950
  async function resolveDescriptorSigner(descriptor, identity, provider) {
951
951
  const owner = provider?.isOurs(descriptor) ? provider : isHDCapableIdentity(identity) && identity.isOurs(descriptor) ? identity : void 0;
952
- if (owner && chunk3OKEUDHU_cjs.parseHDDescriptor(descriptor)) {
952
+ if (owner && chunkNPM5YZBC_cjs.parseHDDescriptor(descriptor)) {
953
953
  return new DescriptorIdentity({ descriptor, signer: owner, base: identity });
954
954
  }
955
955
  let key;
956
956
  try {
957
- key = chunk3OKEUDHU_cjs.deriveDescriptorLeafPubKey(descriptor);
957
+ key = chunkNPM5YZBC_cjs.deriveDescriptorLeafPubKey(descriptor);
958
958
  } catch {
959
959
  throw new ForeignDescriptorError(descriptor);
960
960
  }
@@ -1329,14 +1329,14 @@ function buildSaltedPreimageMessage(xonly, salt) {
1329
1329
  }
1330
1330
  var PREIMAGE_INDEX = 0;
1331
1331
  function isPerArtifactDescriptor(descriptor) {
1332
- return chunk3OKEUDHU_cjs.parseHDDescriptor(descriptor) !== null;
1332
+ return chunkNPM5YZBC_cjs.parseHDDescriptor(descriptor) !== null;
1333
1333
  }
1334
1334
  async function provisionDescriptor(wallet) {
1335
1335
  const allocated = isHDAllocationCapable(wallet) ? await wallet.getNextSigningDescriptor() : void 0;
1336
- return allocated ?? await chunk3OKEUDHU_cjs.identityDescriptor(wallet.identity);
1336
+ return allocated ?? await chunkNPM5YZBC_cjs.identityDescriptor(wallet.identity);
1337
1337
  }
1338
1338
  async function provisionRefundKey(wallet) {
1339
- const descriptor = await chunk3OKEUDHU_cjs.identityDescriptor(wallet.identity);
1339
+ const descriptor = await chunkNPM5YZBC_cjs.identityDescriptor(wallet.identity);
1340
1340
  const signer = await contractSigner(wallet, descriptor);
1341
1341
  const pubkey = await signer.xOnlyPublicKey();
1342
1342
  const identityPubkey = await wallet.identity.xOnlyPublicKey();
@@ -1346,7 +1346,7 @@ async function provisionRefundKey(wallet) {
1346
1346
  );
1347
1347
  }
1348
1348
  const address = await wallet.getAddress();
1349
- const { pkScript } = chunk57636V35_cjs.ArkAddress.decode(address);
1349
+ const { pkScript } = chunk6FTHFJAN_cjs.ArkAddress.decode(address);
1350
1350
  return { descriptor, pubkey, pkScript, address };
1351
1351
  }
1352
1352
  async function provisionClaimSecret(wallet, opts = {}) {
@@ -1392,7 +1392,7 @@ async function contractSigner(wallet, descriptor) {
1392
1392
  const signer = isHDWalletCapable(wallet) ? await wallet.signerForDescriptor(descriptor) : wallet.identity;
1393
1393
  let expected;
1394
1394
  try {
1395
- expected = chunk3OKEUDHU_cjs.deriveDescriptorLeafPubKey(descriptor);
1395
+ expected = chunkNPM5YZBC_cjs.deriveDescriptorLeafPubKey(descriptor);
1396
1396
  } catch (cause) {
1397
1397
  throw new ForeignDescriptorError(descriptor, { cause });
1398
1398
  }
@@ -1611,14 +1611,14 @@ var RestDelegateProvider = class {
1611
1611
  */
1612
1612
  async delegate(intent, forfeitTxs, options) {
1613
1613
  const url = `${this.url}/v1/delegate`;
1614
- const response = await chunk57636V35_cjs.baseFetch(url, {
1614
+ const response = await chunk6FTHFJAN_cjs.baseFetch(url, {
1615
1615
  method: "POST",
1616
1616
  headers: {
1617
1617
  "Content-Type": "application/json"
1618
1618
  },
1619
1619
  body: JSON.stringify({
1620
1620
  intent: {
1621
- message: chunk57636V35_cjs.Intent.encodeMessage(intent.message),
1621
+ message: chunk6FTHFJAN_cjs.Intent.encodeMessage(intent.message),
1622
1622
  proof: intent.proof
1623
1623
  },
1624
1624
  forfeit_txs: forfeitTxs,
@@ -1638,7 +1638,7 @@ var RestDelegateProvider = class {
1638
1638
  */
1639
1639
  async getDelegateInfo() {
1640
1640
  const url = `${this.url}/v1/delegator/info`;
1641
- const response = await chunk57636V35_cjs.rateGate.runHttp(url, () => chunk57636V35_cjs.baseFetch(url));
1641
+ const response = await chunk6FTHFJAN_cjs.rateGate.runHttp(url, () => chunk6FTHFJAN_cjs.baseFetch(url));
1642
1642
  if (!response.ok) {
1643
1643
  const errorText2 = await response.text();
1644
1644
  throw new Error(`Failed to get delegate info: ${errorText2}`);
@@ -1663,7 +1663,7 @@ var ESPLORA_URL = {
1663
1663
  regtest: "http://localhost:3000/api"
1664
1664
  };
1665
1665
  var EsploraProvider = class {
1666
- constructor(baseUrl = ESPLORA_URL[chunk57636V35_cjs.DEFAULT_NETWORK_NAME], opts) {
1666
+ constructor(baseUrl = ESPLORA_URL[chunk6FTHFJAN_cjs.DEFAULT_NETWORK_NAME], opts) {
1667
1667
  this.baseUrl = baseUrl;
1668
1668
  this.pollingInterval = opts?.pollingInterval ?? 15e3;
1669
1669
  this.forcePolling = opts?.forcePolling ?? false;
@@ -1682,14 +1682,14 @@ var EsploraProvider = class {
1682
1682
  */
1683
1683
  addressWatches = /* @__PURE__ */ new Map();
1684
1684
  async getCoins(address) {
1685
- const response = await chunk57636V35_cjs.baseFetch(`${this.baseUrl}/address/${address}/utxo`);
1685
+ const response = await chunk6FTHFJAN_cjs.baseFetch(`${this.baseUrl}/address/${address}/utxo`);
1686
1686
  if (!response.ok) {
1687
1687
  throw new Error(`Failed to fetch UTXOs: ${response.statusText}`);
1688
1688
  }
1689
1689
  return response.json();
1690
1690
  }
1691
1691
  async getFeeRate() {
1692
- const response = await chunk57636V35_cjs.baseFetch(`${this.baseUrl}/fee-estimates`);
1692
+ const response = await chunk6FTHFJAN_cjs.baseFetch(`${this.baseUrl}/fee-estimates`);
1693
1693
  if (response.status === 404) {
1694
1694
  return void 0;
1695
1695
  }
@@ -1710,7 +1710,7 @@ var EsploraProvider = class {
1710
1710
  }
1711
1711
  }
1712
1712
  async getTxOutspends(txid) {
1713
- const response = await chunk57636V35_cjs.baseFetch(`${this.baseUrl}/tx/${txid}/outspends`);
1713
+ const response = await chunk6FTHFJAN_cjs.baseFetch(`${this.baseUrl}/tx/${txid}/outspends`);
1714
1714
  if (!response.ok) {
1715
1715
  const error = await response.text();
1716
1716
  throw new Error(`Failed to get transaction outspends: ${error}`);
@@ -1718,7 +1718,7 @@ var EsploraProvider = class {
1718
1718
  return response.json();
1719
1719
  }
1720
1720
  async getTransactions(address) {
1721
- const response = await chunk57636V35_cjs.baseFetch(`${this.baseUrl}/address/${address}/txs`);
1721
+ const response = await chunk6FTHFJAN_cjs.baseFetch(`${this.baseUrl}/address/${address}/txs`);
1722
1722
  if (!response.ok) {
1723
1723
  const error = await response.text();
1724
1724
  throw new Error(`Failed to get transactions: ${error}`);
@@ -1731,14 +1731,14 @@ var EsploraProvider = class {
1731
1731
  * usable as a change probe for the polling fallback.
1732
1732
  */
1733
1733
  async getAddressStats(address) {
1734
- const response = await chunk57636V35_cjs.baseFetch(`${this.baseUrl}/address/${address}`);
1734
+ const response = await chunk6FTHFJAN_cjs.baseFetch(`${this.baseUrl}/address/${address}`);
1735
1735
  if (!response.ok) {
1736
1736
  throw new Error(`Failed to get address stats: ${response.statusText}`);
1737
1737
  }
1738
1738
  return response.json();
1739
1739
  }
1740
1740
  async getRawTransaction(txid) {
1741
- const response = await chunk57636V35_cjs.baseFetch(`${this.baseUrl}/tx/${txid}/hex`);
1741
+ const response = await chunk6FTHFJAN_cjs.baseFetch(`${this.baseUrl}/tx/${txid}/hex`);
1742
1742
  if (!response.ok) {
1743
1743
  const error = await response.text();
1744
1744
  throw new Error(`Failed to get raw transaction ${txid}: ${error}`);
@@ -1746,7 +1746,7 @@ var EsploraProvider = class {
1746
1746
  return base.hex.decode((await response.text()).trim());
1747
1747
  }
1748
1748
  async getTxStatus(txid) {
1749
- const txresponse = await chunk57636V35_cjs.baseFetch(`${this.baseUrl}/tx/${txid}`);
1749
+ const txresponse = await chunk6FTHFJAN_cjs.baseFetch(`${this.baseUrl}/tx/${txid}`);
1750
1750
  if (!txresponse.ok) {
1751
1751
  throw new Error(txresponse.statusText);
1752
1752
  }
@@ -1754,7 +1754,7 @@ var EsploraProvider = class {
1754
1754
  if (!tx.status.confirmed) {
1755
1755
  return { confirmed: false };
1756
1756
  }
1757
- const response = await chunk57636V35_cjs.baseFetch(`${this.baseUrl}/tx/${txid}/status`);
1757
+ const response = await chunk6FTHFJAN_cjs.baseFetch(`${this.baseUrl}/tx/${txid}/status`);
1758
1758
  if (!response.ok) {
1759
1759
  throw new Error(`Failed to get transaction status: ${response.statusText}`);
1760
1760
  }
@@ -2038,9 +2038,9 @@ var EsploraProvider = class {
2038
2038
  return { subscribers, teardown, started };
2039
2039
  }
2040
2040
  async getChainTip() {
2041
- let tipBlocks = await chunk57636V35_cjs.baseFetch(`${this.baseUrl}/blocks`);
2041
+ let tipBlocks = await chunk6FTHFJAN_cjs.baseFetch(`${this.baseUrl}/blocks`);
2042
2042
  if (tipBlocks.status === 404) {
2043
- tipBlocks = await chunk57636V35_cjs.baseFetch(`${this.baseUrl}/v1/blocks`);
2043
+ tipBlocks = await chunk6FTHFJAN_cjs.baseFetch(`${this.baseUrl}/v1/blocks`);
2044
2044
  }
2045
2045
  if (!tipBlocks.ok) {
2046
2046
  throw new Error(`Failed to get chain tip: ${tipBlocks.statusText}`);
@@ -2062,7 +2062,7 @@ var EsploraProvider = class {
2062
2062
  };
2063
2063
  }
2064
2064
  async broadcastPackage(parent, child) {
2065
- const response = await chunk57636V35_cjs.baseFetch(`${this.baseUrl}/txs/package`, {
2065
+ const response = await chunk6FTHFJAN_cjs.baseFetch(`${this.baseUrl}/txs/package`, {
2066
2066
  method: "POST",
2067
2067
  headers: {
2068
2068
  "Content-Type": "application/json"
@@ -2078,7 +2078,7 @@ var EsploraProvider = class {
2078
2078
  return result;
2079
2079
  }
2080
2080
  async broadcastTx(tx) {
2081
- const response = await chunk57636V35_cjs.baseFetch(`${this.baseUrl}/tx`, {
2081
+ const response = await chunk6FTHFJAN_cjs.baseFetch(`${this.baseUrl}/tx`, {
2082
2082
  method: "POST",
2083
2083
  headers: {
2084
2084
  "Content-Type": "text/plain"
@@ -2261,7 +2261,7 @@ function findP2AOutput(tx) {
2261
2261
  var CHILD_DUST_AMOUNT = 546;
2262
2262
  function buildAnchorChild(params) {
2263
2263
  const { parent, feeRate, fundingCoins, changeAddress, tapInternalKey, network } = params;
2264
- const child = new chunk57636V35_cjs.Transaction({ version: 3, allowLegacyWitnessUtxo: true });
2264
+ const child = new chunk6FTHFJAN_cjs.Transaction({ version: 3, allowLegacyWitnessUtxo: true });
2265
2265
  child.addInput(findP2AOutput(parent));
2266
2266
  const estimator = TxWeightEstimator.create().addP2AInput();
2267
2267
  for (const _ of fundingCoins) {
@@ -2309,7 +2309,7 @@ function buildForfeitTx(inputs, forfeitPkScript, txLocktime) {
2309
2309
  );
2310
2310
  }
2311
2311
  function buildForfeitTxWithOutput(inputs, output, txLocktime) {
2312
- const tx = new chunk57636V35_cjs.Transaction({
2312
+ const tx = new chunk6FTHFJAN_cjs.Transaction({
2313
2313
  version: 3,
2314
2314
  lockTime: txLocktime
2315
2315
  });
@@ -2385,7 +2385,7 @@ function validateVtxoTxGraph(graph, roundTransaction, sweepTapTreeRoot) {
2385
2385
  if (previousScriptKey.length !== 32) {
2386
2386
  throw new Error(`parent output ${childIndex} has invalid script`);
2387
2387
  }
2388
- const cosigners = chunk57636V35_cjs.getArkPsbtFields(child.root, 0, chunk57636V35_cjs.CosignerPublicKey);
2388
+ const cosigners = chunk6FTHFJAN_cjs.getArkPsbtFields(child.root, 0, chunk6FTHFJAN_cjs.CosignerPublicKey);
2389
2389
  if (cosigners.length === 0) {
2390
2390
  throw ErrMissingCosignersPublicKeys;
2391
2391
  }
@@ -2443,7 +2443,7 @@ var EmulatorPacket = class _EmulatorPacket {
2443
2443
  return new _EmulatorPacket(entries);
2444
2444
  }
2445
2445
  static fromBytes(data) {
2446
- const reader = new chunk3KW4TWP2_cjs.BufferReader(data);
2446
+ const reader = new chunk4C5PMGBB_cjs.BufferReader(data);
2447
2447
  const entryCount = reader.readCompactSize();
2448
2448
  const entries = [];
2449
2449
  for (let i = 0; i < entryCount; i++) {
@@ -2461,7 +2461,7 @@ var EmulatorPacket = class _EmulatorPacket {
2461
2461
  return _EmulatorPacket.PACKET_TYPE;
2462
2462
  }
2463
2463
  serialize() {
2464
- const writer = new chunk3KW4TWP2_cjs.BufferWriter();
2464
+ const writer = new chunk4C5PMGBB_cjs.BufferWriter();
2465
2465
  writer.writeCompactSize(this.entries.length);
2466
2466
  for (const entry of this.entries) {
2467
2467
  writer.writeUint16LE(entry.vin);
@@ -2548,7 +2548,7 @@ var Extension = class _Extension {
2548
2548
  `expected magic prefix ${base.hex.encode(ARKADE_MAGIC)}, got ${base.hex.encode(payload.slice(0, Math.min(payload.length, ARKADE_MAGIC.length)))}`
2549
2549
  );
2550
2550
  }
2551
- const reader = new chunk3KW4TWP2_cjs.BufferReader(payload.slice(ARKADE_MAGIC.length));
2551
+ const reader = new chunk4C5PMGBB_cjs.BufferReader(payload.slice(ARKADE_MAGIC.length));
2552
2552
  const packets = [];
2553
2553
  while (reader.remaining() > 0) {
2554
2554
  const packetType = reader.readByte();
@@ -2622,7 +2622,7 @@ var Extension = class _Extension {
2622
2622
  */
2623
2623
  getAssetPacket() {
2624
2624
  for (const p of this.packets) {
2625
- if (p instanceof chunk3KW4TWP2_cjs.Packet) {
2625
+ if (p instanceof chunk4C5PMGBB_cjs.Packet) {
2626
2626
  return p;
2627
2627
  }
2628
2628
  }
@@ -2660,8 +2660,8 @@ var Extension = class _Extension {
2660
2660
  };
2661
2661
  function parsePacket(packetType, data) {
2662
2662
  switch (packetType) {
2663
- case chunk3KW4TWP2_cjs.Packet.PACKET_TYPE:
2664
- return chunk3KW4TWP2_cjs.Packet.fromBytes(data);
2663
+ case chunk4C5PMGBB_cjs.Packet.PACKET_TYPE:
2664
+ return chunk4C5PMGBB_cjs.Packet.fromBytes(data);
2665
2665
  case EmulatorPacket.PACKET_TYPE:
2666
2666
  return EmulatorPacket.fromBytes(data);
2667
2667
  default:
@@ -2708,16 +2708,16 @@ function buildOpReturnScript(data) {
2708
2708
  }
2709
2709
  return script;
2710
2710
  }
2711
- var ErrOffchainOutputNotFound = (address) => new chunk57636V35_cjs.ServerResponseMismatchError(`offchain send output not found: ${address}`);
2712
- var ErrInvalidAssetOutputAmount = (got, want, assetId) => new chunk57636V35_cjs.ServerResponseMismatchError(
2711
+ var ErrOffchainOutputNotFound = (address) => new chunk6FTHFJAN_cjs.ServerResponseMismatchError(`offchain send output not found: ${address}`);
2712
+ var ErrInvalidAssetOutputAmount = (got, want, assetId) => new chunk6FTHFJAN_cjs.ServerResponseMismatchError(
2713
2713
  `invalid asset output amount for ${assetId}: got ${got}, want ${want}`
2714
2714
  );
2715
- var ErrAssetGroupNotFound = (assetId) => new chunk57636V35_cjs.ServerResponseMismatchError(`asset group not found in batch leaf: ${assetId}`);
2716
- var ErrAssetOutputNotFound = (assetId, outputIndex) => new chunk57636V35_cjs.ServerResponseMismatchError(
2715
+ var ErrAssetGroupNotFound = (assetId) => new chunk6FTHFJAN_cjs.ServerResponseMismatchError(`asset group not found in batch leaf: ${assetId}`);
2716
+ var ErrAssetOutputNotFound = (assetId, outputIndex) => new chunk6FTHFJAN_cjs.ServerResponseMismatchError(
2717
2717
  `asset output not found in asset group ${assetId} at index ${outputIndex}`
2718
2718
  );
2719
- var ErrOnchainOutputNotFound = (address) => new chunk57636V35_cjs.ServerResponseMismatchError(`onchain output not found: ${address}`);
2720
- var ErrUnvalidatedOffchainOutput = (address) => new chunk57636V35_cjs.ServerResponseMismatchError(
2719
+ var ErrOnchainOutputNotFound = (address) => new chunk6FTHFJAN_cjs.ServerResponseMismatchError(`onchain output not found: ${address}`);
2720
+ var ErrUnvalidatedOffchainOutput = (address) => new chunk6FTHFJAN_cjs.ServerResponseMismatchError(
2721
2721
  `offchain output ${address} cannot be validated: virtual output tree signing did not run`
2722
2722
  );
2723
2723
  var ErrInvalidOnchainOutputAmount = (address) => new Error(`invalid onchain output amount: ${address}`);
@@ -2726,7 +2726,7 @@ var ErrInvalidOffchainOutputAmount = (address) => new Error(`invalid offchain ou
2726
2726
  function assertFinalCommitmentMatchesValidated(finalCommitmentTx, validatedCommitmentTxid, context) {
2727
2727
  if (!validatedCommitmentTxid) return;
2728
2728
  if (finalCommitmentTx.id === validatedCommitmentTxid) return;
2729
- throw new chunk57636V35_cjs.ServerResponseMismatchError(
2729
+ throw new chunk6FTHFJAN_cjs.ServerResponseMismatchError(
2730
2730
  `${context}: finalization commitment tx ${finalCommitmentTx.id} differs from the validated commitment tx ${validatedCommitmentTxid}`
2731
2731
  );
2732
2732
  }
@@ -2736,7 +2736,7 @@ function validateBatchRecipients(commitmentTx, vtxoTreeLeaves, recipients, netwo
2736
2736
  for (const recipient of recipients) {
2737
2737
  let arkAddress;
2738
2738
  try {
2739
- arkAddress = chunk57636V35_cjs.ArkAddress.decode(recipient.address);
2739
+ arkAddress = chunk6FTHFJAN_cjs.ArkAddress.decode(recipient.address);
2740
2740
  } catch {
2741
2741
  validateOnchainRecipient(commitmentTx, recipient, network, usedOnchainOutputs);
2742
2742
  continue;
@@ -2748,7 +2748,7 @@ function validateBatchRecipientsWithoutTree(commitmentTx, recipients, network) {
2748
2748
  const usedOnchainOutputs = /* @__PURE__ */ new Set();
2749
2749
  for (const recipient of recipients) {
2750
2750
  try {
2751
- chunk57636V35_cjs.ArkAddress.decode(recipient.address);
2751
+ chunk6FTHFJAN_cjs.ArkAddress.decode(recipient.address);
2752
2752
  } catch {
2753
2753
  validateOnchainRecipient(commitmentTx, recipient, network, usedOnchainOutputs);
2754
2754
  continue;
@@ -2981,7 +2981,7 @@ function assetMintResolver() {
2981
2981
  if (!tx.assets?.length || !tx.key.arkTxid) return void 0;
2982
2982
  const minted = tx.assets.filter((a) => {
2983
2983
  try {
2984
- return base.hex.encode(chunk3KW4TWP2_cjs.AssetId.fromString(a.assetId).txid) === tx.key.arkTxid;
2984
+ return base.hex.encode(chunk4C5PMGBB_cjs.AssetId.fromString(a.assetId).txid) === tx.key.arkTxid;
2985
2985
  } catch {
2986
2986
  return false;
2987
2987
  }
@@ -3005,6 +3005,39 @@ function createDefaultActivityRegistry() {
3005
3005
  return registry;
3006
3006
  }
3007
3007
 
3008
+ // src/wallet/restoreHooks.ts
3009
+ var restoreHooks = /* @__PURE__ */ new WeakMap();
3010
+ function registerWalletRestoreHook(wallet, hook) {
3011
+ const hooks = restoreHooks.get(wallet) ?? [];
3012
+ const entry = { ...hook };
3013
+ const existing = hooks.findIndex(({ id }) => id === hook.id);
3014
+ if (existing === -1) hooks.push(entry);
3015
+ else hooks[existing] = entry;
3016
+ restoreHooks.set(wallet, hooks);
3017
+ return () => {
3018
+ const current = restoreHooks.get(wallet);
3019
+ if (!current) return;
3020
+ const index = current.indexOf(entry);
3021
+ if (index === -1) return;
3022
+ current.splice(index, 1);
3023
+ if (current.length === 0) restoreHooks.delete(wallet);
3024
+ };
3025
+ }
3026
+ async function runWalletRestoreHooks(wallet) {
3027
+ const snapshot = [...restoreHooks.get(wallet) ?? []];
3028
+ const errors = [];
3029
+ for (const hook of snapshot) {
3030
+ try {
3031
+ await hook.restore(wallet);
3032
+ } catch (error) {
3033
+ errors.push(error);
3034
+ }
3035
+ }
3036
+ if (errors.length > 0) {
3037
+ throw new AggregateError(errors, "Wallet restore hooks failed");
3038
+ }
3039
+ }
3040
+
3008
3041
  // src/wallet/index.ts
3009
3042
  var TxType = /* @__PURE__ */ ((TxType2) => {
3010
3043
  TxType2["TxSent"] = "SENT";
@@ -3024,7 +3057,7 @@ function createAssetPacket(assetInputs, receivers, changeReceiver) {
3024
3057
  const existing = inputsByAssetId.get(asset.assetId);
3025
3058
  inputsByAssetId.set(asset.assetId, [
3026
3059
  ...existing ?? [],
3027
- chunk3KW4TWP2_cjs.AssetInput.create(inputIndex, asset.amount)
3060
+ chunk4C5PMGBB_cjs.AssetInput.create(inputIndex, asset.amount)
3028
3061
  ]);
3029
3062
  }
3030
3063
  }
@@ -3036,7 +3069,7 @@ function createAssetPacket(assetInputs, receivers, changeReceiver) {
3036
3069
  const existing = outputsByAssetId.get(asset.assetId);
3037
3070
  outputsByAssetId.set(asset.assetId, [
3038
3071
  ...existing ?? [],
3039
- chunk3KW4TWP2_cjs.AssetOutput.create(outputIndex, asset.amount)
3072
+ chunk4C5PMGBB_cjs.AssetOutput.create(outputIndex, asset.amount)
3040
3073
  ]);
3041
3074
  }
3042
3075
  }
@@ -3047,7 +3080,7 @@ function createAssetPacket(assetInputs, receivers, changeReceiver) {
3047
3080
  const existing = outputsByAssetId.get(asset.assetId);
3048
3081
  outputsByAssetId.set(asset.assetId, [
3049
3082
  ...existing ?? [],
3050
- chunk3KW4TWP2_cjs.AssetOutput.create(outputIndex, asset.amount)
3083
+ chunk4C5PMGBB_cjs.AssetOutput.create(outputIndex, asset.amount)
3051
3084
  ]);
3052
3085
  }
3053
3086
  }
@@ -3056,11 +3089,11 @@ function createAssetPacket(assetInputs, receivers, changeReceiver) {
3056
3089
  for (const assetIdStr of allAssetIds) {
3057
3090
  const inputs = inputsByAssetId.get(assetIdStr);
3058
3091
  const outputs = outputsByAssetId.get(assetIdStr);
3059
- const assetId = chunk3KW4TWP2_cjs.AssetId.fromString(assetIdStr);
3060
- const group = chunk3KW4TWP2_cjs.AssetGroup.create(assetId, null, inputs ?? [], outputs ?? [], []);
3092
+ const assetId = chunk4C5PMGBB_cjs.AssetId.fromString(assetIdStr);
3093
+ const group = chunk4C5PMGBB_cjs.AssetGroup.create(assetId, null, inputs ?? [], outputs ?? [], []);
3061
3094
  groups.push(group);
3062
3095
  }
3063
- return chunk3KW4TWP2_cjs.Packet.create(groups);
3096
+ return chunk4C5PMGBB_cjs.Packet.create(groups);
3064
3097
  }
3065
3098
  function selectCoinsWithAsset(coins, assetId, requiredAmount) {
3066
3099
  const coinsWithAsset = coins.filter((coin) => coin.assets?.some((a) => a.assetId === assetId));
@@ -3097,7 +3130,7 @@ function selectedCoinsToAssetInputs(selectedCoins) {
3097
3130
  }
3098
3131
  function toXOnlySignerHex(pubkeyHex) {
3099
3132
  const bytes = base.hex.decode(pubkeyHex);
3100
- if (bytes.length === 32 || bytes.length === 33) return base.hex.encode(chunk3OKEUDHU_cjs.toXOnly(bytes, "signer key"));
3133
+ if (bytes.length === 32 || bytes.length === 33) return base.hex.encode(chunkNPM5YZBC_cjs.toXOnly(bytes, "signer key"));
3101
3134
  throw new Error(`invalid signer pubkey length: expected 32 or 33 bytes, got ${bytes.length}`);
3102
3135
  }
3103
3136
  function signerSetFromInfo(info) {
@@ -3144,13 +3177,13 @@ var toTimelock = (value) => ({
3144
3177
  var toSeconds = (t) => t.type === "seconds" ? t.value : t.value * NOMINAL_BLOCK_SECONDS;
3145
3178
  function assertTimelockInPolicy(timelock, policy, label, overrideOption) {
3146
3179
  if (policy.requireSeconds && timelock.type === "blocks") {
3147
- throw new chunk57636V35_cjs.ServerResponseMismatchError(
3180
+ throw new chunk6FTHFJAN_cjs.ServerResponseMismatchError(
3148
3181
  `${label} rejected: block-typed timelocks are not accepted (got ${timelock.value})`
3149
3182
  );
3150
3183
  }
3151
3184
  const seconds = toSeconds(timelock);
3152
3185
  if (seconds < policy.minSeconds) {
3153
- throw new chunk57636V35_cjs.ServerResponseMismatchError(
3186
+ throw new chunk6FTHFJAN_cjs.ServerResponseMismatchError(
3154
3187
  `${label} rejected: ${timelock.value} ${timelock.type} is below the ${policy.minSeconds}s floor; pass ${overrideOption}: ${seconds}n to Wallet.create to lower it`
3155
3188
  );
3156
3189
  }
@@ -3171,7 +3204,7 @@ function resolveBatchExpiryPolicy(network, overrides) {
3171
3204
  }
3172
3205
  function assertValidBatchExpiry(batchExpiry, policy) {
3173
3206
  if (policy.advertisedVtxoTreeExpiry !== void 0 && batchExpiry !== policy.advertisedVtxoTreeExpiry) {
3174
- throw new chunk57636V35_cjs.ServerResponseMismatchError(
3207
+ throw new chunk6FTHFJAN_cjs.ServerResponseMismatchError(
3175
3208
  `batch expiry rejected: ${batchExpiry} does not match the advertised vtxoTreeExpiry ${policy.advertisedVtxoTreeExpiry}`
3176
3209
  );
3177
3210
  }
@@ -3201,21 +3234,21 @@ function resolveCheckpointExitDelayPolicy(network, overrides) {
3201
3234
  function assertValidServerUnrollScript(checkpointTapscript, policy) {
3202
3235
  let script;
3203
3236
  try {
3204
- script = chunk57636V35_cjs.CSVMultisigTapscript.decode(base.hex.decode(checkpointTapscript));
3237
+ script = chunk6FTHFJAN_cjs.CSVMultisigTapscript.decode(base.hex.decode(checkpointTapscript));
3205
3238
  } catch (e) {
3206
- throw new chunk57636V35_cjs.ServerResponseMismatchError(
3239
+ throw new chunk6FTHFJAN_cjs.ServerResponseMismatchError(
3207
3240
  `checkpoint exit delay rejected: invalid checkpointTapscript from server (${e instanceof Error ? e.message : String(e)})`
3208
3241
  );
3209
3242
  }
3210
3243
  if (policy.advertisedForfeitPubkey !== void 0) {
3211
3244
  const { pubkeys } = script.params;
3212
3245
  if (pubkeys.length !== 1) {
3213
- throw new chunk57636V35_cjs.ServerResponseMismatchError(
3246
+ throw new chunk6FTHFJAN_cjs.ServerResponseMismatchError(
3214
3247
  `checkpoint exit delay rejected: checkpointTapscript must commit to exactly one pubkey, got ${pubkeys.length} [${pubkeys.map(base.hex.encode).join(", ")}]`
3215
3248
  );
3216
3249
  }
3217
3250
  if (!utils_js.equalBytes(pubkeys[0], policy.advertisedForfeitPubkey)) {
3218
- throw new chunk57636V35_cjs.ServerResponseMismatchError(
3251
+ throw new chunk6FTHFJAN_cjs.ServerResponseMismatchError(
3219
3252
  `checkpoint exit delay rejected: checkpointTapscript pubkey ${base.hex.encode(pubkeys[0])} does not match the advertised forfeitPubkey ${base.hex.encode(policy.advertisedForfeitPubkey)}`
3220
3253
  );
3221
3254
  }
@@ -3259,8 +3292,8 @@ function buildOffchainTx(inputs, outputs, serverUnrollScript) {
3259
3292
  function buildVirtualTx(inputs, outputs) {
3260
3293
  let lockTime = 0n;
3261
3294
  for (const input of inputs) {
3262
- const tapscript = chunk57636V35_cjs.decodeTapscript(chunk57636V35_cjs.scriptFromTapLeafScript(input.tapLeafScript));
3263
- if (chunk57636V35_cjs.CLTVMultisigTapscript.is(tapscript)) {
3295
+ const tapscript = chunk6FTHFJAN_cjs.decodeTapscript(chunk6FTHFJAN_cjs.scriptFromTapLeafScript(input.tapLeafScript));
3296
+ if (chunk6FTHFJAN_cjs.CLTVMultisigTapscript.is(tapscript)) {
3264
3297
  if (lockTime !== 0n) {
3265
3298
  if (isSeconds(lockTime) !== isSeconds(tapscript.params.absoluteTimelock)) {
3266
3299
  throw new Error("cannot mix seconds and blocks locktime");
@@ -3271,7 +3304,7 @@ function buildVirtualTx(inputs, outputs) {
3271
3304
  }
3272
3305
  }
3273
3306
  }
3274
- const tx = new chunk57636V35_cjs.Transaction({
3307
+ const tx = new chunk6FTHFJAN_cjs.Transaction({
3275
3308
  version: 3,
3276
3309
  lockTime: Number(lockTime)
3277
3310
  });
@@ -3281,12 +3314,12 @@ function buildVirtualTx(inputs, outputs) {
3281
3314
  index: input.vout,
3282
3315
  sequence: lockTime ? btcSigner.DEFAULT_SEQUENCE - 1 : void 0,
3283
3316
  witnessUtxo: {
3284
- script: chunk57636V35_cjs.VtxoScript.decode(input.tapTree).pkScript,
3317
+ script: chunk6FTHFJAN_cjs.VtxoScript.decode(input.tapTree).pkScript,
3285
3318
  amount: BigInt(input.value)
3286
3319
  },
3287
3320
  tapLeafScript: [input.tapLeafScript]
3288
3321
  });
3289
- chunk57636V35_cjs.setArkPsbtField(tx, i, chunk57636V35_cjs.VtxoTaprootTree, input.tapTree);
3322
+ chunk6FTHFJAN_cjs.setArkPsbtField(tx, i, chunk6FTHFJAN_cjs.VtxoTaprootTree, input.tapTree);
3290
3323
  }
3291
3324
  for (const output of outputs) {
3292
3325
  tx.addOutput(output);
@@ -3295,8 +3328,8 @@ function buildVirtualTx(inputs, outputs) {
3295
3328
  return tx;
3296
3329
  }
3297
3330
  function buildCheckpointTx(vtxo, serverUnrollScript) {
3298
- const collaborativeClosure = chunk57636V35_cjs.decodeTapscript(chunk57636V35_cjs.scriptFromTapLeafScript(vtxo.tapLeafScript));
3299
- const checkpointVtxoScript = new chunk57636V35_cjs.VtxoScript([
3331
+ const collaborativeClosure = chunk6FTHFJAN_cjs.decodeTapscript(chunk6FTHFJAN_cjs.scriptFromTapLeafScript(vtxo.tapLeafScript));
3332
+ const checkpointVtxoScript = new chunk6FTHFJAN_cjs.VtxoScript([
3300
3333
  serverUnrollScript.script,
3301
3334
  collaborativeClosure.script
3302
3335
  ]);
@@ -3372,7 +3405,7 @@ function verifyTapscriptSignatures(tx, inputIndex, requiredSigners, excludePubke
3372
3405
  const sighashType = signature.length === 65 ? signature[64] : btcSigner.SigHash.DEFAULT;
3373
3406
  const sig = signature.subarray(0, 64);
3374
3407
  if (!allowedSighashTypes.includes(sighashType)) {
3375
- const sighashName = chunk57636V35_cjs.formatSighash(sighashType);
3408
+ const sighashName = chunk6FTHFJAN_cjs.formatSighash(sighashType);
3376
3409
  throw new Error(
3377
3410
  `Unallowed sighash type ${sighashName} for input ${inputIndex}, pubkey ${pubKeyHex}.`
3378
3411
  );
@@ -3446,7 +3479,7 @@ function combineTapscriptSigs(signedTx, originalTx) {
3446
3479
  }
3447
3480
  function isValidArkAddress(address) {
3448
3481
  try {
3449
- chunk57636V35_cjs.ArkAddress.decode(address);
3482
+ chunk6FTHFJAN_cjs.ArkAddress.decode(address);
3450
3483
  return true;
3451
3484
  } catch (e) {
3452
3485
  return false;
@@ -3454,16 +3487,16 @@ function isValidArkAddress(address) {
3454
3487
  }
3455
3488
  function matchServerCheckpoints(serverCheckpointTxs, expectedCheckpoints, context) {
3456
3489
  if (serverCheckpointTxs.length !== expectedCheckpoints.length) {
3457
- throw new chunk57636V35_cjs.ServerResponseMismatchError(
3490
+ throw new chunk6FTHFJAN_cjs.ServerResponseMismatchError(
3458
3491
  `${context} returned ${serverCheckpointTxs.length} checkpoints, expected ${expectedCheckpoints.length}`
3459
3492
  );
3460
3493
  }
3461
3494
  const byTxid = new Map(expectedCheckpoints.map((c) => [c.id, c]));
3462
3495
  return serverCheckpointTxs.map((encoded, index) => {
3463
- const server = chunk57636V35_cjs.Transaction.fromPSBT(base.base64.decode(encoded));
3496
+ const server = chunk6FTHFJAN_cjs.Transaction.fromPSBT(base.base64.decode(encoded));
3464
3497
  const local = byTxid.get(server.id);
3465
3498
  if (!local) {
3466
- throw new chunk57636V35_cjs.ServerResponseMismatchError(
3499
+ throw new chunk6FTHFJAN_cjs.ServerResponseMismatchError(
3467
3500
  `${context} checkpoint ${index} txid ${server.id} does not match any submitted checkpoint`
3468
3501
  );
3469
3502
  }
@@ -3473,14 +3506,14 @@ function matchServerCheckpoints(serverCheckpointTxs, expectedCheckpoints, contex
3473
3506
  }
3474
3507
  function assertSubmittedArkTxid(response, signedArkTx, context) {
3475
3508
  if (response.arkTxid !== signedArkTx.id) {
3476
- throw new chunk57636V35_cjs.ServerResponseMismatchError(
3509
+ throw new chunk6FTHFJAN_cjs.ServerResponseMismatchError(
3477
3510
  `${context} returned ark txid ${response.arkTxid}, expected ${signedArkTx.id}`
3478
3511
  );
3479
3512
  }
3480
3513
  if (response.finalArkTx === void 0) return;
3481
- const finalTxid = chunk57636V35_cjs.Transaction.fromPSBT(base.base64.decode(response.finalArkTx)).id;
3514
+ const finalTxid = chunk6FTHFJAN_cjs.Transaction.fromPSBT(base.base64.decode(response.finalArkTx)).id;
3482
3515
  if (finalTxid !== signedArkTx.id) {
3483
- throw new chunk57636V35_cjs.ServerResponseMismatchError(
3516
+ throw new chunk6FTHFJAN_cjs.ServerResponseMismatchError(
3484
3517
  `${context} returned final ark tx ${finalTxid}, expected ${signedArkTx.id}`
3485
3518
  );
3486
3519
  }
@@ -3499,10 +3532,10 @@ function assertServerSignedLeaf(serverTx, localTx, inputIndex, serverPubkeyHex,
3499
3532
  [serverPubkeyHex],
3500
3533
  void 0,
3501
3534
  void 0,
3502
- payment_js.tapLeafHash(chunk57636V35_cjs.scriptFromTapLeafScript(leaf))
3535
+ payment_js.tapLeafHash(chunk6FTHFJAN_cjs.scriptFromTapLeafScript(leaf))
3503
3536
  );
3504
3537
  } catch (error) {
3505
- throw new chunk57636V35_cjs.ServerResponseMismatchError(
3538
+ throw new chunk6FTHFJAN_cjs.ServerResponseMismatchError(
3506
3539
  `${context}: input ${inputIndex} is not signed by the server on the leaf being spent (${error instanceof Error ? error.message : String(error)})`
3507
3540
  );
3508
3541
  }
@@ -3511,20 +3544,20 @@ function assertCheckpointsMatchInputs(checkpoints, inputs, unrollCandidates, con
3511
3544
  const byOutpoint = new Map(inputs.map((input) => [`${input.txid}:${input.vout}`, input]));
3512
3545
  for (const [index, checkpoint] of checkpoints.entries()) {
3513
3546
  if (checkpoint.inputsLength !== 1) {
3514
- throw new chunk57636V35_cjs.ServerResponseMismatchError(
3547
+ throw new chunk6FTHFJAN_cjs.ServerResponseMismatchError(
3515
3548
  `${context}: checkpoint ${index} spends ${checkpoint.inputsLength} inputs, expected 1`
3516
3549
  );
3517
3550
  }
3518
3551
  const spent = checkpoint.getInput(0);
3519
3552
  if (!spent.txid || spent.index === void 0) {
3520
- throw new chunk57636V35_cjs.ServerResponseMismatchError(
3553
+ throw new chunk6FTHFJAN_cjs.ServerResponseMismatchError(
3521
3554
  `${context}: checkpoint ${index} has no input outpoint`
3522
3555
  );
3523
3556
  }
3524
3557
  const outpoint = `${base.hex.encode(spent.txid)}:${spent.index}`;
3525
3558
  const input = byOutpoint.get(outpoint);
3526
3559
  if (!input) {
3527
- throw new chunk57636V35_cjs.ServerResponseMismatchError(
3560
+ throw new chunk6FTHFJAN_cjs.ServerResponseMismatchError(
3528
3561
  `${context}: checkpoint ${index} spends ${outpoint}, which is not one of the requested virtual outputs`
3529
3562
  );
3530
3563
  }
@@ -3532,7 +3565,7 @@ function assertCheckpointsMatchInputs(checkpoints, inputs, unrollCandidates, con
3532
3565
  (unroll) => buildCheckpointTx(input, unroll).tx.id === checkpoint.id
3533
3566
  );
3534
3567
  if (!rebuilt) {
3535
- throw new chunk57636V35_cjs.ServerResponseMismatchError(
3568
+ throw new chunk6FTHFJAN_cjs.ServerResponseMismatchError(
3536
3569
  `${context}: checkpoint ${index} txid ${checkpoint.id} differs from the checkpoint built locally for ${outpoint}`
3537
3570
  );
3538
3571
  }
@@ -3558,9 +3591,9 @@ async function submitOffchainTx(provider, offchainTx, signer, hooks, options) {
3558
3591
  const matched = matchServerCheckpoints(signedCheckpointTxs, offchainTx.checkpoints, "submitTx");
3559
3592
  matched.forEach(({ server }, index) => {
3560
3593
  try {
3561
- chunk57636V35_cjs.assertAllowedSighashTypes(server);
3594
+ chunk6FTHFJAN_cjs.assertAllowedSighashTypes(server);
3562
3595
  } catch (error) {
3563
- throw new chunk57636V35_cjs.ServerResponseMismatchError(
3596
+ throw new chunk6FTHFJAN_cjs.ServerResponseMismatchError(
3564
3597
  `submitTx checkpoint ${index}: ${error instanceof Error ? error.message : String(error)}`
3565
3598
  );
3566
3599
  }
@@ -3568,12 +3601,12 @@ async function submitOffchainTx(provider, offchainTx, signer, hooks, options) {
3568
3601
  const verify = options?.verifyServerSignatures;
3569
3602
  if (verify) {
3570
3603
  if (response.finalArkTx === void 0) {
3571
- throw new chunk57636V35_cjs.ServerResponseMismatchError(
3604
+ throw new chunk6FTHFJAN_cjs.ServerResponseMismatchError(
3572
3605
  "submitTx: server returned no final ark tx to verify its signatures against"
3573
3606
  );
3574
3607
  }
3575
- const finalArkTx = chunk57636V35_cjs.Transaction.fromPSBT(base.base64.decode(response.finalArkTx));
3576
- const serverPubkeyHex = base.hex.encode(chunk3OKEUDHU_cjs.toXOnly(verify.serverPubkey, "server key"));
3608
+ const finalArkTx = chunk6FTHFJAN_cjs.Transaction.fromPSBT(base.base64.decode(response.finalArkTx));
3609
+ const serverPubkeyHex = base.hex.encode(chunkNPM5YZBC_cjs.toXOnly(verify.serverPubkey, "server key"));
3577
3610
  for (let i = 0; i < offchainTx.arkTx.inputsLength; i++) {
3578
3611
  assertServerSignedLeaf(
3579
3612
  finalArkTx,
@@ -3629,17 +3662,37 @@ function claimWithPreimageIdentity(identity, preimage) {
3629
3662
  return {
3630
3663
  ...identity,
3631
3664
  sign: async (tx, inputIndexes) => {
3632
- const signed = chunk57636V35_cjs.Transaction.fromPSBT(
3665
+ const signed = chunk6FTHFJAN_cjs.Transaction.fromPSBT(
3633
3666
  (await identity.sign(tx.clone(), inputIndexes)).toPSBT()
3634
3667
  );
3635
3668
  const indexes = inputIndexes ?? Array.from({ length: signed.inputsLength }, (_, i) => i);
3636
3669
  for (const index of indexes) {
3637
- chunk57636V35_cjs.setArkPsbtField(signed, index, chunk57636V35_cjs.ConditionWitness, [preimage]);
3670
+ chunk6FTHFJAN_cjs.setArkPsbtField(signed, index, chunk6FTHFJAN_cjs.ConditionWitness, [preimage]);
3638
3671
  }
3639
3672
  return signed;
3640
3673
  }
3641
3674
  };
3642
3675
  }
3676
+
3677
+ // src/contracts/types.ts
3678
+ function watchStateOf(contract) {
3679
+ return contract.watch ?? "watched";
3680
+ }
3681
+ function isWatchedContract(contract) {
3682
+ return watchStateOf(contract) !== "retained";
3683
+ }
3684
+ function hasCandidates(handler) {
3685
+ return !!handler && typeof handler.candidatesAt === "function";
3686
+ }
3687
+ function isDiscoverable(handler) {
3688
+ return !!handler && typeof handler.discoverAt === "function";
3689
+ }
3690
+ function isTapscriptDeriving(handler) {
3691
+ return !!handler && typeof handler.deriveTapscripts === "function";
3692
+ }
3693
+ function isContractVtxoEvent(event) {
3694
+ return "contract" in event && event.contract !== void 0;
3695
+ }
3643
3696
  var AmountVariableName = "amount";
3644
3697
  var ExpiryVariableName = "expiry";
3645
3698
  var BirthVariableName = "birth";
@@ -3795,23 +3848,6 @@ function parseProgram(text, env) {
3795
3848
  }
3796
3849
  return { program, text };
3797
3850
  }
3798
-
3799
- // src/contracts/types.ts
3800
- function watchStateOf(contract) {
3801
- return contract.watch ?? "watched";
3802
- }
3803
- function isWatchedContract(contract) {
3804
- return watchStateOf(contract) !== "retained";
3805
- }
3806
- function hasCandidates(handler) {
3807
- return !!handler && typeof handler.candidatesAt === "function";
3808
- }
3809
- function isDiscoverable(handler) {
3810
- return !!handler && typeof handler.discoverAt === "function";
3811
- }
3812
- function isTapscriptDeriving(handler) {
3813
- return !!handler && typeof handler.deriveTapscripts === "function";
3814
- }
3815
3851
  var DUST_AMOUNT = 546;
3816
3852
  var FALLBACK_WALLET_DUST_AMOUNT = 330n;
3817
3853
  function getDustAmount(wallet) {
@@ -3826,7 +3862,7 @@ function extendCoinWithTapscript(boardingTapscript, utxo) {
3826
3862
  };
3827
3863
  }
3828
3864
  function deriveContractTapscripts(contract) {
3829
- const handler = chunk3OKEUDHU_cjs.contractHandlers.get(contract.type);
3865
+ const handler = chunkNPM5YZBC_cjs.contractHandlers.get(contract.type);
3830
3866
  if (!handler) {
3831
3867
  throw new Error(`No handler for contract type '${contract.type}'`);
3832
3868
  }
@@ -3897,7 +3933,7 @@ function getRandomId() {
3897
3933
  }
3898
3934
  function isValidArkAddress2(address) {
3899
3935
  try {
3900
- chunk57636V35_cjs.ArkAddress.decode(address);
3936
+ chunk6FTHFJAN_cjs.ArkAddress.decode(address);
3901
3937
  return true;
3902
3938
  } catch (e) {
3903
3939
  return false;
@@ -3925,7 +3961,7 @@ function assertRecipientArkAddress(encoded, address, context) {
3925
3961
  function assertTapTreeDerivesAddress(encoded, tapTree, address) {
3926
3962
  let derived;
3927
3963
  try {
3928
- derived = chunk57636V35_cjs.VtxoScript.decode(tapTree).pkScript;
3964
+ derived = chunk6FTHFJAN_cjs.VtxoScript.decode(tapTree).pkScript;
3929
3965
  } catch (e) {
3930
3966
  throw new Error(
3931
3967
  `Invalid tapTree for ${encoded}: ${e instanceof Error ? e.message : String(e)}`
@@ -3942,7 +3978,7 @@ function validateRecipients(recipients, dustAmount, context) {
3942
3978
  for (const recipient of recipients) {
3943
3979
  let address;
3944
3980
  try {
3945
- address = chunk57636V35_cjs.ArkAddress.decode(recipient.address);
3981
+ address = chunk6FTHFJAN_cjs.ArkAddress.decode(recipient.address);
3946
3982
  } catch (e) {
3947
3983
  throw new Error(`Invalid Arkade address: ${recipient.address}`);
3948
3984
  }
@@ -3967,7 +4003,7 @@ function validateRecipients(recipients, dustAmount, context) {
3967
4003
 
3968
4004
  // src/contracts/spendability.ts
3969
4005
  function isContractGenericallySpendable(contract) {
3970
- return chunk3OKEUDHU_cjs.contractHandlers.get(contract.type)?.isGenericallySpendable?.(contract) === true;
4006
+ return chunkNPM5YZBC_cjs.contractHandlers.get(contract.type)?.isGenericallySpendable?.(contract) === true;
3971
4007
  }
3972
4008
  function gatedContracts(contracts) {
3973
4009
  const gated = /* @__PURE__ */ new Map();
@@ -3976,11 +4012,20 @@ function gatedContracts(contracts) {
3976
4012
  }
3977
4013
  return gated;
3978
4014
  }
4015
+ function gatedFrom(snapshot) {
4016
+ return gatedContracts(snapshot.map((entry) => entry.contract));
4017
+ }
4018
+ function gatedTypeOf(vtxo, gated) {
4019
+ return vtxo.script === void 0 ? void 0 : gated.get(vtxo.script);
4020
+ }
4021
+ function isGatedVtxo(vtxo, gated) {
4022
+ return gatedTypeOf(vtxo, gated) !== void 0;
4023
+ }
3979
4024
  function gateExclusion(gated) {
3980
4025
  return (vtxo) => {
3981
- const type = vtxo.script === void 0 ? void 0 : gated.get(vtxo.script);
4026
+ const type = gatedTypeOf(vtxo, gated);
3982
4027
  if (type === void 0) return void 0;
3983
- if (!chunk3OKEUDHU_cjs.contractHandlers.has(type)) {
4028
+ if (!chunkNPM5YZBC_cjs.contractHandlers.has(type)) {
3984
4029
  return `at ${vtxo.script} (contract type '${type}') has no handler registered in this build`;
3985
4030
  }
3986
4031
  return `at ${vtxo.script} (contract type '${type}') is not generically spendable`;
@@ -4016,7 +4061,7 @@ function selectPendingRecoveryOutpoints(contractsWithVtxos, signerSet, nowSecond
4016
4061
  continue;
4017
4062
  }
4018
4063
  for (const v of vtxos) {
4019
- if (!chunk57636V35_cjs.hasTerminalSpend(v) && !v.isSwept && !v.isUnrolled) {
4064
+ if (!chunk6FTHFJAN_cjs.hasTerminalSpend(v) && !v.isSwept && !v.isUnrolled) {
4020
4065
  out.add(`${v.txid}:${v.vout}`);
4021
4066
  }
4022
4067
  }
@@ -4051,10 +4096,10 @@ function byValueDescending(vtxos) {
4051
4096
  return [...vtxos].sort((a, b) => b.value - a.value);
4052
4097
  }
4053
4098
  async function fetchTimeHeight(wallet) {
4054
- return chunk57636V35_cjs.resolveTimeHeight(wallet.onchainProvider);
4099
+ return chunk6FTHFJAN_cjs.resolveTimeHeight(wallet.onchainProvider);
4055
4100
  }
4056
4101
  function canMigrateBySend(vtxo, now) {
4057
- if (!chunk57636V35_cjs.canSpendOffchain(vtxo, now)) return false;
4102
+ if (!chunk6FTHFJAN_cjs.canSpendOffchain(vtxo, now)) return false;
4058
4103
  return vtxo.expiresAt !== void 0 || vtxo.expiresAtHeight !== void 0;
4059
4104
  }
4060
4105
  function byExpiryAscending(vtxos, now) {
@@ -4062,7 +4107,7 @@ function byExpiryAscending(vtxos, now) {
4062
4107
  if (vtxo.isSwept) return -Infinity;
4063
4108
  if (vtxo.expiresAt !== void 0) return vtxo.expiresAt.getTime();
4064
4109
  if (vtxo.expiresAtHeight !== void 0) {
4065
- return chunk57636V35_cjs.isPastExpiry(vtxo, now) ? -Infinity : Infinity;
4110
+ return chunk6FTHFJAN_cjs.isPastExpiry(vtxo, now) ? -Infinity : Infinity;
4066
4111
  }
4067
4112
  return Infinity;
4068
4113
  };
@@ -4089,7 +4134,7 @@ function priceSettlementInputs(vtxos, estimator) {
4089
4134
  const payable = [];
4090
4135
  const net = /* @__PURE__ */ new Map();
4091
4136
  for (const vtxo of vtxos) {
4092
- const inputFee = estimator.evalOffchainInput(chunk57636V35_cjs.toOffchainInputFeeParams(vtxo));
4137
+ const inputFee = estimator.evalOffchainInput(chunk6FTHFJAN_cjs.toOffchainInputFeeParams(vtxo));
4093
4138
  if (inputFee.satoshis >= vtxo.value) {
4094
4139
  continue;
4095
4140
  }
@@ -4115,7 +4160,7 @@ function deductOffchainOutputFee(subtotal, estimator, arkAddress) {
4115
4160
  }
4116
4161
  const outputFee = estimator.evalOffchainOutput({
4117
4162
  amount: subtotal,
4118
- script: base.hex.encode(chunk57636V35_cjs.ArkAddress.decode(arkAddress).pkScript)
4163
+ script: base.hex.encode(chunk6FTHFJAN_cjs.ArkAddress.decode(arkAddress).pkScript)
4119
4164
  });
4120
4165
  return subtotal - BigInt(outputFee.satoshis);
4121
4166
  }
@@ -4133,10 +4178,10 @@ var DEFAULT_SETTLEMENT_CONFIG = {
4133
4178
  };
4134
4179
  function getRecoverableVtxos(vtxos, dustAmount, now) {
4135
4180
  return vtxos.filter((vtxo) => {
4136
- if (chunk57636V35_cjs.canRecoverOnchain(vtxo, now)) {
4181
+ if (chunk6FTHFJAN_cjs.canRecoverOnchain(vtxo, now)) {
4137
4182
  return true;
4138
4183
  }
4139
- if (chunk57636V35_cjs.canSpendOffchain(vtxo, now) && vtxo.isPreconfirmed && isSubdust(vtxo, dustAmount)) {
4184
+ if (chunk6FTHFJAN_cjs.canSpendOffchain(vtxo, now) && vtxo.isPreconfirmed && isSubdust(vtxo, dustAmount)) {
4140
4185
  return true;
4141
4186
  }
4142
4187
  return false;
@@ -4168,7 +4213,7 @@ function getRecoverableWithSubdust(vtxos, dustAmount, now) {
4168
4213
  function isVtxoExpiringSoon(vtxo, thresholdMs) {
4169
4214
  if (vtxo.isUnrolled) return false;
4170
4215
  const realThresholdMs = thresholdMs <= 100 ? DEFAULT_THRESHOLD_MS : thresholdMs;
4171
- const expiresAt = chunk57636V35_cjs.normalizeVtxo(vtxo).expiresAt;
4216
+ const expiresAt = chunk6FTHFJAN_cjs.normalizeVtxo(vtxo).expiresAt;
4172
4217
  if (expiresAt === void 0) return false;
4173
4218
  const now = Date.now();
4174
4219
  const batchExpiry = expiresAt.getTime();
@@ -4179,7 +4224,7 @@ function getExpiringAndRecoverableVtxos(vtxos, thresholdMs, dustAmount, now) {
4179
4224
  return vtxos.filter(
4180
4225
  // The leading exclusion covers the `isSubdust` arm too, which is a value
4181
4226
  // property and would otherwise re-admit an exited coin on its own.
4182
- (vtxo) => !vtxo.isUnrolled && (isVtxoExpiringSoon(vtxo, thresholdMs) || chunk57636V35_cjs.canRecoverOnchain(vtxo, now) || isSubdust(vtxo, dustAmount))
4227
+ (vtxo) => !vtxo.isUnrolled && (isVtxoExpiringSoon(vtxo, thresholdMs) || chunk6FTHFJAN_cjs.canRecoverOnchain(vtxo, now) || isSubdust(vtxo, dustAmount))
4183
4228
  );
4184
4229
  }
4185
4230
  function isMigrationCapable(wallet) {
@@ -4778,11 +4823,11 @@ var VtxoManager = class _VtxoManager {
4778
4823
  `Sweep not economical: output ${outputAmount} sats after ${fee} sats fee is below dust (${dustAmount} sats)`
4779
4824
  );
4780
4825
  }
4781
- const tx = new chunk57636V35_cjs.Transaction();
4826
+ const tx = new chunk6FTHFJAN_cjs.Transaction();
4782
4827
  for (const utxo of expiredUtxos) {
4783
- const utxoScript = chunk57636V35_cjs.VtxoScript.decode(utxo.tapTree);
4828
+ const utxoScript = chunk6FTHFJAN_cjs.VtxoScript.decode(utxo.tapTree);
4784
4829
  const utxoExitLeaf = utxoScript.leaves.find(
4785
- (leaf) => chunk57636V35_cjs.CSVMultisigTapscript.isScriptValid(chunk57636V35_cjs.scriptFromTapLeafScript(leaf)) === true
4830
+ (leaf) => chunk6FTHFJAN_cjs.CSVMultisigTapscript.isScriptValid(chunk6FTHFJAN_cjs.scriptFromTapLeafScript(leaf)) === true
4786
4831
  );
4787
4832
  if (!utxoExitLeaf) {
4788
4833
  throw new Error(
@@ -4797,7 +4842,7 @@ var VtxoManager = class _VtxoManager {
4797
4842
  amount: BigInt(utxo.value)
4798
4843
  },
4799
4844
  tapLeafScript: [utxoExitLeaf],
4800
- sequence: chunk57636V35_cjs.getSequence(utxoExitLeaf)
4845
+ sequence: chunk6FTHFJAN_cjs.getSequence(utxoExitLeaf)
4801
4846
  });
4802
4847
  }
4803
4848
  tx.addOutputAddress(boardingAddress, outputAmount, this.getNetwork());
@@ -5040,8 +5085,8 @@ var VtxoManager = class _VtxoManager {
5040
5085
  const cls = classifyAgainstSignerSet(serverPubKey, signerSet, nowSeconds);
5041
5086
  if (cls.status === "CURRENT") continue;
5042
5087
  const live = vtxos.filter((v) => !v.isUnrolled);
5043
- const recoverable = live.filter((v) => v.isSwept && !chunk57636V35_cjs.hasTerminalSpend(v));
5044
- const spendable = live.filter((v) => !chunk57636V35_cjs.hasTerminalSpend(v) && !v.isSwept);
5088
+ const recoverable = live.filter((v) => v.isSwept && !chunk6FTHFJAN_cjs.hasTerminalSpend(v));
5089
+ const spendable = live.filter((v) => !chunk6FTHFJAN_cjs.hasTerminalSpend(v) && !v.isSwept);
5045
5090
  const value = spendable.reduce((sum, v) => sum + v.value, 0);
5046
5091
  let recoverableCount = 0;
5047
5092
  let recoverableValue = 0;
@@ -5054,7 +5099,7 @@ var VtxoManager = class _VtxoManager {
5054
5099
  awaitingSweepCount = spendable.length;
5055
5100
  awaitingSweepValue = value;
5056
5101
  for (const v of spendable) {
5057
- const exp = chunk57636V35_cjs.toBatchExpiry(v);
5102
+ const exp = chunk6FTHFJAN_cjs.toBatchExpiry(v);
5058
5103
  if (exp !== void 0 && (nextSweepEta === void 0 || exp < nextSweepEta)) {
5059
5104
  nextSweepEta = exp;
5060
5105
  }
@@ -5315,7 +5360,7 @@ var VtxoManager = class _VtxoManager {
5315
5360
  /** Decodes the boarding tapscript exit path to extract the CSV timelock. */
5316
5361
  getBoardingTimelock() {
5317
5362
  const wallet = this.getSweepWallet();
5318
- const exitScript = chunk57636V35_cjs.CSVMultisigTapscript.decode(
5363
+ const exitScript = chunk6FTHFJAN_cjs.CSVMultisigTapscript.decode(
5319
5364
  base.hex.decode(wallet.boardingTapscript.exitScript)
5320
5365
  );
5321
5366
  return exitScript.params.timelock;
@@ -5361,7 +5406,7 @@ var VtxoManager = class _VtxoManager {
5361
5406
  this.wallet.getAddress()
5362
5407
  ]);
5363
5408
  const stopWatching = contractManager.onContractEvent((event) => {
5364
- if (event.type !== "vtxo_received") {
5409
+ if (event.type !== "vtxo_received" || !isContractVtxoEvent(event)) {
5365
5410
  return;
5366
5411
  }
5367
5412
  const msSinceLastRenewal = Date.now() - this.lastRenewalTimestamp;
@@ -5446,8 +5491,8 @@ var VtxoManager = class _VtxoManager {
5446
5491
  * or doesn't carry the metadata.
5447
5492
  */
5448
5493
  extractSpentOutpoint(error) {
5449
- const ark = chunk57636V35_cjs.maybeArkError(error);
5450
- if (!chunk57636V35_cjs.isArkError(ark, chunk57636V35_cjs.ArkErrorName.VTXO_ALREADY_SPENT)) return void 0;
5494
+ const ark = chunk6FTHFJAN_cjs.maybeArkError(error);
5495
+ if (!chunk6FTHFJAN_cjs.isArkError(ark, chunk6FTHFJAN_cjs.ArkErrorName.VTXO_ALREADY_SPENT)) return void 0;
5451
5496
  const raw = ark.metadata?.vtxo_outpoint;
5452
5497
  if (typeof raw !== "string") return void 0;
5453
5498
  const [txid, voutStr] = raw.split(":");
@@ -5637,7 +5682,7 @@ var VtxoManager = class _VtxoManager {
5637
5682
  if (filteredVtxos.length >= MAX_VTXOS_PER_SETTLEMENT) {
5638
5683
  break;
5639
5684
  }
5640
- const inputFee = estimator.evalOffchainInput(chunk57636V35_cjs.toOffchainInputFeeParams(v));
5685
+ const inputFee = estimator.evalOffchainInput(chunk6FTHFJAN_cjs.toOffchainInputFeeParams(v));
5641
5686
  if (inputFee.satoshis >= v.value) {
5642
5687
  continue;
5643
5688
  }
@@ -5657,7 +5702,7 @@ var VtxoManager = class _VtxoManager {
5657
5702
  const arkAddress = await this.wallet.getAddress();
5658
5703
  const outputFee = estimator.evalOffchainOutput({
5659
5704
  amount: totalAmount,
5660
- script: base.hex.encode(chunk57636V35_cjs.ArkAddress.decode(arkAddress).pkScript)
5705
+ script: base.hex.encode(chunk6FTHFJAN_cjs.ArkAddress.decode(arkAddress).pkScript)
5661
5706
  });
5662
5707
  totalAmount -= BigInt(outputFee.satoshis);
5663
5708
  if (totalAmount < dustAmount) return;
@@ -5737,7 +5782,7 @@ var ArkNote = class _ArkNote {
5737
5782
  this.value = value;
5738
5783
  this.HRP = HRP;
5739
5784
  const preimageHash = utils_js.sha256(this.preimage);
5740
- this.vtxoScript = new chunk57636V35_cjs.VtxoScript([noteTapscript(preimageHash)]);
5785
+ this.vtxoScript = new chunk6FTHFJAN_cjs.VtxoScript([noteTapscript(preimageHash)]);
5741
5786
  const leaf = this.vtxoScript.leaves[0];
5742
5787
  this.txid = base.hex.encode(new Uint8Array(preimageHash).reverse());
5743
5788
  this.tapTree = this.vtxoScript.encode();
@@ -5904,7 +5949,7 @@ var ArkadeCash = class _ArkadeCash {
5904
5949
  const privateKey = data.slice(1, 33);
5905
5950
  const serverPubKey = data.slice(33, 65);
5906
5951
  const sequence = new DataView(data.buffer, data.byteOffset + 65, 4).getUint32(0, false);
5907
- const csvTimelock = chunk57636V35_cjs.sequenceToTimelock(sequence);
5952
+ const csvTimelock = chunk6FTHFJAN_cjs.sequenceToTimelock(sequence);
5908
5953
  return new _ArkadeCash(privateKey, serverPubKey, csvTimelock, decoded.prefix);
5909
5954
  }
5910
5955
  toString() {
@@ -5912,7 +5957,7 @@ var ArkadeCash = class _ArkadeCash {
5912
5957
  data[0] = _ArkadeCash.Version;
5913
5958
  data.set(this._privateKey, 1);
5914
5959
  data.set(this._serverPubKey, 33);
5915
- const sequence = chunk57636V35_cjs.timelockToSequence(this.csvTimelock);
5960
+ const sequence = chunk6FTHFJAN_cjs.timelockToSequence(this.csvTimelock);
5916
5961
  new DataView(data.buffer, data.byteOffset + 65, 4).setUint32(0, sequence, false);
5917
5962
  const words = base.bech32m.toWords(data);
5918
5963
  return base.bech32m.encode(this.hrp, words, 1023);
@@ -5921,7 +5966,7 @@ var ArkadeCash = class _ArkadeCash {
5921
5966
  return SingleKey.fromPrivateKey(this._privateKey);
5922
5967
  }
5923
5968
  get vtxoScript() {
5924
- return new chunk3OKEUDHU_cjs.DefaultVtxo.Script({
5969
+ return new chunkNPM5YZBC_cjs.DefaultVtxo.Script({
5925
5970
  pubKey: this._publicKey,
5926
5971
  serverPubKey: this._serverPubKey,
5927
5972
  csvTimelock: this.csvTimelock
@@ -6182,7 +6227,7 @@ async function captureExitBranch(params) {
6182
6227
  const nonCommitment = ordered.filter((c) => chainTxTypeToChainedExit(c.type) !== 1 /* Commitment */).map((c) => c.txid);
6183
6228
  if (nonCommitment.length > 0) {
6184
6229
  for (const psbt of await resolver.getVirtualTxs(nonCommitment)) {
6185
- psbtByTxid.set(chunk57636V35_cjs.Transaction.fromPSBT(base.base64.decode(psbt)).id, psbt);
6230
+ psbtByTxid.set(chunk6FTHFJAN_cjs.Transaction.fromPSBT(base.base64.decode(psbt)).id, psbt);
6186
6231
  }
6187
6232
  }
6188
6233
  }
@@ -6225,10 +6270,10 @@ var IndexerExitDataSource = class {
6225
6270
  while (hasMore) {
6226
6271
  const { chain: page, page: meta } = await this.indexer.getVtxoChain(
6227
6272
  { txid: vtxo.txid, vout: vtxo.vout },
6228
- { pageIndex, pageSize: chunk57636V35_cjs.DEFAULT_PAGE_SIZE }
6273
+ { pageIndex, pageSize: chunk6FTHFJAN_cjs.DEFAULT_PAGE_SIZE }
6229
6274
  );
6230
6275
  chain.push(...page);
6231
- hasMore = meta ? page.length === chunk57636V35_cjs.DEFAULT_PAGE_SIZE : false;
6276
+ hasMore = meta ? page.length === chunk6FTHFJAN_cjs.DEFAULT_PAGE_SIZE : false;
6232
6277
  pageIndex++;
6233
6278
  }
6234
6279
  return chain;
@@ -6240,12 +6285,12 @@ var IndexerExitDataSource = class {
6240
6285
  while (hasMore) {
6241
6286
  const { txs, page } = await this.indexer.getVirtualTxs(txids, {
6242
6287
  pageIndex,
6243
- pageSize: chunk57636V35_cjs.DEFAULT_PAGE_SIZE
6288
+ pageSize: chunk6FTHFJAN_cjs.DEFAULT_PAGE_SIZE
6244
6289
  });
6245
6290
  for (const psbt of txs) {
6246
- out.set(chunk57636V35_cjs.Transaction.fromPSBT(base.base64.decode(psbt)).id, psbt);
6291
+ out.set(chunk6FTHFJAN_cjs.Transaction.fromPSBT(base.base64.decode(psbt)).id, psbt);
6247
6292
  }
6248
- hasMore = page ? txs.length === chunk57636V35_cjs.DEFAULT_PAGE_SIZE : false;
6293
+ hasMore = page ? txs.length === chunk6FTHFJAN_cjs.DEFAULT_PAGE_SIZE : false;
6249
6294
  pageIndex++;
6250
6295
  }
6251
6296
  return out;
@@ -6266,7 +6311,7 @@ function chainedTxTypeToChainTxType(t) {
6266
6311
  }
6267
6312
  }
6268
6313
  function psbtInputTxids(psbtBase64) {
6269
- const tx = chunk57636V35_cjs.Transaction.fromPSBT(base.base64.decode(psbtBase64));
6314
+ const tx = chunk6FTHFJAN_cjs.Transaction.fromPSBT(base.base64.decode(psbtBase64));
6270
6315
  const ids = [];
6271
6316
  for (let i = 0; i < tx.inputsLength; i++) {
6272
6317
  const txid = tx.getInput(i).txid;
@@ -6625,10 +6670,10 @@ async function resolveArkInfo(arkProvider, walletRepository) {
6625
6670
  try {
6626
6671
  info = await arkProvider.getInfo();
6627
6672
  } catch (err) {
6628
- if (!chunk57636V35_cjs.isRetryableProviderError(err)) throw err;
6673
+ if (!chunk6FTHFJAN_cjs.isRetryableProviderError(err)) throw err;
6629
6674
  const snapshot = await loadArkInfoSnapshot(walletRepository);
6630
6675
  if (!snapshot) {
6631
- throw new chunk57636V35_cjs.ProviderUnavailableError(
6676
+ throw new chunk6FTHFJAN_cjs.ProviderUnavailableError(
6632
6677
  "Arkade server info is unavailable and no cached snapshot exists",
6633
6678
  { cause: err }
6634
6679
  );
@@ -6956,6 +7001,24 @@ exports.Batch = void 0;
6956
7001
  })(exports.Batch || (exports.Batch = {}));
6957
7002
 
6958
7003
  // src/utils/transactionHistory.ts
7004
+ function localCreatedAtByTxid(vtxos) {
7005
+ const createdAt = /* @__PURE__ */ new Map();
7006
+ for (const vtxo of vtxos) {
7007
+ if (vtxo.txid && !createdAt.has(vtxo.txid)) {
7008
+ createdAt.set(vtxo.txid, vtxo.createdAt.getTime());
7009
+ }
7010
+ }
7011
+ return createdAt;
7012
+ }
7013
+ function gatedTouchpoints(gated) {
7014
+ const paidIn = /* @__PURE__ */ new Set();
7015
+ const paidOut = /* @__PURE__ */ new Set();
7016
+ for (const vtxo of gated) {
7017
+ if (vtxo.txid) paidIn.add(vtxo.txid);
7018
+ if (vtxo.isSpent && vtxo.arkTxId) paidOut.add(vtxo.arkTxId);
7019
+ }
7020
+ return { paidIn, paidOut };
7021
+ }
6959
7022
  var txKey = {
6960
7023
  commitmentTxid: "",
6961
7024
  boardingTxid: "",
@@ -7007,24 +7070,27 @@ function subtractAssets(spent, change) {
7007
7070
  if (map.size === 0) return void 0;
7008
7071
  return Array.from(map, ([assetId, amount]) => ({ assetId, amount }));
7009
7072
  }
7010
- function collectArkTxidsNeedingCreatedAt(vtxos) {
7011
- const ownTxids = new Set(vtxos.map((v) => v.txid));
7073
+ function collectArkTxidsNeedingCreatedAt(vtxos, localCreatedAt) {
7012
7074
  const txids = /* @__PURE__ */ new Set();
7013
7075
  for (const vtxo of vtxos) {
7014
- if (vtxo.isSpent && vtxo.arkTxId && !ownTxids.has(vtxo.arkTxId)) {
7076
+ if (vtxo.isSpent && vtxo.arkTxId && !localCreatedAt.has(vtxo.arkTxId)) {
7015
7077
  txids.add(vtxo.arkTxId);
7016
7078
  }
7017
7079
  }
7018
7080
  return [...txids];
7019
7081
  }
7020
- async function buildTransactionHistory(vtxos, allBoardingTxs, commitmentsToIgnore, resolveTxCreatedAt) {
7021
- const fromOldestVtxo = vtxos.map(chunk57636V35_cjs.normalizeVtxo).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
7022
- const txidsNeedingCreatedAt = resolveTxCreatedAt ? collectArkTxidsNeedingCreatedAt(fromOldestVtxo) : [];
7082
+ async function buildTransactionHistory(vtxos, allBoardingTxs, commitmentsToIgnore, resolveTxCreatedAt, gatedScripts = /* @__PURE__ */ new Map()) {
7083
+ const normalized = vtxos.map(chunk6FTHFJAN_cjs.normalizeVtxo).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
7084
+ const localCreatedAt = localCreatedAtByTxid(normalized);
7085
+ const gatedVtxos = normalized.filter((vtxo) => isGatedVtxo(vtxo, gatedScripts));
7086
+ const ownVtxos = normalized.filter((vtxo) => !isGatedVtxo(vtxo, gatedScripts));
7087
+ const { paidIn: paidIntoGated, paidOut: paidOutOfGated } = gatedTouchpoints(gatedVtxos);
7088
+ const txidsNeedingCreatedAt = resolveTxCreatedAt ? collectArkTxidsNeedingCreatedAt(ownVtxos, localCreatedAt) : [];
7023
7089
  const resolvedCreatedAt = resolveTxCreatedAt && txidsNeedingCreatedAt.length > 0 ? await resolveTxCreatedAt(txidsNeedingCreatedAt) : /* @__PURE__ */ new Map();
7024
7090
  const unmatchedSettledBoardingTxs = allBoardingTxs.filter(isSettledBoardingReceive).sort((a, b) => a.createdAt - b.createdAt);
7025
7091
  const sent = [];
7026
7092
  let received = [];
7027
- for (const vtxo of fromOldestVtxo) {
7093
+ for (const vtxo of ownVtxos) {
7028
7094
  if (vtxo.status.isLeaf) {
7029
7095
  const commitmentTxid = vtxo.commitmentTxIds[0];
7030
7096
  const vtxoCreatedAt = vtxo.createdAt.getTime();
@@ -7034,7 +7100,7 @@ async function buildTransactionHistory(vtxos, allBoardingTxs, commitmentsToIgnor
7034
7100
  unmatchedSettledBoardingTxs,
7035
7101
  (tx) => tx.createdAt <= vtxoCreatedAt && (tx.key.commitmentTxid === commitmentTxid || tx.key.commitmentTxid === vtxo.settledBy)
7036
7102
  );
7037
- } else if (fromOldestVtxo.filter((v) => v.settledBy === vtxo.commitmentTxIds[0]).length === 0) {
7103
+ } else if (ownVtxos.filter((v) => v.settledBy === vtxo.commitmentTxIds[0]).length === 0) {
7038
7104
  const duplicateBoardingReceive = consumeBoardingReceive(
7039
7105
  unmatchedSettledBoardingTxs,
7040
7106
  (tx) => tx.amount === vtxo.value && tx.createdAt <= vtxoCreatedAt
@@ -7055,11 +7121,14 @@ async function buildTransactionHistory(vtxos, allBoardingTxs, commitmentsToIgnor
7055
7121
  });
7056
7122
  }
7057
7123
  }
7058
- } else if (fromOldestVtxo.filter((v) => v.arkTxId === vtxo.txid).length === 0) {
7124
+ } else if (ownVtxos.filter((v) => v.arkTxId === vtxo.txid).length === 0) {
7059
7125
  const assets = collectAssets([vtxo]);
7060
7126
  received.push({
7061
7127
  key: { ...txKey, arkTxid: vtxo.txid },
7062
- tag: "offchain",
7128
+ // The escrow paying out: a swap fill or a cancel spends the
7129
+ // gated coin and lands the proceeds here. Nothing else about
7130
+ // the row changes — the tag only names the counterparty.
7131
+ tag: paidOutOfGated.has(vtxo.txid) ? "gated" : "offchain",
7063
7132
  type: "RECEIVED" /* TxReceived */,
7064
7133
  amount: vtxo.value,
7065
7134
  settled: vtxo.status.isLeaf || vtxo.isSpent,
@@ -7069,8 +7138,8 @@ async function buildTransactionHistory(vtxos, allBoardingTxs, commitmentsToIgnor
7069
7138
  }
7070
7139
  if (vtxo.isSpent) {
7071
7140
  if (vtxo.arkTxId && !sent.some((s) => s.key.arkTxid === vtxo.arkTxId)) {
7072
- const changes = fromOldestVtxo.filter((_) => _.txid === vtxo.arkTxId);
7073
- const allSpent = fromOldestVtxo.filter((v) => v.arkTxId === vtxo.arkTxId);
7141
+ const changes = ownVtxos.filter((_) => _.txid === vtxo.arkTxId);
7142
+ const allSpent = ownVtxos.filter((v) => v.arkTxId === vtxo.arkTxId);
7074
7143
  const spentAmount = allSpent.reduce((acc, v) => acc + v.value, 0);
7075
7144
  let txAmount = 0;
7076
7145
  let txTime = 0;
@@ -7080,13 +7149,16 @@ async function buildTransactionHistory(vtxos, allBoardingTxs, commitmentsToIgnor
7080
7149
  txTime = changes[0].createdAt.getTime();
7081
7150
  } else {
7082
7151
  txAmount = spentAmount;
7083
- txTime = resolvedCreatedAt.get(vtxo.arkTxId) ?? vtxo.createdAt.getTime() + 1;
7152
+ txTime = localCreatedAt.get(vtxo.arkTxId) ?? resolvedCreatedAt.get(vtxo.arkTxId) ?? vtxo.createdAt.getTime() + 1;
7084
7153
  }
7085
7154
  const assets = subtractAssets(allSpent, changes);
7086
7155
  if (txAmount !== 0 || assets) {
7087
7156
  sent.push({
7088
7157
  key: { ...txKey, arkTxid: vtxo.arkTxId },
7089
- tag: "offchain",
7158
+ // Funding the escrow: an output of this tx landed on a
7159
+ // gated contract of the wallet's, so the send is to the
7160
+ // user's own covenant rather than to a stranger.
7161
+ tag: paidIntoGated.has(vtxo.arkTxId) ? "gated" : "offchain",
7090
7162
  type: "SENT" /* TxSent */,
7091
7163
  amount: txAmount,
7092
7164
  settled: true,
@@ -7096,10 +7168,10 @@ async function buildTransactionHistory(vtxos, allBoardingTxs, commitmentsToIgnor
7096
7168
  }
7097
7169
  }
7098
7170
  if (vtxo.settledBy && !commitmentsToIgnore.has(vtxo.settledBy) && !sent.some((s) => s.key.commitmentTxid === vtxo.settledBy)) {
7099
- const changes = fromOldestVtxo.filter(
7171
+ const changes = ownVtxos.filter(
7100
7172
  (v) => v.status.isLeaf && v.commitmentTxIds.length > 0 && v.commitmentTxIds.every((_) => vtxo.settledBy === _)
7101
7173
  );
7102
- const forfeitVtxos = fromOldestVtxo.filter((v) => v.settledBy === vtxo.settledBy);
7174
+ const forfeitVtxos = ownVtxos.filter((v) => v.settledBy === vtxo.settledBy);
7103
7175
  const forfeitAmount = forfeitVtxos.reduce((acc, v) => acc + v.value, 0);
7104
7176
  if (changes.length > 0) {
7105
7177
  const settledAmount = changes.reduce((acc, v) => acc + v.value, 0);
@@ -7182,7 +7254,7 @@ var AssetManager = class extends ReadonlyAssetManager {
7182
7254
  const virtualCoins = await this.wallet.getSpendableVtxos({
7183
7255
  withRecoverable: false
7184
7256
  });
7185
- const controlAssetRef = params.controlAssetId ? chunk3KW4TWP2_cjs.AssetRef.fromId(chunk3KW4TWP2_cjs.AssetId.fromString(params.controlAssetId)) : null;
7257
+ const controlAssetRef = params.controlAssetId ? chunk4C5PMGBB_cjs.AssetRef.fromId(chunk4C5PMGBB_cjs.AssetId.fromString(params.controlAssetId)) : null;
7186
7258
  const coinSelection = selectVirtualCoins(virtualCoins, Number(this.wallet.dustAmount));
7187
7259
  let totalBtcSelected = 0n;
7188
7260
  const assetChanges = /* @__PURE__ */ new Map();
@@ -7195,8 +7267,8 @@ var AssetManager = class extends ReadonlyAssetManager {
7195
7267
  }
7196
7268
  }
7197
7269
  const groups = [];
7198
- const issuedAssetOutput = chunk3KW4TWP2_cjs.AssetOutput.create(0, params.amount);
7199
- const issuedAssetGroup = chunk3KW4TWP2_cjs.AssetGroup.create(
7270
+ const issuedAssetOutput = chunk4C5PMGBB_cjs.AssetOutput.create(0, params.amount);
7271
+ const issuedAssetGroup = chunk4C5PMGBB_cjs.AssetGroup.create(
7200
7272
  null,
7201
7273
  controlAssetRef,
7202
7274
  [],
@@ -7211,28 +7283,28 @@ var AssetManager = class extends ReadonlyAssetManager {
7211
7283
  for (const [inputIndex, assets] of assetInputs) {
7212
7284
  for (const asset of assets) {
7213
7285
  if (asset.assetId !== assetId) continue;
7214
- changeInputs.push(chunk3KW4TWP2_cjs.AssetInput.create(inputIndex, asset.amount));
7286
+ changeInputs.push(chunk4C5PMGBB_cjs.AssetInput.create(inputIndex, asset.amount));
7215
7287
  }
7216
7288
  }
7217
7289
  groups.push(
7218
- chunk3KW4TWP2_cjs.AssetGroup.create(
7219
- chunk3KW4TWP2_cjs.AssetId.fromString(assetId),
7290
+ chunk4C5PMGBB_cjs.AssetGroup.create(
7291
+ chunk4C5PMGBB_cjs.AssetId.fromString(assetId),
7220
7292
  null,
7221
7293
  changeInputs,
7222
- [chunk3KW4TWP2_cjs.AssetOutput.create(0, amount)],
7294
+ [chunk4C5PMGBB_cjs.AssetOutput.create(0, amount)],
7223
7295
  []
7224
7296
  )
7225
7297
  );
7226
7298
  }
7227
7299
  }
7228
7300
  const address = await this.wallet.getAddress();
7229
- const outputAddress = chunk57636V35_cjs.ArkAddress.decode(address);
7301
+ const outputAddress = chunk6FTHFJAN_cjs.ArkAddress.decode(address);
7230
7302
  const outputs = [
7231
7303
  {
7232
7304
  script: outputAddress.pkScript,
7233
7305
  amount: BigInt(totalBtcSelected)
7234
7306
  },
7235
- Extension.create([chunk3KW4TWP2_cjs.Packet.create(groups)]).txOut()
7307
+ Extension.create([chunk4C5PMGBB_cjs.Packet.create(groups)]).txOut()
7236
7308
  ];
7237
7309
  const { arkTxid } = await this.wallet.buildAndSubmitOffchainTx(
7238
7310
  coinSelection.inputs,
@@ -7240,7 +7312,7 @@ var AssetManager = class extends ReadonlyAssetManager {
7240
7312
  );
7241
7313
  return {
7242
7314
  arkTxId: arkTxid,
7243
- assetId: chunk3KW4TWP2_cjs.AssetId.create(arkTxid, 0).toString()
7315
+ assetId: chunk4C5PMGBB_cjs.AssetId.create(arkTxid, 0).toString()
7244
7316
  };
7245
7317
  }
7246
7318
  /**
@@ -7312,16 +7384,16 @@ var AssetManager = class extends ReadonlyAssetManager {
7312
7384
  for (const [inputIndex, assets] of assetInputs) {
7313
7385
  for (const asset of assets) {
7314
7386
  if (asset.assetId !== params.assetId) continue;
7315
- reissueInputs.push(chunk3KW4TWP2_cjs.AssetInput.create(inputIndex, asset.amount));
7387
+ reissueInputs.push(chunk4C5PMGBB_cjs.AssetInput.create(inputIndex, asset.amount));
7316
7388
  }
7317
7389
  }
7318
7390
  const totalAssetAmount = assetToReissueAmount + params.amount;
7319
- const reissueAssetIdObj = chunk3KW4TWP2_cjs.AssetId.fromString(params.assetId);
7320
- const reissueAssetGroup = chunk3KW4TWP2_cjs.AssetGroup.create(
7391
+ const reissueAssetIdObj = chunk4C5PMGBB_cjs.AssetId.fromString(params.assetId);
7392
+ const reissueAssetGroup = chunk4C5PMGBB_cjs.AssetGroup.create(
7321
7393
  reissueAssetIdObj,
7322
7394
  null,
7323
7395
  reissueInputs,
7324
- [chunk3KW4TWP2_cjs.AssetOutput.create(0, totalAssetAmount)],
7396
+ [chunk4C5PMGBB_cjs.AssetOutput.create(0, totalAssetAmount)],
7325
7397
  []
7326
7398
  );
7327
7399
  const groups = [reissueAssetGroup];
@@ -7330,27 +7402,27 @@ var AssetManager = class extends ReadonlyAssetManager {
7330
7402
  for (const [inputIndex, assets] of assetInputs) {
7331
7403
  for (const asset of assets) {
7332
7404
  if (asset.assetId !== assetId) continue;
7333
- changeInputs.push(chunk3KW4TWP2_cjs.AssetInput.create(inputIndex, asset.amount));
7405
+ changeInputs.push(chunk4C5PMGBB_cjs.AssetInput.create(inputIndex, asset.amount));
7334
7406
  }
7335
7407
  }
7336
7408
  groups.push(
7337
- chunk3KW4TWP2_cjs.AssetGroup.create(
7338
- chunk3KW4TWP2_cjs.AssetId.fromString(assetId),
7409
+ chunk4C5PMGBB_cjs.AssetGroup.create(
7410
+ chunk4C5PMGBB_cjs.AssetId.fromString(assetId),
7339
7411
  null,
7340
7412
  changeInputs,
7341
- [chunk3KW4TWP2_cjs.AssetOutput.create(0, amount)],
7413
+ [chunk4C5PMGBB_cjs.AssetOutput.create(0, amount)],
7342
7414
  []
7343
7415
  )
7344
7416
  );
7345
7417
  }
7346
7418
  const address = await this.wallet.getAddress();
7347
- const outputAddress = chunk57636V35_cjs.ArkAddress.decode(address);
7419
+ const outputAddress = chunk6FTHFJAN_cjs.ArkAddress.decode(address);
7348
7420
  const outputs = [
7349
7421
  {
7350
7422
  script: outputAddress.pkScript,
7351
7423
  amount: BigInt(totalBtcSelected)
7352
7424
  },
7353
- Extension.create([chunk3KW4TWP2_cjs.Packet.create(groups)]).txOut()
7425
+ Extension.create([chunk4C5PMGBB_cjs.Packet.create(groups)]).txOut()
7354
7426
  ];
7355
7427
  const { arkTxid } = await this.wallet.buildAndSubmitOffchainTx(selectedCoins, outputs);
7356
7428
  return arkTxid;
@@ -7417,27 +7489,27 @@ var AssetManager = class extends ReadonlyAssetManager {
7417
7489
  for (const [inputIndex, assets] of assetInputs) {
7418
7490
  for (const asset of assets) {
7419
7491
  if (asset.assetId !== assetId) continue;
7420
- changeInputs.push(chunk3KW4TWP2_cjs.AssetInput.create(inputIndex, asset.amount));
7492
+ changeInputs.push(chunk4C5PMGBB_cjs.AssetInput.create(inputIndex, asset.amount));
7421
7493
  }
7422
7494
  }
7423
7495
  groups.push(
7424
- chunk3KW4TWP2_cjs.AssetGroup.create(
7425
- chunk3KW4TWP2_cjs.AssetId.fromString(assetId),
7496
+ chunk4C5PMGBB_cjs.AssetGroup.create(
7497
+ chunk4C5PMGBB_cjs.AssetId.fromString(assetId),
7426
7498
  null,
7427
7499
  changeInputs,
7428
- amount > 0n ? [chunk3KW4TWP2_cjs.AssetOutput.create(0, amount)] : [],
7500
+ amount > 0n ? [chunk4C5PMGBB_cjs.AssetOutput.create(0, amount)] : [],
7429
7501
  []
7430
7502
  )
7431
7503
  );
7432
7504
  }
7433
7505
  const address = await this.wallet.getAddress();
7434
- const outputAddress = chunk57636V35_cjs.ArkAddress.decode(address);
7506
+ const outputAddress = chunk6FTHFJAN_cjs.ArkAddress.decode(address);
7435
7507
  const outputs = [
7436
7508
  {
7437
7509
  script: outputAddress.pkScript,
7438
7510
  amount: BigInt(totalBtcSelected)
7439
7511
  },
7440
- Extension.create([chunk3KW4TWP2_cjs.Packet.create(groups)]).txOut()
7512
+ Extension.create([chunk4C5PMGBB_cjs.Packet.create(groups)]).txOut()
7441
7513
  ];
7442
7514
  const { arkTxid } = await this.wallet.buildAndSubmitOffchainTx(selectedCoins, outputs);
7443
7515
  return arkTxid;
@@ -7462,7 +7534,7 @@ function castMetadata(metadata) {
7462
7534
  } else {
7463
7535
  throw new Error("Invalid metadata value type");
7464
7536
  }
7465
- md.push(chunk3KW4TWP2_cjs.Metadata.create(textEncoder.encode(key), valueBytes));
7537
+ md.push(chunk4C5PMGBB_cjs.Metadata.create(textEncoder.encode(key), valueBytes));
7466
7538
  }
7467
7539
  return md;
7468
7540
  }
@@ -7483,10 +7555,10 @@ var DelegateManagerImpl = class {
7483
7555
  if (vtxos.length === 0) {
7484
7556
  return { delegated: [], failed: [] };
7485
7557
  }
7486
- const destinationScript = chunk57636V35_cjs.ArkAddress.decode(destination).pkScript;
7558
+ const destinationScript = chunk6FTHFJAN_cjs.ArkAddress.decode(destination).pkScript;
7487
7559
  const arkInfo = await this.arkInfoProvider.getInfo();
7488
7560
  const delegateInfo = await this.delegateProvider.getDelegateInfo();
7489
- const eligible = vtxos.map(chunk57636V35_cjs.normalizeVtxo).filter(
7561
+ const eligible = vtxos.map(chunk6FTHFJAN_cjs.normalizeVtxo).filter(
7490
7562
  (v) => isAnnotated(v) && findDelegateTapLeaf(v, delegateInfo.pubkey) !== void 0
7491
7563
  );
7492
7564
  if (eligible.length === 0) {
@@ -7515,11 +7587,11 @@ var DelegateManagerImpl = class {
7515
7587
  const groupByExpiry = /* @__PURE__ */ new Map();
7516
7588
  let recoverableVtxos = [];
7517
7589
  for (const vtxo of eligible) {
7518
- if (chunk57636V35_cjs.canRecoverOnchain(vtxo, now)) {
7590
+ if (chunk6FTHFJAN_cjs.canRecoverOnchain(vtxo, now)) {
7519
7591
  recoverableVtxos.push(vtxo);
7520
7592
  continue;
7521
7593
  }
7522
- const expiry = chunk57636V35_cjs.toBatchExpiry(vtxo);
7594
+ const expiry = chunk6FTHFJAN_cjs.toBatchExpiry(vtxo);
7523
7595
  if (!expiry) continue;
7524
7596
  const dayKey = getDayTimestamp(expiry);
7525
7597
  groupByExpiry.set(dayKey, [...groupByExpiry.get(dayKey) ?? [], vtxo]);
@@ -7584,7 +7656,7 @@ async function delegate(identity, delegateProvider, arkInfo, delegateInfo, vtxos
7584
7656
  }
7585
7657
  if (!delegateAt) {
7586
7658
  const now = { timestamp: /* @__PURE__ */ new Date() };
7587
- const expiryTimestamp = vtxos.filter((coin) => !chunk57636V35_cjs.canRecoverOnchain(coin, now) && chunk57636V35_cjs.toBatchExpiry(coin)).reduce((min, coin) => Math.min(min, chunk57636V35_cjs.toBatchExpiry(coin)), Number.MAX_SAFE_INTEGER);
7659
+ const expiryTimestamp = vtxos.filter((coin) => !chunk6FTHFJAN_cjs.canRecoverOnchain(coin, now) && chunk6FTHFJAN_cjs.toBatchExpiry(coin)).reduce((min, coin) => Math.min(min, chunk6FTHFJAN_cjs.toBatchExpiry(coin)), Number.MAX_SAFE_INTEGER);
7588
7660
  if (!expiryTimestamp || expiryTimestamp === Number.MAX_SAFE_INTEGER) {
7589
7661
  delegateAt = new Date(Date.now() + 1 * 60 * 1e3);
7590
7662
  } else {
@@ -7613,7 +7685,7 @@ async function delegate(identity, delegateProvider, arkInfo, delegateInfo, vtxos
7613
7685
  let amount = 0n;
7614
7686
  for (const coin of vtxos) {
7615
7687
  const inputFee = estimator.evalOffchainInput({
7616
- ...chunk57636V35_cjs.toOffchainInputFeeParams(coin),
7688
+ ...chunk6FTHFJAN_cjs.toOffchainInputFeeParams(coin),
7617
7689
  type: "vtxo"
7618
7690
  });
7619
7691
  if (inputFee.value >= coin.value) {
@@ -7627,7 +7699,7 @@ async function delegate(identity, delegateProvider, arkInfo, delegateInfo, vtxos
7627
7699
  const delegateFee = BigInt(Number(fee));
7628
7700
  if (delegateFee > 0n) {
7629
7701
  outputs.push({
7630
- script: chunk57636V35_cjs.ArkAddress.decode(delegateAddress).pkScript,
7702
+ script: chunk6FTHFJAN_cjs.ArkAddress.decode(delegateAddress).pkScript,
7631
7703
  amount: delegateFee
7632
7704
  });
7633
7705
  }
@@ -7660,10 +7732,10 @@ async function delegate(identity, delegateProvider, arkInfo, delegateInfo, vtxos
7660
7732
  destinationScript
7661
7733
  );
7662
7734
  const forfeitOutputScript = btcSigner.OutScript.encode(
7663
- btcSigner.Address(chunk57636V35_cjs.getNetwork(network)).decode(forfeitAddress)
7735
+ btcSigner.Address(chunk6FTHFJAN_cjs.getNetwork(network)).decode(forfeitAddress)
7664
7736
  );
7665
7737
  const forfeits = await Promise.all(
7666
- vtxos.filter((v) => !chunk57636V35_cjs.canRecoverOnchain(v, { timestamp: /* @__PURE__ */ new Date() })).map(async (coin) => {
7738
+ vtxos.filter((v) => !chunk6FTHFJAN_cjs.canRecoverOnchain(v, { timestamp: /* @__PURE__ */ new Date() })).map(async (coin) => {
7667
7739
  const forfeit = await makeDelegateForfeitTx(
7668
7740
  coin,
7669
7741
  dust,
@@ -7688,7 +7760,7 @@ async function makeDelegateForfeitTx(input, connectorAmount, delegatePubkey, for
7688
7760
  index: input.vout,
7689
7761
  witnessUtxo: {
7690
7762
  amount: BigInt(input.value),
7691
- script: chunk57636V35_cjs.VtxoScript.decode(input.tapTree).pkScript
7763
+ script: chunk6FTHFJAN_cjs.VtxoScript.decode(input.tapTree).pkScript
7692
7764
  },
7693
7765
  sighashType: btcSigner.SigHash.ALL_ANYONECANPAY,
7694
7766
  tapLeafScript: [delegateTapLeaf]
@@ -7746,7 +7818,7 @@ async function makeSignedDelegateIntent(identity, coins, outputs, onchainOutputs
7746
7818
  expire_at: 0,
7747
7819
  cosigners_public_keys: cosignerPubKeys
7748
7820
  };
7749
- const proof = chunk57636V35_cjs.Intent.create(message, coins, outputs);
7821
+ const proof = chunk6FTHFJAN_cjs.Intent.create(message, coins, outputs);
7750
7822
  const signedProof = await identity.sign(proof);
7751
7823
  return {
7752
7824
  proof: base.base64.encode(signedProof.toPSBT()),
@@ -7764,10 +7836,10 @@ function getDayTimestamp(timestamp) {
7764
7836
  function findDelegateTapLeaf(vtxo, delegatePubkey) {
7765
7837
  if (!vtxo.tapTree) return void 0;
7766
7838
  const pk = delegatePubkey.length === 66 ? delegatePubkey.slice(2) : delegatePubkey;
7767
- const vtxoScript = chunk57636V35_cjs.VtxoScript.decode(vtxo.tapTree);
7839
+ const vtxoScript = chunk6FTHFJAN_cjs.VtxoScript.decode(vtxo.tapTree);
7768
7840
  return vtxoScript.leaves.find((tapLeaf) => {
7769
- const arkTapscript = chunk57636V35_cjs.decodeTapscript(chunk57636V35_cjs.scriptFromTapLeafScript(tapLeaf));
7770
- if (!chunk57636V35_cjs.MultisigTapscript.is(arkTapscript)) return false;
7841
+ const arkTapscript = chunk6FTHFJAN_cjs.decodeTapscript(chunk6FTHFJAN_cjs.scriptFromTapLeafScript(tapLeaf));
7842
+ if (!chunk6FTHFJAN_cjs.MultisigTapscript.is(arkTapscript)) return false;
7771
7843
  return arkTapscript.params.pubkeys.map(base.hex.encode).includes(pk);
7772
7844
  });
7773
7845
  }
@@ -8048,7 +8120,7 @@ function createManagedConnection(dbName, version, initDatabase2) {
8048
8120
  };
8049
8121
  }
8050
8122
  function scriptFromArkAddress(address) {
8051
- return base.hex.encode(chunk57636V35_cjs.ArkAddress.decode(address).pkScript);
8123
+ return base.hex.encode(chunk6FTHFJAN_cjs.ArkAddress.decode(address).pkScript);
8052
8124
  }
8053
8125
 
8054
8126
  // src/repositories/indexedDB/schema.ts
@@ -8543,7 +8615,7 @@ function validateVtxosForScript(vtxos, script, context) {
8543
8615
  }
8544
8616
  async function getVtxosForContract(repo, contract) {
8545
8617
  const vtxos = repo.getVtxosForScript ? await repo.getVtxosForScript(contract.script) : filterVtxosForScript(await repo.getVtxos(contract.address), contract.script);
8546
- return vtxos.map(chunk57636V35_cjs.normalizeVtxo);
8618
+ return vtxos.map(chunk6FTHFJAN_cjs.normalizeVtxo);
8547
8619
  }
8548
8620
  async function saveVtxosForContract(repo, contract, vtxos) {
8549
8621
  if (repo.saveVtxosForScript) {
@@ -8685,7 +8757,7 @@ function decodeArkContract(encoded) {
8685
8757
  }
8686
8758
  function contractFromArkContract(encoded, options = {}) {
8687
8759
  const parsed = decodeArkContract(encoded);
8688
- const handler = chunk3OKEUDHU_cjs.contractHandlers.get(parsed.type);
8760
+ const handler = chunkNPM5YZBC_cjs.contractHandlers.get(parsed.type);
8689
8761
  if (!handler) {
8690
8762
  throw new Error(`No handler registered for contract type '${parsed.type}'`);
8691
8763
  }
@@ -8699,9 +8771,9 @@ function contractFromArkContract(encoded, options = {}) {
8699
8771
  metadata: options.metadata
8700
8772
  };
8701
8773
  }
8702
- function contractFromArkContractWithAddress(encoded, serverPubKey, addressPrefix = chunk57636V35_cjs.DEFAULT_NETWORK.hrp, options = {}) {
8774
+ function contractFromArkContractWithAddress(encoded, serverPubKey, addressPrefix = chunk6FTHFJAN_cjs.DEFAULT_NETWORK.hrp, options = {}) {
8703
8775
  const parsed = decodeArkContract(encoded);
8704
- const handler = chunk3OKEUDHU_cjs.contractHandlers.getOrThrow(parsed.type);
8776
+ const handler = chunkNPM5YZBC_cjs.contractHandlers.getOrThrow(parsed.type);
8705
8777
  const params = parsed.data;
8706
8778
  const vtxoScript = handler.createScript(params);
8707
8779
  return {
@@ -8733,6 +8805,8 @@ var DEFAULT_CONTRACT_WATCHER_CONFIG = {
8733
8805
  var ContractWatcher = class {
8734
8806
  config;
8735
8807
  contracts = /* @__PURE__ */ new Map();
8808
+ /** In-memory and process-lifetime; never persisted. */
8809
+ watchedScripts = /* @__PURE__ */ new Map();
8736
8810
  subscriptionId;
8737
8811
  abortController;
8738
8812
  isWatching = false;
@@ -8853,6 +8927,47 @@ var ContractWatcher = class {
8853
8927
  getWatchedContracts() {
8854
8928
  return this.getAllContracts().filter(isWatchedContract);
8855
8929
  }
8930
+ /**
8931
+ * Every script the subscription must carry. Wider than
8932
+ * {@link getWatchedContracts}, which stays the sync scope.
8933
+ */
8934
+ getSubscribedScripts() {
8935
+ const scripts = new Set(this.getWatchedContracts().map((c) => c.script));
8936
+ for (const script of this.watchedScripts.keys()) {
8937
+ scripts.add(script);
8938
+ }
8939
+ return Array.from(scripts);
8940
+ }
8941
+ /** @see IContractManager.watchScript for the delivery and filter contract. */
8942
+ async addWatchedScript(script, options) {
8943
+ const existing = this.watchedScripts.get(script);
8944
+ if (existing) {
8945
+ if (options?.label !== void 0) existing.label = options.label;
8946
+ return;
8947
+ }
8948
+ this.watchedScripts.set(script, {
8949
+ label: options?.label,
8950
+ lastKnownVtxos: /* @__PURE__ */ new Map()
8951
+ });
8952
+ if (this.isWatching) {
8953
+ await this.pollWatchedScripts([script]);
8954
+ await this.tryUpdateSubscription();
8955
+ }
8956
+ }
8957
+ /** Stop watching a script added by {@link addWatchedScript}. */
8958
+ async removeWatchedScript(script) {
8959
+ if (!this.watchedScripts.delete(script)) return;
8960
+ if (this.isWatching) {
8961
+ await this.tryUpdateSubscription();
8962
+ }
8963
+ }
8964
+ /** Every script registered via {@link addWatchedScript}. */
8965
+ getWatchedScripts() {
8966
+ return Array.from(this.watchedScripts.entries()).map(([script, state]) => ({
8967
+ script,
8968
+ label: state.label
8969
+ }));
8970
+ }
8856
8971
  /**
8857
8972
  * Get virtual outputs for contracts, grouped by contract script.
8858
8973
  * @see WalletRepository for `repo`
@@ -8955,9 +9070,9 @@ var ContractWatcher = class {
8955
9070
  this.connectionState = "connected";
8956
9071
  this.reconnectAttempts = 0;
8957
9072
  this.listenLoop().catch((e) => {
8958
- if (chunk57636V35_cjs.isEventSourceError(e)) {
9073
+ if (chunk6FTHFJAN_cjs.isEventSourceError(e)) {
8959
9074
  console.debug("ContractWatcher subscription disconnected; reconnecting");
8960
- } else if (!chunk57636V35_cjs.isEventSourceUnavailableError(e)) {
9075
+ } else if (!chunk6FTHFJAN_cjs.isEventSourceUnavailableError(e)) {
8961
9076
  console.error(e);
8962
9077
  }
8963
9078
  this.connectionState = "disconnected";
@@ -8969,7 +9084,7 @@ var ContractWatcher = class {
8969
9084
  this.scheduleReconnect();
8970
9085
  });
8971
9086
  } catch (error) {
8972
- if (!chunk57636V35_cjs.isEventSourceUnavailableError(error)) {
9087
+ if (!chunk6FTHFJAN_cjs.isEventSourceUnavailableError(error)) {
8973
9088
  console.error("ContractWatcher connection failed:", error);
8974
9089
  }
8975
9090
  this.connectionState = "disconnected";
@@ -8995,7 +9110,7 @@ var ContractWatcher = class {
8995
9110
  * slower; what it loses is push latency.
8996
9111
  */
8997
9112
  reportEventSourceUnavailable(error) {
8998
- if (!chunk57636V35_cjs.isEventSourceUnavailableError(error)) return false;
9113
+ if (!chunk6FTHFJAN_cjs.isEventSourceUnavailableError(error)) return false;
8999
9114
  if (!this.eventSourceReported) {
9000
9115
  this.eventSourceReported = true;
9001
9116
  console.warn(
@@ -9044,8 +9159,72 @@ var ContractWatcher = class {
9044
9159
  }
9045
9160
  async pollAllContracts() {
9046
9161
  const scripts = this.getWatchedContracts().map((c) => c.script);
9162
+ if (scripts.length > 0) {
9163
+ await this.pollContracts(scripts);
9164
+ }
9165
+ await this.pollWatchedScripts(Array.from(this.watchedScripts.keys()));
9166
+ }
9167
+ /**
9168
+ * Poll watch-only scripts against the indexer and emit the delta.
9169
+ *
9170
+ * Separate from {@link pollContracts} because that one diffs the wallet
9171
+ * repository, which is permanently empty for a script this wallet does not
9172
+ * own — reusing it would report every live output as spent on every tick.
9173
+ * Not a second poll loop: same timer and callers, different source.
9174
+ */
9175
+ async pollWatchedScripts(candidates) {
9176
+ if (!this.eventCallback) return;
9177
+ const scripts = candidates.filter((s) => {
9178
+ const state = this.contracts.get(s);
9179
+ return this.watchedScripts.has(s) && (state === void 0 || !isWatchedContract(state.contract));
9180
+ });
9047
9181
  if (scripts.length === 0) return;
9048
- await this.pollContracts(scripts);
9182
+ const now = Date.now();
9183
+ let current;
9184
+ try {
9185
+ current = await chunk6FTHFJAN_cjs.getAllNormalizedVtxos(this.config.indexerProvider, scripts, {
9186
+ spendableOnly: true
9187
+ });
9188
+ } catch (error) {
9189
+ console.error("ContractWatcher watch-only poll failed:", error);
9190
+ return;
9191
+ }
9192
+ const byScript = /* @__PURE__ */ new Map();
9193
+ for (const vtxo of current) {
9194
+ let bucket = byScript.get(vtxo.script);
9195
+ if (!bucket) {
9196
+ bucket = [];
9197
+ byScript.set(vtxo.script, bucket);
9198
+ }
9199
+ bucket.push(vtxo);
9200
+ }
9201
+ for (const script of scripts) {
9202
+ const state = this.watchedScripts.get(script);
9203
+ if (!state) continue;
9204
+ const currentVtxos = byScript.get(script) || [];
9205
+ const currentKeys = new Set(currentVtxos.map((v) => `${v.txid}:${v.vout}`));
9206
+ const newVtxos = [];
9207
+ for (const vtxo of currentVtxos) {
9208
+ const key = `${vtxo.txid}:${vtxo.vout}`;
9209
+ if (!state.lastKnownVtxos.has(key)) {
9210
+ newVtxos.push(vtxo);
9211
+ state.lastKnownVtxos.set(key, vtxo);
9212
+ }
9213
+ }
9214
+ const spentVtxos = [];
9215
+ for (const [key, vtxo] of state.lastKnownVtxos) {
9216
+ if (!currentKeys.has(key)) {
9217
+ spentVtxos.push(vtxo);
9218
+ state.lastKnownVtxos.delete(key);
9219
+ }
9220
+ }
9221
+ if (newVtxos.length > 0) {
9222
+ this.emitWatchedScriptEvent(script, newVtxos, "vtxo_received", now);
9223
+ }
9224
+ if (spentVtxos.length > 0) {
9225
+ this.emitWatchedScriptEvent(script, spentVtxos, "vtxo_spent", now);
9226
+ }
9227
+ }
9049
9228
  }
9050
9229
  /**
9051
9230
  * Poll specific contracts and emit events for changes.
@@ -9056,13 +9235,14 @@ var ContractWatcher = class {
9056
9235
  try {
9057
9236
  const vtxosMap = await this.getContractVtxos({
9058
9237
  contractScripts,
9059
- includeSpent: false
9060
- // only spendable ones!
9238
+ includeSpent: true
9061
9239
  });
9062
9240
  for (const contractScript of contractScripts) {
9063
9241
  const state = this.contracts.get(contractScript);
9064
9242
  if (!state) continue;
9065
- const currentVtxos = vtxosMap.get(contractScript) || [];
9243
+ const known = vtxosMap.get(contractScript) || [];
9244
+ const knownByKey = new Map(known.map((v) => [`${v.txid}:${v.vout}`, v]));
9245
+ const currentVtxos = known.filter((v) => !v.isSpent);
9066
9246
  const currentKeys = new Set(currentVtxos.map((v) => `${v.txid}:${v.vout}`));
9067
9247
  const newVtxos = [];
9068
9248
  for (const vtxo of currentVtxos) {
@@ -9075,7 +9255,7 @@ var ContractWatcher = class {
9075
9255
  const spentVtxos = [];
9076
9256
  for (const [key, vtxo] of state.lastKnownVtxos) {
9077
9257
  if (!currentKeys.has(key)) {
9078
- spentVtxos.push(vtxo);
9258
+ spentVtxos.push(knownByKey.get(key) ?? vtxo);
9079
9259
  state.lastKnownVtxos.delete(key);
9080
9260
  }
9081
9261
  }
@@ -9146,10 +9326,10 @@ var ContractWatcher = class {
9146
9326
  /**
9147
9327
  * Update the subscription with scripts that should be watched.
9148
9328
  *
9149
- * @see getWatchedContracts
9329
+ * @see getSubscribedScripts
9150
9330
  */
9151
9331
  async updateSubscription() {
9152
- const scriptsToWatch = this.getWatchedContracts().map((c) => c.script);
9332
+ const scriptsToWatch = this.getSubscribedScripts();
9153
9333
  if (scriptsToWatch.length === 0) {
9154
9334
  if (this.subscriptionId) {
9155
9335
  try {
@@ -9211,14 +9391,14 @@ var ContractWatcher = class {
9211
9391
  const timestamp = Date.now();
9212
9392
  if (update.newVtxos?.length) {
9213
9393
  this.processSubscriptionVtxos(
9214
- update.newVtxos.map(chunk57636V35_cjs.normalizeVtxo),
9394
+ update.newVtxos.map(chunk6FTHFJAN_cjs.normalizeVtxo),
9215
9395
  "vtxo_received",
9216
9396
  timestamp
9217
9397
  );
9218
9398
  }
9219
9399
  if (update.spentVtxos?.length) {
9220
9400
  this.processSubscriptionVtxos(
9221
- update.spentVtxos.map(chunk57636V35_cjs.normalizeVtxo),
9401
+ update.spentVtxos.map(chunk6FTHFJAN_cjs.normalizeVtxo),
9222
9402
  "vtxo_spent",
9223
9403
  timestamp
9224
9404
  );
@@ -9233,16 +9413,26 @@ var ContractWatcher = class {
9233
9413
  */
9234
9414
  processSubscriptionVtxos(vtxos, eventType, timestamp) {
9235
9415
  const byContract = /* @__PURE__ */ new Map();
9416
+ const byWatchedScript = /* @__PURE__ */ new Map();
9236
9417
  let unknownScript = 0;
9418
+ const now = { timestamp: /* @__PURE__ */ new Date() };
9237
9419
  for (const vtxo of vtxos) {
9238
- if (!this.contracts.has(vtxo.script)) {
9420
+ const state = this.contracts.get(vtxo.script);
9421
+ const watchOnly = this.watchedScripts.has(vtxo.script);
9422
+ const preferContract = state !== void 0 && (!watchOnly || isWatchedContract(state.contract));
9423
+ const target = preferContract ? byContract : watchOnly ? byWatchedScript : void 0;
9424
+ if (!target) {
9239
9425
  unknownScript++;
9240
9426
  continue;
9241
9427
  }
9242
- let bucket = byContract.get(vtxo.script);
9428
+ if (target === byWatchedScript && eventType === "vtxo_received") {
9429
+ const n = chunk6FTHFJAN_cjs.normalizeVtxo(vtxo);
9430
+ if (chunk6FTHFJAN_cjs.hasTerminalSpend(n) || n.isSwept || chunk6FTHFJAN_cjs.isPastExpiry(n, now)) continue;
9431
+ }
9432
+ let bucket = target.get(vtxo.script);
9243
9433
  if (!bucket) {
9244
9434
  bucket = [];
9245
- byContract.set(vtxo.script, bucket);
9435
+ target.set(vtxo.script, bucket);
9246
9436
  }
9247
9437
  bucket.push(vtxo);
9248
9438
  }
@@ -9265,6 +9455,29 @@ var ContractWatcher = class {
9265
9455
  }
9266
9456
  this.emitVtxoEvent(contractScript, bucketVtxos, eventType, timestamp);
9267
9457
  }
9458
+ for (const [script, bucketVtxos] of byWatchedScript) {
9459
+ const state = this.watchedScripts.get(script);
9460
+ if (state) {
9461
+ for (const vtxo of bucketVtxos) {
9462
+ const key = `${vtxo.txid}:${vtxo.vout}`;
9463
+ if (eventType === "vtxo_received") {
9464
+ state.lastKnownVtxos.set(key, vtxo);
9465
+ } else {
9466
+ state.lastKnownVtxos.delete(key);
9467
+ }
9468
+ }
9469
+ }
9470
+ this.emitWatchedScriptEvent(script, bucketVtxos, eventType, timestamp);
9471
+ }
9472
+ }
9473
+ /** As {@link emitVtxoEvent}, less the `contract` and the annotation. */
9474
+ emitWatchedScriptEvent(script, vtxos, eventType, timestamp) {
9475
+ if (!this.eventCallback) return;
9476
+ if (eventType === "vtxo_received") {
9477
+ this.eventCallback({ type: "vtxo_received", contractScript: script, vtxos, timestamp });
9478
+ return;
9479
+ }
9480
+ this.eventCallback({ type: "vtxo_spent", contractScript: script, vtxos, timestamp });
9268
9481
  }
9269
9482
  /**
9270
9483
  * Emit a virtual output event for a contract.
@@ -9313,7 +9526,7 @@ var NON_TERMINAL_INTENT_STATES = ALL_INTENT_STATES.filter(
9313
9526
  (s) => !isTerminalIntentState(s)
9314
9527
  );
9315
9528
  function isConsumed(vtxo) {
9316
- return vtxo !== void 0 && chunk57636V35_cjs.hasTerminalSpend(vtxo);
9529
+ return vtxo !== void 0 && chunk6FTHFJAN_cjs.hasTerminalSpend(vtxo);
9317
9530
  }
9318
9531
  async function classifyIntent(intent, vtxosByOutpoint, now) {
9319
9532
  if (isTerminalIntentState(intent.state)) return void 0;
@@ -9356,7 +9569,7 @@ async function reconcileIntents(deps) {
9356
9569
  let vtxosByOutpoint = /* @__PURE__ */ new Map();
9357
9570
  if (outpoints.length > 0) {
9358
9571
  try {
9359
- const { vtxos } = await chunk57636V35_cjs.getNormalizedVtxos(deps.indexerProvider, { outpoints });
9572
+ const { vtxos } = await chunk6FTHFJAN_cjs.getNormalizedVtxos(deps.indexerProvider, { outpoints });
9360
9573
  vtxosByOutpoint = new Map(vtxos.map((v) => [outpointKey(v), v]));
9361
9574
  } catch (e) {
9362
9575
  console.error("reconcileIntents: failed to fetch input VTXO state", e);
@@ -9436,6 +9649,7 @@ var ContractManager = class _ContractManager {
9436
9649
  syncDegradedReason;
9437
9650
  /** Epoch-ms of the last successful provider sync, if any. */
9438
9651
  lastSyncedAt;
9652
+ syncedAtByScript = /* @__PURE__ */ new Map();
9439
9653
  /** Last chain tip read, with the epoch-ms it was read at. @see currentChainTip */
9440
9654
  chainTipCache;
9441
9655
  /** In-flight chain tip read, so concurrent cache misses share one. */
@@ -9489,6 +9703,10 @@ var ContractManager = class _ContractManager {
9489
9703
  lastSyncedAt: this.lastSyncedAt
9490
9704
  };
9491
9705
  }
9706
+ /** @see ContractManagerConfig.vtxoSyncMaxAgeMs — for factory-built managers. */
9707
+ setVtxoSyncMaxAge(maxAgeMs) {
9708
+ this.config.vtxoSyncMaxAgeMs = maxAgeMs;
9709
+ }
9492
9710
  markSyncOnline() {
9493
9711
  this.lastSyncedAt = Date.now();
9494
9712
  this.syncDegradedReason = this.annotationDegradedReason();
@@ -9530,7 +9748,7 @@ var ContractManager = class _ContractManager {
9530
9748
  await this.reconcileWatched();
9531
9749
  this.markSyncOnline();
9532
9750
  } catch (err) {
9533
- if (!chunk57636V35_cjs.isRetryableProviderError(err)) throw err;
9751
+ if (!chunk6FTHFJAN_cjs.isRetryableProviderError(err)) throw err;
9534
9752
  this.markSyncDegraded(err);
9535
9753
  }
9536
9754
  this.initialized = true;
@@ -9662,7 +9880,7 @@ var ContractManager = class _ContractManager {
9662
9880
  const from = Math.max(0, watermark - lookAhead.size);
9663
9881
  const to = watermark + lookAhead.size;
9664
9882
  const deps = lookAhead.candidateDeps();
9665
- const handlers = chunk3OKEUDHU_cjs.contractHandlers.getRegisteredTypes().map((t) => chunk3OKEUDHU_cjs.contractHandlers.get(t)).filter(hasCandidates);
9883
+ const handlers = chunkNPM5YZBC_cjs.contractHandlers.getRegisteredTypes().map((t) => chunkNPM5YZBC_cjs.contractHandlers.get(t)).filter(hasCandidates);
9666
9884
  const band = /* @__PURE__ */ new Map();
9667
9885
  for (let index = from; index <= to; index++) {
9668
9886
  const descriptor = lookAhead.materialize(index);
@@ -9673,7 +9891,7 @@ var ContractManager = class _ContractManager {
9673
9891
  index,
9674
9892
  params: {
9675
9893
  ...candidate,
9676
- ...chunk3OKEUDHU_cjs.speculativeReceiveMetadata(descriptor)
9894
+ ...chunkNPM5YZBC_cjs.speculativeReceiveMetadata(descriptor)
9677
9895
  }
9678
9896
  });
9679
9897
  }
@@ -9735,7 +9953,7 @@ var ContractManager = class _ContractManager {
9735
9953
  });
9736
9954
  for (const entry of pending) entry.catchUpPending = false;
9737
9955
  } catch (err) {
9738
- if (!chunk57636V35_cjs.isRetryableProviderError(err)) throw err;
9956
+ if (!chunk6FTHFJAN_cjs.isRetryableProviderError(err)) throw err;
9739
9957
  this.markSyncDegraded(err);
9740
9958
  }
9741
9959
  }
@@ -9785,13 +10003,48 @@ var ContractManager = class _ContractManager {
9785
10003
  await this.fetchContractVxosFromIndexer([contract]);
9786
10004
  this.markSyncOnline();
9787
10005
  } catch (err) {
9788
- if (!chunk57636V35_cjs.isRetryableProviderError(err)) throw err;
10006
+ if (!chunk6FTHFJAN_cjs.isRetryableProviderError(err)) throw err;
9789
10007
  this.markSyncDegraded(err);
9790
10008
  }
9791
10009
  await this.watcher.addContract(contract);
9792
10010
  }
9793
10011
  return contract;
9794
10012
  }
10013
+ /**
10014
+ * `createContract`'s step order, fetch batched: persist all, hydrate once,
10015
+ * then watch. Hydrating first keeps it equivalent — the watcher seeds from
10016
+ * the repository, so an unhydrated row reads as all-new. A part-way failure
10017
+ * still watches what it wrote; a retry reports those rows as existing.
10018
+ */
10019
+ async createContracts(paramsList) {
10020
+ if (paramsList.length === 0) return [];
10021
+ return this.watcher.withCoalescedSubscription(async () => {
10022
+ const upserted = [];
10023
+ try {
10024
+ for (const params of paramsList) upserted.push(await this.upsertContract(params));
10025
+ } catch (err) {
10026
+ for (const u of upserted) {
10027
+ if (!u.persisted) continue;
10028
+ await this.watcher.addContract(u.contract).catch(
10029
+ (e) => console.error(`ContractManager: ${u.contract.script} left dark`, e)
10030
+ );
10031
+ }
10032
+ throw err;
10033
+ }
10034
+ const fresh = upserted.filter((u) => u.persisted).map((u) => u.contract);
10035
+ if (fresh.length > 0) {
10036
+ try {
10037
+ await this.fetchContractVxosFromIndexer(fresh);
10038
+ this.markSyncOnline();
10039
+ } catch (err) {
10040
+ if (!chunk6FTHFJAN_cjs.isRetryableProviderError(err)) throw err;
10041
+ this.markSyncDegraded(err);
10042
+ }
10043
+ for (const contract of fresh) await this.watcher.addContract(contract);
10044
+ }
10045
+ return upserted.map((u) => u.contract);
10046
+ });
10047
+ }
9795
10048
  /**
9796
10049
  * Lightweight variant of {@link createContract} for batch discovery
9797
10050
  * paths (currently: {@link scanContracts}). Validates, dedupes, persists,
@@ -9822,7 +10075,7 @@ var ContractManager = class _ContractManager {
9822
10075
  return result;
9823
10076
  }
9824
10077
  async upsertContractRow(params) {
9825
- const handler = chunk3OKEUDHU_cjs.contractHandlers.get(params.type);
10078
+ const handler = chunkNPM5YZBC_cjs.contractHandlers.get(params.type);
9826
10079
  if (!handler) {
9827
10080
  throw new Error(`No handler registered for contract type '${params.type}'`);
9828
10081
  }
@@ -9922,7 +10175,7 @@ var ContractManager = class _ContractManager {
9922
10175
  `scanContracts: batchSize must be a positive integer (got ${String(opts.batchSize)})`
9923
10176
  );
9924
10177
  }
9925
- const registered = chunk3OKEUDHU_cjs.contractHandlers.getRegisteredTypes().map((t) => chunk3OKEUDHU_cjs.contractHandlers.get(t)).filter(isDiscoverable);
10178
+ const registered = chunkNPM5YZBC_cjs.contractHandlers.getRegisteredTypes().map((t) => chunkNPM5YZBC_cjs.contractHandlers.get(t)).filter(isDiscoverable);
9926
10179
  const discoverables = [
9927
10180
  ...registered.filter((h) => h.type === "boarding"),
9928
10181
  ...registered.filter((h) => h.type !== "boarding")
@@ -10053,12 +10306,16 @@ var ContractManager = class _ContractManager {
10053
10306
  }
10054
10307
  async getContractsWithVtxos(filter, pageSize) {
10055
10308
  const contracts = await this.getContracts(filter);
10056
- try {
10057
- await this.syncContracts({ contracts, pageSize });
10058
- this.markSyncOnline();
10059
- } catch (err) {
10060
- if (!chunk57636V35_cjs.isRetryableProviderError(err)) throw err;
10061
- this.markSyncDegraded(err);
10309
+ if (this.syncedWithin(contracts, this.config.vtxoSyncMaxAgeMs ?? 0)) {
10310
+ await this.demoteFundedAwaitingContracts(contracts);
10311
+ } else {
10312
+ try {
10313
+ await this.syncContracts({ contracts, pageSize });
10314
+ this.markSyncOnline();
10315
+ } catch (err) {
10316
+ if (!chunk6FTHFJAN_cjs.isRetryableProviderError(err)) throw err;
10317
+ this.markSyncDegraded(err);
10318
+ }
10062
10319
  }
10063
10320
  const vtxos = await this.getVtxosForContracts(contracts);
10064
10321
  return contracts.map((contract) => ({
@@ -10078,7 +10335,7 @@ var ContractManager = class _ContractManager {
10078
10335
  }
10079
10336
  const tapscriptCache = tapscripts ?? /* @__PURE__ */ new Map();
10080
10337
  return vtxos.map(
10081
- (vtxo) => extendVirtualCoinForContract(chunk57636V35_cjs.normalizeVtxo(vtxo), byScript, tapscriptCache)
10338
+ (vtxo) => extendVirtualCoinForContract(chunk6FTHFJAN_cjs.normalizeVtxo(vtxo), byScript, tapscriptCache)
10082
10339
  );
10083
10340
  }
10084
10341
  /** @inheritdoc */
@@ -10122,14 +10379,14 @@ var ContractManager = class _ContractManager {
10122
10379
  const byScript = new Map(contracts.map((contract) => [contract.script, contract]));
10123
10380
  const asking = vtxos.filter((vtxo) => {
10124
10381
  const contract = byScript.get(vtxo.script);
10125
- return contract !== void 0 && chunk3OKEUDHU_cjs.contractHandlers.get(contract.type)?.assertSpendableNow !== void 0;
10382
+ return contract !== void 0 && chunkNPM5YZBC_cjs.contractHandlers.get(contract.type)?.assertSpendableNow !== void 0;
10126
10383
  });
10127
10384
  if (asking.length === 0) return refused;
10128
10385
  const tip = await this.currentChainTip();
10129
10386
  const walletKey = await walletPubKey?.();
10130
10387
  for (const vtxo of asking) {
10131
10388
  const contract = byScript.get(vtxo.script);
10132
- const handler = chunk3OKEUDHU_cjs.contractHandlers.get(contract.type);
10389
+ const handler = chunkNPM5YZBC_cjs.contractHandlers.get(contract.type);
10133
10390
  if (!handler?.assertSpendableNow) continue;
10134
10391
  const context = {
10135
10392
  collaborative: true,
@@ -10144,7 +10401,7 @@ var ContractManager = class _ContractManager {
10144
10401
  // the next handler to answer a CSV question would meet a
10145
10402
  // TypeError instead of a `false`. Carry the coin only when it
10146
10403
  // really is one.
10147
- vtxo: chunk57636V35_cjs.isVirtualCoin(vtxo) && "status" in vtxo ? vtxo : void 0
10404
+ vtxo: chunk6FTHFJAN_cjs.isVirtualCoin(vtxo) && "status" in vtxo ? vtxo : void 0
10148
10405
  };
10149
10406
  try {
10150
10407
  await handler.assertSpendableNow(
@@ -10300,7 +10557,7 @@ var ContractManager = class _ContractManager {
10300
10557
  const { contractScript, collaborative = true, walletPubKey, vtxo } = options;
10301
10558
  const [contract] = await this.getContracts({ script: contractScript });
10302
10559
  if (!contract) return [];
10303
- const handler = chunk3OKEUDHU_cjs.contractHandlers.get(contract.type);
10560
+ const handler = chunkNPM5YZBC_cjs.contractHandlers.get(contract.type);
10304
10561
  if (!handler) return [];
10305
10562
  const script = handler.createScript(contract.params);
10306
10563
  const tip = await this.currentChainTip();
@@ -10328,7 +10585,7 @@ var ContractManager = class _ContractManager {
10328
10585
  const { contractScript, collaborative = true, walletPubKey } = options;
10329
10586
  const [contract] = await this.getContracts({ script: contractScript });
10330
10587
  if (!contract) return [];
10331
- const handler = chunk3OKEUDHU_cjs.contractHandlers.get(contract.type);
10588
+ const handler = chunkNPM5YZBC_cjs.contractHandlers.get(contract.type);
10332
10589
  if (!handler) return [];
10333
10590
  const script = handler.createScript(contract.params);
10334
10591
  const context = {
@@ -10384,7 +10641,7 @@ var ContractManager = class _ContractManager {
10384
10641
  }
10385
10642
  async refreshOutpoints(outpoints) {
10386
10643
  if (outpoints.length === 0) return;
10387
- const { vtxos } = await chunk57636V35_cjs.getNormalizedVtxos(this.config.indexerProvider, {
10644
+ const { vtxos } = await chunk6FTHFJAN_cjs.getNormalizedVtxos(this.config.indexerProvider, {
10388
10645
  outpoints
10389
10646
  });
10390
10647
  if (vtxos.length === 0) return;
@@ -10420,6 +10677,18 @@ var ContractManager = class _ContractManager {
10420
10677
  async isWatching() {
10421
10678
  return this.watcher.isCurrentlyWatching();
10422
10679
  }
10680
+ /** @see IContractManager.watchScript */
10681
+ async watchScript(script, options) {
10682
+ await this.watcher.addWatchedScript(script, options);
10683
+ }
10684
+ /** @see IContractManager.unwatchScript */
10685
+ async unwatchScript(script) {
10686
+ await this.watcher.removeWatchedScript(script);
10687
+ }
10688
+ /** @see IContractManager.getWatchedScripts */
10689
+ async getWatchedScripts() {
10690
+ return this.watcher.getWatchedScripts();
10691
+ }
10423
10692
  /**
10424
10693
  * Emit an event to all registered callbacks.
10425
10694
  */
@@ -10440,11 +10709,15 @@ var ContractManager = class _ContractManager {
10440
10709
  try {
10441
10710
  switch (event.type) {
10442
10711
  // Delta-sync only the changed virtual outputs for this contract.
10712
+ // The guard below is the ownership boundary: a watch-only script
10713
+ // reports these same types, so it must precede `syncContracts`.
10443
10714
  case "vtxo_received":
10715
+ if (!isContractVtxoEvent(event)) break;
10444
10716
  await this.syncContracts({ contracts: [event.contract] });
10445
10717
  this.markSyncOnline();
10446
10718
  break;
10447
10719
  case "vtxo_spent":
10720
+ if (!isContractVtxoEvent(event)) break;
10448
10721
  await this.syncContracts({ contracts: [event.contract] });
10449
10722
  this.markSyncOnline();
10450
10723
  if (this.config.onVtxosSpent) {
@@ -10457,13 +10730,14 @@ var ContractManager = class _ContractManager {
10457
10730
  }
10458
10731
  break;
10459
10732
  case "connection_reset":
10733
+ this.syncedAtByScript.clear();
10460
10734
  await this.scheduleLookAheadDrain();
10461
10735
  await this.reconcileWatched();
10462
10736
  this.markSyncOnline();
10463
10737
  break;
10464
10738
  }
10465
10739
  } catch (err) {
10466
- if (!chunk57636V35_cjs.isRetryableProviderError(err)) throw err;
10740
+ if (!chunk6FTHFJAN_cjs.isRetryableProviderError(err)) throw err;
10467
10741
  this.markSyncDegraded(err);
10468
10742
  }
10469
10743
  this.emitEvent(event);
@@ -10503,9 +10777,21 @@ var ContractManager = class _ContractManager {
10503
10777
  const cutoff = cursorCutoff(requestStartedAt);
10504
10778
  await advanceSyncCursor(this.config.walletRepository, cutoff);
10505
10779
  }
10780
+ if (options.window === void 0) {
10781
+ for (const contract of contracts) {
10782
+ this.syncedAtByScript.set(contract.script, requestStartedAt);
10783
+ }
10784
+ }
10506
10785
  await this.demoteFundedAwaitingContracts(contracts);
10507
10786
  return result;
10508
10787
  }
10788
+ syncedWithin(contracts, maxAgeMs) {
10789
+ if (maxAgeMs <= 0) return false;
10790
+ const floor = Date.now() - maxAgeMs;
10791
+ return contracts.every(
10792
+ (contract) => (this.syncedAtByScript.get(contract.script) ?? 0) >= floor
10793
+ );
10794
+ }
10509
10795
  /**
10510
10796
  * Demote every `awaiting-funds` contract in `contracts` that has been
10511
10797
  * funded — the automatic half of {@link ContractWatchState}.
@@ -10542,7 +10828,7 @@ var ContractManager = class _ContractManager {
10542
10828
  */
10543
10829
  async reconcilePendingFrontier(contracts) {
10544
10830
  const scriptToContract = new Map(contracts.map((c) => [c.script, c]));
10545
- const vtxos = await chunk57636V35_cjs.getAllNormalizedVtxos(
10831
+ const vtxos = await chunk6FTHFJAN_cjs.getAllNormalizedVtxos(
10546
10832
  this.config.indexerProvider,
10547
10833
  contracts.map((c) => c.script),
10548
10834
  { pendingOnly: true }
@@ -10625,7 +10911,7 @@ var ContractManager = class _ContractManager {
10625
10911
  }
10626
10912
  return result;
10627
10913
  }
10628
- async fetchContractVtxosBulk(contracts, pageSize = chunk57636V35_cjs.DEFAULT_PAGE_SIZE, syncWindow) {
10914
+ async fetchContractVtxosBulk(contracts, pageSize = chunk6FTHFJAN_cjs.DEFAULT_PAGE_SIZE, syncWindow) {
10629
10915
  if (contracts.length === 0) {
10630
10916
  return { vtxosByScript: /* @__PURE__ */ new Map(), promoted: /* @__PURE__ */ new Map() };
10631
10917
  }
@@ -10641,7 +10927,7 @@ var ContractManager = class _ContractManager {
10641
10927
  before: syncWindow.before
10642
10928
  }
10643
10929
  } : {};
10644
- const vtxos = await chunk57636V35_cjs.getAllNormalizedVtxos(
10930
+ const vtxos = await chunk6FTHFJAN_cjs.getAllNormalizedVtxos(
10645
10931
  this.config.indexerProvider,
10646
10932
  contracts.map((c) => c.script),
10647
10933
  { ...windowOpts, pageSize }
@@ -10786,7 +11072,7 @@ var deserializeTapLeaf = (t) => {
10786
11072
  const s = base.hex.decode(t.s);
10787
11073
  return [cb, s];
10788
11074
  };
10789
- var deserializeVtxo = (o) => chunk57636V35_cjs.normalizeVtxo({
11075
+ var deserializeVtxo = (o) => chunk6FTHFJAN_cjs.normalizeVtxo({
10790
11076
  ...o,
10791
11077
  createdAt: new Date(o.createdAt),
10792
11078
  tapTree: base.hex.decode(o.tapTree),
@@ -11609,7 +11895,7 @@ var HDDescriptorProvider = class _HDDescriptorProvider {
11609
11895
  */
11610
11896
  materializeDescriptorAt(index) {
11611
11897
  const descriptor = this.identity.descriptor;
11612
- const network = chunk3OKEUDHU_cjs.isMainnetDescriptor(descriptor) ? descriptorsScure.networks.bitcoin : descriptorsScure.networks.testnet;
11898
+ const network = chunkNPM5YZBC_cjs.isMainnetDescriptor(descriptor) ? descriptorsScure.networks.bitcoin : descriptorsScure.networks.testnet;
11613
11899
  const expansion = descriptorsScure.expand({ descriptor, network, index });
11614
11900
  const keyInfo = expansion.expansionMap?.["@0"];
11615
11901
  if (!keyInfo?.keyExpression) {
@@ -11757,7 +12043,7 @@ var WalletReceiveRotator = class _WalletReceiveRotator {
11757
12043
  const provider = await resolveDescriptorProvider(config, setup.walletRepository);
11758
12044
  if (!provider) return void 0;
11759
12045
  const allowSilentFallback = (config.walletMode ?? "auto") === "auto";
11760
- const expectedContractType = setup.offchainTapscript instanceof chunk3OKEUDHU_cjs.DelegateVtxo.Script ? "delegate" : "default";
12046
+ const expectedContractType = setup.offchainTapscript instanceof chunkNPM5YZBC_cjs.DelegateVtxo.Script ? "delegate" : "default";
11761
12047
  const factoryOpts = {
11762
12048
  walletRepository: setup.walletRepository,
11763
12049
  contractRepository: setup.contractRepository,
@@ -11958,7 +12244,7 @@ var WalletReceiveRotator = class _WalletReceiveRotator {
11958
12244
  };
11959
12245
  function deriveLeafPubkey(descriptor) {
11960
12246
  try {
11961
- return chunk3OKEUDHU_cjs.deriveDescriptorLeafPubKey(descriptor);
12247
+ return chunkNPM5YZBC_cjs.deriveDescriptorLeafPubKey(descriptor);
11962
12248
  } catch (e) {
11963
12249
  throw new NonRangeableDescriptorError(
11964
12250
  "Cannot derive leaf pubkey: descriptor is not a materialized, parsable tr(...) shape.",
@@ -11970,7 +12256,7 @@ function buildReceiveContract(current, descriptor, hrp, tagSource) {
11970
12256
  const pubKey = deriveLeafPubkey(descriptor);
11971
12257
  const tapscript = rebuildTapscript(current, pubKey);
11972
12258
  const serverPubKey = tapscript.options.serverPubKey;
11973
- const csvTimelock = chunk57636V35_cjs.timelockToSequence(tapscript.options.csvTimelock).toString();
12259
+ const csvTimelock = chunk6FTHFJAN_cjs.timelockToSequence(tapscript.options.csvTimelock).toString();
11974
12260
  const base$1 = {
11975
12261
  script: base.hex.encode(tapscript.pkScript),
11976
12262
  address: tapscript.address(hrp, serverPubKey).encode(),
@@ -11981,11 +12267,11 @@ function buildReceiveContract(current, descriptor, hrp, tagSource) {
11981
12267
  // index-0 key. Without it, spends produce unsigned PSBTs that the
11982
12268
  // server rejects with `INVALID_PSBT_INPUT (5): missing tapscript spend sig`.
11983
12269
  metadata: {
11984
- ...tagSource && { source: chunk3OKEUDHU_cjs.WALLET_RECEIVE_SOURCE },
12270
+ ...tagSource && { source: chunkNPM5YZBC_cjs.WALLET_RECEIVE_SOURCE },
11985
12271
  signingDescriptor: descriptor
11986
12272
  }
11987
12273
  };
11988
- const params = tapscript instanceof chunk3OKEUDHU_cjs.DelegateVtxo.Script ? {
12274
+ const params = tapscript instanceof chunkNPM5YZBC_cjs.DelegateVtxo.Script ? {
11989
12275
  ...base$1,
11990
12276
  type: "delegate",
11991
12277
  params: {
@@ -12006,10 +12292,10 @@ function buildReceiveContract(current, descriptor, hrp, tagSource) {
12006
12292
  return { tapscript, params };
12007
12293
  }
12008
12294
  function rebuildTapscript(current, pubKey) {
12009
- if (current instanceof chunk3OKEUDHU_cjs.DelegateVtxo.Script) {
12010
- return new chunk3OKEUDHU_cjs.DelegateVtxo.Script({ ...current.options, pubKey });
12295
+ if (current instanceof chunkNPM5YZBC_cjs.DelegateVtxo.Script) {
12296
+ return new chunkNPM5YZBC_cjs.DelegateVtxo.Script({ ...current.options, pubKey });
12011
12297
  }
12012
- return new chunk3OKEUDHU_cjs.DefaultVtxo.Script({ ...current.options, pubKey });
12298
+ return new chunkNPM5YZBC_cjs.DefaultVtxo.Script({ ...current.options, pubKey });
12013
12299
  }
12014
12300
  async function pickActiveReceive(contractRepository, serverPubKey, expectedType) {
12015
12301
  const candidates = await contractRepository.getContracts({
@@ -12018,7 +12304,7 @@ async function pickActiveReceive(contractRepository, serverPubKey, expectedType)
12018
12304
  });
12019
12305
  const serverPubKeyHex = base.hex.encode(serverPubKey);
12020
12306
  const matching = candidates.filter(
12021
- (c) => c.params.serverPubKey === serverPubKeyHex && c.metadata?.source === chunk3OKEUDHU_cjs.WALLET_RECEIVE_SOURCE
12307
+ (c) => c.params.serverPubKey === serverPubKeyHex && c.metadata?.source === chunkNPM5YZBC_cjs.WALLET_RECEIVE_SOURCE
12022
12308
  ).sort((a, b) => {
12023
12309
  if (b.createdAt !== a.createdAt) return b.createdAt - a.createdAt;
12024
12310
  return signingDescriptorIndex(b.metadata?.signingDescriptor) - signingDescriptorIndex(a.metadata?.signingDescriptor);
@@ -12074,7 +12360,7 @@ function computeOffchainBalance(vtxos, caps) {
12074
12360
  }
12075
12361
  };
12076
12362
  for (const vtxo of vtxos) {
12077
- if (chunk57636V35_cjs.hasTerminalSpend(vtxo)) continue;
12363
+ if (chunk6FTHFJAN_cjs.hasTerminalSpend(vtxo)) continue;
12078
12364
  addAssets(owned, vtxo);
12079
12365
  if (vtxo.isUnrolled) {
12080
12366
  unrolled += vtxo.value;
@@ -12084,11 +12370,11 @@ function computeOffchainBalance(vtxos, caps) {
12084
12370
  pendingRecovery += vtxo.value;
12085
12371
  continue;
12086
12372
  }
12087
- if (chunk57636V35_cjs.canRecoverOnchain(vtxo, now)) {
12373
+ if (chunk6FTHFJAN_cjs.canRecoverOnchain(vtxo, now)) {
12088
12374
  recoverable += vtxo.value;
12089
12375
  continue;
12090
12376
  }
12091
- if (!chunk57636V35_cjs.canSpendOffchain(vtxo, now)) continue;
12377
+ if (!chunk6FTHFJAN_cjs.canSpendOffchain(vtxo, now)) continue;
12092
12378
  if (vtxo.isPreconfirmed) {
12093
12379
  preconfirmed += vtxo.value;
12094
12380
  } else {
@@ -12258,12 +12544,12 @@ var InputSignerRouter = class {
12258
12544
  };
12259
12545
 
12260
12546
  // src/wallet/wallet.ts
12261
- var getArkadeServerUrl = ({ arkServerUrl }) => arkServerUrl || chunk57636V35_cjs.DEFAULT_ARKADE_SERVER_URL;
12547
+ var getArkadeServerUrl = ({ arkServerUrl }) => arkServerUrl || chunk6FTHFJAN_cjs.DEFAULT_ARKADE_SERVER_URL;
12262
12548
  function intentProofJobs(coins) {
12263
12549
  if (coins.length === 0) return [];
12264
12550
  const coinJobs = coins.map((coin, i) => ({
12265
12551
  index: i + 1,
12266
- lookupScript: chunk57636V35_cjs.VtxoScript.decode(coin.tapTree).pkScript
12552
+ lookupScript: chunk6FTHFJAN_cjs.VtxoScript.decode(coin.tapTree).pkScript
12267
12553
  }));
12268
12554
  return [{ index: 0, lookupScript: coinJobs[0].lookupScript }, ...coinJobs];
12269
12555
  }
@@ -12295,7 +12581,7 @@ function dedupeTimelocks(timelocks) {
12295
12581
  const seen = /* @__PURE__ */ new Set();
12296
12582
  const deduped = [];
12297
12583
  for (const timelock of timelocks) {
12298
- const sequence = chunk57636V35_cjs.timelockToSequence(timelock).toString();
12584
+ const sequence = chunk6FTHFJAN_cjs.timelockToSequence(timelock).toString();
12299
12585
  if (seen.has(sequence)) continue;
12300
12586
  seen.add(sequence);
12301
12587
  deduped.push(timelock);
@@ -12312,7 +12598,7 @@ async function resolveBoardingBootTapscript(contractRepository, serverPubKey, ba
12312
12598
  state: "active"
12313
12599
  });
12314
12600
  const newest = candidates.filter(
12315
- (c) => c.params.serverPubKey === serverPubKeyHex && c.metadata?.source === chunk3OKEUDHU_cjs.WALLET_RECEIVE_SOURCE
12601
+ (c) => c.params.serverPubKey === serverPubKeyHex && c.metadata?.source === chunkNPM5YZBC_cjs.WALLET_RECEIVE_SOURCE
12316
12602
  ).sort((a, b) => {
12317
12603
  if (b.createdAt !== a.createdAt) return b.createdAt - a.createdAt;
12318
12604
  return signingDescriptorIndex(b.metadata?.signingDescriptor) - signingDescriptorIndex(a.metadata?.signingDescriptor);
@@ -12320,7 +12606,7 @@ async function resolveBoardingBootTapscript(contractRepository, serverPubKey, ba
12320
12606
  if (!newest?.params.pubKey) return baseline;
12321
12607
  try {
12322
12608
  const pubKey = base.hex.decode(newest.params.pubKey);
12323
- return new chunk3OKEUDHU_cjs.DefaultVtxo.Script({ ...baseline.options, pubKey });
12609
+ return new chunkNPM5YZBC_cjs.DefaultVtxo.Script({ ...baseline.options, pubKey });
12324
12610
  } catch (e) {
12325
12611
  console.warn("Skipping malformed boarding contract at boot", newest.script, e);
12326
12612
  return baseline;
@@ -12339,10 +12625,10 @@ function filterSnapshotVtxos(snapshot, filter, pendingSpendOutpoints) {
12339
12625
  if (vtxo.isUnrolled) {
12340
12626
  return !!f.withUnrolled;
12341
12627
  }
12342
- if (chunk57636V35_cjs.hasTerminalSpend(vtxo)) {
12628
+ if (chunk6FTHFJAN_cjs.hasTerminalSpend(vtxo)) {
12343
12629
  return false;
12344
12630
  }
12345
- if (!f.withRecoverable && chunk57636V35_cjs.canRecoverOnchain(vtxo, now)) {
12631
+ if (!f.withRecoverable && chunk6FTHFJAN_cjs.canRecoverOnchain(vtxo, now)) {
12346
12632
  return false;
12347
12633
  }
12348
12634
  return true;
@@ -12682,7 +12968,7 @@ var ReadonlyWallet = class _ReadonlyWallet {
12682
12968
  */
12683
12969
  static async setupWalletConfig(config, pubKey) {
12684
12970
  const arkadeServerUrl = getArkadeServerUrl(config);
12685
- const arkProvider = config.arkProvider || new chunk57636V35_cjs.RestArkProvider(arkadeServerUrl);
12971
+ const arkProvider = config.arkProvider || new chunk6FTHFJAN_cjs.RestArkProvider(arkadeServerUrl);
12686
12972
  let indexerProvider = config.indexerProvider;
12687
12973
  if (!indexerProvider) {
12688
12974
  let indexerUrl = config.indexerUrl;
@@ -12699,7 +12985,7 @@ var ReadonlyWallet = class _ReadonlyWallet {
12699
12985
  indexerUrl = arkadeServerUrl;
12700
12986
  }
12701
12987
  }
12702
- indexerProvider = new chunk3KW4TWP2_cjs.RestIndexerProvider(indexerUrl);
12988
+ indexerProvider = new chunk4C5PMGBB_cjs.RestIndexerProvider(indexerUrl);
12703
12989
  }
12704
12990
  const walletRepository = config.storage?.walletRepository ?? new IndexedDBWalletRepository();
12705
12991
  const contractRepository = config.storage?.contractRepository ?? new IndexedDBContractRepository();
@@ -12708,7 +12994,7 @@ var ReadonlyWallet = class _ReadonlyWallet {
12708
12994
  source: serverInfoSource,
12709
12995
  lastOnlineAt: serverInfoLastOnlineAt
12710
12996
  } = await resolveArkInfo(arkProvider, walletRepository);
12711
- const network = chunk57636V35_cjs.getNetwork(info.network);
12997
+ const network = chunk6FTHFJAN_cjs.getNetwork(info.network);
12712
12998
  if ("descriptor" in config.identity) {
12713
12999
  const descriptor = config.identity.descriptor;
12714
13000
  const identityIsMainnet = !descriptor.includes("tpub");
@@ -12748,18 +13034,18 @@ var ReadonlyWallet = class _ReadonlyWallet {
12748
13034
  value: info.boardingExitDelay,
12749
13035
  type: info.boardingExitDelay < 512n ? "blocks" : "seconds"
12750
13036
  };
12751
- const serverPubKey = chunk3OKEUDHU_cjs.toXOnly(base.hex.decode(info.signerPubkey), "ark signer key");
12752
- const delegatePubKey = config.delegateProvider ? await config.delegateProvider.getDelegateInfo().then((info2) => chunk3OKEUDHU_cjs.toXOnly(base.hex.decode(info2.pubkey), "delegate key")).catch(() => void 0) : config.delegatorProvider ? await config.delegatorProvider.getDelegateInfo().then((info2) => chunk3OKEUDHU_cjs.toXOnly(base.hex.decode(info2.pubkey), "delegate key")).catch(() => void 0) : void 0;
13037
+ const serverPubKey = chunkNPM5YZBC_cjs.toXOnly(base.hex.decode(info.signerPubkey), "ark signer key");
13038
+ const delegatePubKey = config.delegateProvider ? await config.delegateProvider.getDelegateInfo().then((info2) => chunkNPM5YZBC_cjs.toXOnly(base.hex.decode(info2.pubkey), "delegate key")).catch(() => void 0) : config.delegatorProvider ? await config.delegatorProvider.getDelegateInfo().then((info2) => chunkNPM5YZBC_cjs.toXOnly(base.hex.decode(info2.pubkey), "delegate key")).catch(() => void 0) : void 0;
12753
13039
  const offchainOptions = {
12754
13040
  pubKey,
12755
13041
  serverPubKey,
12756
13042
  csvTimelock: exitTimelock
12757
13043
  };
12758
- const offchainTapscript = !delegatePubKey ? new chunk3OKEUDHU_cjs.DefaultVtxo.Script(offchainOptions) : new chunk3OKEUDHU_cjs.DelegateVtxo.Script({ ...offchainOptions, delegatePubKey });
12759
- const boardingTapscript = chunk3OKEUDHU_cjs.BoardingContractHandler.createScript({
13044
+ const offchainTapscript = !delegatePubKey ? new chunkNPM5YZBC_cjs.DefaultVtxo.Script(offchainOptions) : new chunkNPM5YZBC_cjs.DelegateVtxo.Script({ ...offchainOptions, delegatePubKey });
13045
+ const boardingTapscript = chunkNPM5YZBC_cjs.BoardingContractHandler.createScript({
12760
13046
  pubKey: base.hex.encode(pubKey),
12761
13047
  serverPubKey: base.hex.encode(serverPubKey),
12762
- csvTimelock: chunk57636V35_cjs.timelockToSequence(boardingTimelock).toString()
13048
+ csvTimelock: chunk6FTHFJAN_cjs.timelockToSequence(boardingTimelock).toString()
12763
13049
  });
12764
13050
  return {
12765
13051
  arkProvider,
@@ -12911,7 +13197,7 @@ var ReadonlyWallet = class _ReadonlyWallet {
12911
13197
  const vtxos = filterSnapshotVtxos(snapshot, filter, this._pendingSpendOutpoints);
12912
13198
  const { gated, pendingRecovery } = this.spendabilityView(snapshot);
12913
13199
  const selectable = vtxos.filter(
12914
- (vtxo) => !gated.has(vtxo.script) && !pendingRecovery.has(`${vtxo.txid}:${vtxo.vout}`)
13200
+ (vtxo) => !isGatedVtxo(vtxo, gated) && !pendingRecovery.has(`${vtxo.txid}:${vtxo.vout}`)
12915
13201
  );
12916
13202
  const unlocked = await spendableVtxosExcludingLocked(selectable, this.intentRepository);
12917
13203
  logExcludedVtxos("getSpendableVtxos", vtxos, [
@@ -12925,7 +13211,7 @@ var ReadonlyWallet = class _ReadonlyWallet {
12925
13211
  if (!filter?.withUnrolled) {
12926
13212
  logExcludedVtxos(
12927
13213
  "getSpendableVtxos",
12928
- snapshot.flatMap((contract) => contract.vtxos).filter((vtxo) => vtxo.isUnrolled && !chunk57636V35_cjs.hasTerminalSpend(vtxo)),
13214
+ snapshot.flatMap((contract) => contract.vtxos).filter((vtxo) => vtxo.isUnrolled && !chunk6FTHFJAN_cjs.hasTerminalSpend(vtxo)),
12929
13215
  [() => UNROLLED_REASON]
12930
13216
  );
12931
13217
  }
@@ -13009,7 +13295,7 @@ var ReadonlyWallet = class _ReadonlyWallet {
13009
13295
  */
13010
13296
  spendabilityView(snapshot) {
13011
13297
  return {
13012
- gated: gatedContracts(snapshot.map((_) => _.contract)),
13298
+ gated: gatedFrom(snapshot),
13013
13299
  pendingRecovery: this.selectPendingRecovery(snapshot)
13014
13300
  };
13015
13301
  }
@@ -13024,7 +13310,7 @@ var ReadonlyWallet = class _ReadonlyWallet {
13024
13310
  return {
13025
13311
  now: { timestamp: /* @__PURE__ */ new Date() },
13026
13312
  isPendingRecovery: (vtxo) => pendingRecovery.has(`${vtxo.txid}:${vtxo.vout}`),
13027
- isGenericallySpendable: (vtxo) => !gated.has(vtxo.script),
13313
+ isGenericallySpendable: (vtxo) => !isGatedVtxo(vtxo, gated),
13028
13314
  isUnlocked: (vtxo) => unlocked.has(`${vtxo.txid}:${vtxo.vout}`)
13029
13315
  };
13030
13316
  }
@@ -13064,16 +13350,18 @@ var ReadonlyWallet = class _ReadonlyWallet {
13064
13350
  * Return wallet transaction history derived from Arkade state and boarding transactions.
13065
13351
  */
13066
13352
  async getTransactionHistory() {
13067
- const contractManager = await this.getContractManager();
13068
- const response = await contractManager.getContractsWithVtxos();
13069
- const allVtxos = response.flatMap((_) => _.vtxos);
13070
- const { boardingTxs, commitmentsToIgnore } = await this.getBoardingTxs();
13071
- const resolveTxCreatedAt = (txids) => chunk57636V35_cjs.fetchVtxoCreatedAtByTxid(this.indexerProvider, txids);
13353
+ const [snapshot, { boardingTxs, commitmentsToIgnore }] = await Promise.all([
13354
+ this.contractSnapshot(),
13355
+ this.getBoardingTxs()
13356
+ ]);
13357
+ const allVtxos = snapshot.flatMap((_) => _.vtxos);
13358
+ const resolveTxCreatedAt = (txids) => chunk6FTHFJAN_cjs.fetchVtxoCreatedAtByTxid(this.indexerProvider, txids);
13072
13359
  return buildTransactionHistory(
13073
13360
  allVtxos,
13074
13361
  boardingTxs,
13075
13362
  commitmentsToIgnore,
13076
- resolveTxCreatedAt
13363
+ resolveTxCreatedAt,
13364
+ gatedFrom(snapshot)
13077
13365
  );
13078
13366
  }
13079
13367
  /**
@@ -13162,7 +13450,7 @@ var ReadonlyWallet = class _ReadonlyWallet {
13162
13450
  },
13163
13451
  isUnrolled: true,
13164
13452
  ...boardingFacts,
13165
- virtualStatus: chunk57636V35_cjs.toVirtualStatus(boardingFacts),
13453
+ virtualStatus: chunk6FTHFJAN_cjs.toVirtualStatus(boardingFacts),
13166
13454
  spentBy: "",
13167
13455
  createdAt: tx.status.confirmed ? new Date(tx.status.block_time * 1e3) : /* @__PURE__ */ new Date(0),
13168
13456
  script: scriptHex
@@ -13218,9 +13506,9 @@ var ReadonlyWallet = class _ReadonlyWallet {
13218
13506
  async getBoardingTapscripts(allowedSigners) {
13219
13507
  const byScript = /* @__PURE__ */ new Map();
13220
13508
  const add = (s) => byScript.set(base.hex.encode(s.pkScript), s);
13221
- const boardingCsv = this.boardingTapscript.options.csvTimelock ?? chunk3OKEUDHU_cjs.DefaultVtxo.Script.DEFAULT_TIMELOCK;
13509
+ const boardingCsv = this.boardingTapscript.options.csvTimelock ?? chunkNPM5YZBC_cjs.DefaultVtxo.Script.DEFAULT_TIMELOCK;
13222
13510
  add(
13223
- new chunk3OKEUDHU_cjs.DefaultVtxo.Script({
13511
+ new chunkNPM5YZBC_cjs.DefaultVtxo.Script({
13224
13512
  pubKey: await this.identity.xOnlyPublicKey(),
13225
13513
  serverPubKey: this.boardingTapscript.options.serverPubKey,
13226
13514
  csvTimelock: boardingCsv
@@ -13235,7 +13523,7 @@ var ReadonlyWallet = class _ReadonlyWallet {
13235
13523
  for (const c of boardingContracts) {
13236
13524
  if (!allowed.has(toXOnlySignerHex(c.params.serverPubKey))) continue;
13237
13525
  try {
13238
- add(chunk3OKEUDHU_cjs.BoardingContractHandler.createScript(c.params));
13526
+ add(chunkNPM5YZBC_cjs.BoardingContractHandler.createScript(c.params));
13239
13527
  } catch (e) {
13240
13528
  console.warn("Skipping malformed boarding contract", c.script, e);
13241
13529
  }
@@ -13273,7 +13561,7 @@ var ReadonlyWallet = class _ReadonlyWallet {
13273
13561
  // Per-row CSV delay decoded from THIS tapscript's exit leaf —
13274
13562
  // not the wallet's current boarding timelock, which a signer
13275
13563
  // rotation may have changed.
13276
- csvTimelock: chunk57636V35_cjs.CSVMultisigTapscript.decode(base.hex.decode(tapscript.exitScript)).params.timelock,
13564
+ csvTimelock: chunk6FTHFJAN_cjs.CSVMultisigTapscript.decode(base.hex.decode(tapscript.exitScript)).params.timelock,
13277
13565
  coins: utxos
13278
13566
  });
13279
13567
  }
@@ -13371,7 +13659,7 @@ var ReadonlyWallet = class _ReadonlyWallet {
13371
13659
  const cm = await this.getContractManager();
13372
13660
  let annotationQueue = Promise.resolve();
13373
13661
  indexerStopFunc = cm.onContractEvent((event) => {
13374
- if (event.type !== "vtxo_received" && event.type !== "vtxo_spent") {
13662
+ if (!isContractVtxoEvent(event)) {
13375
13663
  return;
13376
13664
  }
13377
13665
  if (event.contract.type !== "default" && event.contract.type !== "delegate") {
@@ -13406,7 +13694,7 @@ var ReadonlyWallet = class _ReadonlyWallet {
13406
13694
  /** Fetch Arkade transaction ids that are still pending final settlement. */
13407
13695
  async fetchPendingTxs() {
13408
13696
  const scripts = await this.getWalletScripts();
13409
- const vtxos = await chunk57636V35_cjs.getAllNormalizedVtxos(this.indexerProvider, scripts);
13697
+ const vtxos = await chunk6FTHFJAN_cjs.getAllNormalizedVtxos(this.indexerProvider, scripts);
13410
13698
  return vtxos.filter(
13411
13699
  (vtxo) => (vtxo.isSpent || vtxo.isPreconfirmed && !vtxo.isSwept) && vtxo.arkTxId !== void 0
13412
13700
  ).map((_) => _.arkTxId);
@@ -13437,7 +13725,7 @@ var ReadonlyWallet = class _ReadonlyWallet {
13437
13725
  });
13438
13726
  for (const contract of contracts) {
13439
13727
  if (map.has(contract.script)) continue;
13440
- const handler = chunk3OKEUDHU_cjs.contractHandlers.get(contract.type);
13728
+ const handler = chunkNPM5YZBC_cjs.contractHandlers.get(contract.type);
13441
13729
  if (handler) {
13442
13730
  const script = handler.createScript(contract.params);
13443
13731
  map.set(contract.script, script);
@@ -13549,7 +13837,7 @@ var ReadonlyWallet = class _ReadonlyWallet {
13549
13837
  }
13550
13838
  });
13551
13839
  const baselinePubkey = await this.identity.xOnlyPublicKey();
13552
- const delegatePubKey = this.offchainTapscript instanceof chunk3OKEUDHU_cjs.DelegateVtxo.Script ? this.offchainTapscript.options.delegatePubKey : void 0;
13840
+ const delegatePubKey = this.offchainTapscript instanceof chunkNPM5YZBC_cjs.DelegateVtxo.Script ? this.offchainTapscript.options.delegatePubKey : void 0;
13553
13841
  const baselineSigners = [
13554
13842
  this.offchainTapscript.options.serverPubKey,
13555
13843
  ...[...this._deprecatedSigners.keys()].map((h) => base.hex.decode(h))
@@ -13557,8 +13845,8 @@ var ReadonlyWallet = class _ReadonlyWallet {
13557
13845
  const seenBaselineScripts = /* @__PURE__ */ new Set();
13558
13846
  for (const serverPubKey of baselineSigners) {
13559
13847
  for (const csvTimelock of this.walletContractTimelocks) {
13560
- const csvTimelockStr = chunk57636V35_cjs.timelockToSequence(csvTimelock).toString();
13561
- const defaultScript = new chunk3OKEUDHU_cjs.DefaultVtxo.Script({
13848
+ const csvTimelockStr = chunk6FTHFJAN_cjs.timelockToSequence(csvTimelock).toString();
13849
+ const defaultScript = new chunkNPM5YZBC_cjs.DefaultVtxo.Script({
13562
13850
  pubKey: baselinePubkey,
13563
13851
  serverPubKey,
13564
13852
  csvTimelock
@@ -13579,7 +13867,7 @@ var ReadonlyWallet = class _ReadonlyWallet {
13579
13867
  });
13580
13868
  }
13581
13869
  if (delegatePubKey) {
13582
- const delegateScript = new chunk3OKEUDHU_cjs.DelegateVtxo.Script({
13870
+ const delegateScript = new chunkNPM5YZBC_cjs.DelegateVtxo.Script({
13583
13871
  pubKey: baselinePubkey,
13584
13872
  serverPubKey,
13585
13873
  delegatePubKey,
@@ -13603,9 +13891,9 @@ var ReadonlyWallet = class _ReadonlyWallet {
13603
13891
  }
13604
13892
  }
13605
13893
  }
13606
- const boardingCsvTimelock = this.boardingTapscript.options.csvTimelock ?? chunk3OKEUDHU_cjs.DefaultVtxo.Script.DEFAULT_TIMELOCK;
13894
+ const boardingCsvTimelock = this.boardingTapscript.options.csvTimelock ?? chunkNPM5YZBC_cjs.DefaultVtxo.Script.DEFAULT_TIMELOCK;
13607
13895
  for (const serverPubKey of baselineSigners) {
13608
- const baselineBoarding = new chunk3OKEUDHU_cjs.DefaultVtxo.Script({
13896
+ const baselineBoarding = new chunkNPM5YZBC_cjs.DefaultVtxo.Script({
13609
13897
  pubKey: baselinePubkey,
13610
13898
  serverPubKey,
13611
13899
  csvTimelock: boardingCsvTimelock
@@ -13618,7 +13906,7 @@ var ReadonlyWallet = class _ReadonlyWallet {
13618
13906
  params: {
13619
13907
  pubKey: base.hex.encode(baselineBoarding.options.pubKey),
13620
13908
  serverPubKey: base.hex.encode(serverPubKey),
13621
- csvTimelock: chunk57636V35_cjs.timelockToSequence(boardingCsvTimelock).toString()
13909
+ csvTimelock: chunk6FTHFJAN_cjs.timelockToSequence(boardingCsvTimelock).toString()
13622
13910
  },
13623
13911
  script: boardingScriptHex,
13624
13912
  address: baselineBoarding.address(this.network.hrp, serverPubKey).encode(),
@@ -13818,7 +14106,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
13818
14106
  serverPubKey: this.offchainTapscript.options.serverPubKey,
13819
14107
  deprecatedSignerPubKeys: [...this._deprecatedSigners.keys()].map((h) => base.hex.decode(h)),
13820
14108
  csvTimelocks: this.walletContractTimelocks,
13821
- delegatePubKey: this.offchainTapscript instanceof chunk3OKEUDHU_cjs.DelegateVtxo.Script ? this.offchainTapscript.options.delegatePubKey : void 0
14109
+ delegatePubKey: this.offchainTapscript instanceof chunkNPM5YZBC_cjs.DelegateVtxo.Script ? this.offchainTapscript.options.delegatePubKey : void 0
13822
14110
  };
13823
14111
  }
13824
14112
  _signerRouter;
@@ -14063,7 +14351,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
14063
14351
  const [row] = await manager.getContracts({ script: base.hex.encode(display.pkScript) });
14064
14352
  const persisted = row?.metadata?.signingDescriptor;
14065
14353
  if (typeof persisted === "string") return persisted;
14066
- return chunk3OKEUDHU_cjs.identityDescriptor(this.identity);
14354
+ return chunkNPM5YZBC_cjs.identityDescriptor(this.identity);
14067
14355
  }
14068
14356
  /**
14069
14357
  * Build, persist and shape one address of `type` owned by `descriptor` —
@@ -14079,7 +14367,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
14079
14367
  async mintAddress(manager, type, descriptor, tagSource, allocated) {
14080
14368
  if (type === "boarding") {
14081
14369
  const built2 = this.buildBoardingContract(
14082
- chunk3OKEUDHU_cjs.deriveDescriptorLeafPubKey(descriptor),
14370
+ chunkNPM5YZBC_cjs.deriveDescriptorLeafPubKey(descriptor),
14083
14371
  descriptor,
14084
14372
  tagSource
14085
14373
  );
@@ -14124,11 +14412,11 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
14124
14412
  * {@link buildReceiveContract}.
14125
14413
  */
14126
14414
  buildBoardingContract(pubKey, descriptor, tagSource) {
14127
- const tapscript = new chunk3OKEUDHU_cjs.DefaultVtxo.Script({
14415
+ const tapscript = new chunkNPM5YZBC_cjs.DefaultVtxo.Script({
14128
14416
  ...this._boardingTapscript.options,
14129
14417
  pubKey
14130
14418
  });
14131
- const csvTimelock = tapscript.options.csvTimelock ?? chunk3OKEUDHU_cjs.DefaultVtxo.Script.DEFAULT_TIMELOCK;
14419
+ const csvTimelock = tapscript.options.csvTimelock ?? chunkNPM5YZBC_cjs.DefaultVtxo.Script.DEFAULT_TIMELOCK;
14132
14420
  return {
14133
14421
  tapscript,
14134
14422
  params: {
@@ -14136,13 +14424,13 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
14136
14424
  params: {
14137
14425
  pubKey: base.hex.encode(pubKey),
14138
14426
  serverPubKey: base.hex.encode(tapscript.options.serverPubKey),
14139
- csvTimelock: chunk57636V35_cjs.timelockToSequence(csvTimelock).toString()
14427
+ csvTimelock: chunk6FTHFJAN_cjs.timelockToSequence(csvTimelock).toString()
14140
14428
  },
14141
14429
  script: base.hex.encode(tapscript.pkScript),
14142
14430
  address: tapscript.address(this.network.hrp, this.arkServerPublicKey).encode(),
14143
14431
  state: "active",
14144
14432
  metadata: {
14145
- ...tagSource && { source: chunk3OKEUDHU_cjs.WALLET_RECEIVE_SOURCE },
14433
+ ...tagSource && { source: chunkNPM5YZBC_cjs.WALLET_RECEIVE_SOURCE },
14146
14434
  signingDescriptor: descriptor
14147
14435
  }
14148
14436
  }
@@ -14171,7 +14459,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
14171
14459
  if (this._descriptorProvider instanceof HDDescriptorProvider) {
14172
14460
  return (await this.getContractManager()).getNextSigningDescriptor();
14173
14461
  }
14174
- return chunk3OKEUDHU_cjs.identityDescriptor(this.identity);
14462
+ return chunkNPM5YZBC_cjs.identityDescriptor(this.identity);
14175
14463
  }
14176
14464
  /**
14177
14465
  * @see HDAllocationCapable.advanceSigningDescriptorWatermark
@@ -14267,7 +14555,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
14267
14555
  * the stable public API.
14268
14556
  */
14269
14557
  async rotateServerSigner(newServerPubKey, checkpointTapscript) {
14270
- const xonly = chunk3OKEUDHU_cjs.toXOnly(newServerPubKey, "ark signer key");
14558
+ const xonly = chunkNPM5YZBC_cjs.toXOnly(newServerPubKey, "ark signer key");
14271
14559
  const newServerUnrollScript = assertValidServerUnrollScript(
14272
14560
  checkpointTapscript,
14273
14561
  resolveCheckpointExitDelayPolicy(this.network, this.checkpointExitDelayPolicy)
@@ -14296,21 +14584,21 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
14296
14584
  const [currentBoardingRow] = await manager.getContracts({
14297
14585
  script: currentBoardingScript
14298
14586
  });
14299
- const newOffchain = this.offchainTapscript instanceof chunk3OKEUDHU_cjs.DelegateVtxo.Script ? new chunk3OKEUDHU_cjs.DelegateVtxo.Script({
14587
+ const newOffchain = this.offchainTapscript instanceof chunkNPM5YZBC_cjs.DelegateVtxo.Script ? new chunkNPM5YZBC_cjs.DelegateVtxo.Script({
14300
14588
  ...this.offchainTapscript.options,
14301
14589
  serverPubKey: xonly
14302
- }) : new chunk3OKEUDHU_cjs.DefaultVtxo.Script({
14590
+ }) : new chunkNPM5YZBC_cjs.DefaultVtxo.Script({
14303
14591
  ...this.offchainTapscript.options,
14304
14592
  serverPubKey: xonly
14305
14593
  });
14306
- const newBoarding = new chunk3OKEUDHU_cjs.DefaultVtxo.Script({
14594
+ const newBoarding = new chunkNPM5YZBC_cjs.DefaultVtxo.Script({
14307
14595
  ...this._boardingTapscript.options,
14308
14596
  serverPubKey: xonly
14309
14597
  });
14310
- const offchainCsv = chunk57636V35_cjs.timelockToSequence(newOffchain.options.csvTimelock).toString();
14598
+ const offchainCsv = chunk6FTHFJAN_cjs.timelockToSequence(newOffchain.options.csvTimelock).toString();
14311
14599
  const newOffchainScript = base.hex.encode(newOffchain.pkScript);
14312
14600
  const newOffchainAddress = newOffchain.address(this.network.hrp, xonly).encode();
14313
- if (newOffchain instanceof chunk3OKEUDHU_cjs.DelegateVtxo.Script) {
14601
+ if (newOffchain instanceof chunkNPM5YZBC_cjs.DelegateVtxo.Script) {
14314
14602
  await manager.createContract({
14315
14603
  type: "delegate",
14316
14604
  params: {
@@ -14338,13 +14626,13 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
14338
14626
  metadata: currentOffchainRow?.metadata
14339
14627
  });
14340
14628
  }
14341
- const boardingCsv = newBoarding.options.csvTimelock ?? chunk3OKEUDHU_cjs.DefaultVtxo.Script.DEFAULT_TIMELOCK;
14629
+ const boardingCsv = newBoarding.options.csvTimelock ?? chunkNPM5YZBC_cjs.DefaultVtxo.Script.DEFAULT_TIMELOCK;
14342
14630
  await manager.createContract({
14343
14631
  type: "boarding",
14344
14632
  params: {
14345
14633
  pubKey: base.hex.encode(newBoarding.options.pubKey),
14346
14634
  serverPubKey: base.hex.encode(xonly),
14347
- csvTimelock: chunk57636V35_cjs.timelockToSequence(boardingCsv).toString()
14635
+ csvTimelock: chunk6FTHFJAN_cjs.timelockToSequence(boardingCsv).toString()
14348
14636
  },
14349
14637
  script: base.hex.encode(newBoarding.pkScript),
14350
14638
  address: newBoarding.address(this.network.hrp, xonly).encode(),
@@ -14377,14 +14665,14 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
14377
14665
  _restoreInFlight;
14378
14666
  _addPendingSpends(inputs) {
14379
14667
  for (const input of inputs) {
14380
- if (chunk57636V35_cjs.isVirtualCoin(input)) {
14668
+ if (chunk6FTHFJAN_cjs.isVirtualCoin(input)) {
14381
14669
  this._pendingSpendOutpoints.add(`${input.txid}:${input.vout}`);
14382
14670
  }
14383
14671
  }
14384
14672
  }
14385
14673
  _removePendingSpends(inputs) {
14386
14674
  for (const input of inputs) {
14387
- if (chunk57636V35_cjs.isVirtualCoin(input)) {
14675
+ if (chunk6FTHFJAN_cjs.isVirtualCoin(input)) {
14388
14676
  this._pendingSpendOutpoints.delete(`${input.txid}:${input.vout}`);
14389
14677
  }
14390
14678
  }
@@ -14433,7 +14721,10 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
14433
14721
  `restore: gapLimit must be a positive integer (got ${String(opts?.gapLimit)})`
14434
14722
  );
14435
14723
  }
14436
- this._restoreInFlight = this._runRestore(gapLimit).finally(() => {
14724
+ this._restoreInFlight = (async () => {
14725
+ await this._runRestore(gapLimit);
14726
+ await runWalletRestoreHooks(this);
14727
+ })().finally(() => {
14437
14728
  this._restoreInFlight = void 0;
14438
14729
  });
14439
14730
  return this._restoreInFlight;
@@ -14442,13 +14733,13 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
14442
14733
  const manager = await this.getContractManager();
14443
14734
  const provider = this._descriptorProvider;
14444
14735
  const hd = provider instanceof HDDescriptorProvider;
14445
- const staticDescriptor = hd ? void 0 : await chunk3OKEUDHU_cjs.identityDescriptor(this.identity);
14736
+ const staticDescriptor = hd ? void 0 : await chunkNPM5YZBC_cjs.identityDescriptor(this.identity);
14446
14737
  const materialize = (index) => hd ? provider.materializeDescriptorAt(index) : staticDescriptor;
14447
- const delegatePubKey = this.offchainTapscript instanceof chunk3OKEUDHU_cjs.DelegateVtxo.Script ? this.offchainTapscript.options.delegatePubKey : void 0;
14738
+ const delegatePubKey = this.offchainTapscript instanceof chunkNPM5YZBC_cjs.DelegateVtxo.Script ? this.offchainTapscript.options.delegatePubKey : void 0;
14448
14739
  const arkInfo = await this.arkProvider.getInfo();
14449
- const currentSignerPubKey = chunk3OKEUDHU_cjs.toXOnly(base.hex.decode(arkInfo.signerPubkey), "ark signer key");
14740
+ const currentSignerPubKey = chunkNPM5YZBC_cjs.toXOnly(base.hex.decode(arkInfo.signerPubkey), "ark signer key");
14450
14741
  const deprecatedSignerPubKeys = arkInfo.deprecatedSigners.map(
14451
- (s) => chunk3OKEUDHU_cjs.toXOnly(base.hex.decode(s.pubkey), "deprecated signer key")
14742
+ (s) => chunkNPM5YZBC_cjs.toXOnly(base.hex.decode(s.pubkey), "deprecated signer key")
14452
14743
  );
14453
14744
  const deps = {
14454
14745
  indexerProvider: this.indexerProvider,
@@ -14463,7 +14754,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
14463
14754
  csvTimelocks: this.walletContractTimelocks,
14464
14755
  // Boarding-exit CSV so the boarding handler can build its
14465
14756
  // candidate script (distinct from the unilateral-exit matrix).
14466
- boardingTimelock: this.boardingTapscript.options.csvTimelock ?? chunk3OKEUDHU_cjs.DefaultVtxo.Script.DEFAULT_TIMELOCK,
14757
+ boardingTimelock: this.boardingTapscript.options.csvTimelock ?? chunkNPM5YZBC_cjs.DefaultVtxo.Script.DEFAULT_TIMELOCK,
14467
14758
  delegatePubKey
14468
14759
  };
14469
14760
  const result = await manager.scanContracts({
@@ -14577,7 +14868,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
14577
14868
  throw new Error("Invalid configured public key");
14578
14869
  }
14579
14870
  const setup = await ReadonlyWallet.setupWalletConfig(config, pubkey);
14580
- const forfeitPubkey = chunk3OKEUDHU_cjs.toXOnly(base.hex.decode(setup.info.forfeitPubkey), "forfeit key");
14871
+ const forfeitPubkey = chunkNPM5YZBC_cjs.toXOnly(base.hex.decode(setup.info.forfeitPubkey), "forfeit key");
14581
14872
  const forfeitAddress = btcSigner.Address(setup.network).decode(setup.info.forfeitAddress);
14582
14873
  const forfeitOutputScript = btcSigner.OutScript.encode(forfeitAddress);
14583
14874
  const checkpointExitDelayOverrides = {
@@ -14726,7 +15017,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
14726
15017
  inputs: params.selectedVtxos,
14727
15018
  changeAmount: BigInt(changeAmount)
14728
15019
  };
14729
- const outputAddress = chunk57636V35_cjs.ArkAddress.decode(params.address);
15020
+ const outputAddress = chunk6FTHFJAN_cjs.ArkAddress.decode(params.address);
14730
15021
  assertRecipientArkAddress(
14731
15022
  params.address,
14732
15023
  outputAddress,
@@ -14792,13 +15083,13 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
14792
15083
  void this.logUngatedInputs("settle({ inputs })", params.inputs);
14793
15084
  }
14794
15085
  const offchainAddress = await this.getAddress();
14795
- const offchainPkScript = chunk57636V35_cjs.ArkAddress.decode(offchainAddress).pkScript;
15086
+ const offchainPkScript = chunk6FTHFJAN_cjs.ArkAddress.decode(offchainAddress).pkScript;
14796
15087
  const offchainOutputScript = base.hex.encode(offchainPkScript);
14797
15088
  if (!params) {
14798
15089
  const { fees, vtxoMaxAmount } = await this.arkProvider.getInfo();
14799
15090
  const estimator = new Estimator(fees.intentFee);
14800
15091
  let amount = 0;
14801
- const exitScript = chunk57636V35_cjs.CSVMultisigTapscript.decode(
15092
+ const exitScript = chunk6FTHFJAN_cjs.CSVMultisigTapscript.decode(
14802
15093
  base.hex.decode(this.boardingTapscript.exitScript)
14803
15094
  );
14804
15095
  const boardingTimelock = exitScript.params.timelock;
@@ -14827,7 +15118,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
14827
15118
  if (filteredVtxos.length >= MAX_VTXOS_PER_SETTLEMENT) {
14828
15119
  break;
14829
15120
  }
14830
- const inputFee = estimator.evalOffchainInput(chunk57636V35_cjs.toOffchainInputFeeParams(vtxo));
15121
+ const inputFee = estimator.evalOffchainInput(chunk6FTHFJAN_cjs.toOffchainInputFeeParams(vtxo));
14831
15122
  if (inputFee.satoshis >= vtxo.value) {
14832
15123
  continue;
14833
15124
  }
@@ -14874,7 +15165,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
14874
15165
  let script;
14875
15166
  let arkAddress;
14876
15167
  try {
14877
- arkAddress = chunk57636V35_cjs.ArkAddress.decode(output.address);
15168
+ arkAddress = chunk6FTHFJAN_cjs.ArkAddress.decode(output.address);
14878
15169
  } catch {
14879
15170
  arkAddress = void 0;
14880
15171
  }
@@ -14964,7 +15255,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
14964
15255
  const abortController = new AbortController();
14965
15256
  let stream;
14966
15257
  let committedTxid;
14967
- const settleInputVtxos = params.inputs.filter(chunk57636V35_cjs.isVirtualCoin);
15258
+ const settleInputVtxos = params.inputs.filter(chunk6FTHFJAN_cjs.isVirtualCoin);
14968
15259
  const contractManager = await this.getContractManager();
14969
15260
  await contractManager.assertAnnotatable(settleInputVtxos);
14970
15261
  await contractManager.assertSpendableNow?.(
@@ -15076,7 +15367,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15076
15367
  async maybeRotateBoardingAfterBoard(inputs) {
15077
15368
  if (!this._descriptorProvider) return;
15078
15369
  const consumedBoarding = inputs.some(
15079
- (input) => typeof input !== "string" && !chunk57636V35_cjs.isVirtualCoin(input)
15370
+ (input) => typeof input !== "string" && !chunk6FTHFJAN_cjs.isVirtualCoin(input)
15080
15371
  );
15081
15372
  if (!consumedBoarding) return;
15082
15373
  try {
@@ -15100,7 +15391,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15100
15391
  let connectorIndex = 0;
15101
15392
  const connectorsLeaves = connectorsGraph?.leaves() || [];
15102
15393
  for (const input of inputs) {
15103
- if (!chunk57636V35_cjs.isVirtualCoin(input)) {
15394
+ if (!chunk6FTHFJAN_cjs.isVirtualCoin(input)) {
15104
15395
  for (let i = 0; i < settlementPsbt.inputsLength; i++) {
15105
15396
  const settlementInput = settlementPsbt.getInput(i);
15106
15397
  if (!settlementInput.txid || settlementInput.index === void 0) {
@@ -15131,7 +15422,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15131
15422
  }
15132
15423
  continue;
15133
15424
  }
15134
- if (chunk57636V35_cjs.canRecoverOnchain(input, { timestamp: /* @__PURE__ */ new Date() }) || isSubdust({ value: input.value }, this.dustAmount)) {
15425
+ if (chunk6FTHFJAN_cjs.canRecoverOnchain(input, { timestamp: /* @__PURE__ */ new Date() }) || isSubdust({ value: input.value }, this.dustAmount)) {
15135
15426
  continue;
15136
15427
  }
15137
15428
  if (connectorsLeaves.length === 0) {
@@ -15159,7 +15450,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15159
15450
  index: input.vout,
15160
15451
  witnessUtxo: {
15161
15452
  amount: BigInt(input.value),
15162
- script: chunk57636V35_cjs.VtxoScript.decode(input.tapTree).pkScript
15453
+ script: chunk6FTHFJAN_cjs.VtxoScript.decode(input.tapTree).pkScript
15163
15454
  },
15164
15455
  sighashType: btcSigner.SigHash.DEFAULT,
15165
15456
  tapLeafScript: [input.forfeitTapLeafScript]
@@ -15178,7 +15469,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15178
15469
  forfeitTx = await this._signerRouter.sign(forfeitTx, [
15179
15470
  {
15180
15471
  index: 0,
15181
- lookupScript: chunk57636V35_cjs.VtxoScript.decode(input.tapTree).pkScript
15472
+ lookupScript: chunk6FTHFJAN_cjs.VtxoScript.decode(input.tapTree).pkScript
15182
15473
  }
15183
15474
  ]);
15184
15475
  signedForfeits.push(base.base64.encode(forfeitTx.toPSBT()));
@@ -15236,7 +15527,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15236
15527
  resolveBatchExpiryPolicy(this.network, this.batchExpiryPolicy)
15237
15528
  );
15238
15529
  await this.arkProvider.confirmRegistration(intentId);
15239
- const sweepTapscript = chunk57636V35_cjs.CSVMultisigTapscript.encode({
15530
+ const sweepTapscript = chunk6FTHFJAN_cjs.CSVMultisigTapscript.encode({
15240
15531
  timelock,
15241
15532
  pubkeys: [this.forfeitPubkey]
15242
15533
  }).script;
@@ -15251,10 +15542,10 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15251
15542
  throw new Error("Sweep tap tree root not set");
15252
15543
  }
15253
15544
  const xOnlyPublicKeys = event.cosignersPublicKeys.map(
15254
- (k) => base.hex.encode(chunk3OKEUDHU_cjs.toXOnly(base.hex.decode(k), "cosigner key"))
15545
+ (k) => base.hex.encode(chunkNPM5YZBC_cjs.toXOnly(base.hex.decode(k), "cosigner key"))
15255
15546
  );
15256
15547
  const signerPublicKey = await session.getPublicKey();
15257
- const xonlySignerPublicKey = chunk3OKEUDHU_cjs.toXOnly(signerPublicKey, "signer key");
15548
+ const xonlySignerPublicKey = chunkNPM5YZBC_cjs.toXOnly(signerPublicKey, "signer key");
15258
15549
  if (!xOnlyPublicKeys.includes(base.hex.encode(xonlySignerPublicKey))) {
15259
15550
  return { skip: true };
15260
15551
  }
@@ -15344,9 +15635,9 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15344
15635
  ...existing ?? {},
15345
15636
  intentTxId,
15346
15637
  registerProof: intent.proof,
15347
- registerProofMessage: chunk57636V35_cjs.Intent.encodeMessage(intent.message),
15638
+ registerProofMessage: chunk6FTHFJAN_cjs.Intent.encodeMessage(intent.message),
15348
15639
  deleteProof: deleteIntent.proof,
15349
- deleteProofMessage: chunk57636V35_cjs.Intent.encodeMessage(deleteIntent.message),
15640
+ deleteProofMessage: chunk6FTHFJAN_cjs.Intent.encodeMessage(deleteIntent.message),
15350
15641
  intentVtxos: inputs.map((i) => ({
15351
15642
  txid: i.txid,
15352
15643
  vout: i.vout
@@ -15378,7 +15669,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15378
15669
  try {
15379
15670
  return await this.arkProvider.registerIntent(intent);
15380
15671
  } catch (error) {
15381
- if (error instanceof chunk57636V35_cjs.ArkError && error.code === 0 && error.message.includes("duplicated input")) {
15672
+ if (error instanceof chunk6FTHFJAN_cjs.ArkError && error.code === 0 && error.message.includes("duplicated input")) {
15382
15673
  const deleteIntent = await this.makeDeleteIntentSignature(inputs);
15383
15674
  await this.arkProvider.deleteIntent(deleteIntent);
15384
15675
  return this.arkProvider.registerIntent(intent);
@@ -15394,7 +15685,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15394
15685
  expire_at: 0,
15395
15686
  cosigners_public_keys: cosignerPubKeys
15396
15687
  };
15397
- const proof = chunk57636V35_cjs.Intent.create(message, coins, outputs);
15688
+ const proof = chunk6FTHFJAN_cjs.Intent.create(message, coins, outputs);
15398
15689
  const signedProof = await this._signerRouter.sign(proof, intentProofJobs(coins));
15399
15690
  return {
15400
15691
  proof: base.base64.encode(signedProof.toPSBT()),
@@ -15406,7 +15697,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15406
15697
  type: "delete",
15407
15698
  expire_at: 0
15408
15699
  };
15409
- const proof = chunk57636V35_cjs.Intent.create(message, coins, []);
15700
+ const proof = chunk6FTHFJAN_cjs.Intent.create(message, coins, []);
15410
15701
  const signedProof = await this._signerRouter.sign(proof, intentProofJobs(coins));
15411
15702
  return {
15412
15703
  proof: base.base64.encode(signedProof.toPSBT()),
@@ -15418,7 +15709,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15418
15709
  type: "get-pending-tx",
15419
15710
  expire_at: 0
15420
15711
  };
15421
- const proof = chunk57636V35_cjs.Intent.create(message, coins, []);
15712
+ const proof = chunk6FTHFJAN_cjs.Intent.create(message, coins, []);
15422
15713
  const signedProof = await this._signerRouter.sign(proof, intentProofJobs(coins));
15423
15714
  return {
15424
15715
  proof: base.base64.encode(signedProof.toPSBT()),
@@ -15439,7 +15730,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15439
15730
  if (!vtxos || vtxos.length === 0) {
15440
15731
  const scriptMap = await this.getScriptMap();
15441
15732
  const allExtended = [];
15442
- const fetchedVtxos = await chunk57636V35_cjs.getAllNormalizedVtxos(this.indexerProvider, [
15733
+ const fetchedVtxos = await chunk6FTHFJAN_cjs.getAllNormalizedVtxos(this.indexerProvider, [
15443
15734
  ...scriptMap.keys()
15444
15735
  ]);
15445
15736
  for (const vtxo of fetchedVtxos) {
@@ -15483,7 +15774,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15483
15774
  try {
15484
15775
  const checkpointTxs = pendingTx.signedCheckpointTxs.map((c) => {
15485
15776
  const tx = btcSigner.Transaction.fromPSBT(base.base64.decode(c));
15486
- chunk57636V35_cjs.assertAllowedSighashTypes(tx);
15777
+ chunk6FTHFJAN_cjs.assertAllowedSighashTypes(tx);
15487
15778
  return tx;
15488
15779
  });
15489
15780
  assertCheckpointsMatchInputs(
@@ -15555,11 +15846,11 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15555
15846
  * against the current key alone would leave it pending forever.
15556
15847
  */
15557
15848
  checkpointUnrollCandidates(info) {
15558
- const current = chunk57636V35_cjs.CSVMultisigTapscript.decode(base.hex.decode(info.checkpointTapscript));
15849
+ const current = chunk6FTHFJAN_cjs.CSVMultisigTapscript.decode(base.hex.decode(info.checkpointTapscript));
15559
15850
  const candidates = [this._serverUnrollScript, current];
15560
15851
  for (const deprecated of signerSetFromInfo(info).deprecated.keys()) {
15561
15852
  candidates.push(
15562
- chunk57636V35_cjs.CSVMultisigTapscript.encode({
15853
+ chunk6FTHFJAN_cjs.CSVMultisigTapscript.encode({
15563
15854
  ...current.params,
15564
15855
  pubkeys: [base.hex.decode(deprecated)]
15565
15856
  })
@@ -15650,7 +15941,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15650
15941
  if (vtxos.length === 0) {
15651
15942
  throw new Error("No VTXOs found for this arkadeCash");
15652
15943
  }
15653
- const myPkScript = chunk57636V35_cjs.ArkAddress.decode(await this.getAddress()).pkScript;
15944
+ const myPkScript = chunk6FTHFJAN_cjs.ArkAddress.decode(await this.getAddress()).pkScript;
15654
15945
  let { spendable, unclaimed } = this.classifyCashVtxos(vtxos);
15655
15946
  let swept = 0;
15656
15947
  const drainable = vtxos.filter(
@@ -15726,7 +16017,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15726
16017
  const spendable = [];
15727
16018
  const unclaimed = [];
15728
16019
  for (const vtxo of vtxos) {
15729
- if (chunk57636V35_cjs.hasTerminalSpend(vtxo)) {
16020
+ if (chunk6FTHFJAN_cjs.hasTerminalSpend(vtxo)) {
15730
16021
  unclaimed.push(cashReport(vtxo, "already-spent"));
15731
16022
  } else if (vtxo.isUnrolled) {
15732
16023
  unclaimed.push(cashReport(vtxo, "exited"));
@@ -15748,7 +16039,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15748
16039
  const all = [];
15749
16040
  const seen = /* @__PURE__ */ new Set();
15750
16041
  for (let pageIndex = 0; ; pageIndex++) {
15751
- const { vtxos, page } = await chunk57636V35_cjs.getNormalizedVtxos(this.indexerProvider, {
16042
+ const { vtxos, page } = await chunk6FTHFJAN_cjs.getNormalizedVtxos(this.indexerProvider, {
15752
16043
  scripts,
15753
16044
  pageIndex,
15754
16045
  pageSize
@@ -15795,7 +16086,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15795
16086
  for (let i = 0; i < inputs.length; i += MAX_INPUTS_PER_INTENT) {
15796
16087
  const batch = inputs.slice(i, i + MAX_INPUTS_PER_INTENT);
15797
16088
  const message = { type: "get-pending-tx", expire_at: 0 };
15798
- const proof = chunk57636V35_cjs.Intent.create(message, batch, []);
16089
+ const proof = chunk6FTHFJAN_cjs.Intent.create(message, batch, []);
15799
16090
  const signedProof = await identity.sign(
15800
16091
  proof,
15801
16092
  Array.from({ length: batch.length + 1 }, (_, j) => j)
@@ -15817,7 +16108,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15817
16108
  try {
15818
16109
  const checkpointTxs = pendingTx.signedCheckpointTxs.map((checkpoint) => {
15819
16110
  const tx = btcSigner.Transaction.fromPSBT(base.base64.decode(checkpoint));
15820
- chunk57636V35_cjs.assertAllowedSighashTypes(tx);
16111
+ chunk6FTHFJAN_cjs.assertAllowedSighashTypes(tx);
15821
16112
  return tx;
15822
16113
  });
15823
16114
  assertCheckpointsMatchInputs(
@@ -16016,7 +16307,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
16016
16307
  script: recipient.script,
16017
16308
  amount: BigInt(recipient.amount),
16018
16309
  // Already checked against the recipient address in `validateRecipients`.
16019
- ...recipient.tapTree ? { tapTree: chunk57636V35_cjs.TapTreeCoder.decode(recipient.tapTree) } : {}
16310
+ ...recipient.tapTree ? { tapTree: chunk6FTHFJAN_cjs.TapTreeCoder.decode(recipient.tapTree) } : {}
16020
16311
  }));
16021
16312
  const totalBtcOutput = outputs.reduce((sum, o) => sum + Number(o.amount), 0);
16022
16313
  let changeAmount = totalBtcSelected - totalBtcOutput;
@@ -16160,10 +16451,10 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
16160
16451
  const serverPubKey = this.arkServerPublicKey;
16161
16452
  const serverUnrollScript = this.serverUnrollScript;
16162
16453
  const arkAddress = offchainTapscript.address(this.network.hrp, serverPubKey);
16163
- const normalizedInputs = inputs.map(chunk57636V35_cjs.normalizeVtxo);
16164
- const at = now ?? await chunk57636V35_cjs.resolveTimeHeight(this.onchainProvider);
16454
+ const normalizedInputs = inputs.map(chunk6FTHFJAN_cjs.normalizeVtxo);
16455
+ const at = now ?? await chunk6FTHFJAN_cjs.resolveTimeHeight(this.onchainProvider);
16165
16456
  for (const input of normalizedInputs) {
16166
- if (!chunk57636V35_cjs.canSpendOffchain(input, at)) {
16457
+ if (!chunk6FTHFJAN_cjs.canSpendOffchain(input, at)) {
16167
16458
  throw new Error(
16168
16459
  `sendSelectedVtxosToSelf: input ${input.txid}:${input.vout} is not cooperatively spendable`
16169
16460
  );
@@ -16233,7 +16524,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
16233
16524
  );
16234
16525
  const arkTxJobs = inputs.map((input, index) => ({
16235
16526
  index,
16236
- lookupScript: chunk57636V35_cjs.VtxoScript.decode(input.tapTree).pkScript
16527
+ lookupScript: chunk6FTHFJAN_cjs.VtxoScript.decode(input.tapTree).pkScript
16237
16528
  }));
16238
16529
  const identity = this.identity;
16239
16530
  const signer = {
@@ -16319,14 +16610,14 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
16319
16610
  const spentBy = checkpointIdByOutpoint.get(`${vtxo.txid}:${vtxo.vout}`);
16320
16611
  spentVtxos.push({
16321
16612
  ...spentFacts,
16322
- virtualStatus: chunk57636V35_cjs.toVirtualStatus(spentFacts),
16613
+ virtualStatus: chunk6FTHFJAN_cjs.toVirtualStatus(spentFacts),
16323
16614
  ...spentBy ? { spentBy } : {},
16324
16615
  arkTxId: arkTxid
16325
16616
  });
16326
16617
  for (const id of vtxo.commitmentTxIds) {
16327
16618
  commitmentTxIds.add(id);
16328
16619
  }
16329
- const vtxoExpiry = chunk57636V35_cjs.toBatchExpiry(vtxo);
16620
+ const vtxoExpiry = chunk6FTHFJAN_cjs.toBatchExpiry(vtxo);
16330
16621
  if (vtxoExpiry) {
16331
16622
  batchExpiry = Math.min(batchExpiry, vtxoExpiry);
16332
16623
  }
@@ -16339,7 +16630,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
16339
16630
  isSwept: false,
16340
16631
  isPreconfirmed: true,
16341
16632
  commitmentTxIds: Array.from(commitmentTxIds),
16342
- ...chunk57636V35_cjs.parseLegacyExpiry(batchExpiry)
16633
+ ...chunk6FTHFJAN_cjs.parseLegacyExpiry(batchExpiry)
16343
16634
  };
16344
16635
  changeVtxo = {
16345
16636
  txid: arkTxid,
@@ -16351,7 +16642,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
16351
16642
  tapTree: offchainTapscript.encode(),
16352
16643
  value: Number(changeAmount),
16353
16644
  ...changeFacts,
16354
- virtualStatus: chunk57636V35_cjs.toVirtualStatus(changeFacts),
16645
+ virtualStatus: chunk6FTHFJAN_cjs.toVirtualStatus(changeFacts),
16355
16646
  spentBy: "",
16356
16647
  status: {
16357
16648
  confirmed: false
@@ -16420,12 +16711,12 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
16420
16711
  const spentVtxos = [];
16421
16712
  const inputArkTxIds = /* @__PURE__ */ new Set();
16422
16713
  const boardingRemovalsByAddress = /* @__PURE__ */ new Map();
16423
- const vtxoInputs = inputs.filter(chunk57636V35_cjs.isVirtualCoin);
16714
+ const vtxoInputs = inputs.filter(chunk6FTHFJAN_cjs.isVirtualCoin);
16424
16715
  const cm = await this.getContractManager();
16425
16716
  const annotatedVtxos = await cm.annotateVtxos(vtxoInputs);
16426
16717
  const annotatedByKey = new Map(annotatedVtxos.map((v) => [`${v.txid}:${v.vout}`, v]));
16427
16718
  for (const input of inputs) {
16428
- if (chunk57636V35_cjs.isVirtualCoin(input)) {
16719
+ if (chunk6FTHFJAN_cjs.isVirtualCoin(input)) {
16429
16720
  const outpoint = `${input.txid}:${input.vout}`;
16430
16721
  const vtxo = annotatedByKey.get(outpoint);
16431
16722
  if (!vtxo) {
@@ -16437,13 +16728,13 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
16437
16728
  const settledFacts = { ...vtxo, isSpent: true };
16438
16729
  spentVtxos.push({
16439
16730
  ...settledFacts,
16440
- virtualStatus: chunk57636V35_cjs.toVirtualStatus(settledFacts),
16731
+ virtualStatus: chunk6FTHFJAN_cjs.toVirtualStatus(settledFacts),
16441
16732
  settledBy: commitmentTxid
16442
16733
  });
16443
16734
  } else {
16444
16735
  let sourceAddress;
16445
16736
  try {
16446
- sourceAddress = chunk57636V35_cjs.VtxoScript.decode(input.tapTree).onchainAddress(
16737
+ sourceAddress = chunk6FTHFJAN_cjs.VtxoScript.decode(input.tapTree).onchainAddress(
16447
16738
  this.network
16448
16739
  );
16449
16740
  } catch {
@@ -16501,9 +16792,9 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
16501
16792
  }
16502
16793
  };
16503
16794
  function selectVirtualCoins(coins, targetAmount) {
16504
- const sortedCoins = coins.map(chunk57636V35_cjs.normalizeVtxo).sort((a, b) => {
16505
- const expiryA = chunk57636V35_cjs.toBatchExpiry(a) || Number.MAX_SAFE_INTEGER;
16506
- const expiryB = chunk57636V35_cjs.toBatchExpiry(b) || Number.MAX_SAFE_INTEGER;
16795
+ const sortedCoins = coins.map(chunk6FTHFJAN_cjs.normalizeVtxo).sort((a, b) => {
16796
+ const expiryA = chunk6FTHFJAN_cjs.toBatchExpiry(a) || Number.MAX_SAFE_INTEGER;
16797
+ const expiryB = chunk6FTHFJAN_cjs.toBatchExpiry(b) || Number.MAX_SAFE_INTEGER;
16507
16798
  if (expiryA !== expiryB) {
16508
16799
  return expiryA - expiryB;
16509
16800
  }
@@ -16872,7 +17163,7 @@ var MessageBus = class {
16872
17163
  this.initialized = true;
16873
17164
  }
16874
17165
  async buildServices(config) {
16875
- const arkProvider = new chunk57636V35_cjs.RestArkProvider(config.arkServer.url);
17166
+ const arkProvider = new chunk6FTHFJAN_cjs.RestArkProvider(config.arkServer.url);
16876
17167
  const storage = {
16877
17168
  walletRepository: this.walletRepository,
16878
17169
  contractRepository: this.contractRepository,
@@ -17214,7 +17505,7 @@ var offboardNetworkNames = [
17214
17505
  function offboardDestinationScript(destinationAddress) {
17215
17506
  for (const networkName of offboardNetworkNames) {
17216
17507
  try {
17217
- const network = chunk57636V35_cjs.networks[networkName];
17508
+ const network = chunk6FTHFJAN_cjs.networks[networkName];
17218
17509
  const addr = btcSigner.Address(network).decode(destinationAddress);
17219
17510
  return btcSigner.OutScript.encode(addr);
17220
17511
  } catch {
@@ -17278,7 +17569,7 @@ var Ramps = class {
17278
17569
  }
17279
17570
  amount = amount ?? totalAmount;
17280
17571
  const offchainAddress = await this.wallet.getAddress();
17281
- const offchainAddr = chunk57636V35_cjs.ArkAddress.decode(offchainAddress);
17572
+ const offchainAddr = chunk6FTHFJAN_cjs.ArkAddress.decode(offchainAddress);
17282
17573
  const offchainScript = base.hex.encode(offchainAddr.pkScript);
17283
17574
  const outputFee = estimator.evalOffchainOutput({
17284
17575
  amount,
@@ -17338,7 +17629,7 @@ var Ramps = class {
17338
17629
  const filteredVtxos = [];
17339
17630
  let totalAmount = 0n;
17340
17631
  for (const vtxo of vtxos) {
17341
- const inputFee = estimator.evalOffchainInput(chunk57636V35_cjs.toOffchainInputFeeParams(vtxo));
17632
+ const inputFee = estimator.evalOffchainInput(chunk6FTHFJAN_cjs.toOffchainInputFeeParams(vtxo));
17342
17633
  if (inputFee.satoshis >= vtxo.value) {
17343
17634
  continue;
17344
17635
  }
@@ -17443,6 +17734,9 @@ var DelegateNotConfiguredError = class extends Error {
17443
17734
  };
17444
17735
  var DelegatorNotConfiguredError = DelegateNotConfiguredError;
17445
17736
  var DEFAULT_MESSAGE_TAG = "WALLET_UPDATER";
17737
+ function unsupportedByManager(method) {
17738
+ return new Error(`Contract manager does not support ${method}`);
17739
+ }
17446
17740
  var serializeMigrationVtxoRef = (ref) => ({
17447
17741
  txid: ref.txid,
17448
17742
  vout: ref.vout,
@@ -17750,8 +18044,7 @@ var WalletMessageHandler = class {
17750
18044
  });
17751
18045
  }
17752
18046
  case "GET_TRANSACTION_HISTORY": {
17753
- const allVtxos = await this.getVtxosFromRepo();
17754
- const transactions = await this.buildTransactionHistoryFromCache(allVtxos) ?? [];
18047
+ const transactions = await this.buildTransactionHistoryFromCache() ?? [];
17755
18048
  return this.tagged({
17756
18049
  id,
17757
18050
  type: "TRANSACTION_HISTORY",
@@ -17827,6 +18120,39 @@ var WalletMessageHandler = class {
17827
18120
  payload: { contracts }
17828
18121
  });
17829
18122
  }
18123
+ case "WATCH_SCRIPT": {
18124
+ const manager = await this.readonlyWallet.getContractManager();
18125
+ if (!manager.watchScript) throw unsupportedByManager("watchScript");
18126
+ await manager.watchScript(message.payload.script, {
18127
+ label: message.payload.label
18128
+ });
18129
+ return this.tagged({
18130
+ id,
18131
+ type: "SCRIPT_WATCHED",
18132
+ payload: { script: message.payload.script }
18133
+ });
18134
+ }
18135
+ case "UNWATCH_SCRIPT": {
18136
+ const manager = await this.readonlyWallet.getContractManager();
18137
+ if (!manager.unwatchScript) throw unsupportedByManager("unwatchScript");
18138
+ await manager.unwatchScript(message.payload.script);
18139
+ return this.tagged({
18140
+ id,
18141
+ type: "SCRIPT_UNWATCHED",
18142
+ payload: { script: message.payload.script }
18143
+ });
18144
+ }
18145
+ case "GET_WATCHED_SCRIPTS": {
18146
+ const manager = await this.readonlyWallet.getContractManager();
18147
+ if (!manager.getWatchedScripts) {
18148
+ throw unsupportedByManager("getWatchedScripts");
18149
+ }
18150
+ return this.tagged({
18151
+ id,
18152
+ type: "WATCHED_SCRIPTS",
18153
+ payload: { scripts: await manager.getWatchedScripts() }
18154
+ });
18155
+ }
17830
18156
  case "ANNOTATE_VTXOS": {
17831
18157
  const manager = await this.readonlyWallet.getContractManager();
17832
18158
  const annotated = await manager.annotateVtxos(message.payload.vtxos);
@@ -18174,7 +18500,7 @@ var WalletMessageHandler = class {
18174
18500
  // Wallet methods
18175
18501
  async handleInitWallet({ payload }) {
18176
18502
  const { arkServerUrl } = payload;
18177
- this.indexerProvider = new chunk3KW4TWP2_cjs.RestIndexerProvider(arkServerUrl);
18503
+ this.indexerProvider = new chunk4C5PMGBB_cjs.RestIndexerProvider(arkServerUrl);
18178
18504
  await this.onWalletInitialized();
18179
18505
  }
18180
18506
  /**
@@ -18200,7 +18526,7 @@ var WalletMessageHandler = class {
18200
18526
  unconfirmed += utxo.value;
18201
18527
  }
18202
18528
  }
18203
- const gated = gatedContracts(snapshot.map((_) => _.contract));
18529
+ const gated = gatedFrom(snapshot);
18204
18530
  const unlocked = new Set(
18205
18531
  (await spendableVtxosExcludingLocked(allVtxos, this.readonlyWallet?.intentRepository)).map((vtxo) => `${vtxo.txid}:${vtxo.vout}`)
18206
18532
  );
@@ -18208,7 +18534,7 @@ var WalletMessageHandler = class {
18208
18534
  const offchain = computeOffchainBalance(allVtxos, {
18209
18535
  now: { timestamp: /* @__PURE__ */ new Date() },
18210
18536
  isPendingRecovery: (vtxo) => pendingOutpoints.has(`${vtxo.txid}:${vtxo.vout}`),
18211
- isGenericallySpendable: (vtxo) => !gated.has(vtxo.script),
18537
+ isGenericallySpendable: (vtxo) => !isGatedVtxo(vtxo, gated),
18212
18538
  isUnlocked: (vtxo) => unlocked.has(`${vtxo.txid}:${vtxo.vout}`)
18213
18539
  });
18214
18540
  return {
@@ -18348,7 +18674,6 @@ var WalletMessageHandler = class {
18348
18674
  if (!this.readonlyWallet || !this.walletRepository) {
18349
18675
  return;
18350
18676
  }
18351
- const vtxos = await this.getVtxosFromRepo();
18352
18677
  const boardingAddresses = await this.readonlyWallet.getBoardingAddresses();
18353
18678
  const fresh = await this.readonlyWallet.getBoardingUtxos();
18354
18679
  const freshKeys = new Set(fresh.map((u) => `${u.txid}:${u.vout}`));
@@ -18360,7 +18685,7 @@ var WalletMessageHandler = class {
18360
18685
  if (kept.length > 0) await this.walletRepository.saveUtxos(addr, kept);
18361
18686
  }
18362
18687
  const address = await this.readonlyWallet.getAddress();
18363
- const txs = await this.buildTransactionHistoryFromCache(vtxos);
18688
+ const txs = await this.buildTransactionHistoryFromCache();
18364
18689
  if (txs) await this.walletRepository.saveTransactions(address, txs);
18365
18690
  }
18366
18691
  /**
@@ -18463,7 +18788,7 @@ var WalletMessageHandler = class {
18463
18788
  if (v.isUnrolled) {
18464
18789
  return withUnrolled;
18465
18790
  }
18466
- if (chunk57636V35_cjs.hasTerminalSpend(v)) {
18791
+ if (chunk6FTHFJAN_cjs.hasTerminalSpend(v)) {
18467
18792
  return false;
18468
18793
  }
18469
18794
  if (includeRecoverable) {
@@ -18472,10 +18797,10 @@ var WalletMessageHandler = class {
18472
18797
  if (dustAmount != null && isSubdust(v, dustAmount)) {
18473
18798
  return false;
18474
18799
  }
18475
- if (chunk57636V35_cjs.isRecoverable(v)) {
18800
+ if (chunk6FTHFJAN_cjs.isRecoverable(v)) {
18476
18801
  return false;
18477
18802
  }
18478
- if (chunk57636V35_cjs.isExpired(v)) {
18803
+ if (chunk6FTHFJAN_cjs.isExpired(v)) {
18479
18804
  return false;
18480
18805
  }
18481
18806
  return true;
@@ -18568,13 +18893,29 @@ var WalletMessageHandler = class {
18568
18893
  /**
18569
18894
  * Build transaction history from cached virtual outputs, hitting the indexer only for
18570
18895
  * uncached timestamps. Best-effort, like the plain Wallet path.
18571
- */
18572
- async buildTransactionHistoryFromCache(vtxos) {
18896
+ *
18897
+ * Takes its own {@link repoSnapshot} rather than a caller-supplied VTXO
18898
+ * list: the coins and the gate that judges them have to come off one read
18899
+ * or they answer about different instants, and being the worker's only
18900
+ * history builder means neither caller can supply one without the other.
18901
+ * The snapshot and the boarding read are independent, so they run together
18902
+ * — the same pairing `handleGetBalance` makes.
18903
+ */
18904
+ async buildTransactionHistoryFromCache() {
18573
18905
  if (!this.readonlyWallet) return null;
18574
- const { boardingTxs, commitmentsToIgnore } = await this.readonlyWallet.getBoardingTxs();
18906
+ const [{ snapshot, vtxos }, { boardingTxs, commitmentsToIgnore }] = await Promise.all([
18907
+ this.repoSnapshot(),
18908
+ this.readonlyWallet.getBoardingTxs()
18909
+ ]);
18575
18910
  const indexerProvider = this.indexerProvider;
18576
- const resolveTxCreatedAt = indexerProvider ? (txids) => chunk57636V35_cjs.fetchVtxoCreatedAtByTxid(indexerProvider, txids) : void 0;
18577
- return buildTransactionHistory(vtxos, boardingTxs, commitmentsToIgnore, resolveTxCreatedAt);
18911
+ const resolveTxCreatedAt = indexerProvider ? (txids) => chunk6FTHFJAN_cjs.fetchVtxoCreatedAtByTxid(indexerProvider, txids) : void 0;
18912
+ return buildTransactionHistory(
18913
+ vtxos,
18914
+ boardingTxs,
18915
+ commitmentsToIgnore,
18916
+ resolveTxCreatedAt,
18917
+ gatedFrom(snapshot)
18918
+ );
18578
18919
  }
18579
18920
  async ensureContractEventBroadcasting() {
18580
18921
  const wallet = this.readonlyWallet;
@@ -18630,6 +18971,7 @@ var DEFAULT_MESSAGE_TIMEOUTS = {
18630
18971
  GET_TRANSACTION_HISTORY: 2e4,
18631
18972
  GET_CONTRACTS: 2e4,
18632
18973
  GET_CONTRACTS_WITH_VTXOS: 2e4,
18974
+ GET_WATCHED_SCRIPTS: 1e4,
18633
18975
  ANNOTATE_VTXOS: 2e4,
18634
18976
  GET_SPENDABLE_PATHS: 2e4,
18635
18977
  GET_ALL_SPENDING_PATHS: 2e4,
@@ -18666,6 +19008,10 @@ var DEFAULT_MESSAGE_TIMEOUTS = {
18666
19008
  SIGN_TRANSACTION: 3e4,
18667
19009
  CREATE_CONTRACT: 3e4,
18668
19010
  UPDATE_CONTRACT: 3e4,
19011
+ // Registering a watch is an in-memory map write plus one subscription
19012
+ // update — no indexer round trip on the request path.
19013
+ WATCH_SCRIPT: 1e4,
19014
+ UNWATCH_SCRIPT: 1e4,
18669
19015
  DELETE_CONTRACT: 1e4,
18670
19016
  REFRESH_VTXOS: 3e4,
18671
19017
  REFRESH_OUTPOINTS: 3e4
@@ -18686,6 +19032,7 @@ var DEDUPABLE_REQUEST_TYPES = /* @__PURE__ */ new Set([
18686
19032
  "GET_SPENDABLE_VTXOS",
18687
19033
  "GET_CONTRACTS",
18688
19034
  "GET_CONTRACTS_WITH_VTXOS",
19035
+ "GET_WATCHED_SCRIPTS",
18689
19036
  "ANNOTATE_VTXOS",
18690
19037
  "GET_SPENDABLE_PATHS",
18691
19038
  "GET_ALL_SPENDING_PATHS",
@@ -19269,7 +19616,7 @@ var ServiceWorkerReadonlyWallet = class _ServiceWorkerReadonlyWallet {
19269
19616
  };
19270
19617
  try {
19271
19618
  const response = await this.sendMessage(message);
19272
- return response.payload.vtxos.map(chunk57636V35_cjs.normalizeVtxo);
19619
+ return response.payload.vtxos.map(chunk6FTHFJAN_cjs.normalizeVtxo);
19273
19620
  } catch (error) {
19274
19621
  throw new Error(`Failed to get vtxos: ${error}`);
19275
19622
  }
@@ -19294,7 +19641,7 @@ var ServiceWorkerReadonlyWallet = class _ServiceWorkerReadonlyWallet {
19294
19641
  };
19295
19642
  try {
19296
19643
  const response = await this.sendMessage(message);
19297
- return response.payload.vtxos.map(chunk57636V35_cjs.normalizeVtxo);
19644
+ return response.payload.vtxos.map(chunk6FTHFJAN_cjs.normalizeVtxo);
19298
19645
  } catch (error) {
19299
19646
  throw new Error(`Failed to get spendable vtxos: ${error}`);
19300
19647
  }
@@ -19394,6 +19741,46 @@ var ServiceWorkerReadonlyWallet = class _ServiceWorkerReadonlyWallet {
19394
19741
  throw new Error("Failed to get contracts with vtxos");
19395
19742
  }
19396
19743
  },
19744
+ async watchScript(script, options) {
19745
+ const message = {
19746
+ type: "WATCH_SCRIPT",
19747
+ id: getRandomId(),
19748
+ tag: messageTag,
19749
+ payload: { script, label: options?.label }
19750
+ };
19751
+ try {
19752
+ await sendContractMessage(message);
19753
+ } catch (e) {
19754
+ throw new Error("Failed to watch script");
19755
+ }
19756
+ },
19757
+ async unwatchScript(script) {
19758
+ const message = {
19759
+ type: "UNWATCH_SCRIPT",
19760
+ id: getRandomId(),
19761
+ tag: messageTag,
19762
+ payload: { script }
19763
+ };
19764
+ try {
19765
+ await sendContractMessage(message);
19766
+ } catch (e) {
19767
+ throw new Error("Failed to unwatch script");
19768
+ }
19769
+ },
19770
+ async getWatchedScripts() {
19771
+ const message = {
19772
+ type: "GET_WATCHED_SCRIPTS",
19773
+ id: getRandomId(),
19774
+ tag: messageTag,
19775
+ payload: {}
19776
+ };
19777
+ try {
19778
+ const response = await sendContractMessage(message);
19779
+ return response.payload.scripts;
19780
+ } catch (e) {
19781
+ throw new Error("Failed to get watched scripts");
19782
+ }
19783
+ },
19397
19784
  getSyncState() {
19398
19785
  return syncState;
19399
19786
  },
@@ -19425,7 +19812,7 @@ var ServiceWorkerReadonlyWallet = class _ServiceWorkerReadonlyWallet {
19425
19812
  };
19426
19813
  try {
19427
19814
  const response = await sendContractMessage(message);
19428
- return response.payload.vtxos.map(chunk57636V35_cjs.normalizeVtxo);
19815
+ return response.payload.vtxos.map(chunk6FTHFJAN_cjs.normalizeVtxo);
19429
19816
  } catch (e) {
19430
19817
  throw new Error("Failed to annotate vtxos");
19431
19818
  }
@@ -19624,6 +20011,7 @@ var ServiceWorkerWallet = class _ServiceWorkerWallet extends ServiceWorkerReadon
19624
20011
  identity;
19625
20012
  _assetManager;
19626
20013
  hasDelegate;
20014
+ _restoreInFlight;
19627
20015
  get assetManager() {
19628
20016
  return this._assetManager;
19629
20017
  }
@@ -19886,6 +20274,16 @@ var ServiceWorkerWallet = class _ServiceWorkerWallet extends ServiceWorkerReadon
19886
20274
  * reconstructed here so callers can inspect `.errors`.
19887
20275
  */
19888
20276
  async restore(opts) {
20277
+ if (this._restoreInFlight) return this._restoreInFlight;
20278
+ this._restoreInFlight = (async () => {
20279
+ await this._restoreWorkerWallet(opts);
20280
+ await runWalletRestoreHooks(this);
20281
+ })().finally(() => {
20282
+ this._restoreInFlight = void 0;
20283
+ });
20284
+ return this._restoreInFlight;
20285
+ }
20286
+ async _restoreWorkerWallet(opts) {
19889
20287
  const message = {
19890
20288
  id: getRandomId(),
19891
20289
  tag: this.messageTag,
@@ -20026,7 +20424,7 @@ var ServiceWorkerWallet = class _ServiceWorkerWallet extends ServiceWorkerReadon
20026
20424
  };
20027
20425
  try {
20028
20426
  const response = await wallet.sendMessage(message);
20029
- return response.payload.vtxos.map(chunk57636V35_cjs.normalizeVtxo);
20427
+ return response.payload.vtxos.map(chunk6FTHFJAN_cjs.normalizeVtxo);
20030
20428
  } catch (e) {
20031
20429
  throw new Error(`Failed to get expiring vtxos: ${e}`);
20032
20430
  }
@@ -20138,12 +20536,12 @@ var OnchainWallet = class _OnchainWallet {
20138
20536
  * @returns Configured onchain wallet
20139
20537
  * @throws Error if the configured identity cannot produce a valid x-only public key
20140
20538
  */
20141
- static async create(identity, networkName = chunk57636V35_cjs.DEFAULT_NETWORK_NAME, provider) {
20539
+ static async create(identity, networkName = chunk6FTHFJAN_cjs.DEFAULT_NETWORK_NAME, provider) {
20142
20540
  const pubkey = await identity.xOnlyPublicKey();
20143
20541
  if (!pubkey) {
20144
20542
  throw new Error("Invalid configured public key");
20145
20543
  }
20146
- const network = chunk57636V35_cjs.getNetwork(networkName);
20544
+ const network = chunk6FTHFJAN_cjs.getNetwork(networkName);
20147
20545
  const onchainProvider = provider || new EsploraProvider(ESPLORA_URL[networkName]);
20148
20546
  const onchainP2TR = btcSigner.p2tr(pubkey, void 0, network);
20149
20547
  return new _OnchainWallet(identity, network, onchainP2TR, onchainProvider);
@@ -20249,7 +20647,7 @@ var OnchainWallet = class _OnchainWallet {
20249
20647
  if (!inputs) {
20250
20648
  throw new Error("Fee estimation failed");
20251
20649
  }
20252
- let tx = new chunk57636V35_cjs.Transaction();
20650
+ let tx = new chunk6FTHFJAN_cjs.Transaction();
20253
20651
  for (const input of inputs) {
20254
20652
  tx.addInput({
20255
20653
  txid: input.txid,
@@ -20307,7 +20705,7 @@ var OnchainWallet = class _OnchainWallet {
20307
20705
  * @throws If the parent has no anchor, or funding cannot be selected/signed
20308
20706
  */
20309
20707
  async bumpAnchor(parentHex, feeRate) {
20310
- const parent = chunk57636V35_cjs.Transaction.fromRaw(base.hex.decode(parentHex));
20708
+ const parent = chunk6FTHFJAN_cjs.Transaction.fromRaw(base.hex.decode(parentHex));
20311
20709
  const coins = (await this.getCoins()).filter((c) => c.status.confirmed);
20312
20710
  const child = await this.buildBumpPackage(parent, feeRate, coins);
20313
20711
  return [parent.hex, child.hex];
@@ -21214,7 +21612,7 @@ async function resolvePrevTxs(txids, source, onchain) {
21214
21612
  try {
21215
21613
  const { txs } = await source.getVirtualTxs(wanted);
21216
21614
  for (const psbt of txs) {
21217
- const tx = chunk57636V35_cjs.Transaction.fromPSBT(base.base64.decode(psbt));
21615
+ const tx = chunk6FTHFJAN_cjs.Transaction.fromPSBT(base.base64.decode(psbt));
21218
21616
  resolved.set(tx.id, tx.toBytes());
21219
21617
  }
21220
21618
  } catch (err) {
@@ -21247,7 +21645,7 @@ async function resolvePrevTxs(txids, source, onchain) {
21247
21645
  async function attachPrevArkTxs(tx, txids, source, onchain) {
21248
21646
  const pending = [];
21249
21647
  for (let i = 0; i < tx.inputsLength; i++) {
21250
- if (chunk57636V35_cjs.getArkPsbtFields(tx, i, chunk57636V35_cjs.PrevArkTxField).length === 0) pending.push(i);
21648
+ if (chunk6FTHFJAN_cjs.getArkPsbtFields(tx, i, chunk6FTHFJAN_cjs.PrevArkTxField).length === 0) pending.push(i);
21251
21649
  }
21252
21650
  if (pending.length === 0) return;
21253
21651
  const resolved = await resolvePrevTxs(
@@ -21256,13 +21654,13 @@ async function attachPrevArkTxs(tx, txids, source, onchain) {
21256
21654
  onchain
21257
21655
  );
21258
21656
  for (const i of pending) {
21259
- chunk57636V35_cjs.setArkPsbtField(tx, i, chunk57636V35_cjs.PrevArkTxField, resolved.get(txidAt(txids, i)));
21657
+ chunk6FTHFJAN_cjs.setArkPsbtField(tx, i, chunk6FTHFJAN_cjs.PrevArkTxField, resolved.get(txidAt(txids, i)));
21260
21658
  }
21261
21659
  }
21262
21660
  async function attachPrevoutTxs(tx, source) {
21263
21661
  const pending = [];
21264
21662
  for (let i = 0; i < tx.inputsLength; i++) {
21265
- if (chunk57636V35_cjs.getArkPsbtFields(tx, i, chunk57636V35_cjs.PrevoutTxField).length > 0) continue;
21663
+ if (chunk6FTHFJAN_cjs.getArkPsbtFields(tx, i, chunk6FTHFJAN_cjs.PrevoutTxField).length > 0) continue;
21266
21664
  const input = tx.getInput(i);
21267
21665
  if (!input?.txid) throw new PrevTxUnavailableError(`input ${i} has no outpoint`);
21268
21666
  pending.push({ index: i, txid: base.hex.encode(input.txid) });
@@ -21273,7 +21671,7 @@ async function attachPrevoutTxs(tx, source) {
21273
21671
  resolved.set(txid, await source.getRawTransaction(txid));
21274
21672
  }
21275
21673
  for (const { index, txid } of pending) {
21276
- chunk57636V35_cjs.setArkPsbtField(tx, index, chunk57636V35_cjs.PrevoutTxField, resolved.get(txid));
21674
+ chunk6FTHFJAN_cjs.setArkPsbtField(tx, index, chunk6FTHFJAN_cjs.PrevoutTxField, resolved.get(txid));
21277
21675
  }
21278
21676
  }
21279
21677
  async function withPrevTxs(coins, source, onchain) {
@@ -21299,7 +21697,7 @@ exports.BIP322 = void 0;
21299
21697
  async function sign2(message, identity, network) {
21300
21698
  const xOnlyPubKey = await identity.xOnlyPublicKey();
21301
21699
  const payment = btcSigner.p2tr(xOnlyPubKey, void 0, network);
21302
- const toSpend = chunk57636V35_cjs.craftToSpendTx(message, payment.script, TAG_BIP322);
21700
+ const toSpend = chunk6FTHFJAN_cjs.craftToSpendTx(message, payment.script, TAG_BIP322);
21303
21701
  const toSign = craftBIP322ToSignP2TR(toSpend, payment.script, xOnlyPubKey);
21304
21702
  const signed = await identity.sign(toSign, [0]);
21305
21703
  signed.finalizeIdx(0);
@@ -21357,7 +21755,7 @@ function verifyP2TR(message, witnessItems, pkScript, pubkey) {
21357
21755
  if (sighashType !== btcSigner.SigHash.DEFAULT && sighashType !== btcSigner.SigHash.ALL) {
21358
21756
  return false;
21359
21757
  }
21360
- const toSpend = chunk57636V35_cjs.craftToSpendTx(message, pkScript, TAG_BIP322);
21758
+ const toSpend = chunk6FTHFJAN_cjs.craftToSpendTx(message, pkScript, TAG_BIP322);
21361
21759
  const toSign = craftBIP322ToSignP2TR(toSpend, pkScript, pubkey);
21362
21760
  const sighash = toSign.preimageWitnessV1(0, [pkScript], sighashType, [0n]);
21363
21761
  const rawSig = sig.length === 65 ? sig.subarray(0, 64) : sig;
@@ -21378,7 +21776,7 @@ function verifyP2WPKH(message, witnessItems, pkScript, addressHash) {
21378
21776
  }
21379
21777
  const sighashType = sigWithHash[sigWithHash.length - 1];
21380
21778
  const derSig = sigWithHash.subarray(0, sigWithHash.length - 1);
21381
- const toSpend = chunk57636V35_cjs.craftToSpendTx(message, pkScript, TAG_BIP322);
21779
+ const toSpend = chunk6FTHFJAN_cjs.craftToSpendTx(message, pkScript, TAG_BIP322);
21382
21780
  const toSign = craftBIP322ToSignSimple(toSpend, pkScript);
21383
21781
  const scriptCode = btcSigner.OutScript.encode({ type: "pkh", hash: addressHash });
21384
21782
  const sighash = toSign.preimageWitnessV0(0, scriptCode, sighashType, 0n);
@@ -21431,7 +21829,7 @@ function encodeCompactSize(n) {
21431
21829
  return buf;
21432
21830
  }
21433
21831
  function craftBIP322ToSignP2TR(toSpend, pkScript, tapInternalKey) {
21434
- const tx = new chunk57636V35_cjs.Transaction({ version: 0 });
21832
+ const tx = new chunk6FTHFJAN_cjs.Transaction({ version: 0 });
21435
21833
  tx.addInput({
21436
21834
  txid: toSpend.id,
21437
21835
  index: 0,
@@ -21445,12 +21843,12 @@ function craftBIP322ToSignP2TR(toSpend, pkScript, tapInternalKey) {
21445
21843
  });
21446
21844
  tx.addOutput({
21447
21845
  amount: 0n,
21448
- script: chunk57636V35_cjs.OP_RETURN_EMPTY_PKSCRIPT
21846
+ script: chunk6FTHFJAN_cjs.OP_RETURN_EMPTY_PKSCRIPT
21449
21847
  });
21450
21848
  return tx;
21451
21849
  }
21452
21850
  function craftBIP322ToSignSimple(toSpend, pkScript) {
21453
- const tx = new chunk57636V35_cjs.Transaction({ version: 0 });
21851
+ const tx = new chunk6FTHFJAN_cjs.Transaction({ version: 0 });
21454
21852
  tx.addInput({
21455
21853
  txid: toSpend.id,
21456
21854
  index: 0,
@@ -21462,7 +21860,7 @@ function craftBIP322ToSignSimple(toSpend, pkScript) {
21462
21860
  });
21463
21861
  tx.addOutput({
21464
21862
  amount: 0n,
21465
- script: chunk57636V35_cjs.OP_RETURN_EMPTY_PKSCRIPT
21863
+ script: chunk6FTHFJAN_cjs.OP_RETURN_EMPTY_PKSCRIPT
21466
21864
  });
21467
21865
  return tx;
21468
21866
  }
@@ -21475,7 +21873,7 @@ var RestEmulatorProvider = class {
21475
21873
  serverUrl;
21476
21874
  async getInfo() {
21477
21875
  const url = `${this.serverUrl}/v1/info`;
21478
- const response = await fetch(url);
21876
+ const response = await chunk6FTHFJAN_cjs.baseFetch(url);
21479
21877
  if (!response.ok) {
21480
21878
  const errorText2 = await response.text();
21481
21879
  throw new Error(`Failed to get emulator info: ${errorText2}`);
@@ -21593,7 +21991,7 @@ var RestEmulatorProvider = class {
21593
21991
  }
21594
21992
  };
21595
21993
  function finalizeVirtualTx(type, psbtBase64) {
21596
- const tx = chunk57636V35_cjs.Transaction.fromPSBT(base.base64.decode(psbtBase64));
21994
+ const tx = chunk6FTHFJAN_cjs.Transaction.fromPSBT(base.base64.decode(psbtBase64));
21597
21995
  if (type === "INDEXER_CHAINED_TX_TYPE_TREE" /* TREE */) {
21598
21996
  const input = tx.getInput(0);
21599
21997
  if (!input) {
@@ -21620,14 +22018,14 @@ var ExitPathError = class extends Error {
21620
22018
  reason;
21621
22019
  };
21622
22020
  function delayWeight(sequence) {
21623
- const t = chunk57636V35_cjs.sequenceToTimelock(sequence);
22021
+ const t = chunk6FTHFJAN_cjs.sequenceToTimelock(sequence);
21624
22022
  return t.type === "blocks" ? Number(t.value) : Number(t.value) / 600;
21625
22023
  }
21626
22024
  async function resolveUnilateralPath(params) {
21627
22025
  const { vtxo, scriptHex, contractRepository } = params;
21628
22026
  const contract = contractRepository ? (await contractRepository.getContracts({ script: scriptHex }))[0] : void 0;
21629
22027
  if (contract) {
21630
- const handler = chunk3OKEUDHU_cjs.contractHandlers.get(contract.type);
22028
+ const handler = chunkNPM5YZBC_cjs.contractHandlers.get(contract.type);
21631
22029
  if (!handler) {
21632
22030
  throw new ExitPathError(
21633
22031
  "no-handler",
@@ -21650,12 +22048,12 @@ async function resolveUnilateralPath(params) {
21650
22048
  paths.sort((a, b) => delayWeight(a.sequence) - delayWeight(b.sequence));
21651
22049
  return { selection: paths[0], label: `${contract.type}:unilateral` };
21652
22050
  }
21653
- const decoded = chunk57636V35_cjs.VtxoScript.decode(vtxo.tapTree);
22051
+ const decoded = chunk6FTHFJAN_cjs.VtxoScript.decode(vtxo.tapTree);
21654
22052
  let best;
21655
22053
  for (const exit of decoded.exitPaths()) {
21656
22054
  const leaf = decoded.findLeaf(base.hex.encode(exit.script));
21657
22055
  if (!leaf) continue;
21658
- const sequence = chunk57636V35_cjs.timelockToSequence(exit.params.timelock);
22056
+ const sequence = chunk6FTHFJAN_cjs.timelockToSequence(exit.params.timelock);
21659
22057
  const weight = delayWeight(sequence);
21660
22058
  if (!best || weight < best.weight) {
21661
22059
  best = { selection: { leaf, sequence }, weight };
@@ -21875,7 +22273,7 @@ async function prepareUnrollTransaction(wallet, vtxoTxIds, outputAddress) {
21875
22273
  let totalAmount = 0n;
21876
22274
  const txWeightEstimator = TxWeightEstimator.create();
21877
22275
  for (const vtxo of vtxos) {
21878
- if (!chunk57636V35_cjs.canSweepOnchain(vtxo)) {
22276
+ if (!chunk6FTHFJAN_cjs.canSweepOnchain(vtxo)) {
21879
22277
  throw new Error(
21880
22278
  `Vtxo ${vtxo.txid}:${vtxo.vout} cannot be swept onchain: it is not fully unrolled (use unroll first), or its exit output was already spent`
21881
22279
  );
@@ -21886,14 +22284,14 @@ async function prepareUnrollTransaction(wallet, vtxoTxIds, outputAddress) {
21886
22284
  }
21887
22285
  const resolved = await resolveUnilateralPath({
21888
22286
  vtxo,
21889
- scriptHex: base.hex.encode(chunk57636V35_cjs.VtxoScript.decode(vtxo.tapTree).pkScript),
22287
+ scriptHex: base.hex.encode(chunk6FTHFJAN_cjs.VtxoScript.decode(vtxo.tapTree).pkScript),
21890
22288
  contractRepository: wallet.contractRepository,
21891
22289
  walletPubKeyHex: base.hex.encode(await wallet.identity.xOnlyPublicKey()),
21892
22290
  currentTime: Date.now()
21893
22291
  });
21894
22292
  const spendingLeaf = resolved.selection.leaf;
21895
22293
  const sequence = resolved.selection.sequence;
21896
- const timelock = chunk57636V35_cjs.sequenceToTimelock(sequence);
22294
+ const timelock = chunk6FTHFJAN_cjs.sequenceToTimelock(sequence);
21897
22295
  const elapsed = timelock.type === "blocks" ? chainTip.height >= txStatus.blockHeight + Number(timelock.value) : chainTip.time >= txStatus.blockTime + Number(timelock.value);
21898
22296
  if (!elapsed) {
21899
22297
  throw new Error(`no available exit path found for vtxo ${vtxo.txid}:${vtxo.vout}`);
@@ -21906,7 +22304,7 @@ async function prepareUnrollTransaction(wallet, vtxoTxIds, outputAddress) {
21906
22304
  sequence,
21907
22305
  witnessUtxo: {
21908
22306
  amount: BigInt(vtxo.value),
21909
- script: chunk57636V35_cjs.VtxoScript.decode(vtxo.tapTree).pkScript
22307
+ script: chunk6FTHFJAN_cjs.VtxoScript.decode(vtxo.tapTree).pkScript
21910
22308
  },
21911
22309
  sighashType: btcSigner.SigHash.DEFAULT
21912
22310
  });
@@ -21916,7 +22314,7 @@ async function prepareUnrollTransaction(wallet, vtxoTxIds, outputAddress) {
21916
22314
  btcSigner.TaprootControlBlock.encode(spendingLeaf[0]).length
21917
22315
  );
21918
22316
  }
21919
- const tx = new chunk57636V35_cjs.Transaction({ version: 2 });
22317
+ const tx = new chunk6FTHFJAN_cjs.Transaction({ version: 2 });
21920
22318
  for (const input of inputs) {
21921
22319
  tx.addInput(input);
21922
22320
  }
@@ -21999,7 +22397,7 @@ async function buildSignedSweep(params) {
21999
22397
  `uneconomic vtxo ${vtxo.txid}:${vtxo.vout}: value ${vtxo.value} - fee ${fee} < dust`
22000
22398
  );
22001
22399
  }
22002
- const tx = new chunk57636V35_cjs.Transaction({ version: 2 });
22400
+ const tx = new chunk6FTHFJAN_cjs.Transaction({ version: 2 });
22003
22401
  tx.addInput({
22004
22402
  txid: vtxo.txid,
22005
22403
  index: vtxo.vout,
@@ -22024,7 +22422,7 @@ async function buildSignedSweep(params) {
22024
22422
  finalScriptWitness: [
22025
22423
  tapScriptSig[0][1],
22026
22424
  ...path.extraWitness,
22027
- chunk57636V35_cjs.scriptFromTapLeafScript(path.leaf),
22425
+ chunk6FTHFJAN_cjs.scriptFromTapLeafScript(path.leaf),
22028
22426
  btcSigner.TaprootControlBlock.encode(controlBlock)
22029
22427
  ]
22030
22428
  });
@@ -22054,7 +22452,7 @@ async function resolveFeeRate(opts) {
22054
22452
  }
22055
22453
  async function selectExitVtxos(opts) {
22056
22454
  if (!opts.vtxos) return opts.wallet.getVtxos();
22057
- const res = await chunk57636V35_cjs.getNormalizedVtxos(opts.wallet.indexerProvider, { outpoints: opts.vtxos });
22455
+ const res = await chunk6FTHFJAN_cjs.getNormalizedVtxos(opts.wallet.indexerProvider, { outpoints: opts.vtxos });
22058
22456
  const tapTrees = /* @__PURE__ */ new Map();
22059
22457
  const out = [];
22060
22458
  for (const vtxo of res.vtxos) {
@@ -22069,7 +22467,7 @@ async function selectExitVtxos(opts) {
22069
22467
  `no contract registered for vtxo script ${vtxo.script} \u2014 register the contract before exiting`
22070
22468
  );
22071
22469
  }
22072
- const handler = chunk3OKEUDHU_cjs.contractHandlers.get(contract.type);
22470
+ const handler = chunkNPM5YZBC_cjs.contractHandlers.get(contract.type);
22073
22471
  if (!handler) {
22074
22472
  throw new Error(`no contract handler registered for type '${contract.type}'`);
22075
22473
  }
@@ -22099,7 +22497,7 @@ async function computeExitLayout(opts, feeRate) {
22099
22497
  if (pendingNodes.length > 0) {
22100
22498
  const txs = await resolver.getVirtualTxs(pendingNodes.map((n) => n.txid));
22101
22499
  for (const psbt of txs) {
22102
- psbts.set(chunk57636V35_cjs.Transaction.fromPSBT(base.base64.decode(psbt)).id, psbt);
22500
+ psbts.set(chunk6FTHFJAN_cjs.Transaction.fromPSBT(base.base64.decode(psbt)).id, psbt);
22103
22501
  }
22104
22502
  }
22105
22503
  const childVsize = Number(
@@ -22135,7 +22533,7 @@ async function computeExitLayout(opts, feeRate) {
22135
22533
  try {
22136
22534
  const resolved = await resolveUnilateralPath({
22137
22535
  vtxo,
22138
- scriptHex: base.hex.encode(chunk57636V35_cjs.VtxoScript.decode(vtxo.tapTree).pkScript),
22536
+ scriptHex: base.hex.encode(chunk6FTHFJAN_cjs.VtxoScript.decode(vtxo.tapTree).pkScript),
22139
22537
  contractRepository: wallet.contractRepository,
22140
22538
  walletPubKeyHex,
22141
22539
  currentTime: Date.now()
@@ -22154,7 +22552,7 @@ async function computeExitLayout(opts, feeRate) {
22154
22552
  });
22155
22553
  continue;
22156
22554
  }
22157
- const t = chunk57636V35_cjs.sequenceToTimelock(resolved.selection.sequence);
22555
+ const t = chunk6FTHFJAN_cjs.sequenceToTimelock(resolved.selection.sequence);
22158
22556
  const delay = { type: t.type, value: Number(t.value) };
22159
22557
  infos.push({ outpoint, value: vtxo.value, sweepFee, path: resolved.label, delay });
22160
22558
  sweeps.push({ vtxo, resolved, sweepFee, delay });
@@ -22555,7 +22953,7 @@ async function prepare(opts) {
22555
22953
  txid: sweep.vtxo.txid,
22556
22954
  vout: sweep.vtxo.vout,
22557
22955
  value: sweep.vtxo.value,
22558
- pkScript: chunk57636V35_cjs.VtxoScript.decode(sweep.vtxo.tapTree).pkScript
22956
+ pkScript: chunk6FTHFJAN_cjs.VtxoScript.decode(sweep.vtxo.tapTree).pkScript
22559
22957
  },
22560
22958
  path: sweep.resolved.selection,
22561
22959
  outputAddress: opts.sweepAddress,
@@ -22643,7 +23041,7 @@ async function prepare(opts) {
22643
23041
  if (newFee <= splitterFee) break;
22644
23042
  splitterFee = newFee;
22645
23043
  }
22646
- const splitter = new chunk57636V35_cjs.Transaction({ version: 2 });
23044
+ const splitter = new chunk6FTHFJAN_cjs.Transaction({ version: 2 });
22647
23045
  for (const coin of selected.inputs) {
22648
23046
  splitter.addInput({
22649
23047
  txid: coin.txid,
@@ -22787,41 +23185,41 @@ var UnilateralExit = {
22787
23185
  // src/arkade/index.ts
22788
23186
  var arkade_exports = {};
22789
23187
  chunk5BLDMQED_cjs.__export(arkade_exports, {
22790
- ARKADE_OP: () => chunk3OKEUDHU_cjs.ARKADE_OP,
22791
- ARKADE_OPCODES: () => chunk3OKEUDHU_cjs.ARKADE_OPCODES,
22792
- ARKADE_OPCODE_NAMES: () => chunk3OKEUDHU_cjs.ARKADE_OPCODE_NAMES,
22793
- ARKADE_OPCODE_VALUES: () => chunk3OKEUDHU_cjs.ARKADE_OPCODE_VALUES,
22794
- ARKADE_OPS: () => chunk3OKEUDHU_cjs.ARKADE_OPS,
23188
+ ARKADE_OP: () => chunkNPM5YZBC_cjs.ARKADE_OP,
23189
+ ARKADE_OPCODES: () => chunkNPM5YZBC_cjs.ARKADE_OPCODES,
23190
+ ARKADE_OPCODE_NAMES: () => chunkNPM5YZBC_cjs.ARKADE_OPCODE_NAMES,
23191
+ ARKADE_OPCODE_VALUES: () => chunkNPM5YZBC_cjs.ARKADE_OPCODE_VALUES,
23192
+ ARKADE_OPS: () => chunkNPM5YZBC_cjs.ARKADE_OPS,
22795
23193
  Arkade: () => Arkade,
22796
23194
  ArkadeContract: () => ArkadeContract,
22797
- ArkadeProgramScript: () => chunk3OKEUDHU_cjs.ArkadeProgramScript,
22798
- ArkadeScript: () => chunk3OKEUDHU_cjs.ArkadeScript,
23195
+ ArkadeProgramScript: () => chunkNPM5YZBC_cjs.ArkadeProgramScript,
23196
+ ArkadeScript: () => chunkNPM5YZBC_cjs.ArkadeScript,
22799
23197
  ArkadeTransactionBuilder: () => ArkadeTransactionBuilder,
22800
- BigNum: () => chunk3OKEUDHU_cjs.bignum_exports,
23198
+ BigNum: () => chunkNPM5YZBC_cjs.bignum_exports,
22801
23199
  OP: () => btcSigner.OP,
22802
- OPCODE_NAMES: () => chunk3OKEUDHU_cjs.OPCODE_NAMES,
22803
- OPCODE_VALUES: () => chunk3OKEUDHU_cjs.OPCODE_VALUES,
22804
- SUPPORTED_PROGRAM_VERSION: () => chunk3OKEUDHU_cjs.SUPPORTED_PROGRAM_VERSION,
23200
+ OPCODE_NAMES: () => chunkNPM5YZBC_cjs.OPCODE_NAMES,
23201
+ OPCODE_VALUES: () => chunkNPM5YZBC_cjs.OPCODE_VALUES,
23202
+ SUPPORTED_PROGRAM_VERSION: () => chunkNPM5YZBC_cjs.SUPPORTED_PROGRAM_VERSION,
22805
23203
  Script: () => btcSigner.Script,
22806
- arkadeScriptHash: () => chunk3OKEUDHU_cjs.arkadeScriptHash,
22807
- arkadeWitnessHash: () => chunk3OKEUDHU_cjs.arkadeWitnessHash,
22808
- asmToBytes: () => chunk3OKEUDHU_cjs.asmToBytes,
22809
- bytesToASM: () => chunk3OKEUDHU_cjs.bytesToASM,
22810
- computeArkadeScriptPublicKey: () => chunk3OKEUDHU_cjs.computeArkadeScriptPublicKey,
23204
+ arkadeScriptHash: () => chunkNPM5YZBC_cjs.arkadeScriptHash,
23205
+ arkadeWitnessHash: () => chunkNPM5YZBC_cjs.arkadeWitnessHash,
23206
+ asmToBytes: () => chunkNPM5YZBC_cjs.asmToBytes,
23207
+ bytesToASM: () => chunkNPM5YZBC_cjs.bytesToASM,
23208
+ computeArkadeScriptPublicKey: () => chunkNPM5YZBC_cjs.computeArkadeScriptPublicKey,
22811
23209
  createArkadeBatchHandler: () => createArkadeBatchHandler,
22812
- deserializeArkadeContractParams: () => chunk3OKEUDHU_cjs.deserializeArkadeContractParams,
22813
- fromASM: () => chunk3OKEUDHU_cjs.fromASM,
22814
- getOpcodeName: () => chunk3OKEUDHU_cjs.getOpcodeName,
22815
- getOpcodeValue: () => chunk3OKEUDHU_cjs.getOpcodeValue,
22816
- parseArtifact: () => chunk3OKEUDHU_cjs.parseArtifact,
22817
- resolveAsm: () => chunk3OKEUDHU_cjs.resolveAsm,
22818
- serializeArkadeContractParams: () => chunk3OKEUDHU_cjs.serializeArkadeContractParams,
22819
- stringifyArtifact: () => chunk3OKEUDHU_cjs.stringifyArtifact,
22820
- toASM: () => chunk3OKEUDHU_cjs.toASM,
22821
- validateProgram: () => chunk3OKEUDHU_cjs.validateProgram,
22822
- witnessRefToBytes: () => chunk3OKEUDHU_cjs.witnessRefToBytes
23210
+ deserializeArkadeContractParams: () => chunkNPM5YZBC_cjs.deserializeArkadeContractParams,
23211
+ fromASM: () => chunkNPM5YZBC_cjs.fromASM,
23212
+ getOpcodeName: () => chunkNPM5YZBC_cjs.getOpcodeName,
23213
+ getOpcodeValue: () => chunkNPM5YZBC_cjs.getOpcodeValue,
23214
+ parseArtifact: () => chunkNPM5YZBC_cjs.parseArtifact,
23215
+ resolveAsm: () => chunkNPM5YZBC_cjs.resolveAsm,
23216
+ serializeArkadeContractParams: () => chunkNPM5YZBC_cjs.serializeArkadeContractParams,
23217
+ stringifyArtifact: () => chunkNPM5YZBC_cjs.stringifyArtifact,
23218
+ toASM: () => chunkNPM5YZBC_cjs.toASM,
23219
+ validateProgram: () => chunkNPM5YZBC_cjs.validateProgram,
23220
+ witnessRefToBytes: () => chunkNPM5YZBC_cjs.witnessRefToBytes
22823
23221
  });
22824
- var isVtxoCoin = (input) => chunk57636V35_cjs.isVirtualCoin(input);
23222
+ var isVtxoCoin = (input) => chunk6FTHFJAN_cjs.isVirtualCoin(input);
22825
23223
  function createArkadeBatchHandler(intentId, inputs, signer, signedProof, message, session, arkProvider, emulator, network, recipients, batchExpiryPolicy) {
22826
23224
  let batchId;
22827
23225
  let sweepTapTreeRoot;
@@ -22842,23 +23240,23 @@ function createArkadeBatchHandler(intentId, inputs, signer, signedProof, message
22842
23240
  );
22843
23241
  await arkProvider.confirmRegistration(intentId);
22844
23242
  batchId = event.id;
22845
- const sweepTapscript = chunk57636V35_cjs.CSVMultisigTapscript.encode({
23243
+ const sweepTapscript = chunk6FTHFJAN_cjs.CSVMultisigTapscript.encode({
22846
23244
  timelock,
22847
- pubkeys: [chunk3OKEUDHU_cjs.toXOnly(base.hex.decode(info.forfeitPubkey), "forfeit key")]
23245
+ pubkeys: [chunkNPM5YZBC_cjs.toXOnly(base.hex.decode(info.forfeitPubkey), "forfeit key")]
22848
23246
  }).script;
22849
23247
  sweepTapTreeRoot = payment_js.tapLeafHash(sweepTapscript);
22850
23248
  return { skip: false };
22851
23249
  },
22852
23250
  onTreeSigningStarted: async (event, vtxoTree) => {
22853
23251
  const signerPubKey = await session.getPublicKey();
22854
- const xonlySignerPubKey = chunk3OKEUDHU_cjs.toXOnly(signerPubKey, "signer key");
23252
+ const xonlySignerPubKey = chunkNPM5YZBC_cjs.toXOnly(signerPubKey, "signer key");
22855
23253
  const xOnlyPubkeys = event.cosignersPublicKeys.map(
22856
- (k) => base.hex.encode(chunk3OKEUDHU_cjs.toXOnly(base.hex.decode(k), "cosigner key"))
23254
+ (k) => base.hex.encode(chunkNPM5YZBC_cjs.toXOnly(base.hex.decode(k), "cosigner key"))
22857
23255
  );
22858
23256
  if (!xOnlyPubkeys.includes(base.hex.encode(xonlySignerPubKey))) {
22859
23257
  return { skip: true };
22860
23258
  }
22861
- const commitmentTx = chunk57636V35_cjs.Transaction.fromPSBT(base.base64.decode(event.unsignedCommitmentTx));
23259
+ const commitmentTx = chunk6FTHFJAN_cjs.Transaction.fromPSBT(base.base64.decode(event.unsignedCommitmentTx));
22862
23260
  validateVtxoTxGraph(vtxoTree, commitmentTx, sweepTapTreeRoot);
22863
23261
  if (recipients && recipients.length > 0) {
22864
23262
  validateBatchRecipients(commitmentTx, vtxoTree.leaves(), recipients, network);
@@ -22890,7 +23288,7 @@ function createArkadeBatchHandler(intentId, inputs, signer, signedProof, message
22890
23288
  if (connectorTree) {
22891
23289
  validateConnectorsTxGraph(event.commitmentTx, connectorTree);
22892
23290
  }
22893
- let commitmentPsbt = chunk57636V35_cjs.Transaction.fromPSBT(base.base64.decode(event.commitmentTx));
23291
+ let commitmentPsbt = chunk6FTHFJAN_cjs.Transaction.fromPSBT(base.base64.decode(event.commitmentTx));
22894
23292
  assertFinalCommitmentMatchesValidated(
22895
23293
  commitmentPsbt,
22896
23294
  validatedCommitmentTxid,
@@ -22925,7 +23323,7 @@ function createArkadeBatchHandler(intentId, inputs, signer, signedProof, message
22925
23323
  boardingIndices.push(boardingIdx);
22926
23324
  continue;
22927
23325
  }
22928
- if (chunk57636V35_cjs.isRecoverable(input) || isSubdust(input, info.dust)) {
23326
+ if (chunk6FTHFJAN_cjs.isRecoverable(input) || isSubdust(input, info.dust)) {
22929
23327
  continue;
22930
23328
  }
22931
23329
  if (connectorIndex >= connectorLeaves.length) {
@@ -22946,7 +23344,7 @@ function createArkadeBatchHandler(intentId, inputs, signer, signedProof, message
22946
23344
  index: input.vout,
22947
23345
  witnessUtxo: {
22948
23346
  amount: BigInt(input.value),
22949
- script: chunk57636V35_cjs.VtxoScript.decode(input.tapTree).pkScript
23347
+ script: chunk6FTHFJAN_cjs.VtxoScript.decode(input.tapTree).pkScript
22950
23348
  },
22951
23349
  sighashType: btcSigner.SigHash.DEFAULT,
22952
23350
  tapLeafScript: [input.forfeitTapLeafScript]
@@ -23037,16 +23435,16 @@ var Arkade = class _Arkade {
23037
23435
  /** Connect and resolve the server key, checkpoint closure and (if present) the co-signer key. */
23038
23436
  static async connect(opts) {
23039
23437
  const info = await opts.arkade.getInfo();
23040
- const serverKey = chunk3OKEUDHU_cjs.toXOnly(base.hex.decode(info.signerPubkey), "ark signer key");
23041
- const checkpoint = chunk57636V35_cjs.CSVMultisigTapscript.decode(base.hex.decode(info.checkpointTapscript));
23042
- const network = opts.network ?? chunk57636V35_cjs.DEFAULT_NETWORK;
23438
+ const serverKey = chunkNPM5YZBC_cjs.toXOnly(base.hex.decode(info.signerPubkey), "ark signer key");
23439
+ const checkpoint = chunk6FTHFJAN_cjs.CSVMultisigTapscript.decode(base.hex.decode(info.checkpointTapscript));
23440
+ const network = opts.network ?? chunk6FTHFJAN_cjs.DEFAULT_NETWORK;
23043
23441
  let emulatorKey;
23044
23442
  if (opts.emulator) {
23045
- emulatorKey = base.hex.decode(chunk57636V35_cjs.resolveEmulatorPubkey(network, opts.emulatorPubkey));
23443
+ emulatorKey = base.hex.decode(chunk6FTHFJAN_cjs.resolveEmulatorPubkey(network, opts.emulatorPubkey));
23046
23444
  }
23047
23445
  let userKey;
23048
23446
  if (opts.identity) {
23049
- userKey = chunk3OKEUDHU_cjs.toXOnly(await opts.identity.xOnlyPublicKey(), "identity key");
23447
+ userKey = chunkNPM5YZBC_cjs.toXOnly(await opts.identity.xOnlyPublicKey(), "identity key");
23050
23448
  }
23051
23449
  return new _Arkade({
23052
23450
  arkProvider: opts.arkade,
@@ -23072,7 +23470,7 @@ var Arkade = class _Arkade {
23072
23470
  * key respectively; explicit args always win.
23073
23471
  */
23074
23472
  contract(program, args = {}) {
23075
- const declared = (program.params ?? []).map(chunk3OKEUDHU_cjs.inputName);
23473
+ const declared = (program.params ?? []).map(chunkNPM5YZBC_cjs.inputName);
23076
23474
  if (declared.includes("server") && args.server === void 0) {
23077
23475
  args = { ...args, server: this.serverKey };
23078
23476
  }
@@ -23092,7 +23490,7 @@ var ArkadeContract = class _ArkadeContract {
23092
23490
  userKey: client.userKey,
23093
23491
  emulatorKey: client.emulatorKey
23094
23492
  };
23095
- this.vtxoScript = new chunk3OKEUDHU_cjs.ArkadeProgramScript(program, args, this.keys);
23493
+ this.vtxoScript = new chunkNPM5YZBC_cjs.ArkadeProgramScript(program, args, this.keys);
23096
23494
  this.tapTree = this.vtxoScript.encode();
23097
23495
  this.compiled = this.vtxoScript.compiled;
23098
23496
  }
@@ -23120,7 +23518,7 @@ var ArkadeContract = class _ArkadeContract {
23120
23518
  `ArkadeContract.fromContract: expected contract type 'arkade', got '${contract.type}'`
23121
23519
  );
23122
23520
  }
23123
- const typed = chunk3OKEUDHU_cjs.deserializeArkadeContractParams(contract.params);
23521
+ const typed = chunkNPM5YZBC_cjs.deserializeArkadeContractParams(contract.params);
23124
23522
  return new _ArkadeContract(client, typed.program, typed.args, {
23125
23523
  serverKey: typed.serverKey,
23126
23524
  userKey: typed.userKey,
@@ -23161,7 +23559,7 @@ var ArkadeContract = class _ArkadeContract {
23161
23559
  toContractParams() {
23162
23560
  return {
23163
23561
  type: "arkade",
23164
- params: chunk3OKEUDHU_cjs.serializeArkadeContractParams({
23562
+ params: chunkNPM5YZBC_cjs.serializeArkadeContractParams({
23165
23563
  program: this.program,
23166
23564
  args: this.args,
23167
23565
  serverKey: this.keys.serverKey,
@@ -23211,18 +23609,18 @@ var ArkadeContract = class _ArkadeContract {
23211
23609
  if (registered) {
23212
23610
  const [withVtxos] = await manager.getContractsWithVtxos({ script: scriptHex });
23213
23611
  return (withVtxos?.vtxos ?? []).filter(
23214
- (v) => !chunk57636V35_cjs.hasTerminalSpend(v) && !v.isUnrolled
23612
+ (v) => !chunk6FTHFJAN_cjs.hasTerminalSpend(v) && !v.isUnrolled
23215
23613
  );
23216
23614
  }
23217
23615
  }
23218
23616
  if (!this.client.indexer) {
23219
23617
  throw new Error("ArkadeContract.getUtxos: an indexer is required");
23220
23618
  }
23221
- const { vtxos } = await chunk57636V35_cjs.getNormalizedVtxos(this.client.indexer, {
23619
+ const { vtxos } = await chunk6FTHFJAN_cjs.getNormalizedVtxos(this.client.indexer, {
23222
23620
  scripts: [scriptHex],
23223
23621
  spendableOnly: true
23224
23622
  });
23225
- return vtxos.filter((v) => !chunk57636V35_cjs.hasTerminalSpend(v) && !v.isUnrolled);
23623
+ return vtxos.filter((v) => !chunk6FTHFJAN_cjs.hasTerminalSpend(v) && !v.isUnrolled);
23226
23624
  }
23227
23625
  /** Total spendable balance (requires an indexer). */
23228
23626
  async getBalance() {
@@ -23320,7 +23718,7 @@ var ArkadeTransactionBuilder = class {
23320
23718
  this.contract.client.checkpoint
23321
23719
  );
23322
23720
  if (coin.sourceTx) {
23323
- chunk57636V35_cjs.setArkPsbtField(arkTx, 0, chunk57636V35_cjs.PrevArkTxField, coin.sourceTx);
23721
+ chunk6FTHFJAN_cjs.setArkPsbtField(arkTx, 0, chunk6FTHFJAN_cjs.PrevArkTxField, coin.sourceTx);
23324
23722
  }
23325
23723
  if (this.fn.arkadeScript) {
23326
23724
  const indexer = this.contract.client.indexer;
@@ -23337,8 +23735,8 @@ var ArkadeTransactionBuilder = class {
23337
23735
  }
23338
23736
  const condition = (def.tapscript.witness ?? []).map((w) => this.witnessBytes(w));
23339
23737
  if (condition.length > 0) {
23340
- chunk57636V35_cjs.setArkPsbtField(arkTx, 0, chunk57636V35_cjs.ConditionWitness, condition);
23341
- chunk57636V35_cjs.setArkPsbtField(checkpoints[0], 0, chunk57636V35_cjs.ConditionWitness, condition);
23738
+ chunk6FTHFJAN_cjs.setArkPsbtField(arkTx, 0, chunk6FTHFJAN_cjs.ConditionWitness, condition);
23739
+ chunk6FTHFJAN_cjs.setArkPsbtField(checkpoints[0], 0, chunk6FTHFJAN_cjs.ConditionWitness, condition);
23342
23740
  }
23343
23741
  const packets = [];
23344
23742
  if (this.assetSpecs.length > 0) {
@@ -23377,7 +23775,7 @@ var ArkadeTransactionBuilder = class {
23377
23775
  base.base64.encode(signedArk2.toPSBT()),
23378
23776
  signedCps.map((c) => base.base64.encode(c.toPSBT()))
23379
23777
  );
23380
- const txid = chunk57636V35_cjs.Transaction.fromPSBT(base.base64.decode(res2.signedArkTx)).id;
23778
+ const txid = chunk6FTHFJAN_cjs.Transaction.fromPSBT(base.base64.decode(res2.signedArkTx)).id;
23381
23779
  return {
23382
23780
  txid,
23383
23781
  signedArkTx: res2.signedArkTx,
@@ -23436,23 +23834,23 @@ var ArkadeTransactionBuilder = class {
23436
23834
  }
23437
23835
  buildAssetPacket() {
23438
23836
  const groups = this.assetSpecs.map((s) => {
23439
- const id = typeof s.assetId === "string" ? chunk3KW4TWP2_cjs.AssetId.fromString(s.assetId) : chunk3KW4TWP2_cjs.AssetId.fromBytes(s.assetId);
23440
- return chunk3KW4TWP2_cjs.AssetGroup.create(
23837
+ const id = typeof s.assetId === "string" ? chunk4C5PMGBB_cjs.AssetId.fromString(s.assetId) : chunk4C5PMGBB_cjs.AssetId.fromBytes(s.assetId);
23838
+ return chunk4C5PMGBB_cjs.AssetGroup.create(
23441
23839
  id,
23442
23840
  null,
23443
- s.inputs.map((i) => chunk3KW4TWP2_cjs.AssetInput.create(i.vin, i.amount)),
23444
- s.outputs.map((o) => chunk3KW4TWP2_cjs.AssetOutput.create(o.vout, o.amount)),
23445
- (s.metadata ?? []).map((m) => chunk3KW4TWP2_cjs.Metadata.create(m.key, m.value))
23841
+ s.inputs.map((i) => chunk4C5PMGBB_cjs.AssetInput.create(i.vin, i.amount)),
23842
+ s.outputs.map((o) => chunk4C5PMGBB_cjs.AssetOutput.create(o.vout, o.amount)),
23843
+ (s.metadata ?? []).map((m) => chunk4C5PMGBB_cjs.Metadata.create(m.key, m.value))
23446
23844
  );
23447
23845
  });
23448
- return chunk3KW4TWP2_cjs.Packet.create(groups);
23846
+ return chunk4C5PMGBB_cjs.Packet.create(groups);
23449
23847
  }
23450
23848
  witnessBytes(ref) {
23451
- return chunk3OKEUDHU_cjs.witnessRefToBytes(ref, this.args, this.contract.args);
23849
+ return chunkNPM5YZBC_cjs.witnessRefToBytes(ref, this.args, this.contract.args);
23452
23850
  }
23453
23851
  };
23454
23852
  function bindInputs(fn, callArgs) {
23455
- const names = (fn.def.inputs ?? []).map(chunk3OKEUDHU_cjs.inputName);
23853
+ const names = (fn.def.inputs ?? []).map(chunkNPM5YZBC_cjs.inputName);
23456
23854
  if (callArgs.length !== names.length) {
23457
23855
  throw new Error(`${fn.name}: expected ${names.length} argument(s), got ${callArgs.length}`);
23458
23856
  }
@@ -24072,6 +24470,7 @@ exports.isArkContract = isArkContract;
24072
24470
  exports.isBatchSignable = isBatchSignable;
24073
24471
  exports.isBtcAddress = isBtcAddress;
24074
24472
  exports.isContractGenericallySpendable = isContractGenericallySpendable;
24473
+ exports.isContractVtxoEvent = isContractVtxoEvent;
24075
24474
  exports.isCooperativelyMigratable = isCooperativelyMigratable;
24076
24475
  exports.isDeterministicSigner = isDeterministicSigner;
24077
24476
  exports.isDiscoverable = isDiscoverable;
@@ -24103,6 +24502,7 @@ exports.outpointReasons = outpointReasons;
24103
24502
  exports.promisifyRequest = promisifyRequest;
24104
24503
  exports.provisionClaimSecret = provisionClaimSecret;
24105
24504
  exports.provisionRefundKey = provisionRefundKey;
24505
+ exports.registerWalletRestoreHook = registerWalletRestoreHook;
24106
24506
  exports.requiresMigration = requiresMigration;
24107
24507
  exports.resolveAssetAmount = resolveAssetAmount;
24108
24508
  exports.resolveBatchExpiryPolicy = resolveBatchExpiryPolicy;
@@ -24134,5 +24534,5 @@ exports.waitForIncomingFunds = waitForIncomingFunds;
24134
24534
  exports.walletFeeSource = walletFeeSource;
24135
24535
  exports.warnAndFilterVtxosForScript = warnAndFilterVtxosForScript;
24136
24536
  exports.withPrevTxs = withPrevTxs;
24137
- //# sourceMappingURL=chunk-XTCOSZ34.cjs.map
24138
- //# sourceMappingURL=chunk-XTCOSZ34.cjs.map
24537
+ //# sourceMappingURL=chunk-U5I3ITV7.cjs.map
24538
+ //# sourceMappingURL=chunk-U5I3ITV7.cjs.map